text
stringlengths
184
4.48M
from enum import Enum class _AutoNumber(Enum): def __new__(cls): value = len(cls.__members__) + 1 obj = object.__new__(cls) obj._value_ = value return obj class ErrorCode(_AutoNumber): # Invalid data INVALID_DATA = () NO_CONFIG_PROVIDED = () INVALID_CERTIFICATE = () INVALID_SERIAL_NUM = () FILE_NOT_FOUND = () X509_VERIFICATION_FAILED = () DATA_SIGNING_FAILED = () DATA_ENCRYPTION_FAILED = () DATA_ENCODING_FAILED = () SIGNATURE_VERIFICATION_ON_DATA_FAILED = () DATA_DECRYPTION_FAILED = () DATA_DECODING_FAILED = () # TODO: Find a better name CMS_DATA_CREATION_FAILED = () CMS_DATA_EXTRACTION_FAILED = () def __str__(self): return str(self.name).lower().replace('_', '-') def __repr__(self): return str(self) class Error(Exception): def __init__(self, errorCode=None, error=None): self.errorCode = errorCode self.error = error message = str(self.errorCode) if errorCode else None super(Exception, self).__init__(message) def __str__(self): message = 'Error: {}'.format(str(self.errorCode)) if self.error: message += '. Reason: {}'.format(str(self.error)) return message def __eq__(self, other): if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ else: return False class CryptoError(Error): pass class DecodeError(Error): pass class ExecError(Exception): def __init__(self, cmd, error): self.cmd = cmd self.error = error super(ExecError, self).__init__(self.error)
# Homework12 ## UML диаграмма авторизации ### код ```plantuml @startuml interface IController { + generateAuthToken(): string + getToken(): string } interface IManager { + authorizeUser(token: string): boolean + validateToken(token: string): boolean } interface IRepository { + saveToken(token: string): void + queryDatabase(): void } class Controller implements IController { - token: string + generateAuthToken(): string + getToken(): string } class Manager implements IManager { - controller: IController + authorizeUser(token: string): boolean + validateToken(token: string): boolean } class Repository implements IRepository { + saveToken(token: string): void + queryDatabase(): void } class User { + username: string + password: string } class Application { - controller: IController - manager: IManager - repository: IRepository + run(): void } Controller ..> IController Manager ..> IManager Repository ..> IRepository Application --> Controller Application --> Manager Application --> Repository User --> Application @enduml ``` ![img.png](..%2FHomework11%2Fimg.png) ## Таблица UAT тестов для протокола тестирования клиентского приложения: | Тестовый сценарий | Описание | Ожидаемый результат | | --- | --- | --- | | Пользователь вводит неправильные учетные данные | Пользователь вводит неправильное имя пользователя или пароль | Приложение должно отобразить сообщение об ошибке и предложить повторить попытку входа | | Пользователь вводит правильные учетные данные | Пользователь вводит правильное имя пользователя и пароль | Приложение должно авторизовать пользователя и открыть главный экран | | Пользователь запрашивает сброс пароля | Пользователь нажимает на ссылку для сброса пароля | Приложение должно отправить на электронную почту пользователя инструкции по сбросу пароля | | Пользователь обновляет свой профиль | Пользователь изменяет свои персональные данные | Приложение должно сохранить обновленные данные и отобразить успешное сообщение об обновлении профиля | | Пользователь выходит из приложения | Пользователь нажимает на кнопку выхода из приложения | Приложение должно разлогинить пользователя и вернуть его на экран входа | ## Таблица E2E тестов для протокола тестирования клиентского приложения | Шаг | Действие | Ожидаемый результат | | --- | --- | --- | | 1 | Запустить клиентское приложение | Приложение успешно запускается без ошибок | | 2 | Сгенерировать токен с помощью метода generateAuthToken контроллера | Токен успешно сгенерирован | | 3 | Получить сгенерированный токен с помощью метода getToken контроллера | Получен правильный токен | | 4 | Авторизовать пользователя с помощью метода authorizeUser менеджера, передавая сгенерированный токен | Пользователь успешно авторизован | | 5 | Проверить валидность токена с помощью метода validateToken менеджера, передавая сгенерированный токен | Токен является валидным | | 6 | Сохранить токен в хранилище с помощью метода saveToken репозитория | Токен успешно сохранен | | 7 | Запросить данные из базы данных с помощью метода queryDatabase репозитория | Данные успешно получены из базы данных | | 8 | Завершить тестирование приложения | Тестирование завершено успешно | # UML api ```plantuml @startuml class Robot { - id: integer - model: string - version: string - status: string - resource: integer - fabric_model: string - ip_address: string } class User { - id: integer - login: string - hash_password: string - email: string } class Schedule { - id: integer - dateTime: string - id_robot: integer } class Error { - code_error: integer - message_error: string } class Robots { - robots: Robot[] } class Users { - users: User[] } class Schedules { - schedules: Schedule[] } class hm12api { - version: string + getAllRobots(): Robot[] + createRobot(robot: Robot): Robot + getRobotById(robotId: integer): Robot + getAllUsers(): User[] + createUser(user: User): User + getUserById(userId: integer): User + updateSchedule(schedule: Schedule): Schedule + getAllSchedules(): Schedule[] } hm12api --> Robots hm12api --> Users hm12api --> Schedules Robot --> Error User --> Error Schedule --> Error @enduml ``` ## Таблица UAT тестов для протокола тестирования клиентского приложения | Тестовый сценарий | Описание | Ожидаемый результат | Результат | | --- | --- | --- | --- | | Аутентификация пользователя | Попытка входа в приложение с правильными учетными данными пользователя | Успешная аутентификация и переход на главный экран приложения | | | Аутентификация пользователя | Попытка входа в приложение с неправильными учетными данными пользователя | Отображение сообщения об ошибке аутентификации | | | Создание робота | Попытка создания нового робота с корректными данными | Успешное создание робота и отображение его в списке роботов | | | Создание робота | Попытка создания нового робота с неправильными данными | Отображение сообщения об ошибке создания робота | | | Получение информации о роботе | Запрос информации о существующем роботе | Отображение подробной информации о роботе | | | Получение информации о роботе | Запрос информации о несуществующем роботе | Отображение сообщения об ошибке получения информации | | | Обновление расписания | Попытка обновления расписания для существующего робота | Успешное обновление расписания и отображение изменений | | | Обновление расписания | Попытка обновления расписания для несуществующего робота | Отображение сообщения об ошибке обновления расписания | | | Получение списка пользователей | Запрос списка всех пользователей | Отображение полного списка пользователей | | | Получение списка пользователей | Запрос списка пользователей с неправильными правами доступа | Отображение сообщения об ошибке доступа | | ## Таблица E2E тестов для протокола тестирования клиентского приложения | Шаг | Описание | Ожидаемый результат | | --- | --- | --- | | 1 | Проверить соединение с API | Успешное подключение | | 2 | Получить список всех роботов | Список роботов | | 3 | Создать нового робота | Робот успешно создан | | 4 | Получить информацию о конкретном роботе по его ID | Информация о роботе | | 5 | Получить список всех пользователей | Список пользователей | | 6 | Создать нового пользователя | Пользователь успешно создан | | 7 | Получить информацию о конкретном пользователе по его ID | Информация о пользователе | | 8 | Обновить расписание робота | Расписание успешно обновлено | | 9 | Получить список всех расписаний | Список расписаний |
\subsection{Running Streams - Quickstart} Designing a simple stream process does not require more than writing some XML declaration and executing that XML with the stream-runner as shown in the following figure: \begin{figure}[h!] \centering \includegraphics[scale=0.3]{graphics/quickstart-xml} \caption{\label{fig:quickstart}Conceptual way of executing a data flow graph that is defined in XML.} \end{figure} The simple example presented below, defines a single process that reads from a CSV stream and prints out the data items to standard output: \begin{figure}[h!] \centering \begin{lstlisting}[language=XML] <container> <stream id="firstStream" class="stream.io.CsvStream" url="http://www.jwall.org/streams/sample-stream.csv" /> <process input="firstStream"> <PrintData /> </process> </container> \end{lstlisting} \end{figure} The {\em stream-runner} required to execute this stream is a simple executable Java archive available for download: \begin{displaymath} \mbox{\url{http://download.jwall.org/streams/stream-runner.jar}} \end{displaymath} \subsubsection{Running a \streams Process} The simple process defined above can be run by \hspace{4ex}\sample{\# java -jar stream-runner.jar first-process.xml} The process will simply read the stream in CSV-format and execute the processor {\ttfamily PrintData} for each item obtained from the stream. \subsubsection{Including additional Libraries} There exists a set pre-packaged libraries such as {\em streams-analysis} or {\em streams-video}, which are provided at \begin{displaymath} \mbox{\url{http://download.jwall.org/streams/libs/}} \end{displaymath} These add additional processors and stream implementations to the \streams runtime for different domain specific intentions. To start the \streams runtime with additional libraries, these need to be provided on the classpath. The following example uses the {\ttfamily MJpegImageStream} to process a stream of video data from some URL. This stream implementation is provided in the {\em streams-video} package. \begin{figure}[h!] \centering \begin{lstlisting}[language=XML] <container> <stream id="video" class="stream.io.MJpegImageStream" url="http://download.jwall.org/streams/coffee.mjpeg.gz" /> <process input="video" > <stream.image.DisplayImage key="data" /> <stream.image.AverageRGB /> <WithKeys keys="frame:*"> <stream.plotter.Plotter history="1000" keepOpen="true" keys="frame:red:avg,frame:green:avg,frame:blue:avg" /> </WithKeys> </process> </container> \end{lstlisting} \caption{\label{fig:videoExample}Displaying an MJPEG video stream and plotting the average RGB channels.} \end{figure} For the libraries to be included in the path, the following command needs to be issued to start the \streams run-time: \hspace{4ex}\sample{\# java -cp stream-runner.jar:streams-video-0.0.1.jar $\backslash$ stream.run video.xml}
import { ReactNode, useCallback, useContext, useEffect } from "react"; import { useState } from "react"; import { createContext } from "react"; import { api } from "../services/api"; interface GenreResponseProps { id: number; name: "action" | "comedy" | "documentary" | "drama" | "horror" | "family"; title: string; } interface MovieProps { imdbID: string; Title: string; Poster: string; Ratings: Array<{ Source: string; Value: string; }>; Runtime: string; } interface MovieContextData { selectedGenreId: number; genres: GenreResponseProps[]; movies: MovieProps[]; selectedGenre: GenreResponseProps; handleClickButton: (id: number) => void; } interface MoviesProviderProps { children: ReactNode; } const MoviesContext = createContext<MovieContextData>({} as MovieContextData); export function MoviesProvider({ children }: MoviesProviderProps) { const [selectedGenreId, setSelectedGenreId] = useState(1); const [genres, setGenres] = useState<GenreResponseProps[]>([]); const [movies, setMovies] = useState<MovieProps[]>([]); const [selectedGenre, setSelectedGenre] = useState<GenreResponseProps>( {} as GenreResponseProps ); useEffect(() => { api.get<GenreResponseProps[]>("genres").then((response) => { setGenres(response.data); }); }, []); useEffect(() => { api .get<MovieProps[]>(`movies/?Genre_id=${selectedGenreId}`) .then((response) => { setMovies(response.data); }); api .get<GenreResponseProps>(`genres/${selectedGenreId}`) .then((response) => { setSelectedGenre(response.data); }); }, [selectedGenreId]); const handleClickButton = useCallback( (id: number) => { return setSelectedGenreId(id); },[]) return ( <MoviesContext.Provider value={{ selectedGenreId, genres, movies, selectedGenre, handleClickButton, }} > {children} </MoviesContext.Provider> ); } export function useMoviesContext() { const context = useContext(MoviesContext); return context; }
import { Injectable } from '@angular/core'; import { CanActivate, Router } from '@angular/router'; import { KeyManagementService } from '../../services/key.service'; @Injectable({ providedIn: 'root' }) export class LoginGuard implements CanActivate { constructor(private router: Router, private keyManagementService: KeyManagementService) {} canActivate(): boolean { // Check if the user's private key is stored const privKey = this.keyManagementService.getPrivKey(); if (!privKey) { // If the user's private key is not stored, redirect them to the login page this.router.navigate(['/login']); return false; } // If the user's private key is stored, allow access to the component return true; } }
/* ** EPITECH PROJECT, 2024 ** Scene ** File description: ** Raytracer */ #pragma once #include <vector> #include <string> #include <memory> #include <iostream> #include <functional> #include <unordered_map> #include <libconfig.h++> #include "Lights/Point.hpp" #include "Lights/Ambient.hpp" #include "Primitives/Cone.hpp" #include "Primitives/Mesh.hpp" #include "Parser/DLLoader.hpp" #include "Primitives/Plane.hpp" #include "Primitives/Sphere.hpp" #include "Lights/Directional.hpp" #include "Primitives/Cylinder.hpp" #include "Primitives/Triangle.hpp" #include "Primitives/RectangularCuboid.hpp" namespace Raytracer { class Factory; }; class Raytracer::Factory { public: using PrimitivesCreator = std::function<std::shared_ptr<Primitive::IPrimitive>()>; using LightsCreator = std::function<std::shared_ptr<Light::ILight>()>; /** * @brief Construct a new Scene object. * */ Factory(); /** * @brief Destruct a Scene object. * */ ~Factory() = default; /* * @brief Create a type component. * @param type Component to create * @return The Component */ std::shared_ptr<Primitive::IPrimitive> createPrimitivesComponent(const std::string &type); /* * @brief Register a type component. * @param type Component to register * @param creator Function to create the component */ void registerPrimitivesComponent(const std::string& type, PrimitivesCreator creator); /* * @brief Create a type component. * @param type Component to create * @return The Component */ std::shared_ptr<Light::ILight> createLightsComponent(const std::string &type); /* * @brief Register a type component. * @param type Component to register * @param creator Function to create the component */ void registerLightsComponent(const std::string& type, LightsCreator creator); private: std::unordered_map<std::string, PrimitivesCreator> _componentPrimitivesList; std::unordered_map<std::string, LightsCreator> _componentLightsList; std::vector<std::shared_ptr<DLLoader>> _libraryLoader; };
# Entity Framework Core Entity Framework (EF) Core is a lightweight, extensible, open source and cross-platform version of the popular Entity Framework data access technology. EF Core can serve as an object-relational mapper (O/RM), Which enables .NET developers to work with a database using .NET objects. And eliminates the need for most of the data-access code that typically needs to be written. ## Get Entity Framework Core EF Core is shipped as NuGet packages. To add EF Core to an application, install the NuGet package for the database provider you want to use. To install or update NuGet packages, you can use the .NET Core command-line interface (CLI), the Visual Studio Package Manager Dialog, or the Visual Studio Package Manager Console. ## Get the Entity Framework Core tools You can install tools to carry out EF Core-related tasks in your project, Like creating and applying database migrations, or creating an EF Core model based on an existing database. Two sets of tools are available: - The .NET Core command-line interface (CLI) tools can be used on Windows, Linux, or macOS. These commands begin with dotnet ef. - The Package Manager Console (PMC) tools run in Visual Studio on Windows. These commands start with a verb, for example Add-Migration, Update-Database. ## References - https://learn.microsoft.com/en-us/ef/core/ - https://learn.microsoft.com/en-us/ef/core/get-started/overview/install
"""OpenFOAM input files .. rubric:: AST and parser .. autosummary:: :toctree: ast generators parser format .. rubric:: Helper to create input files .. autosummary:: :toctree: blockmesh control_dict fields fv_schemes constant_files fv_options decompose_par util """ from abc import ABC, abstractmethod from inflection import underscore from .ast import Dict, DimensionSet, FoamInputFile, List, Value from .parser import dump, parse __all__ = [ "parse", "dump", "create_field_from_code", "FoamInputFile", "DEFAULT_HEADER", "ControlDictHelper", "Dict", "List", "Value", "BlockMeshDict", "VolScalarField", "VolVectorField", "FvSchemesHelper", "Vertex", "read_field_file", "FileHelper", "ConstantFileHelper", "BlockMeshDictRectilinear", "FvOptionsHelper", "DimensionSet", "DecomposeParDictHelper", "format_code", "FoamFormatError", "read_header", "parse_header", ] def _as_py_name(name): return underscore(name).replace(".", "_") def _update_dict_with_params(data, params_data): for key, value in data.items(): name = underscore(key) try: param_value = params_data[name] except (KeyError, AttributeError): continue if isinstance(value, dict): _update_dict_with_params(value, param_value) else: data[key] = param_value def _complete_params_dict(subparams, name, default, doc=None): name = _as_py_name(name) subsubparams = subparams._set_child(name, doc=doc) for key, value in default.items(): if isinstance(value, dict): _complete_params_dict(subsubparams, key, value) continue subsubparams._set_attrib(_as_py_name(key), value) class FileHelper(ABC): """Abstract class for "Helper" objects""" @abstractmethod def complete_params(self, params): """Complete the params object""" @abstractmethod def make_tree(self, params): """Make the AST corresponding to a file""" DEFAULT_HEADER = r""" /*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v2206 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ """ DEFAULT_HEADER = DEFAULT_HEADER[1:-1] def read_header(path): """Read the header ("FoamFile" entry) of an OpenFOAM file""" lines_header = [] with open(path) as file: # reach header for line in file: if line.startswith("FoamFile\n"): lines_header.append(line) break for line in file: lines_header.append(line) if line.startswith("}"): break if not lines_header: raise ValueError("No FoamFile entry found") code_header = "".join(lines_header) tree = parse(code_header) return tree.value def parse_header(code: str): """Parse the header ("FoamFile" entry) of an OpenFOAM file""" code_header = ( "FoamFile" + code.split("FoamFile", 1)[1].split("\n}", 1)[0] + "\n}" ) tree = parse(code_header) return tree.value from .blockmesh import BlockMeshDict, BlockMeshDictRectilinear, Vertex from .constant_files import ConstantFileHelper from .control_dict import ControlDictHelper from .decompose_par import DecomposeParDictHelper from .fields import ( VolScalarField, VolVectorField, create_field_from_code, read_field_file, ) from .format import FoamFormatError, format_code from .fv_options import FvOptionsHelper from .fv_schemes import FvSchemesHelper
package org.example.tree.BST; import org.example.tree.IndexInterface; import java.util.HashMap; import java.util.HashSet; import java.util.Map; public class BinarySearchTree implements IndexInterface<TreeNode> { public TreeNode root; public TreeNode getRoot() { return root; } public void setRoot(TreeNode root) { this.root = root; } public BinarySearchTree() { root = null; } private TreeNode searchItem(TreeNode tNode, Comparable searchKey) { if (tNode == null) return null; if (searchKey.compareTo(tNode.key) == 0) { return tNode; } if (searchKey.compareTo(tNode.key) < 0) { return searchItem(tNode.left, searchKey); } return searchItem(tNode.right, searchKey); // > 0 인 상황 } @Override public TreeNode search(Comparable searchKey) { TreeNode searched = searchItem(root, searchKey); if (searched == null) throw new IllegalArgumentException("트리에 있는 key 값을 넣어주세요"); return searched; } private TreeNode insertItem(TreeNode tNode, Comparable newItem) { if (tNode == null) tNode = new TreeNode(newItem, null, null); else if (newItem.compareTo(tNode.key) < 0) { tNode.left = insertItem(tNode.left, newItem); } else { tNode.right = insertItem(tNode.right, newItem); } return tNode; } @Override public void insert(Comparable newKey) { root = insertItem(root, newKey); } private TreeNode deleteItem(TreeNode tNode, Comparable searchKey) { if (tNode == null) return null; if (searchKey == tNode.key) tNode = deleteNode(tNode); else if (searchKey.compareTo(tNode.key) < 0) { tNode.left = deleteItem(tNode.left, searchKey); } else { tNode.right = deleteItem(tNode.right, searchKey); } return tNode; } private TreeNode deleteNode(TreeNode tNode) { // 1. 리프 노드 지우기 if (tNode.left == null && tNode.right == null) { return null; } else if (tNode.left == null) { // 2. 오른쪽 노드만 존재 return tNode.right; } else if (tNode.right == null) { // 3. 왼쪽 노드만 존재 return tNode.left; } else { // 4. 두 자식 노드 다 존재. returnPair returnPair = deleteMinItem(tNode.right); tNode.key = returnPair.key; tNode.right = returnPair.node; return tNode; } } private returnPair deleteMinItem(TreeNode tNode) { if (tNode.left == null) return new returnPair(tNode.key, tNode.right); returnPair rPair = deleteMinItem(tNode.left); tNode.left = rPair.node; rPair.node = tNode; return rPair; } private static class returnPair { private Comparable key; private TreeNode node; public returnPair(Comparable it, TreeNode nd) { key = it; node = nd; } } @Override public void delete(Comparable x) { root = deleteItem(root, x); } @Override public boolean isEmpty() { return root == null; } @Override public void clear() { root = null; } public void preorder(TreeNode nd) { System.out.print(nd+" "); if (nd.left != null) preorder(nd.left); if (nd.right != null) preorder(nd.right); } public void inorder(TreeNode nd) { if (nd.left != null) inorder(nd.left); System.out.print(nd+" "); if (nd.right != null) inorder(nd.right); } public void postorder(TreeNode nd) { if (nd.left != null) postorder(nd.left); if (nd.right != null) postorder(nd.right); System.out.print(nd+" "); } }
package com.pilipiknow.knowyouknow; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.lorentzos.flingswipe.SwipeFlingAdapterView; import java.util.ArrayList; import java.util.List; public class Festivals extends AppCompatActivity { public static Festivals.MyAppAdapter myAppAdapter; public static Festivals.ViewHolder viewHolder; private ArrayList<Data> array; private SwipeFlingAdapterView flingContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_festivals); flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame); array = new ArrayList<>(); array.add(new Data("https://i.pinimg.com/originals/5d/88/79/5d8879daaae6520cdd946815f8bb229c.jpg", "The Sinulog-Santo Niño Festival\n" + "is an annual cultural and religious festival held on the third Sunday of January in Cebu City \n" + "and is the centre of the Santo Niño Catholic celebrations in the Philippines. \n" + "The festival is considered to be first of most popular festivals in the Philippines, with every celebration of the festival routinely attracting around 1 to 2 million people from all over the Philippines every year.[1] Aside from the religious aspect of the festival, Sinulog is also famous for its street parties, usually happening at night before and at the night of the main festival.")); array.add(new Data("https://i.pinimg.com/originals/4d/80/18/4d8018e207171dab69239864980cd31c.jpg", "Ati-Atihan \n" + "Kalibo, Aklan (Third week/Sunday of January)\n" + "Another celebration to honour the Santo Niño, Ati-Atihan is where people go to the streets parading their traditional costumes and weapons, and painting their bodies black. Participants march and dance in the town, matched with loud drumbeats. This festival will definitely make you dance your heart out while enjoying a true Filipino atmosphere.")); array.add(new Data("https://lovepilipinas.com/wp-content/uploads/Dinagyang-Festival.jpg", "Dinagyang Festival \n" + "Dinagyang is Iloilo City’s version of the Ati-Atihan Festival. While the festival in Kalibo, Aklan gets the most attention, the Dinagyang Festival in Iloilo City is equally deserving of its place on the Philippine calendar. The festival dates back to 1967 when a replica of the Señor Santo Niño was brought to Iloilo City from Cebu, and it has been called the Dinagyang Festival since 1977—Dinagyang being a term used to refer to “revelry” in the Ilonggo dialect. Today the festival includes tribal dance competitions, street parties, and firework displays.")); array.add(new Data("https://philnewsph.com/wp-content/uploads/2017/01/Panagbenga-Festival-2017.jpg", "Panagbenga festival\n" + "Witness the colorful celebration of the annual flower festival parade in Baguio with a day tour at the Panagbenga Festival for P949 instead of P2500\n" + "Being the Summer Capital of the country, people usually come to Baguio to experience the chilly weather, and of course, the world-famous Panagbenga Festival every February, which is a month-long flower festival featuring a grand parade of floats made of flowers\n" + "Bask in the beauty of Baguio with a city tour and visit Burnham Park, Strawberry Farm, and The Mansion\n" + "Experience the festivity in convenience with round-trip bus transfers and an onboard tour guide throughout the trip\n" + "Enjoy your Baguio escapade to the fullest as this package is also inclusive of driver's fee, toll fees, and fuel charge\n" + "The tour also comes with a light snack and bottled water to keep you energized during the festivity.")); array.add(new Data("https://4.bp.blogspot.com/-CTzg6pTdehM/WMi1wn8os3I/AAAAAAAACKU/Tsyl-atC-rMWl1BALiLxHlpHO1YKs66AwCPcB/s1600/Marinduque%2BMoriones%2BFestival_Holy%2BWeek.jpg", "Moriones Festival \n" + "The Moriones is a lenten rites held annually on Holy Week on the island of Marinduque, Philippines. The \"Moriones\" are men and women in costumes and masks replicating the garb of biblical Roman soldiers as interpreted by local folks. The Moriones or Moryonan tradition has inspired the creation of other festivals in the Philippines where cultural practices or folk history is turned into street festivals.It is a colorful festival celebrated on the island of Marinduque in the Philippines. The participants use morion masks to depict the Roman soldiers and Syrian mercenaries within the story of the Passion of the Christ. The mask was named after the 16th and 17th century Morion helmet.The Moriones refers to the masked and costumed penitents who march around the town for seven days searching for Longinus. Morions roam the streets in town from Holy Monday to Easter Sunday scaring the kids, or engaging in antics or surprises to draw attention. This is a folk-religious festival that re-enacts the story of Saint Longinus, a Roman centurion who was blind in one eye. The festival is characterized by colorful Roman costumes, painted masks and helmets, and brightly colored tunics. The towns of Boac, Gasan, Santa Cruz, Buenavista and Mogpog in the island of Marinduque become one gigantic stage. The observances form part of the Lenten celebrations of Marinduque. The various towns also hold the unique tradition of the pabasa or the recitation of Christ's passion in verse.")); array.add(new Data("https://4.bp.blogspot.com/-4n_unfK-TBA/Vzm-CCU4l9I/AAAAAAAABbY/aVFHdiBeLOE7D1XlJ6rnsBsA-wXCyVnCgCLcB/s1600/Uncovering-Eden-Pahiyas-Festival-3.jpg", "Pahiyas Festival \n" + "May 15 is when the locals of Lucban decorate their houses extravagantly with vibrant and lively colours. Vegetables are hung as decorations because this festival celebrates the season of harvesting. People are allowed to bring their own basket and pick fresh vegetables from the walls, with no charge – happy fiesta and shopping at the same time!.")); array.add(new Data("https://lovepilipinas.com/wp-content/uploads/2018/02/Pintados-Kasadyaan-Festival.jpg", "Pintados-Kasadayan Festival \n" + "Pintados-Kasadayan Festival is another religious celebration in the name of the Santo Niño held in Tacloban City. It showcases the rich culture and colourful history of the province of Leyte. The dancers paint their faces and bodies with vibrant colours of blue and green to depict Leyte’s ancestral people. Some dancers are also painted with designs that look like armour to represent the warriors that lived in Leyte long ago.\n" + "The folk dances they perform portray the many traditions people of Leyte practised before the Spanish era. Among these is the worship of idols, indigenous music, and epic stories, to name a few. The term, pintados, is derived from what the tattoed native warriors of Leyte were once called, while kasadayan means merriment in the Visayan tongue.")); array.add(new Data("https://philippinescities.com/wp-content/uploads/2013/05/Baybay-City-Biliran-Festivals.jpg", "Sirong Festival \n" + "Surigao del Sur (August 15th)\n" + "Sirong Festival is another cultural and religious celebration. Various towns claim that it originated in their municipalities in Surigao del Sur. Most of these towns were founded during the pre-Spanish occupation and were attacked by the Moros. Sirong Festival features a war dance between the Muslims and the Christians. It marks the Christianisation of the early Cantilangnons. Whoever wins the best dance in the festival brings home a cash prize.")); array.add(new Data("https://lifestyle.inquirer.net/241595/masskara-behind-the-masks/", "Masskara Festival \n" + "Bacolod City (October)\n" + "A festival that is celebrated from the city of smiles – Bacolod City. Mass (crowd) kara (face) Festival is filled with people wearing colourful smiling masks designed with feathers, flowers, and native beads. The festival allows tourists to enjoy 20 days of beer drinking, street dancing, and merrymaking. Every street is filled with locals wearing their smiling masks and festive costumes while dancing around and spreading the happy atmosphere throughout the city.\n" + "During the festival, locals are encouraged to forget the economic struggle brought about by the dead season of the sugar harvest. They also see the festival as their way of escapism and obscurantism. The sugar harvest is important to the people of Bacolod since Negros Occidental, where Bacolod is found, is known as the Sugar Bowl of the Philippines.")); array.add(new Data("https://2.bp.blogspot.com/-2BQNA_6sMDU/XJL398ICjPI/AAAAAAAALwU/RT2nrIFUyO0jdC942ueKJU1WSPrLUu2UQCLcBGAs/s1600/kadayawan%2B2019.png", "Kadayawan Festival \n" + "The Kadayawan festival is celebrated every August. Indak-Indak sa Kadalanan ( Street Dancing)will showcase dance contingents from the different regions of Mindanao. A people's celebration and merriment through choreographed and theatrical street-dancing completion anchored on indigenous garbs and cultural performances while Pamulak sa Kadayawan (Floral Float Parade) will showcase of blooming and lush flora in a float parade and competition teeming with artistry as the floats impress the festival's theme and blessings of bounty which are the main highlights of the Kadayawan sa Dabaw Festival 2019. It showcased the different colors, cultures and traditional dances of the different tribes of Davao and Mindanao as they paraded along the city.")); myAppAdapter = new Festivals.MyAppAdapter(array, Festivals.this); flingContainer.setAdapter(myAppAdapter); flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() { @Override public void removeFirstObjectInAdapter() { } @Override public void onLeftCardExit(Object dataObject) { array.remove(0); myAppAdapter.notifyDataSetChanged(); //Do something on the left! //You also have access to the original object. //If you want to use it just cast it (String) dataObject } @Override public void onRightCardExit(Object dataObject) { array.remove(0); myAppAdapter.notifyDataSetChanged(); } @Override public void onAdapterAboutToEmpty(int itemsInAdapter) { } @Override public void onScroll(float scrollProgressPercent) { View view = flingContainer.getSelectedView(); view.findViewById(R.id.background).setAlpha(0); view.findViewById(R.id.item_swipe_right_indicator).setAlpha(scrollProgressPercent < 0 ? -scrollProgressPercent : 0); view.findViewById(R.id.item_swipe_left_indicator).setAlpha(scrollProgressPercent > 0 ? scrollProgressPercent : 0); } }); // Optionally add an OnItemClickListener flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() { @Override public void onItemClicked(int itemPosition, Object dataObject) { View view = flingContainer.getSelectedView(); view.findViewById(R.id.background).setAlpha(0); myAppAdapter.notifyDataSetChanged(); } }); } public static class ViewHolder { public static FrameLayout background; public TextView DataText; public ImageView cardImage; } public class MyAppAdapter extends BaseAdapter { public List<Data> parkingList; public Context context; private MyAppAdapter(List<Data> apps, Context context) { this.parkingList = apps; this.context = context; } @Override public int getCount() { return parkingList.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View rowView = convertView; if (rowView == null) { LayoutInflater inflater = getLayoutInflater(); rowView = inflater.inflate(R.layout.item, parent, false); // configure view holder viewHolder = new Festivals.ViewHolder(); viewHolder.DataText = (TextView) rowView.findViewById(R.id.bookText); viewHolder.background = (FrameLayout) rowView.findViewById(R.id.background); viewHolder.cardImage = (ImageView) rowView.findViewById(R.id.cardImage); rowView.setTag(viewHolder); } else { viewHolder = (Festivals.ViewHolder) convertView.getTag(); } viewHolder.DataText.setText(parkingList.get(position).getDescription() + ""); Glide.with(Festivals.this).load(parkingList.get(position).getImagePath()).into(viewHolder.cardImage); return rowView; } } }
import React, { useState } from 'react' import { Link, useNavigate } from 'react-router-dom'; import axios from 'axios'; import '../SignUp/SignUp.css'; import {BASE_URL} from '../../services/helper' const SignUp = () => { const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [error, setError] = useState(''); const navigate = useNavigate(); const handleSignup = async (e) => { e.preventDefault(); try { const response = await axios.post(`${BASE_URL}/api/v1/users/signup`, { name, email, username, password, }); console.log(response.data); // You can handle the response as per your requirements // Redirect to login page on successful signup navigate('/login'); } catch (error) { setError(error.response.data.message); } }; return ( <div className="container signup"> <h2 className="signup-heading mx-auto">Signup</h2> <form onSubmit={handleSignup}> <div className="form-group"> <label htmlFor="name">Name</label> <input type="text" className="form-control" id="name" value={name} onChange={(e) => setName(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="email">Email</label> <input type="email" className="form-control" id="email" value={email} onChange={(e) => setEmail(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="username">Username</label> <input type="text" className="form-control" id="username" value={username} onChange={(e) => setUsername(e.target.value)} /> </div> <div className="form-group"> <label htmlFor="password">Password</label> <input type="password" className="form-control" id="password" value={password} onChange={(e) => setPassword(e.target.value)} /> </div> {error && <p className="error-message">{error}</p>} <button type="submit" className="btn btn-outline-primary sbtn"> Sign up </button> <br /> <span>Have an account? <Link to = "/">Login</Link></span> </form> </div> ); }; export default SignUp
<template> <div v-if=isAuth class="swipekey-your-secrets-root"> <h4>Your Secrets</h4> <p> This page contains all of your application secrets for use within your applications. All of these are encrypted and can only be read with your SwipeKey master token. </p> <div v-if="isAuth" className="add-secret"> <h6>Add a new secret for your app:</h6> <input v-model="app_name" type="text" class="form-control" placeholder="Application Name" /> <input v-model="secret_name" type="text" class="form-control" placeholder="Secret Name" /> <input v-model="secret_value" type="text" class="form-control" placeholder="Secret Value" /> <button class="btn btn-success" @click="createSecret()"> Add Secret </button> </div> <h6>Or to view secrets, please enter your master token:</h6> <input v-model="token" type="password" class="form-control" placeholder="Enter master token here" @keyup.enter="validateToken(token)" /> <button id="fetch-secrets-btn" @click="getSecrets" v-if="isAuth" class="btn btn-success">Fetch Secrets</button> <table class="secrets-table"> <tr> <th>Application</th> <th>Secret Name</th> <th>Secret Value</th> </tr> <tr v-for="secret, idx in secrets" :key="idx"> <td>{{ secret.application }}</td> <td>{{ secret.secret_name }}</td> <td v-if="!secret.secret_revealed"> <button class="btn btn-danger" @click="secret.secret_revealed = true"> Reveal </button> </td> <td v-if="secret.secret_revealed">{{ secret.secret_value }}</td> </tr> </table> </div> </template> <script lang="ts"> import { defineComponent } from "vue"; import axios from "axios"; interface ApiRequest { username: string; email: string; password: string; token: string; } interface Secret { application: string; secret_name: string; secret_value: string; secret_revealed: boolean; } export default defineComponent({ name: "YourSecrets", props: { isAuthetnicated: Boolean }, data() { return { token: "" as string, app_name: "" as string, secret_name: "" as string, secret_value: "" as string, secrets: [] as Secret[], isAuth: this.isAuthetnicated as boolean }; }, methods: { async validateToken(token: string) { const request: ApiRequest = { username: "", email: "", password: "", token: token, }; await axios .post("http://localhost:3000/auth", null, { params: request }) }, getSecrets() { if(this.isAuth) { axios.get("http://localhost:3000/secrets").then(response => { for(let i in response.data.secrets) { if(this.secrets.length === response.data.secrets.length) { return; } else { this.secrets.push(response.data.secrets[i]) } } }) } }, createSecret() { if (this.isAuth) { let secret: Secret = { application: this.app_name, secret_name: this.secret_name, secret_value: this.secret_value, secret_revealed: false, }; this.secrets.push(secret); } }, }, }); </script> <style> .swipekey-your-secrets-root { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; position: fixed; background-color: rgba(0, 0, 0, 0.3); width: 95%; top: 0; left: 10%; height: 100%; padding: 15px; } .secrets-table { position: fixed; top: 225px; } .add-secret { position:fixed; top:425px; padding:5px; } .form-control { margin:5px; padding:5px; width:450px; } th { padding: 10px; border: 1px solid white; background-color: white; } td { padding: 10px; border: 1px solid white; } #fetch-secrets-btn { position:fixed; top:175px; } </style>
import { type NFTInfo } from '@btcgreen/api'; import { useTransferNFTMutation } from '@btcgreen/api-react'; import { Button, ButtonLoading, EstimatedFee, Form, Flex, TextField, btcgreenToMojo, useOpenDialog, useShowError, } from '@btcgreen/core'; import { Trans } from '@lingui/macro'; import { Alert, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Typography } from '@mui/material'; import React, { useEffect } from 'react'; import { useForm } from 'react-hook-form'; import useBurnAddress from '../../hooks/useBurnAddress'; import NFTSummary from './NFTSummary'; import NFTTransferConfirmationDialog from './NFTTransferConfirmationDialog'; type NFTPreviewDialogProps = { nft: NFTInfo; open?: boolean; onClose?: () => void; }; type FormData = { fee: string; destination: string; }; export default function NFTBurnDialog(props: NFTPreviewDialogProps) { const { nft, onClose = () => ({}), open = false, ...rest } = props; const burnAddress = useBurnAddress(); const openDialog = useOpenDialog(); const showError = useShowError(); const [transferNFT] = useTransferNFTMutation(); const methods = useForm<FormData>({ defaultValues: { fee: '', destination: '', }, }); const { isSubmitting } = methods.formState; useEffect(() => { if (burnAddress) { methods.setValue('destination', burnAddress); } }, [burnAddress, methods]); function handleClose() { onClose(); } async function handleSubmit(values: FormData) { const { fee, destination } = values; if (!destination) { return; } const confirmation = await openDialog( <NFTTransferConfirmationDialog destination={destination} fee={fee} confirmColor="danger" title={<Trans>Burn NFT confirmation</Trans>} description={ <Alert severity="warning" icon={false}> <Trans> If you burn this NFT, nobody (including you) will ever be able to access it again. Are you sure you want to continue? </Trans> </Alert> } confirmTitle={<Trans>Burn</Trans>} /> ); if (!confirmation) { return; } try { const feeInMojos = btcgreenToMojo(fee || 0); await transferNFT({ walletId: nft.walletId, nftCoinId: nft.nftCoinId, launcherId: nft.launcherId, targetAddress: destination, fee: feeInMojos, }).unwrap(); onClose(); } catch (error) { showError(error); } } return ( <Dialog open={open} onClose={handleClose} maxWidth="sm" fullWidth {...rest}> <DialogTitle id="nft-transfer-dialog-title"> <Flex flexDirection="row" gap={1}> <Typography variant="h6"> <Trans>Do you want to burn this NFT?</Trans> </Typography> </Flex> </DialogTitle> <DialogContent> <Form methods={methods} onSubmit={handleSubmit}> <Flex flexDirection="column" gap={3}> <DialogContentText id="nft-transfer-dialog-description"> <Trans> Burning a non-fungible token means removing it from circulation by sending it to a verifiably un-spendable address. However, transactions leading up to the burn will remain on the blockchain ledger. </Trans> </DialogContentText> <Flex flexDirection="column" gap={3}> <Flex flexDirection="column" gap={1}> <NFTSummary launcherId={nft.launcherId} /> </Flex> <TextField name="destination" variant="filled" color="secondary" InputProps={{ readOnly: true, }} fullWidth label={<Trans>Send to Address</Trans>} /> <EstimatedFee id="filled-secondary" variant="filled" name="fee" color="secondary" label={<Trans>Fee</Trans>} disabled={isSubmitting} txType="burnNFT" fullWidth /> <DialogActions> <Flex flexDirection="row" gap={2}> <Button onClick={handleClose} color="secondary" variant="outlined" autoFocus> <Trans>Cancel</Trans> </Button> <ButtonLoading type="submit" autoFocus color="danger" variant="contained" loading={isSubmitting} disableElevation > <Trans>Burn</Trans> </ButtonLoading> </Flex> </DialogActions> </Flex> </Flex> </Form> </DialogContent> </Dialog> ); }
class Node(): def __init__(self, data): self.data = data self.left = None self.right = None class BST(): def __init__(self): self.root = None def insert(self, data): self.root = self.insert_helper(self.root, data) def insert_helper(self, node, data): if node is None: node = Node(data) elif data < node.data: node.left = self.insert_helper(node.left, data) elif data > node.data: node.right = self.insert_helper(node.right, data) return node def printTree(self, node, level=1): if node is not None: self.printTree(node.right, level+1) print(' '* level,node.data) self.printTree(node.left, level+1) def printPreOrder(self): self.printPreOrderHelper(self.root) def printPreOrderHelper(self, node): if node is not None: print(node.data, end=' ') self.printPreOrderHelper(node.left) self.printPreOrderHelper(node.right) def printInOrder(self): self.printInOrderHelper(self.root) def printInOrderHelper(self, node): if node is not None: self.printInOrderHelper(node.left) print(node.data, end=' ') self.printInOrderHelper(node.right) def printPostOrder(self): self.printPostOrderHelper(self.root) def printPostOrderHelper(self, node): if node is not None: self.printPostOrderHelper(node.left) self.printPostOrderHelper(node.right) print(node.data, end=' ') bst= BST() # Create a binary search tree bst = BST() bst.insert(10) bst.insert(5) bst.insert(15) bst.insert(3) bst.insert(7) bst.insert(12) bst.insert(18) # Print the tree structure print("Binary Search Tree:") bst.printTree(bst.root) # Perform preorder traversal print("\nPreorder Traversal:") bst.printPreOrder() # Output: 10 5 3 7 15 12 18 # Perform inorder traversal print("\nInorder Traversal:") bst.printInOrder() # Output: 3 5 7 10 12 15 18 # Perform postorder traversal print("\nPostorder Traversal:") bst.printPostOrder() # Output: 3 7 5 12 18 15 10
import { FC } from "react"; import { useRouter } from "next/router"; import spotifyIcon from "../../static/spotify-icon.png"; import Image from "next/image"; interface ArtistInfoProps { artistName: string; url: string; artistID: string; position?: number; artistURL: string; } const ArtistInfo: FC<ArtistInfoProps> = (props) => { const router = useRouter(); const handleArtistClick = (e: React.SyntheticEvent): void => { e.preventDefault(); router.push(`/artist/${props.artistID}`); }; return ( <div className="w-1/3 h-1/3 lg:w-60 lg:h-80 m-3 cursor-pointer font-roboto"> <img src={props.url} alt="artist pic" onClick={handleArtistClick} /> <div className="">Artist Name:</div> <div className="flex items-center"> <div onClick={handleArtistClick} className=""> {props.artistName}{" "} </div> <a href={props.artistURL} className="flex-shrink-0 ml-auto"> <Image className="cursor-pointer transform object-scale-down scale-50 " src={spotifyIcon} alt="spotify-icon" /> </a> </div> {/* <div className="lg:hidden text-center">{props.artistName}</div> */} </div> ); }; export default ArtistInfo;
import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders} from '@angular/common/http'; import { Router } from '@angular/router'; import Swal from 'sweetalert2'; @Component({ selector: 'app-all-courses', templateUrl: './all-courses.component.html', styleUrls: ['./all-courses.component.css'] }) export class AllCoursesComponent implements OnInit { courses: any[] = []; access_token: string = localStorage.getItem("access_token") || "" showAlert(title,text,status,button) { Swal.fire({ title, text, icon:status, confirmButtonText:button, }); } constructor(private http: HttpClient , private router: Router ) {} ngOnInit(): void { this.http.get<any[]>('http://52.66.38.71/api/students/courses/').subscribe( (data) => { this.courses = data; }, (error) => { console.error('Error fetching data:', error); } ); } enroll(courseId: number): void { const headers = new HttpHeaders({ 'Authorization': `Bearer ${this.access_token}` }); const options = { headers: headers }; this.http.post<any>('http://52.66.38.71/api/students/enroll/', { course:courseId,student:1} , options).subscribe( (response) => { // Handle successful enrollment, e.g., show a success message console.log('Enrollment successful:', response); this.showAlert("SUCCESS","Enrolled Successfully","success","OK") }, (error) => { // Handle enrollment error, e.g., show an error message console.log('Enrollment error:', error); if(error.error.statusText =='Already enrolled in this course'){ this.showAlert("ERROR","Already enrolled in this course","error","OK") } else{ this.showAlert("Please Login!!",error.statusText,"error","OK") this.router.navigate(['/student-login']) } } ); } }
<?php /** * @file * The Out of stock notification module file * * It provides both client side and server side stock validation. */ /** * Implements of hook_form_alter() */ function uc_out_of_stock_form_alter(&$form, &$form_state, $form_id) { static $settings_js = array(); $forms = array('uc_product_add_to_cart_form', 'uc_catalog_buy_it_now_form'); foreach ($forms as $id) { if ( drupal_substr($form_id, 0, drupal_strlen($id)) == $id ) { // Only add Javascript if it was enabled if (!variable_get('uc_out_of_stock_disable_js', FALSE)) { drupal_add_js(drupal_get_path('module', 'uc_out_of_stock') . '/uc_out_of_stock.js'); drupal_add_css(drupal_get_path('module', 'uc_out_of_stock') . '/uc_out_of_stock.css'); if (empty($settings_js)) { $settings_js['uc_out_of_stock']['path'] = url('uc_out_of_stock/query'); $settings_js['uc_out_of_stock']['throbber'] = variable_get('uc_out_of_stock_throbber', TRUE); $settings_js['uc_out_of_stock']['instock'] = variable_get('uc_out_of_stock_instock', TRUE); $uc_out_of_stock_text = variable_get('uc_out_of_stock_text', array('value' => '<span style="color: red;">Out of stock</span>', 'format' => NULL)); $settings_js['uc_out_of_stock']['msg'] = check_markup($uc_out_of_stock_text['value'], $uc_out_of_stock_text['format']); drupal_add_js($settings_js, 'setting'); } } $form['#validate'][] = 'uc_out_of_stock_validate_form_addtocart'; } } if ($form_id == 'uc_cart_view_form') { $form['#validate'][] = 'uc_out_of_stock_validate_form_cart'; } if ($form_id == 'uc_cart_checkout_form' || $form_id == 'uc_cart_checkout_review_form') { $form['#validate'][] = 'uc_out_of_stock_validate_form_checkout'; } } /** * Implementation of hook_menu() */ function uc_out_of_stock_menu() { $items = array(); $items['admin/store/settings/uc_out_of_stock'] = array( 'title' => 'Out of Stock Notification', 'access arguments' => array('administer store'), 'description' => 'Configure out of stock settings.', 'page callback' => 'drupal_get_form', 'page arguments' => array('uc_out_of_stock_settings'), 'type' => MENU_NORMAL_ITEM, ); $items['uc_out_of_stock/query'] = array( 'title' => 'stock query', 'page callback' => 'uc_out_of_stock_query', 'access callback' => TRUE, 'type' => MENU_CALLBACK, ); return $items; } /**************************** * Helper functions ***************************/ /** * Helper function to retrieve stock information directly from the stock table * querying it by model * * @param string $model * @return mixed * Return an array of the stock information or null if NONE */ function uc_out_of_stock_getstockinfo_from_model($model) { $stockinfo = array(); $stock = db_query("SELECT ups.stock FROM {uc_product_stock} ups WHERE ups.active = 1 AND ups.sku = :sku", array(':sku' => $model))->fetchField(); if (is_numeric($stock)) { $stockinfo['stock'] = $stock; $stockinfo['model'] = $model; } return $stockinfo; } /** * Helper function to retrieve stock information looked up by nid and attributes * * @param integer $nid * @param array $attrs * @return mixed * Return an array of the stock information or null if NONE */ function uc_out_of_stock_getstockinfo($nid, $attrs) { $stockinfo = array(); // Query main sku is true by default, if some attribute combination is found, // it will be set to FALSE // If the combination was not found, and all attributes were indeed selected, we are assuming that some // combination shares an SKU with the actual product, thus, the product have to be queried as well. $query_main_sku = TRUE; if (module_exists('uc_attribute')) { // if attributes module exists, and product has attributes first search for attributes $post_attrs = count($attrs); $sql = "FROM {uc_product_adjustments} upa LEFT JOIN {uc_product_stock} ups ON ups.sku = upa.model WHERE upa.nid = :nid"; $db_attrs = db_query('SELECT COUNT(*) ' . $sql, array(':nid' => $nid))->fetchField(); if ($post_attrs && $db_attrs > 0) { $result = db_query('SELECT * ' . $sql, array(':nid' => $nid)); foreach ($result as $row) { $combination = unserialize($row->combination); // Apparently, on D6, one entry of the stock table has always the main SKU regardless the adjustments settings // Therefor, if the join gives a null record for the stock table, the main sku will be queried as well if ( isset($row->sku) && $combination == $attrs ) { // Because a combination is found, don't look for the main SKU $query_main_sku = FALSE; // Only check if active if ($row->active) { $stockinfo['stock'] = $row->stock; $stockinfo['model'] = $row->model; } } } } else { // If there are attributes for the product, but no attributes were sent, do nothing // as it's probably coming from the catalog table list view and we can't // disable the add to cart button for products with attributes if ($post_attrs == 0 && $db_attrs > 0) { $query_main_sku = FALSE; } } } if ($query_main_sku) { // seach for main product $result = db_query("SELECT * FROM {uc_products} up LEFT JOIN {uc_product_stock} ups ON ups.sku = up.model WHERE up.nid = :nid AND ups.active = 1", array(':nid' => $nid)); foreach ($result as $row) { $stockinfo['stock'] = $row->stock; $stockinfo['model'] = $row->model; } } return $stockinfo; } function uc_out_of_stock_query() { if (count($_POST['form_ids']) != count($_POST['node_ids'])) { print 'Different amount of form_ids than node_ids.'; exit; } if (count($_POST['node_ids']) == 0) { print 'No node_ids sent.'; exit; } $return = array_combine($_POST['form_ids'], array_fill(0, count($_POST['form_ids']), NULL)); // If no attributes given we can do one query to fetch everything $filtered_attrs = array_filter($_POST['attr_ids']); if (empty($filtered_attrs)) { $result = db_query('SELECT ups.stock, up.nid FROM {uc_products} up LEFT JOIN {uc_product_stock} ups ON ups.sku = up.model WHERE up.nid IN(:nids) AND ups.active = 1', array(':nids' => $_POST['node_ids'])); foreach ($result as $product) { $key = array_search($product->nid, $_POST['node_ids']); $return[$_POST['form_ids'][$key]] = $product->stock; } } else { $attribs = array(); foreach ($_POST['attr_ids'] as $value) { list($nid, $attr_id, $attr_val) = explode(':', $value); $attribs[$nid][$attr_id] = $attr_val; } foreach ($_POST['node_ids'] as $key => $nid) { $stockinfo = uc_out_of_stock_getstockinfo($nid, isset($attribs[$nid]) ? $attribs[$nid] : array()); if ($stockinfo) { $return[$_POST['form_ids'][$key]] = $stockinfo['stock']; } } } // if there is some response, print it print drupal_json_output($return); exit; } function uc_out_of_stock_settings() { $form['uc_out_of_stock_throbber'] = array( '#type' => 'checkbox', '#title' => t('Display throbber'), '#default_value' => variable_get('uc_out_of_stock_throbber', TRUE), '#description' => t('Display a throbber (animated wheel) next to add to cart button. This can be themed/styled and removed via CSS as well, but you can just disable it with this setting.'), ); $form['uc_out_of_stock_instock'] = array( '#type' => 'checkbox', '#title' => t('Display in stock information'), '#default_value' => variable_get('uc_out_of_stock_instock', TRUE), '#description' => t('Display how many items are in stock above the add to cart button or below the qty field if it is present. It can be themed and translated as normal. Please see the uc_out_of_stock.js file for hints. If product has attributes, it may be impossible to know the stock until the attribute is selected, so it will simply display a default "In stock" message.'), ); $uc_out_of_stock_text = variable_get('uc_out_of_stock_text', array('value' => '<span style="color: red;">Out of stock</span>', 'format' => NULL)); $text = check_markup($uc_out_of_stock_text['value'], $uc_out_of_stock_text['format']); $description = t('<div class="description">This is the value below rendered as you would expect to see it</div>'); $text = '<div style="border: 1px solid lightgrey; padding: 10px;">' . $text . '</div>' . $description; $form['uc_out_of_stock_demo'] = array( '#markup' => $text, ); $form['uc_out_of_stock_text'] = array( '#type' => 'text_format', '#title' => t('Out of stock replacement HTML'), '#default_value' => $uc_out_of_stock_text['value'], '#format' => $uc_out_of_stock_text['format'], '#description' => t('The HTML that will replace the Add To Cart button if no stock is available.'), ); $form['advanced'] = array( '#type' => 'fieldset', '#title' => t('Advanced settings'), '#collapsible' => TRUE, '#collapsed' => !variable_get('uc_out_of_stock_disable_js', FALSE), ); $form['advanced']['uc_out_of_stock_disable_js'] = array( '#type' => 'checkbox', '#title' => t('Disable javascript'), '#default_value' => variable_get('uc_out_of_stock_disable_js', FALSE), '#description' => t('If you disable javascript you will lose real-time checking of stock, support for checking for stock on attribute change and all of the HTML replacement confgured above. Use it with caution. This can be useful if you think this module is in conflict with some other third-party Ubercart module and you want to keep the server side validation of this module.'), ); return system_settings_form($form); } /** * Shared logic for add to cart validation in both form validation and * hook_add_to_cart * * @param int $nid * @param array $attrs * @return mixed * FALSE if no error * Error message if error */ function uc_out_of_stock_validate_addtocart($nid, $attrs, $qty_add) { $error = FALSE; $stockinfo = uc_out_of_stock_getstockinfo($nid, $attrs); if ($stockinfo) { if ($stockinfo['stock'] <= 0) { $error = _uc_out_of_stock_get_error('out_of_stock', $nid, $attrs, $stockinfo['stock']); } else { $qty = 0; $items = uc_cart_get_contents(); foreach ($items as $item) { if ($item->nid == $nid && $stockinfo['model'] == $item->model) { $qty += $item->qty; } } if ($stockinfo['stock'] - ($qty + $qty_add) < 0) { $error = _uc_out_of_stock_get_error('not_enough', $nid, $attrs, $stockinfo['stock'], $qty); } } } return $error; } /** * Validate the 'Add To Cart' form of each product preventing the addition of * out of stock items or more items that ones currently on stock. * * Support teaser view, full node view and catalog view */ function uc_out_of_stock_validate_form_addtocart($form, &$form_state) { $class = $form_state['clicked_button']['#attributes']['class']; // Uses the class of the add to cart button of both node view and catalog // view to decide if we should validate stock or not // i.e. If some other form_alter added another button, do nothing (uc_wishlist) if (in_array('node-add-to-cart', $class) || in_array('list-add-to-cart', $class)) { $attrs = isset($form_state['values']['attributes']) ? $form_state['values']['attributes'] : array(); foreach ((array)$attrs as $aid => $oids) { $attribute = uc_attribute_load($aid); // 1 is select and 2 is radio, the only supported attributes that may have stock adjustments if ($attribute->display != 1 && $attribute->display != 2) { unset($attrs[$aid]); } } $nid = $form_state['values']['nid']; $qty = $form_state['values']['qty'] ? $form_state['values']['qty'] : 1; $error = uc_out_of_stock_validate_addtocart($nid, $attrs, $qty); if ($error !== FALSE) { form_set_error('uc_out_of_stock', $error['msg']); } } } /** * Helper function that would validate items in the cart referenced in a form * Used in @uc_out_of_stock_validate_form_checkout * Used in @uc_out_of_stock_validate_form_cart * * @param array $items */ function uc_out_of_stock_validate_cart_items($items, $page = 'cart') { // just in the rare case (http://drupal.org/node/496782) // that $items is not an array, do nothing if (!is_array($items)) { return; } $cart_items = array(); $stored_cart_items = uc_cart_get_contents(); // First group by model foreach ($items as $k => $item) { // Convert it to object just in case is an array (if coming from a form POST) $item = (object) $item; // Unserialize data if string if (is_string($item->data)) { $item->data = unserialize($item->data); } // If the items comes from the submitted cart, it doesn't have the model // set, so we try to get it from the stored cart items which is filled // properly with the model. // For that, we assume that the sorting is the same, and if not, // we provide an alternative method which is probably not // very good in terms of performance, but the sorting of both arrays // should be the same if (!isset($item->model)) { $stored_item = $stored_cart_items[$item->cart_item_id]; if ($item->nid == $stored_item->nid && $item->data == $stored_item->data) { $model = $stored_item->model; } else { foreach ($stored_cart_items as $stored_item) { if ($item->nid == $stored_item->nid && $item->data == $stored_item->data) { $model = $stored_item->model; } } } $item->model = $model; } $cart_items[$item->model]['item'] = $item; if (!isset($cart_items[$item->model]['qty'])) { $cart_items[$item->model]['qty'] = 0; } $cart_items[$item->model]['qty'] += $item->qty; $cart_items[$item->model]['key'] = $k; } // Now for each model, check the stock foreach ($cart_items as $model => $cart_item) { $item = $cart_item['item']; // Only validates if there are items on the cart, otherwise it's likely // it's being tried to be removed by setting the qty to 0. if ($cart_item['qty'] > 0) { $stockinfo = uc_out_of_stock_getstockinfo_from_model($model); if ($stockinfo) { if ($stockinfo['stock'] - $cart_item['qty'] < 0) { $qty = 0; if ($page == 'checkout') { $qty = $cart_item['qty']; } if ($stockinfo['stock'] <= 0) { $error = _uc_out_of_stock_get_error('out_of_stock', $item->nid, isset($item->data['attributes']) ? $item->data['attributes'] : array(), $stockinfo['stock']); } else { $error = _uc_out_of_stock_get_error('not_enough', $item->nid, isset($item->data['attributes']) ? $item->data['attributes'] : array(), $stockinfo['stock'], $qty); } form_set_error("items][{$cart_item['key']}][qty", $error['msg']); } } } } } /** * Validate the 'Order Checkout' and 'Order Review' form preventing the order * going through if the stock information have changed while the user was * browsing the site. (i.e. some other client has just bought the same item) */ function uc_out_of_stock_validate_form_checkout($form, &$form_state) { $items = uc_cart_get_contents(); uc_out_of_stock_validate_cart_items($items, 'checkout'); } /** * Validate the 'Shopping cart' form preventing the addition of more items that * the ones currently in stock. */ function uc_out_of_stock_validate_form_cart($form, &$form_state) { $items = $form_state['values']['items']; if (substr($form_state['clicked_button']['#name'], 0, 7) != 'remove-') { uc_out_of_stock_validate_cart_items($items, 'cart'); } } /** * Helper function to properly format the form error messages across the * different validation hooks. * * @param <type> $error * type of error * @param <type> $nid * node id * @param <type> $attrs * attributes array * @param <type> $stock * stock of the current item * @param <type> $qty * qty in cart * @param <type> $cart_item_id * ID on the shopping cart */ function _uc_out_of_stock_get_error($type, $nid, $attrs, $stock, $qty = 0) { $product = node_load($nid); if (count($attrs)) { foreach ($attrs as $attr_id => $option_id) { $attr = uc_attribute_load($attr_id); $option = uc_attribute_option_load($option_id); $attr_names[] = $attr->name; $option_names[] = $option->name; } } $error['stock'] = $stock; $error['qty_in_cart'] = $qty; $error['type'] = $type; $error['product'] = $product->title; if (count($attrs)) { $error['attributes'] = implode('/', $attr_names); $error['options'] = implode('/', $option_names); } if ($type == 'out_of_stock') { if (count($attrs)) { $error['msg'] = t("We're sorry. The product @product (@options) is out of stock. Please consider trying this product with a different @attributes.", array('@product' => $error['product'], '@attributes' => $error['attributes'], '@options' => $error['options'])); } else { $error['msg'] = t("We're sorry. The product @product is out of stock.", array('@product' => $error['product'])); } } if ($type == 'not_enough') { if (count($attrs)) { $error['msg'] = t("We're sorry. We have now only @qty of the product @product (@options) left in stock.", array('@qty' => format_plural($error['stock'], '1 unit', '@count units'), '@product' => $error['product'], '@options' => $error['options'])); } else { $error['msg'] = t("We're sorry. We have now only @qty of the product @product left in stock.", array('@qty' => format_plural($error['stock'], '1 unit', '@count units'), '@product' => $error['product'])); } if ($error['qty_in_cart']) { $error['msg'] .= ' ' . t("You have currently @qty in your <a href=\"@cart-url\">shopping cart</a>.", array('@qty' => format_plural($error['qty_in_cart'], '1 unit', '@count units'), '@cart-url' => url('cart'))); } } // Invoke hook_uc_out_of_stock_error_alter() to allow all modules to alter the resulting error message. drupal_alter('uc_out_of_stock_error', $error, $product); return $error; }
import React, { useEffect, useState } from "react"; import { Link, useParams } from "react-router-dom"; import SidebarGA from "../components/sidebar-ga"; function DetailInterviewGA() { const [interview, setInterview] = useState(null); const { id } = useParams(); function formatTime(datetimeString) { const dateTime = new Date(datetimeString); const hours = dateTime.getHours().toString().padStart(2, "0"); const minutes = dateTime.getMinutes().toString().padStart(2, "0"); return `${hours}:${minutes}`; } function formatDateTime(datetimeString) { const options = { weekday: "long", day: "numeric", month: "long", year: "numeric", }; const formattedDate = new Date(datetimeString).toLocaleDateString( "id-ID", options ); return formattedDate; } const rectangleStyle = { width: "70%", height: "550px", backgroundColor: "#fff", borderRadius: "10px", marginLeft: "22%", boxShadow: "0 2px 10px rgba(0, 0, 0, 0.4)", marginTop: "-19%", }; useEffect(() => { const getInterview = async () => { try { const response = await fetch( `https://sihire-be.vercel.app/api/interview/get-interview/${id}/` ); const data = await response.json(); setInterview(data); } catch (error) { console.error("Error fetching job:", error); } }; getInterview(); }, [id]); return ( <React.Fragment> <p style={{ marginLeft: "22%", fontWeight: "bold", fontSize: "32px", color: "#2A3E4B", position: "absolute", marginTop: "12px", }} > Wawancara </p> <SidebarGA /> <Link to="/get-list-interview-ga"> <p style={{ marginLeft: "22%", position: "absolute", marginTop: "-320px", }} > List Wawancara </p> </Link> <p style={{ marginLeft: "30%", position: "absolute", marginTop: "-320px" }} > {">"} </p> {interview && ( <React.Fragment key={interview.id}> <Link to={`/get-list-interview-ga/${id}`}> <p style={{ marginLeft: "31%", position: "absolute", marginTop: "-320px", }} > {interview.job_application_id.job.job_name} </p> </Link> <div className="detail-interview-ga"> <div className="rectangle-style" style={rectangleStyle}> <p style={{ marginTop: "40px", marginLeft: "5%", fontWeight: "bold", fontSize: "32px", color: "#2A3E4B", position: "absolute", }} > {interview.job_application_id.applicant.user.name} -{" "} {interview.job_application_id.job.job_name} </p> <p style={{ marginTop: "100px", marginLeft: "5%", fontWeight: "bold", fontSize: "24px", color: "#2A3E4B", position: "absolute", }} > Status </p> <div style={{ marginTop: "140px", marginLeft: "5%", color: "#fff", background: "#2A3E4B", fontSize: "12px", width: "100px", height: "40px", border: "2px solid #fff", borderRadius: "90px", display: "flex", justifyContent: "center", alignItems: "center", position: "absolute", textAlign:"center" }} > {interview.confirm} </div> <p style={{ marginTop: "200px", marginLeft: "5%", fontWeight: "bold", fontSize: "24px", color: "#2A3E4B", position: "absolute", }} > Jadwal Interview </p> <p style={{ marginTop: "240px", marginLeft: "5%", fontSize: "16px", color: "#2A3E4B", position: "absolute", }} > Hari/Tanggal :{" "} {interview.datetime_start && formatDateTime(interview.datetime_start)} </p> <p style={{ marginTop: "270px", marginLeft: "5%", fontSize: "16px", color: "#2A3E4B", position: "absolute", }} > Waktu :{" "} {interview.datetime_start && formatTime(interview.datetime_start)}{" "} - {interview.datetime_end && formatTime(interview.datetime_end)} </p> <p style={{ marginTop: "300px", marginLeft: "5%", fontSize: "16px", color: "#2A3E4B", position: "absolute", }} > Pewawancara : {interview.interviewer_user_id?.name} </p> <p style={{ marginTop: "350px", marginLeft: "5%", fontWeight: "bold", fontSize: "24px", color: "#2A3E4B", position: "absolute", }} > Alasan </p> <p style={{ marginTop: "390px", marginLeft: "5%", fontSize: "16px", color: "#2A3E4B", position: "absolute", }} > {interview.reschedule_comment} </p> <Link to={`/get-list-interview-ga/${id}/update`}> <button style={{ width: "10%", padding: "8px", fontSize: "16px", fontFamily: "Inter, sans-serif", fontWeight: "bold", color: "#fff", background: "#2A3E4B", borderRadius: "6px", cursor: "pointer", marginTop: "480px", border: "2px solid #2A3E4B", marginLeft: "57%", position: "absolute", }} > Ubah Jadwal </button> </Link> </div> </div> </React.Fragment> )} </React.Fragment> ); } export default DetailInterviewGA;
package org.thoughtcrime.securesms.util; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Build; import android.view.View; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.WorkerThread; import androidx.appcompat.widget.AppCompatImageView; import androidx.core.content.ContextCompat; import androidx.core.graphics.drawable.IconCompat; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.resource.bitmap.BitmapTransformation; import com.bumptech.glide.load.resource.bitmap.CenterCrop; import com.bumptech.glide.load.resource.bitmap.CircleCrop; import com.bumptech.glide.request.target.CustomTarget; import com.bumptech.glide.request.target.CustomViewTarget; import com.bumptech.glide.request.transition.Transition; import org.signal.core.util.ThreadUtil; import org.signal.core.util.logging.Log; import org.thoughtcrime.securesms.R; import org.thoughtcrime.securesms.contacts.avatars.ContactPhoto; import org.thoughtcrime.securesms.contacts.avatars.GeneratedContactPhoto; import org.thoughtcrime.securesms.contacts.avatars.ProfileContactPhoto; import org.thoughtcrime.securesms.mms.GlideApp; import org.thoughtcrime.securesms.mms.GlideRequest; import org.thoughtcrime.securesms.mms.GlideRequests; import org.thoughtcrime.securesms.providers.AvatarProvider; import org.thoughtcrime.securesms.recipients.Recipient; import java.util.Objects; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; public final class AvatarUtil { private static final String TAG = Log.tag(AvatarUtil.class); public static final int UNDEFINED_SIZE = -1; private AvatarUtil() { } public static void loadBlurredIconIntoImageView(@NonNull Recipient recipient, @NonNull AppCompatImageView target) { Context context = target.getContext(); ContactPhoto photo; if (recipient.isSelf()) { photo = new ProfileContactPhoto(Recipient.self()); } else if (recipient.getContactPhoto() == null) { target.setImageDrawable(null); target.setBackgroundColor(ContextCompat.getColor(target.getContext(), R.color.black)); return; } else { photo = recipient.getContactPhoto(); } GlideApp.with(target) .load(photo) .transform(new BlurTransformation(context, 0.25f, BlurTransformation.MAX_RADIUS), new CenterCrop()) .into(new CustomViewTarget<View, Drawable>(target) { @Override public void onLoadFailed(@Nullable Drawable errorDrawable) { target.setImageDrawable(null); target.setBackgroundColor(ContextCompat.getColor(target.getContext(), R.color.black)); } @Override public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) { target.setImageDrawable(resource); } @Override protected void onResourceCleared(@Nullable Drawable placeholder) { target.setImageDrawable(placeholder); } }); } public static void loadIconIntoImageView(@NonNull Recipient recipient, @NonNull ImageView target) { loadIconIntoImageView(recipient, target, -1); } public static void loadIconIntoImageView(@NonNull Recipient recipient, @NonNull ImageView target, int requestedSize) { Context context = target.getContext(); requestCircle(GlideApp.with(context).asDrawable(), context, recipient, requestedSize).into(target); } public static Bitmap loadIconBitmapSquareNoCache(@NonNull Context context, @NonNull Recipient recipient, int width, int height) throws ExecutionException, InterruptedException { return requestSquare(GlideApp.with(context).asBitmap(), context, recipient) .skipMemoryCache(true) .diskCacheStrategy(DiskCacheStrategy.NONE) .submit(width, height) .get(); } @WorkerThread public static @NonNull IconCompat getIconCompat(@NonNull Context context, @NonNull Recipient recipient) { if (Build.VERSION.SDK_INT > 29) { return IconCompat.createWithContentUri(AvatarProvider.getContentUri(recipient.getId())); } else { return IconCompat.createWithBitmap(getBitmapForNotification(context, recipient, DrawableUtil.SHORTCUT_INFO_WRAPPED_SIZE)); } } @WorkerThread public static Bitmap getBitmapForNotification(@NonNull Context context, @NonNull Recipient recipient) { return getBitmapForNotification(context, recipient, UNDEFINED_SIZE); } @WorkerThread public static @NonNull Bitmap getBitmapForNotification(@NonNull Context context, @NonNull Recipient recipient, int size) { ThreadUtil.assertNotMainThread(); try { AvatarTarget avatarTarget = new AvatarTarget(size); GlideRequests glideRequests = GlideApp.with(context); requestCircle(glideRequests.asBitmap(), context, recipient, size).into(avatarTarget); Bitmap bitmap = avatarTarget.await(); return Objects.requireNonNullElseGet(bitmap, () -> DrawableUtil.toBitmap(getFallback(context, recipient, size), size, size)); } catch (InterruptedException e) { return DrawableUtil.toBitmap(getFallback(context, recipient, size), size, size); } } private static <T> GlideRequest<T> requestCircle(@NonNull GlideRequest<T> glideRequest, @NonNull Context context, @NonNull Recipient recipient, int targetSize) { return request(glideRequest, context, recipient, targetSize, new CircleCrop()); } private static <T> GlideRequest<T> requestSquare(@NonNull GlideRequest<T> glideRequest, @NonNull Context context, @NonNull Recipient recipient) { return request(glideRequest, context, recipient, UNDEFINED_SIZE, new CenterCrop()); } private static <T> GlideRequest<T> request(@NonNull GlideRequest<T> glideRequest, @NonNull Context context, @NonNull Recipient recipient, int targetSize, @Nullable BitmapTransformation transformation) { return request(glideRequest, context, recipient, true, targetSize, transformation); } private static <T> GlideRequest<T> request(@NonNull GlideRequest<T> glideRequest, @NonNull Context context, @NonNull Recipient recipient, boolean loadSelf, int targetSize, @Nullable BitmapTransformation transformation) { final ContactPhoto photo; if (Recipient.self().equals(recipient) && loadSelf) { photo = new ProfileContactPhoto(recipient); } else { photo = recipient.getContactPhoto(); } final int size = targetSize == -1 ? DrawableUtil.SHORTCUT_INFO_WRAPPED_SIZE : targetSize; final GlideRequest<T> request = glideRequest.load(photo) .error(getFallback(context, recipient, size)) .diskCacheStrategy(DiskCacheStrategy.ALL) .override(size); if (recipient.shouldBlurAvatar()) { BlurTransformation blur = new BlurTransformation(context, 0.25f, BlurTransformation.MAX_RADIUS); if (transformation != null) { return request.transform(blur, transformation); } else { return request.transform(blur); } } else if (transformation != null) { return request.transform(transformation); } else { return request; } } private static Drawable getFallback(@NonNull Context context, @NonNull Recipient recipient, int targetSize) { String name = Optional.of(recipient.getDisplayName(context)).orElse(""); return new GeneratedContactPhoto(name, R.drawable.ic_profile_outline_40, targetSize).asDrawable(context, recipient.getAvatarColor()); } /** * Allows caller to synchronously await for a bitmap of an avatar. */ private static class AvatarTarget extends CustomTarget<Bitmap> { private final CountDownLatch countDownLatch = new CountDownLatch(1); private final AtomicReference<Bitmap> bitmap = new AtomicReference<>(); private final int size; private AvatarTarget(int size) { this.size = size == UNDEFINED_SIZE ? DrawableUtil.SHORTCUT_INFO_WRAPPED_SIZE : size; } public @Nullable Bitmap await() throws InterruptedException { if (countDownLatch.await(1, TimeUnit.SECONDS)) { return bitmap.get(); } else { Log.w(TAG, "AvatarTarget#await: Failed to load avatar in time! Returning null"); return null; } } @Override public void onDestroy() { Log.d(TAG, "AvatarTarget: onDestroy"); super.onDestroy(); } @Override public void onLoadStarted(@Nullable Drawable placeholder) { Log.d(TAG, "AvatarTarget: onLoadStarted"); super.onLoadStarted(placeholder); } @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { Log.d(TAG, "AvatarTarget: onResourceReady"); bitmap.set(resource); countDownLatch.countDown(); } @Override public void onLoadFailed(@Nullable Drawable errorDrawable) { Log.d(TAG, "AvatarTarget: onLoadFailed"); if (errorDrawable == null) { throw new AssertionError("Expected an error drawable."); } Bitmap errorBitmap = DrawableUtil.toBitmap(errorDrawable, size, size); bitmap.set(errorBitmap); countDownLatch.countDown(); } @Override public void onLoadCleared(@Nullable Drawable placeholder) { Log.d(TAG, "AvatarTarget: onLoadCleared"); bitmap.set(null); countDownLatch.countDown(); } } }
--- date: 2024-02-03 19:03:17.132416-07:00 description: "How to: Working directly with YAML in Bash requires a bit of ingenuity\ \ since Bash does not have built-in support for parsing YAML. However, you can use\u2026" lastmod: '2024-03-13T22:45:00.262459-06:00' model: gpt-4-0125-preview summary: Working directly with YAML in Bash requires a bit of ingenuity since Bash does not have built-in support for parsing YAML. title: Working with YAML weight: 41 --- ## How to: Working directly with YAML in Bash requires a bit of ingenuity since Bash does not have built-in support for parsing YAML. However, you can use external tools like `yq` (a lightweight and portable command-line YAML processor) to interact with YAML files efficiently. Let's go through some common operations: ### Installing `yq`: Before diving into the examples, ensure you have `yq` installed. You can usually install it from your package manager, for example, on Ubuntu: ```bash sudo apt-get install yq ``` Or you can download it directly from its GitHub repository. ### Reading a value: Consider you have a file named `config.yaml` with the following content: ```yaml database: host: localhost port: 5432 user: name: admin password: secret ``` To read the database host, you can use `yq` as follows: ```bash yq e '.database.host' config.yaml ``` **Sample Output:** ``` localhost ``` ### Updating a value: To update the user's name in `config.yaml`, use the `yq eval` command with the `-i` (in-place) option: ```bash yq e '.user.name = "newadmin"' -i config.yaml ``` Verify the change with: ```bash yq e '.user.name' config.yaml ``` **Sample Output:** ``` newadmin ``` ### Adding a new element: To add a new element under the database section, like a new field `timeout`: ```bash yq e '.database.timeout = 30' -i config.yaml ``` Checking the contents of the file will confirm the addition. ### Deleting an element: To remove the password under user: ```bash yq e 'del(.user.password)' -i config.yaml ``` This operation will remove the password field from the configuration. Remember, `yq` is a powerful tool and has a lot more capabilities, including converting YAML to JSON, merging files, and even more complex manipulations. Refer to the `yq` documentation for further exploration.
import { ApiProperty } from '@nestjs/swagger'; import { IsNumber, IsOptional, IsString, IsUUID, MinLength, } from 'class-validator'; export class CreateBookingLocationDto { @IsString() @MinLength(2) @ApiProperty() title: string; @IsUUID() @ApiProperty() cityId: string; @IsOptional() @IsNumber() @ApiProperty() order?: number; }
/* * Copyright 2012-2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.huawei.nwbl.opensource.dashboard.domain; import org.hibernate.validator.constraints.NotEmpty; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.PreRemove; import javax.persistence.Table; import java.util.Calendar; import java.util.Set; /** * Member entity in member table */ @Entity @Table public class Member { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotEmpty(message = "Name is required.") @Column(unique = true) private String name; @NotEmpty(message = "Valid account id is required.") @OneToMany(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY, mappedBy = "member") private Set<GerritAccount> accounts; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "companyId") private Company company; @ManyToMany(mappedBy = "members") private Set<Project> projects; @Column(columnDefinition = "CHAR(1)") private boolean visible = true; private Calendar created = Calendar.getInstance(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<GerritAccount> getAccounts() { return accounts; } public void setAccounts(Set<GerritAccount> accounts) { this.accounts = accounts; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public Set<Project> getProjects() { return projects; } public void setProjects(Set<Project> projects) { this.projects = projects; } public boolean isVisible() { return visible; } public void setVisible(boolean visible) { this.visible = visible; } public Calendar getCreated() { return created; } public void setCreated(Calendar created) { this.created = created; } public String toString() { return String.format("%s", getName()); } @PreRemove public void removeMemberFromOthers() { for (Project project : projects) { project.getMembers().remove(this); } for (GerritAccount account : accounts) { account.setMember(null); } } }
export enum MessageError { CLIENT_TOKEN_NOT_GIVEN = 'Token not given', CLIENT_TOKEN_EXPIRED = 'Token expired.', CLIENT_TOKEN_INVALID_SIGNATURE = 'Token invalid signature.', CLIENT_TOKEN_NOT_FOUND = 'Token not found.', CLIENT_TOKEN_FK_USER_NOT_FOUND = 'Token foreign key user not found.', CLIENT_PERMISSION_DENIED = 'Permission denied.', CLIENT_EMAIL_BAD_SYNTAX = 'Email has bad syntax.', CLIENT_EMAIL_IS_TEMPORARY = 'Email is temporary mail.', CLIENT_USER_IS_BLACKLISTED = 'User is blacklisted.', CLIENT_USER_NOT_FOUND = 'User not found.', CLIENT_USER_INVALID_PASSWORD = 'Invalid password.', SERVER_ROLE_NOT_FOUND = 'Role not found.', SERVER_INTERNAL_ERROR = 'Internal Server error.', SERVER_DATABASE_ERROR = 'Database error.', CLIENT_PASSWORD_IS_THE_SAME = 'Password is the same.', } export class ErrorEntity extends Error { /** * The code of the error * @type number */ private readonly code: number; /** * Collection of error messages */ private readonly MessageAndCode = { [MessageError.CLIENT_TOKEN_NOT_GIVEN]: 400, [MessageError.CLIENT_TOKEN_EXPIRED]: 400, [MessageError.CLIENT_TOKEN_INVALID_SIGNATURE]: 400, [MessageError.CLIENT_TOKEN_NOT_FOUND]: 400, [MessageError.CLIENT_TOKEN_FK_USER_NOT_FOUND]: 400, [MessageError.CLIENT_PERMISSION_DENIED]: 403, [MessageError.CLIENT_EMAIL_BAD_SYNTAX]: 400, [MessageError.CLIENT_EMAIL_IS_TEMPORARY]: 400, [MessageError.CLIENT_USER_IS_BLACKLISTED]: 403, [MessageError.CLIENT_USER_NOT_FOUND]: 500, [MessageError.CLIENT_USER_INVALID_PASSWORD]: 400, [MessageError.SERVER_ROLE_NOT_FOUND]: 500, [MessageError.SERVER_INTERNAL_ERROR]: 500, [MessageError.SERVER_DATABASE_ERROR]: 500, [MessageError.CLIENT_PASSWORD_IS_THE_SAME]: 400, }; private static createBetterSqlMessageError(sqlCode: string, sqlMessage: string): string { if (sqlCode === 'ER_DUP_ENTRY') { const messageSplit = sqlMessage.split('\''); const value = messageSplit[1]; const column = (messageSplit[3]?.split('.')[1])?.split('_')[0]; return `This ${column} : ${value} is already used.`; } return sqlMessage; } /** * Create an error manager * @param message * @param sqlMessage * @param sqlCode */ constructor(message: MessageError, sqlMessage?: string, sqlCode?: string) { super(message); this.code = this.MessageAndCode[message]; if (sqlMessage && sqlCode) this.message = ErrorEntity.createBetterSqlMessageError(sqlCode.toString(), sqlMessage); } public getCode(): number { return this.code; } public getMessage(): string { return this.message; } }
from django.shortcuts import get_object_or_404 from django.core.exceptions import PermissionDenied from rest_framework import viewsets from posts.models import Comment, Group, Post from rest_framework.pagination import LimitOffsetPagination from .serializers import (CommentSerializer, GroupSerializer, PostSerializer) class PostViewSet(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer pagination_class = LimitOffsetPagination def perform_create(self, serializer): serializer.save(author=self.request.user) def perform_update(self, serializer): if serializer.instance.author != self.request.user: raise PermissionDenied('Изменение чужого контента запрещено!') super().perform_update(serializer) def perform_destroy(self, serializer): if serializer.author != self.request.user: raise PermissionDenied('Изменение чужого контента запрещено!') super().perform_destroy(serializer) class GroupViewSet(viewsets.ReadOnlyModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer pagination_class = LimitOffsetPagination def perform_update(self, serializer): if serializer.instance.author != self.request.user: raise PermissionDenied('Изменение чужого контента запрещено!') super().perform_update(serializer) def perform_destroy(self, serializer): if serializer.author != self.request.user: raise PermissionDenied('Изменение чужого контента запрещено!') super().perform_destroy(serializer) class CommentViewSet(viewsets.ModelViewSet): serializer_class = CommentSerializer pagination_class = LimitOffsetPagination def get_queryset(self): com = Comment.objects.filter(post=self.kwargs.get('post_id')) return com def perform_create(self, serializer): post = get_object_or_404(Post, pk=self.kwargs.get('post_id')) serializer.save(author=self.request.user, post=post) def perform_update(self, serializer): if serializer.instance.author != self.request.user: raise PermissionDenied('Изменение чужого контента запрещено!') super().perform_update(serializer) def perform_destroy(self, serializer): if serializer.author != self.request.user: raise PermissionDenied('Изменение чужого контента запрещено!') super().perform_destroy(serializer)
<?php namespace Box\Spout\Common\Helper; /** * Class GlobalFunctionsHelper * This class wraps global functions to facilitate testing * * @codeCoverageIgnore */ class GlobalFunctionsHelper { /** * Wrapper around global function fopen() * @see fopen() * * @param string $fileName * @param string $mode * @return resource|bool */ public function fopen($fileName, $mode) { return \fopen($fileName, $mode); } /** * Wrapper around global function fgets() * @see fgets() * * @param resource $handle * @param int|null $length * @return string */ public function fgets($handle, $length = null) { return \fgets($handle, $length); } /** * Wrapper around global function fputs() * @see fputs() * * @param resource $handle * @param string $string * @return int */ public function fputs($handle, $string) { return \fputs($handle, $string); } /** * Wrapper around global function fflush() * @see fflush() * * @param resource $handle * @return bool */ public function fflush($handle) { return \fflush($handle); } /** * Wrapper around global function fseek() * @see fseek() * * @param resource $handle * @param int $offset * @return int */ public function fseek($handle, $offset) { return \fseek($handle, $offset); } /** * Wrapper around global function fgetcsv() * @see fgetcsv() * * @param resource $handle * @param int|null $length * @param string|null $delimiter * @param string|null $enclosure * @return array */ public function fgetcsv($handle, $length = null, $delimiter = null, $enclosure = null) { // PHP uses '\' as the default escape character. This is not RFC-4180 compliant... // To fix that, simply disable the escape character. // @see https://bugs.php.net/bug.php?id=43225 // @see http://tools.ietf.org/html/rfc4180 $escapeCharacter = PHP_VERSION_ID >= 70400 ? '' : "\0"; return \fgetcsv($handle, $length, $delimiter, $enclosure, $escapeCharacter); } /** * Wrapper around global function fputcsv() * @see fputcsv() * * @param resource $handle * @param array $fields * @param string|null $delimiter * @param string|null $enclosure * @return int */ public function fputcsv($handle, array $fields, $delimiter = null, $enclosure = null) { // PHP uses '\' as the default escape character. This is not RFC-4180 compliant... // To fix that, simply disable the escape character. // @see https://bugs.php.net/bug.php?id=43225 // @see http://tools.ietf.org/html/rfc4180 $escapeCharacter = PHP_VERSION_ID >= 70400 ? '' : "\0"; return \fputcsv($handle, $fields, $delimiter, $enclosure, $escapeCharacter); } /** * Wrapper around global function fwrite() * @see fwrite() * * @param resource $handle * @param string $string * @return int */ public function fwrite($handle, $string) { return \fwrite($handle, $string); } /** * Wrapper around global function fclose() * @see fclose() * * @param resource $handle * @return bool */ public function fclose($handle) { return \fclose($handle); } /** * Wrapper around global function rewind() * @see rewind() * * @param resource $handle * @return bool */ public function rewind($handle) { return \rewind($handle); } /** * Wrapper around global function file_exists() * @see file_exists() * * @param string $fileName * @return bool */ public function file_exists($fileName) { return \file_exists($fileName); } /** * Wrapper around global function file_get_contents() * @see file_get_contents() * * @param string $filePath * @return string */ public function file_get_contents($filePath) { $realFilePath = $this->convertToUseRealPath($filePath); return \file_get_contents($realFilePath); } /** * Updates the given file path to use a real path. * This is to avoid issues on some Windows setup. * * @param string $filePath File path * @return string The file path using a real path */ protected function convertToUseRealPath($filePath) { $realFilePath = $filePath; if ($this->isZipStream($filePath)) { if (\preg_match('/zip:\/\/(.*)#(.*)/', $filePath, $matches)) { $documentPath = $matches[1]; $documentInsideZipPath = $matches[2]; $realFilePath = 'zip://' . \realpath($documentPath) . '#' . $documentInsideZipPath; } } else { $realFilePath = \realpath($filePath); } return $realFilePath; } /** * Returns whether the given path is a zip stream. * * @param string $path Path pointing to a document * @return bool TRUE if path is a zip stream, FALSE otherwise */ protected function isZipStream($path) { return (\strpos($path, 'zip://') === 0); } /** * Wrapper around global function feof() * @see feof() * * @param resource $handle * @return bool */ public function feof($handle) { return \feof($handle); } /** * Wrapper around global function is_readable() * @see is_readable() * * @param string $fileName * @return bool */ public function is_readable($fileName) { return \is_readable($fileName); } /** * Wrapper around global function basename() * @see basename() * * @param string $path * @param string|null $suffix * @return string */ public function basename($path, $suffix = null) { return \basename($path, $suffix); } /** * Wrapper around global function header() * @see header() * * @param string $string * @return void */ public function header($string) { \header($string); } /** * Wrapper around global function ob_end_clean() * @see ob_end_clean() * * @return void */ public function ob_end_clean() { if (\ob_get_length() > 0) { \ob_end_clean(); } } /** * Wrapper around global function iconv() * @see iconv() * * @param string $string The string to be converted * @param string $sourceEncoding The encoding of the source string * @param string $targetEncoding The encoding the source string should be converted to * @return string|bool the converted string or FALSE on failure. */ public function iconv($string, $sourceEncoding, $targetEncoding) { return \iconv($sourceEncoding, $targetEncoding, $string); } /** * Wrapper around global function mb_convert_encoding() * @see mb_convert_encoding() * * @param string $string The string to be converted * @param string $sourceEncoding The encoding of the source string * @param string $targetEncoding The encoding the source string should be converted to * @return string|bool the converted string or FALSE on failure. */ public function mb_convert_encoding($string, $sourceEncoding, $targetEncoding) { return \mb_convert_encoding($string, $targetEncoding, $sourceEncoding); } /** * Wrapper around global function stream_get_wrappers() * @see stream_get_wrappers() * * @return array */ public function stream_get_wrappers() { return \stream_get_wrappers(); } /** * Wrapper around global function function_exists() * @see function_exists() * * @param string $functionName * @return bool */ public function function_exists($functionName) { return \function_exists($functionName); } }
from pydub import AudioSegment from pydub.silence import detect_nonsilent import argparse import os import csv def analyse_audio(file_path): # Load the audio file audio = AudioSegment.from_file(file_path, format="mp3") print(f"Channels Detected: {audio.channels}") bursts = [0] * audio.channels # Analysis of the audio file - each channel for channel in range(audio.channels): print(f"Channel {channel + 1}:") channel_audio = audio.split_to_mono()[channel] # Detect non-silent parts of the audio nonsilent_regions = detect_nonsilent(channel_audio, min_silence_len=300, silence_thresh=-20) # Calculate the average volume level in dB if len(nonsilent_regions) > 0: total_volume = sum([channel_audio[start:end].dBFS for start, end in nonsilent_regions]) average_volume = total_volume / len(nonsilent_regions) print(f"Total Non-silent regions: {len(nonsilent_regions)} > {nonsilent_regions} Average Volume Level: {average_volume:.2f} dB") bursts[channel] = len(nonsilent_regions) else: bursts[channel] = 0 print("No bursts audio detected") return bursts if __name__ == "__main__": # file_path = "data/Neurons.58_cropped.mp3" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) parser.add_argument("path", help="Folder path with audio file to be analyzed") args = parser.parse_args() folder_path = args.path # List all files in the folder file_list = os.listdir(folder_path) # Specify the path of a CSV file to store the transcriptions csv_file_path = f'{os.path.basename(os.path.dirname(args.path))}_data.csv' # Create a CSV file to store the transcriptions with open(csv_file_path, mode='w', newline='') as file: writer = csv.writer(file) csv_row_data = ["File", "Ch1", "Ch2", "Total"] writer.writerow(csv_row_data) # Loop through the files and read their contents for file_name in file_list: if os.path.isfile(os.path.join(folder_path, file_name)): # Check if it's a file (not a directory) base_name, extension = os.path.splitext(file_name) if extension == '.mp3': # transcribe the file print(f"Analysing {file_name}...") audio_data = analyse_audio(f"{args.path}{file_name}") # Write the results to the CSV file csv_row_data = [file_name, audio_data[0], audio_data[1], audio_data[0] + audio_data[1]] writer.writerow(csv_row_data) print(f'Reults stored in: "{csv_file_path}"')
package urltree_test import ( "testing" "github.com/stretchr/testify/assert" ) func TestGivenConstantEndpointURLTreeLookupReturnsResult(t *testing.T) { t.Parallel() wantValue := &TestStruct{Data: 1} urlTree := constantURLTree(wantValue) lookupResult := urlTree.Lookup("twitter.com/user/1234") assert.Equal(t, wantValue, lookupResult.Value) } func TestGivenWildcardEndpointURLTreeLookupReturnsResult(t *testing.T) { t.Parallel() wantValue := &TestStruct{Data: 1} urlTree := wildcardURLTree(wantValue) lookupResult := urlTree.Lookup("twitter.com/user/1234/messages") assert.Equal(t, wantValue, lookupResult.Value) } func TestGivenWildcardEndpointURLTreeLookupReturnsNormalizedURL(t *testing.T) { t.Parallel() wantValue := &TestStruct{Data: 1} urlTree := wildcardURLTree(wantValue) lookupResult := urlTree.Lookup("twitter.com/user/1234/messages") assert.Equal(t, "twitter.com/user/*", lookupResult.NormalizedURL) } func TestGivenPrefixMatchingWildcardEndpointURLTreeLookupReturnsResult( t *testing.T, ) { t.Parallel() wantValue := &TestStruct{Data: 1} urlTree := wildcardURLTree(wantValue) lookupResult := urlTree.Lookup("twitter.com/user") assert.Equal(t, wantValue, lookupResult.Value) } func TestGivenPathParamEndpointURLTreeLookupReturnsResult(t *testing.T) { t.Parallel() wantValue := &TestStruct{Data: 1} urlTree := pathParamURLTree(wantValue) lookupResult := urlTree.Lookup("twitter.com/user/1234") wantParams := map[string]string{"userID": "1234"} assert.Equal(t, wantValue, lookupResult.Value) assert.Equal(t, wantParams, lookupResult.PathParams) } func TestGivenPathParamEndpointURLTreeLookupPathParamReturnsResult( t *testing.T, ) { t.Parallel() wantValue := &TestStruct{Data: 1} urlTree := pathParamURLTree(wantValue) lookupResult := urlTree.Lookup("twitter.com/user/{userID}") assert.Equal(t, wantValue, lookupResult.Value) assert.Nil(t, lookupResult.PathParams) } func TestGivenPathParamEndpointURLTreeLookupPathParamWithDifferentNameReturnsResult( //nolint:lll t *testing.T, ) { t.Parallel() wantValue := &TestStruct{Data: 1} urlTree := pathParamURLTree(wantValue) lookupResult := urlTree.Lookup("twitter.com/user/{uid}") assert.Equal(t, wantValue, lookupResult.Value) assert.Nil(t, lookupResult.PathParams) } func TestGivenMixedEndpointURLTreeLookupReturnsResult(t *testing.T) { t.Parallel() wantConstantValue := &TestStruct{Data: 999} wantWildcardValue := &TestStruct{Data: 888} urlTree := mixedURLTree(wantConstantValue, wantWildcardValue) lookupResult1 := urlTree.Lookup("twitter.com/user/1234/messages") lookupResult2 := urlTree.Lookup("twitter.com/user/1234/messages/5678") assert.Equal(t, wantConstantValue, lookupResult1.Value) assert.Equal(t, wantWildcardValue, lookupResult2.Value) } func TestGivenUnmatchedConstantEndpointURLTreeLookupReturnsNilResult( t *testing.T, ) { t.Parallel() testValue := &TestStruct{Data: 1} urlTree := constantURLTree(testValue) lookupResult := urlTree.Lookup("twitter.com/user/foobar") assert.Nil(t, lookupResult.Value) } func TestGivenConstantEndpointURLTreePathParameterLookupReturnsNilResult( t *testing.T, ) { t.Parallel() testValue := &TestStruct{Data: 1} urlTree := constantURLTree(testValue) lookupResult := urlTree.Lookup("twitter.com/user/{userID}") assert.Nil(t, lookupResult.Value) } func TestGivenUnmatchedWildcardEndpointURLTreeLookupReturnsNilResult( t *testing.T, ) { t.Parallel() testValue := &TestStruct{Data: 1} urlTree := wildcardURLTree(testValue) lookupResult := urlTree.Lookup("twitter.com/post/1234") assert.Nil(t, lookupResult.Value) } func TestGivenUnmatchedPathParamEndpointURLTreeLookupReturnsNilResult( t *testing.T, ) { t.Parallel() testValue := &TestStruct{Data: 1} urlTree := pathParamURLTree(testValue) lookupResult := urlTree.Lookup("twitter.com/user/1234/messages") assert.Nil(t, lookupResult.Value) assert.Nil(t, lookupResult.PathParams) } func TestGivenUnmatchedMixedEndpointURLTreeLookupReturnsResult(t *testing.T) { t.Parallel() wantConstantValue := &TestStruct{Data: 999} wantWildcardValue := &TestStruct{Data: 888} urlTree := mixedURLTree(wantConstantValue, wantWildcardValue) lookupResult := urlTree.Lookup("twitter.com/post/1234/messages") assert.Nil(t, lookupResult.Value) }
package Automobile; import java.util.Objects; public class ElectricCar extends Automobile implements Vehicle { private double maximumSpeed; public ElectricCar(String brand, String model, double maximumSpeed) { super(brand, model); this.maximumSpeed = maximumSpeed; } public double getMaximumSpeed() { return maximumSpeed; } public void setMaximumSpeed(double maximumSpeed) { this.maximumSpeed = maximumSpeed; } @Override public void start() { super.start(); System.out.println(" (электрический автомобиль)"); } @Override public void stop() { super.stop(); System.out.println(" (электрический автомобиль)"); } @Override public String toString() { return super.toString() + " " + "максимальная скорость " + maximumSpeed; } @Override public boolean equals(Object object) { if (!super.equals(object)) { return false; } ElectricCar electricCar = (ElectricCar) object; return Objects.equals(maximumSpeed, electricCar.maximumSpeed); } @Override public int hashCode() { return Objects.hash(super.hashCode(), maximumSpeed); } }
"use client"; import { setPath } from "@/GlobalRedux/path/pathSlice"; import { pushPathName } from "@/services/routes"; import Link from "next/link"; import { useRouter } from "next/navigation"; import React from "react"; import { useDispatch } from "react-redux"; interface Props { children: React.ReactNode; className?: string; link?: string; onClick?: Function; } export default function MLink({ children, className, link, onClick }: Props) { const router = useRouter(); const dispatch = useDispatch(); return ( <Link onClick={() => { if (onClick) { onClick(); } if (link) { dispatch(setPath(link)); } }} href={`${link}` ?? "#"} className={className} > {children} </Link> ); }
package vn.edu.hcmuaf.fit.bean; import java.io.Serializable; public class User implements Serializable { private int id; private String fullName; private String email; private String phoneNumber; private String address; private String birthday; private String username; private String password; private int role; public User() { } public User(int id, String fullName, String email, String phoneNumber, String address, String birthday, String username, String password, int role) { this.id = id; this.fullName = fullName; this.email = email; this.phoneNumber = phoneNumber; this.birthday = birthday; this.username = username; this.password = password; this.role = role; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getRole() { return role; } public void setRole(int role) { this.role = role; } public boolean checkRole(int role) { return this.role >= role; } @Override public String toString() { return "User{" + "id=" + id + ", fullName='" + fullName + '\'' + ", email='" + email + '\'' + ", phoneNumber='" + phoneNumber + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", role=" + role + '}'; } }
--- title: OSO Spawners author: Braden Judson date: " `r Sys.Date()` " date-format: "YYYY-MM-DDTHH:mm:ssZ" format: pdf: documentclass: article toc: true editor: visual execute: cache: true --- # Osoyoos Lake Sockeye Spawners ```{r setup} #| echo: false #| include: false # getwd() options(show.signif.stars = FALSE) library(tidyr);library(dplyr);library(ggplot2) ``` ```{r local_functions} #| include: false # Custom "not in" operator. '%ni%' <- Negate('%in%') # ggplot theme via Braden Judson Custom_Theme <- theme_bw() + theme(panel.background = element_rect(fill = "white", colour = "black", linetype = "solid"), panel.grid.minor = element_line(colour = "white"), plot.caption = element_text(hjust = 0, vjust = 1, size = 12)) DOJY <- function(mon,day){ # vectorized version # Day of Julian Year # mon as 1 to 12 or "Jan" to "Dec" or "January" to "December" # add 10 for solar day (Dec 21 = DOJY 355). add 1 if leap year and DOJY > 58 prev_end_doy = c(0,31,59,90,120,151,181,212,243,273,304,334) # first the easy one if(is.numeric(mon))return(prev_end_doy[mon]+day) # works for vectors # then long or short month names get convereted to a number. n = length(mon) mon_n = integer(n) # number for month TBD month_char=month.abb # short names from R if(max(nchar(mon)) > 3) month_char=month.name #l long names from R for(j in 1:n) mon_n[j] = which(month_char %in% mon[j]) return(prev_end_doy[mon_n]+day) } #examples #obs_day= c(26, 4, 13, 28, 18) #DOJY1(mon=c(5, 8, 9, 11, 1), obs_day) # 146 216 256 332 18 #DOJY1(mon=c('May','Aug','Sep','Nov','Jan'),obs_day) #DOJY1(mon=c('May','August','September','November','January'),obs_day) ``` Spawner biosample data for Osoyoos Sockeye. Most data from Margot Stockwell's files ```{r} # Read in raw data. Remove empty rows. dat <- read.csv("data/oso_spawner_valsonly_nov3.2022.csv") %>% filter(!is.na(year)) dim(dat) # 32558 x 15. print(lapply(dat, class)) # Check class of each column. Mostly characters. dat$year <- as.factor(dat$year) # Year as factor. unique(dat$year) # 20 levels, 2000 to 2019. ``` ```{r} dat %>% count(year) %>% # Visualize sample sizes by year. ggplot() + # Pipe into ggplot. geom_col(aes(x = year, y = n)) + # Sample size by year. theme(axis.text.x = element_text(angle = 60)) + # Fix axis labs. ylab("Sample size (n)") # Change y lab. ``` Standardize each variable. Lots of noise. 1\. Conservation units. ```{r} unique(dat$conservation_unit) # All Osoyoos SOX - good! ``` \# 2. Dates. ```{r} unique(dat$date) # Numerical excel format. Fix. dat$ymd <- as.Date(dat$date, origin = "1899-12-30") # Dates now yyyy/mm/dd. dat$doy <- as.numeric(strftime(dat$ymd, format = "%j")) # Also add day of year (doy). class(dat$ymd) # Class "Date". dat <- dat[,colnames(dat) %ni% "date"] # Remove Excel-formatted dates. summary(dat$ymd) # Checks out (2000 - Nov 2019). dates_df <- dat %>% # Isolate dates. select(c("year", "doy")) # DOY is the most important variable. (year_summ <- aggregate(. ~ year, data = dates_df, # Observations by year. FUN = function(x) # Which years more representative than others. c(dev = round(sd(x),2), # standard deviation - how variable were sample dates? spread = max(x)-min(x), # Days between last and first sampling day. days = length(unique(x)))) %>% # Unique days sampled on. as.data.frame(.)) # Save as a DF and print. ``` unique(dat\$date) \# Numerical excel format. Fix. dat\$ymd \<- as.Date(dat\$date, origin = "1899-12-30") \# Dates now yyyy/mm/dd. dat\$doy \<- as.numeric(strftime(dat\$ymd, format = "%j")) \# Also add day of year (doy). class(dat\$ymd) \# Class "Date". dat \<- dat\[,colnames(dat) %ni% "date"\] \# Remove Excel-formatted dates. summary(dat\$ymd) \# Checks out (2000 - Nov 2019). dates_df \<- dat %\>% \# Isolate dates. select(c("year", "doy")) \# DOY is the most important variable. (year_summ \<- aggregate(. \~ year, data = dates_df, \# Observations by year. FUN = function(x) \# Which years more representative than others. c(dev = round(sd(x),2), \# standard deviation - how variable were sample dates? spread = max(x)-min(x), \# Days between last and first sampling day. days = length(unique(x)))) %\>% \# Unique days sampled on. as.data.frame(.)) \# Save as a DF and print. \# 3. Locations. unique(dat\$location) \# Whopping 82 factors - tons of redundancy. Messy. dat\$location \<- tolower(dat\$location) %\>% \# Set locations to all lowercase. { gsub(pattern = ".\*:\\\\s", replacement = "", .) %\>% \# Remove"reach" info - anything before : and a space afterwards. gsub(pattern = "-", replacement = "to", .) %\>% \# Make 2015 - 2016 and 2015 to 2016 the same. na_if(., "n/a") %\>% \# Turn character n/a into an actual NA. gsub(pattern = "; radio tagged", "", .) %\>% \# Trim unnecessary text from location identifiers. gsub(pattern = "; pit tag \# 3d9.1c2c5054ff", "", .) %\>% \# Again. gsub(pattern = "; pit tag \# 3d9.1c2c508be2", "", .) %\>% \# Again. gsub(pattern = "; 1 otolith", "", .) %\>% \# Again sub(x = ., \# Below is ugly fix to consolidating similar strings. "ok prov park to vds 17\|ok falls to vds 17\|okanagan provincial park to vds 17\|ok falls prov park to vds 17\|ok falls prov. park to vds 17", "ok falls to vds 17") %\>% sub(x = ., "hwy bridge to boat launch\|hwy 97 bridge crossing to boat launch", "hwy 97 bridge to boat launch")} unique(na.omit(dat\$location)) \# 42 factors now, excluding no data. \########## LOCATION QUESTIONS \################################################## \# Is direction important? \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# E.g., Is VDS 17 to VDS 16 the same as VDS 16 to VDS 17? \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Needs review from somebody who knows system - not sure how to consolidate \*\*\*\* \################################################################################ \# 4. Sampling. unique(dat\$Sampling); length(unique(dat\$Sampling)) \# Three factors. Assuming NA is same as unknown. dat\$Sampling \<- gsub(dat\$Sampling, pattern = "\^\$", replacement = "Unknown") %\>% as.factor() \# Set as factor (instead of character string). unique(dat\$Sampling); \# Two factors, Unknown and DP. summary(dat\$Sampling) \# 29825 dead pitch (91.6%) and 2733 unknown (8.4% total). \# 5. Sex unique(dat\$sex) \# 16 factors with a lot of redundancy. \# Unknown as: U, -, 0, ?, \*, (blank), and unk. Consolidate below. dat\$sex \<- tolower(dat\$sex) %\>% \# Set all lowercase. { gsub(pattern = "\^\\\\?\|\^\\\\-{1}?\|\^u{1}\$\|\^unk{1}\$\|\\\\\*\|0\|\^\$", \# Combine redundant "unknowns". replacement = "unknown", .) %\>% \# Replace. gsub(pattern = "m jack", "jack", .) } \# Consolidate jacks (all male). unique(dat\$sex) \# Looking much better, but there are Kokanee in the dataset. dat_sox \<- filter(dat, !grepl("ko", sex)) \# Dataset now entirely Sockeye. nrow(dat) - nrow(dat_sox) \# Only five Kokanee removed. dat_sox\$sex \<- as.factor(dat_sox\$sex) \# Sex as factor. Do this last to allow grepl above. summary(dat_sox\$sex) \# Four levels. M, F, Unknown and 14 jacks. \########## FISH SEX QUESTIONS \################################################## \# What to do with Jacks? Remove, or keep as a separate factor? \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Discard or retain fish of unknown sex? \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \################################################################################ \# 6. Fish length (fork and POH) dat_sox\$fork_length_mm \<- as.numeric(dat_sox\$fork_length_mm) \# Convert to numbers. Sets text to NAs. dat_sox\$fork_length_mm\[dat_sox\$fork_length_mm == 0\] \<- NA \# Replace 0s with NAs. summary(dat_sox\$fork_length_mm) \# Reasonable summary stats. hist(dat_sox\$fork_length_mm) \# No obvious errors. dat_sox %\>% \# Fish from 2016, 2017 and 2018 seem small. group_by(year) %\>% \# Group by year. summarise_at(vars(POH_mm, fork_length_mm), \# Mean lengths by each sample year. \~mean(., na.rm = T)) %\>% \# Remove NAs from mean estim. print() %\>% \# Print summary values. as.data.frame() %\>% \# Organize as DF (for ggplot). ggplot(.) + \# Read into ggplot. geom_col(aes(y = fork_length_mm, x = year)) + \# Columns are length, bars are years. theme(axis.text.x = element_text(angle = 70)) \# Angle text otherwise tough to read. dat_sox\$POH_mm \<- as.numeric(dat_sox\$POH_mm) \# Same as FL, but for POH ests. dat_sox\$POH_mm\[dat_sox\$POH_mm == 0\] \<- NA summary(dat_sox\$POH_mm) \# Lowest values appear erroneous. hist(dat_sox\$POH_mm) \# Low value stands out. sort(dat_sox\$POH_mm, decreasing = F)\[1:10\] \# POH of 29 and 41 clearly wrong. sum(dat_sox\$POH_mm \< 100, na.rm = T) \# Two fish below 10cm. na.omit(dat_sox\[dat_sox\$POH_mm \< 100, \]) \# Given FL and mass, clearly an error. Must be 290mm. dat_sox\$POH_mm\[dat_sox\$POH_mm == 29\] \<- 290 \# Now POH is 290mm. dat_sox \<- subset(dat_sox, \# Remove 41mm fish. No FL or mass data to reinforce. dat_sox\$POH_mm != 41 \| is.na(dat_sox\$POH_mm)) \# Remove POH of 41, but keep all POHs of NA. summary(dat_sox\$POH_mm) \# Seems much better. hist(dat_sox\$POH_mm) \# No obvious visual outliers. sum(!is.na(dat_sox\$fork_length_mm & dat_sox\$POH_mm)) #\~4k fish with both FL and POH numbers. dat_sox\[,c("fork_length_mm", "POH_mm")\] \<- round(dat_sox\[,c("fork_length_mm", "POH_mm")\],3) lm(data = dat_sox, fork_length_mm \~ POH_mm) %\>% \# adjR2 = 95.6 (p \< 0.001; n = 4218). summary(.) \# intercept = 18.25, POH = 1.18. \# Note that in Hyatt et al. 2017 states that among parent pops of OSO SOX the relationship \# is: FL = 1.29\*POH - 1.08 (r2 = 0.96, n = 541 b/w 2013 and 2018). \# Also note the data here are in mm, whereas Hyatt et al. uses cm. FL_reg \<- (dat_sox\$POH_mm) \* 1.18 + 18.25 \# Estimate FL based off POHs. dat_sox\$FL_reg \<- ifelse(!is.na(dat_sox\$fork_length_mm), \# If fork length are available, use those. dat_sox\$fork_length_mm, FL_reg) \# If not, used regression-based estimates. hist(dat_sox\$FL_reg) \# Distribution of FLs. sum(!is.na(dat_sox\$fork_length_mm) & !is.na(dat_sox\$POH_mm)) \# \~4k have both POH + FL, but use FL. sum(is.na(dat_sox\$fork_length_mm) & !is.na(dat_sox\$POH_mm)) \# \~14k use regression-estimated FLs. sum(!is.na(dat_sox\$fork_length_mm) & is.na(dat_sox\$POH_mm)) \# \~12k raw FLs are the only data. \########## LENGTH QUESTIONS \#################################################### \# Convert all lengths to POH? Use regression? Relationship might vary by year \*\* \# \~13% of fish have both FL and POH values \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Check my math on the FL \~ POH regression \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Check reasonable sizes - 150mm for a spawner? seems small \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# See comments on 2016-2017 fish sizes \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \################################################################################ \# 7. Age unique(dat_sox\$age) \# 21 factors with a lot of messiness. dat_sox\$age \<- dat_sox\$age %\>% {gsub(pattern = "0\|\^n{1}\$\|ns\|nr\|No sample\|NR\|n\\\\\\a\|n/a\|\^\$\|na\|\\\\#REF!\|\\\\#N/A", replacement = "Unknown", .) %\>% \# Replace redundant "Unknown" symbols. gsub(pattern = "1F", "1", .) } dat_sox\$age\[is.na(dat_sox\$age)\] \<- "Unknown" \# Replace NAs with a factor for Unknown. dat_sox \<- dat_sox %\>% \# Assign years-at-sea (salt age). mutate(salt_age = as.numeric(substr(x = dat_sox\$age, \# Make numeric, remove characters. start = 3, stop = 3))) \# Extract from European Age values. hist(dat_sox\$salt_age) \# 2 years at sea most common by far. dat_sox\$age \<- as.factor(dat_sox\$age) \# European ages as factors. summary(dat_sox\$age) \# Non-decimal values are TOTAL AGES. \########## AGE QUESTIONS \####################################################### \# NOTE: In 2018 lots of ages are entered only as TOTAL AGE in both the Total Age \# and European Age columns. \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# What about total ages? Remove? Can't make sense of them \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Only relevant in 2018 for about \~430 fish \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \################################################################################ \# 8. Thermal mark / Origin. unique(dat_sox\$thermal_mark) \# Needs consolidating / tidying. 23 Factors. dat_sox\$thermal_mark \<- dat_sox\$thermal_mark %\>% \# Convert into origins (H, N, U). {gsub(pattern = "UNK\|lost\|0\|n/a\|\^\$\|NS", replacement = "Unknown", .) %\>% \# Unknown origins. gsub(pattern = "\^N,\\\\S+\|\^N{1}\$", replacement = "Natural", .) %\>% \# Natural origin (i.e. Wild fish). gsub(pattern = "\^Y.+\|\^Y\$\|\^\[\[:digit:\]\].+", replacement = "Hatchery") %\>% \# Hatchery origin fish. as.factor(.)} \# Set as factor. summary(dat_sox\$thermal_mark) \# Summary of origin/thermal mark factor. \# 4.6% of dead pitch fish from hatchery. \# 35.1% of dead pitch fish wild. \# Remaining \~60.3% of fish unknown origin (unresolvable otoliths, or not sampled at all). \########## ORIGIN QUESTIONS \#################################################### \# Thermal mark = 0 - does this mean no (i.e., natural origin) or unknown? \*\*\*\*\*\* \# There aren't any with 1.... \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Same with NS = not sampled? not sure \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \################################################################################ \# 9. Weight. dat_sox\$weight_g \<- as.numeric(dat_sox\$weight_g) \# Convert to numeric. summary(dat_sox\$weight_g); hist(dat_sox\$weight_g) \# Zeroes still in data. dat_sox\$weight_g\[dat_sox\$weight_g == 0\] \<- NA \# Replace zeroes with NAs. summary(dat_sox\$weight_g); hist(dat_sox\$weight_g) \# No super obvious outliers. sort(dat_sox\$weight_g, decreasing = F)\[1:20\] \# Lowest weights. \########## WEIGHT QUESTIONS \#################################################### \# Are 56.8 and 75.4g reasonable weights for spawners? \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# 56.8 is a male - maybe a jack? 75.4 is female though. \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \################################################################################ \# 10. Fecundity. summary(as.numeric(dat_sox\$fecundity)) \# Heavily skewed. sum(is.na(as.numeric(dat_sox\$fecundity))) \# 32359. nrow(dat_sox) \# 32552. \# Fecundity data missing for \>99% of fish, skewed - remove. \# I think these fecundity were estimated from dead pitch? Not useful for this. dat_sox \<- dat_sox\[,colnames(dat_sox) %ni% "fecundity"\] \# Remove. brd_fec \<- read.csv("oso_sox_fecundity.csv", \# M. Stockwell's broodstock fecundity data. stringsAsFactors = T)\[,c(1:8)\] \# Strings as factors. brd_fec\$year \<- as.factor(brd_fec\$year) \# Year as factor. summary(brd_fec\$year) \# Distribution of fecundity samples. dim(brd_fec) \# 413 x 8. brd_fec\$salt_age \<- as.numeric(substr(x = brd_fec\$age, \# Factor for years at sea (salt age). start = 3, stop = 3))# Number after decimal in Euro style. brd_fec\$salt_age \<- as.numeric(brd_fec\$salt_age) brd_fec\$eggs \<- as.numeric(brd_fec\$eggs) \# Eggs (i.e., fecundity) as number. brd_fec\$fork_l\_cm \<- as.numeric(brd_fec\$fork_l\_cm)\*10 \# FL as number, convert to mm. summary(aov(eggs \~ year, data = brd_fec)) \# Significant. summary(aov(fork_l\_cm \~ year, data = brd_fec)) \# Significant. cor(brd_fec\[,colnames(brd_fec) %in% c("salt_age", \# Make a correlation matrix. "eggs", \# Three numerical values. "fork_l\_cm")\], \# Returns r (Pearson's CC). use = "complete.obs") \# Ignores NAs for age. \# Fork length and salt age highly related, r \> 0.8. \# Shouldn't use both in the same regression model. summary(lm(eggs \~ fork_l\_cm, data = brd_fec)) \# Adj R2 = 0.542, p \< 0.0001, DF1 = 411. summary(lm(eggs \~ salt_age, data = brd_fec)) \# Adj R2 = 0.339, p \< 0.0001, DF1 = 351. \# FL better predictor of fecundity than salt age. \# eggs \~ 9.6984 \* FL - 2139.0770 dat_sox\$eggs_est \<- 9.6984 \* dat_sox\$FL_reg - 2139.0770 \# Estimate eggs based on FL regression. dat_sox\$eggs_est \<- case_when( \# Estimate fecundity based on LM. sex == "f" \~ (9.6984 \* FL_reg) - 2139.0770, \# For females, compute estimates. sex != "f" \~ NA_real\_ \# For males, no estimates. ) hist(dat_sox\$eggs_est); summary(dat_sox\$eggs_est) \# Summary stats, visualization - estimates. hist(brd_fec\$eggs); summary(brd_fec\$eggs) \# Summary stats, visualization - actual. sort(dat_sox\$eggs_est, decreasing = T)\[1:20\] \# Not sure if these larger values need addressing. \########## FECUNDITY QUESTIONS \################################################# \# Are there more data? Surely \>2016 exists somewhere \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Same as FL regression, check methods (AO) \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Up to \~230mm FL, fecundity estimates are NEGATIVE - check \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# APPLY TO FEMALES ONLY \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Account of AOV results - add year as a factor? Separate regressions? \*\*\*\*\*\*\*\*\* \# Redo LMs - convert to same units (mm). \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\* \# Build side-by-side histograms of estimated and actual fecundity \*\*\*\*\*\*\*\*\*\*\*\*\*\* \################################################################################ \################################################################################ \################################################################################ \################################################################################ \# Before writing good copy: \# Answer all questions above. \# Figure out fecundity estimates (female only!). \# Get annual averages of relevant biostats and cbind with \# data on dates (spread, stdev, etc). Use for regression weights? \# write.csv(dat_sox, "OSO_SOX_spawner_data_tidy.csv", row.names = F)
---------------------- MODULE philosopher ---------------------- (* var waiter : boolean = true; fork : array [0..N-1] of boolean = [N of true]; function left(i : integer) : integer; begin left := i; end; function right(i : integer) : integer; begin right := mod (i-1) N; end; procedure phil(i : integer); begin while true do begin 0: >>> think <<< repeat until waiter; waiter := false; 1: repeat until fork[left(i)]; fork[left(i)] := false; 2: repeat until fork[right(i)]; fork[right(i)] := false; waiter := true; 3: >>> eat <<< fork[left(i)] := true; fork[right(i)] := true; end end; phil(0) || ... || phil(N-1) *) EXTENDS Integers CONSTANT N ASSUME N > 0 VARIABLES waiter, fork, pc TypeOK == [](waiter \in BOOLEAN /\ fork \in [0..N-1 -> BOOLEAN] /\ pc \in [0..N-1 -> 0..3]) left(i) == i right(i) == (i-1) % N eat(i) == fork' = [fork EXCEPT ![left(i)] = TRUE, ![right(i)] = TRUE] counter0(i) == /\ pc[i] = 0 /\ waiter = TRUE /\ waiter' = FALSE /\ pc' = [pc EXCEPT ![i] = 1] /\ fork' = fork counter1(i) == /\ pc[i] = 1 /\ fork[left(i)] = TRUE /\ pc' = [pc EXCEPT ![i] = 2] /\ fork' = [fork EXCEPT ![left(i)] = FALSE] /\ waiter' = waiter counter2(i) == /\ pc[i] = 2 /\ fork[right(i)] = TRUE /\ pc' = [pc EXCEPT ![i] = 3] /\ fork' = [fork EXCEPT ![right(i)] = FALSE] /\ waiter' = TRUE counter3(i) == /\ pc[i] = 3 /\ fork' = [fork EXCEPT ![right(i)] = TRUE, ![left(i)] = TRUE] /\ waiter' = waiter /\ pc' = [pc EXCEPT ![i] = 0] phil(i) == counter0(i) \/ counter1(i) \/ counter2(i) \/ counter3(i) Init == pc = [i \in 0..N-1 |-> 0] /\ fork = [i \in 0..N-1 |-> TRUE] /\ waiter = TRUE Next == \E i \in 0..N-1: phil(i) vars == <<waiter,fork,pc>> Spec == Init /\ [][Next]_vars /\ WF_vars(Next)
// Copyright 2021, Google LLC, Christopher Banes and the Tivi project contributors // SPDX-License-Identifier: Apache-2.0 package app.tivi.common.compose.ui import androidx.compose.animation.Crossfade import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import app.tivi.data.models.TraktUser @ExperimentalMaterial3Api @Composable fun TiviRootScreenAppBar( title: String, loggedIn: Boolean, user: TraktUser?, refreshing: Boolean, onRefreshActionClick: () -> Unit, onUserActionClick: () -> Unit, modifier: Modifier = Modifier, scrollBehavior: TopAppBarScrollBehavior? = null, ) { TopAppBar( modifier = modifier, colors = TopAppBarDefaults.topAppBarColors(containerColor = Color.Transparent), scrollBehavior = scrollBehavior, title = { Text(text = title) }, actions = { // This button refresh allows screen-readers, etc to trigger a refresh. // We only show the button to trigger a refresh, not to indicate that // we're currently refreshing, otherwise we have 4 indicators showing the // same thing. Crossfade( targetState = refreshing, modifier = Modifier.align(Alignment.CenterVertically), ) { isRefreshing -> if (!isRefreshing) { RefreshButton(onClick = onRefreshActionClick) } } UserProfileButton( loggedIn = loggedIn, user = user, onClick = onUserActionClick, modifier = Modifier.align(Alignment.CenterVertically), ) }, ) }
package com.tutorac.bookingapp.ui import android.widget.Toast import androidx.compose.foundation.layout.padding import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.currentBackStackEntryAsState import androidx.navigation.compose.rememberNavController import com.tutorac.bookingapp.R import com.tutorac.bookingapp.domain.Family import kotlinx.coroutines.channels.consumeEach import kotlinx.coroutines.launch @Composable fun AppBar( currentScreen: AppScreens, canNavigateBack: Boolean, navigateUp: () -> Unit, modifier: Modifier = Modifier ) { TopAppBar( title = { Text(stringResource(currentScreen.title)) }, modifier = modifier, navigationIcon = { if (canNavigateBack) { IconButton(onClick = navigateUp) { Icon( imageVector = Icons.Filled.ArrowBack, contentDescription = stringResource(R.string.back_button) ) } } } ) } @Composable fun BookingApp( viewModel: BookingViewModel, navController: NavHostController = rememberNavController() ) { // Get current back stack entry val backStackEntry by navController.currentBackStackEntryAsState() // Get the name of the current screen val currentScreen = AppScreens.valueOf( backStackEntry?.destination?.route ?: AppScreens.BookTicket.name ) val scope = rememberCoroutineScope() val context = LocalContext.current scope.launch { viewModel.showToast.consumeEach { Toast.makeText(context, it, Toast.LENGTH_SHORT).show() } } Scaffold( topBar = { AppBar( currentScreen = currentScreen, canNavigateBack = navController.previousBackStackEntry != null, navigateUp = { navController.navigateUp() } ) } ) { innerPadding -> val family by viewModel.currentFamily.collectAsState() val seat by viewModel.seats.collectAsState() NavHost( navController = navController, startDestination = AppScreens.BookTicket.name, modifier = Modifier.padding(innerPadding) ) { composable(AppScreens.BookTicket.name) { viewModel.getSeatMap() viewModel.resetSelectedSeat() BookTicketScreen( family = family, onSubmit = { viewModel.setFamily(it) if (viewModel.isBookingValid()) { navController.navigate(AppScreens.SelectSeats.name) } else { viewModel.showToast("Only ${viewModel.availableSeatCount()} seats available") } }, onToast = { viewModel.showToast(it) }, onDelete = { viewModel.deleteTicket() } ) } composable(AppScreens.SelectSeats.name) { SelectTicketScreen( seatMap = seat, onSelectIndex = { viewModel.setSelectedIndex(it) }, onUnSelectIndex = { viewModel.unSelectSeat(it) }, onSubmitClick = { if (viewModel.isSeatValid()) { navController.navigate(AppScreens.CustomerDetails.name) } else { viewModel.showToast("Select seats for all persons") } }, onToast = { viewModel.showToast(it) } ) } composable(AppScreens.CustomerDetails.name) { CustomerDetailScreen( familySize = family?.size ?: 0, onSubmitClick = { if (viewModel.setFamilyDetail(it)) { viewModel.bookTicket() navController.navigate(AppScreens.BookingConfirmed.name) } else { viewModel.showToast("Enter Complete Detail") } } ) } composable(AppScreens.BookingConfirmed.name) { BookingConfirmedScreen { viewModel.setFamily(Family(0, "")) viewModel.resetSelectedSeat() navController.popBackStack(route = AppScreens.BookTicket.name, inclusive = false) } } } } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AdminComponent } from './components/admin/admin.component'; import { AdminUserComponent } from './components/admin/user/admin-user/admin-user.component'; import { TransactionsComponent } from './components/admin/user/transactions/transactions.component'; import { CheckoutPageComponent } from './components/page-components/checkout-page/checkout-page.component'; import { ContactPageComponent } from './components/page-components/contact-page/contact-page.component'; import { HomePageComponentComponent } from './components/page-components/home-page-component/home-page-component.component'; import { ProductDetailComponent } from './components/page-components/product-detail/product-detail.component'; import { SiteComponent } from './components/site/site.component'; import { SendMoneyComponent } from './components/page-components/send-money/send-money.component'; import { PayOnlineComponent } from './components/page-components/pay-online/pay-online.component'; import { RequestMoneyComponent } from './components/page-components/request-money/request-money.component'; import { WalletPageComponent } from './components/page-components/wallet-page/wallet-page.component'; import { LoginComponent } from './components/login/login.component'; import { RegisterComponent } from './components/register/register.component'; import { SucessTransactionComponent } from './components/sucess-transaction/sucess-transaction.component'; import { FailureTransacrionComponent } from './components/failure-transacrion/failure-transacrion.component'; import { PayBillsComponent } from './components/page-components/pay-bills/pay-bills.component'; const routes: Routes = [ {path:'admin', component:AdminComponent,children:[ {path:'user', component:AdminUserComponent}, {path:'user/transactions',component:TransactionsComponent} ]}, {path:'',component:SiteComponent,children:[ {path:'', component:HomePageComponentComponent}, {path:'about',component:ProductDetailComponent}, {path:'wallet',component:WalletPageComponent}, {path:'checkout',component:CheckoutPageComponent}, {path:'contact',component:ContactPageComponent}, {path:'send-money',component:SendMoneyComponent}, {path:'request-money',component:RequestMoneyComponent}, {path:'sign_in',component:LoginComponent}, {path:'register',component:RegisterComponent}, {path:'pay-online',component:PayOnlineComponent}, {path:'st',component:SucessTransactionComponent}, {path:'pay-bills',component:PayBillsComponent}, {path:'ft',component:FailureTransacrionComponent}], } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
package com.aditya.storyverse; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.activity.EdgeToEdge; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.graphics.Insets; import androidx.core.view.ViewCompat; import androidx.core.view.WindowInsetsCompat; import com.aditya.storyverse.databinding.ActivitySignUpBinding; import com.aditya.storyverse.firebase.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.Firebase; import com.google.firebase.FirebaseApp; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.FirebaseDatabase; public class SignUpActivity extends AppCompatActivity { ActivitySignUpBinding binding; FirebaseAuth auth; FirebaseDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EdgeToEdge.enable(this); setContentView(R.layout.activity_sign_up); ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> { Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()); v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom); return insets; }); binding = ActivitySignUpBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); auth = FirebaseAuth.getInstance(); db = FirebaseDatabase.getInstance(); binding.btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { auth.createUserWithEmailAndPassword(binding.edtEmailSign.getText().toString(), binding.edtConfirmPassword.getText().toString()) .addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if(task.isSuccessful()){ User user = new User( binding.edtUserName.getText().toString(), binding.edtFirstName.getText().toString(), binding.edtLastName.getText().toString(), binding.edtEmailSign.getText().toString(), binding.edtConfirmPassword.getText().toString() ); String id = task.getResult().getUser().getUid(); db.getReference().child("Users").child(id).setValue(user); Toast.makeText(SignUpActivity.this, "Sign Up Successful, Log In here!!", Toast.LENGTH_SHORT).show(); Intent i = new Intent(SignUpActivity.this, LoginActivity.class); startActivity(i); }else{ Toast.makeText(SignUpActivity.this, "Wrong Email Address", Toast.LENGTH_SHORT).show(); } } }); } }); binding.txtLogIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(SignUpActivity.this, LoginActivity.class); startActivity(i); } }); } }
import { AuthHttpInterceptor } from './auth/auth-http-interceptor'; import { AuthGuard } from './auth/auth.guard'; import { AuthService } from './auth/auth.service'; import { SharedModule } from './shared/shared.module'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { LoginComponent } from './login/login.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { LogoutComponent } from './logout/logout.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, LogoutComponent ], imports: [ HttpClientModule, BrowserModule, AppRoutingModule, BrowserAnimationsModule, SharedModule, FormsModule, ReactiveFormsModule ], providers: [ AuthService, AuthGuard, { provide:HTTP_INTERCEPTORS, useClass: AuthHttpInterceptor, multi:true } ], bootstrap: [AppComponent] }) export class AppModule { }
<!DOCTYPE html> <html lang="en"> <head> <script async src="../../lib/tagmng4.js"></script> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" type="text/css" href="../../lib/tools.css" /> <link rel="apple-touch-icon" sizes="180x180" href="../../lib/favicon/apple-touch-icon.png" /> <link rel="icon" type="image/png" href="../../lib/favicon/favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="../../lib/favicon/favicon-16x16.png" sizes="16x16" /> <link rel="manifest" href="../../lib/favicon/manifest.json" /> <link rel="mask-icon" href="../../lib/favicon/safari-pinned-tab.svg" color="#5bbad5" /> <link rel="shortcut icon" href="../../lib/favicon/favicon.ico" /> <meta name="msapplication-config" content="/lib/favicon/browserconfig.xml" /> <meta name="theme-color" content="#ffffff" /> <meta name="format-detection" content="telephone=no" /> <title>sin(x) | sine function</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/bgoonz/GIT-CDN-FILES/mdn-article.css"> </head> <body> <div id="wrapper"> <div id="nav"> <a href="../../index.html">Home</a>&rsaquo;<a href="../index.html" >Math</a >&rsaquo;<a href="index.html">Trigonometry</a>&rsaquo; Sine function </div> <div id="top-ad"> <ins class="adsbygoogle adslot_1" data-ad-client="ca-pub-7356419691275579" data-ad-slot="1390814895" ></ins> </div> <div id="lcol"> <div id="doc"> <h1>Sine function</h1> <p>sin(x), sine function.</p> <ul> <li><a href="sin.html#definition">Definition of sine</a></li> <li><a href="sin.html#graph">Graph of sine</a></li> <li><a href="sin.html#rules">Sine rules</a></li> <li><a href="sin.html#arcsin">Inverse sine function</a></li> <li><a href="sin.html#table">Sine table</a></li> <li> <a href="../../calc/math/Sin_Calculator.html">Sine calculator</a> </li> </ul> <h2>Sine definition</h2> <p> In a right triangle ABC the sine of &alpha;, sin(&alpha;) is defined as the ratio betwween the side opposite to angle &alpha; and the side opposite to the right angle (hypotenuse): </p> <p class="math">sin <em>&alpha;</em> = <em>a</em> / <em>c</em></p> <h4>Example</h4> <p class="math"><em>a</em> = 3&quot;</p> <p class="math"><em>c</em> = 5&quot;</p> <p class="math"> sin <em>&alpha;</em> = <em>a</em> / <em>c</em> = 3 / 5 = 0.6 </p> <h2>Graph of sine</h2> <p>TBD</p> <h2>Sine rules</h2> <table class="dtable"> <tr> <th>Rule name</th> <th>Rule</th> </tr> <tr> <td>Symmetry</td> <td class="math">sin(-<i>&#952;</i>) = -sin <i>&#952;</i></td> </tr> <tr> <td>Symmetry</td> <td class="math"> sin(90&deg;<i>- &#952;</i>) = cos <i>&#952;</i> </td> </tr> <tr> <td>Pythagorean identity</td> <td class="math"> sin<sup><span style="font-size: 0.8em">2</span></sup ><em> &#945;</em> + cos<sup ><span style="font-size: 0.8em">2</span></sup ><em> &#945;</em> = 1 </td> </tr> <tr> <td>&nbsp;</td> <td class="math"> sin <i>&#952;</i> = cos <i>&#952;</i> &times; tan<i> &#952;</i> </td> </tr> <tr> <td>&nbsp;</td> <td class="math">sin <i>&#952;</i> = 1 / csc<i> &#952;</i></td> </tr> <tr> <td>Double angle</td> <td class="math"> sin 2<i>&#952;</i> = 2 sin <i>&#952;</i> cos <i>&#952;</i> </td> </tr> <tr> <td>Angles sum</td> <td class="math"> sin(<em>&#945;+&#946;</em>) = sin <em>&#945;</em> cos <em>&#946;</em> + cos <em>&#945;</em> sin <em>&#946;</em> </td> </tr> <tr> <td>Angles difference</td> <td class="math"> sin(<em>&#945;-&#946;</em>) = sin <em>&#945; </em>&nbsp;cos <em>&#946;</em> - cos <em>&#945;</em> sin <em>&#946;</em> </td> </tr> <tr> <td>Sum to product</td> <td class="math"> sin<em> &#945;</em> + sin<em> &#946;</em> = 2 sin [(<em>&#945;+&#946;</em>)/2] cos [(<em>&#945;</em>-<em>&#946;</em>)/2] </td> </tr> <tr> <td>Difference to product</td> <td class="math"> sin <em>&#945;</em> - sin<em> &#946;</em> = 2 sin [(<em>&#945;-&#946;</em>)/2] cos [(<em>&#945;+&#946;</em>)/2] </td> </tr> <tr> <td>Law of sines</td> <td class="math"> <em>a</em> / sin <em>&#945;</em> = <em>b</em> / sin <em>&#946;</em> = <em>c</em> / sin <em>&gamma;</em> </td> </tr> <tr> <td>Derivative</td> <td class="math">sin' <i>x</i> = cos <i>x</i></td> </tr> <tr> <td>Integral</td> <td class="math"> &#8747; sin <i>x</i> d<i>x</i> = - cos <i>x</i> + <i>C</i> </td> </tr> <tr> <td>Euler's formula</td> <td class="math"> sin <i>x</i> = (<i>e<sup>ix</sup></i> - <i>e</i ><sup>-<i>ix</i></sup >) / 2<i>i</i> </td> </tr> </table> <h3><a id="arcsin"></a>Inverse sine function</h3> <p> The <a href="arcsin.html">arcsine</a> of x is defined as the inverse sine function of x when -1&#8804;x&#8804;1. </p> <p>When the sine of y is equal to x:</p> <p class="math">sin <i>y</i> = <i>x</i></p> <p> Then the arcsine of x is equal to the inverse sine function of x, which is equal to y: </p> <p class="math"> arcsin <i>x</i> = sin<span style="font-size: 0.8em" ><sup>-1</sup></span >(<i>x</i>) = <i>y</i> </p> <p>See: <a href="arcsin.html">Arcsin function</a></p> <h2>Sine table</h2> <table class="dtable"> <tr> <th> x <p>(&deg;)</p> </th> <th> x <p>(rad)</p> </th> <th>sin x</th> </tr> <tr> <td>-90&deg;</td> <td>-&#960;/2</td> <td>-1</td> </tr> <tr> <td>-60&deg;</td> <td>-&#960;/3</td> <td> -&#8730;<span style="text-decoration: overline">3</span>/2 </td> </tr> <tr> <td>-45&deg;</td> <td>-&#960;/4</td> <td> -&#8730;<span style="text-decoration: overline">2</span>/2 </td> </tr> <tr> <td>-30&deg;</td> <td>-&#960;/6</td> <td>-1/2</td> </tr> <tr> <td>0&deg;</td> <td>0</td> <td>0</td> </tr> <tr> <td>30&deg;</td> <td>&#960;/6</td> <td>1/2</td> </tr> <tr> <td>45&deg;</td> <td>&#960;/4</td> <td>&#8730;<span style="text-decoration: overline">2</span>/2</td> </tr> <tr> <td>60&deg;</td> <td>&#960;/3</td> <td>&#8730;<span style="text-decoration: overline">3</span>/2</td> </tr> <tr> <td>90&deg;</td> <td>&#960;/2</td> <td>1</td> </tr> </table> <p>&nbsp;</p> <hr /> <h2>See also</h2> <ul> <li><a href="arcsin.html">Arcsin function</a></li> <li> <a href="../../calc/math/Sin_Calculator.html">Sine calculator</a> </li> <li><a href="cos.html">Cosine function</a></li> <li> <a href="../../convert/number/degrees-to-radians.html" >Degrees to radians converter</a > </li> </ul> <div id="ban-ad"> <ins class="adsbygoogle adslot_3" data-ad-client="ca-pub-7356419691275579" data-ad-slot="9463417041" ></ins> </div> </div> </div> <div id="rcol"> <ins class="adsbygoogle adslot_2" data-ad-client="ca-pub-7356419691275579" data-ad-slot="5385900220" ></ins> <h5>TRIGONOMETRY</h5> <ul> <li><a href="arccos.html">Arccos function</a></li> <li><a href="arcsin.html">Arcsin function</a></li> <li><a href="arctan.html">Arctan function</a></li> <li><a href="cos.html">Cosine function</a></li> <li><a href="sin.html">Sine function</a></li> <li><a href="tan.html">Tangent function</a></li> </ul> <ul> <li><a href="sin.html#feedback">Send Feedback</a></li> </div> </div> <div id="footer"> <a href="../../index.html">Home</a> | <a href="../../web/index.html">Web</a> | <a href="../index.html">Math</a> | <a href="../../electric/index.html"></a> <a href="../../calc/index.html"></a> | <a href="../../convert/index.html"></a> <a href="../../tools/index.html"></a> <p> &copy; <a href="../../index.html">WebDevHubTools</a> | <a href="../../about/terms.html" rel="nofollow">Terms of Use</a> | <a href="../../about/privacy.html" rel="nofollow">Privacy Policy</a> | <a href="../../about/cookies.html" rel="nofollow">Manage Cookies</a> </p> </div> <div id="banner"> </body> </html>
using Microsoft.Extensions.DependencyInjection; namespace MeetingOrganizer.Services.UserAccount; /// <summary> /// Bootstrapper for configuring services related to user accounts. /// </summary> public static class Bootstrapper { /// <summary> /// Adds the user account service to the service collection as a scoped service. /// </summary> /// <param name="services">The service collection to add the service to.</param> /// <returns>The modified service collection.</returns> public static IServiceCollection AddUserAccountService(this IServiceCollection services) { return services .AddScoped<IUserAccountService, UserAccountService>(); } }
<?php namespace App\Console\Commands; use App\Models\Customer; use App\Models\Order; use App\Models\Tracking; use App\Notifications\Customers\NotificationEmailTrackingLaPosteNumber; use App\Notifications\Customers\NotificationEmailTrackingNumber; use App\Notifications\Customers\NotificationSmsTrackingLaPosteNumber; use App\Notifications\Customers\NotificationSmsTrackingNumber; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Notification; class GetTrackingCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'tracking:get'; /** * The console command description. * * @var string */ protected $description = 'Suivi la poste'; /** * Execute the console command. */ public function handle() { $trackings = Tracking::where('is_active', true)->orderByDesc('id')->get(); $trackings->each(function($tracking) { $response = Http::withHeaders(['X-Okapi-Key' => 'g4XRxfXHkj5BJndV6wnFxeCwytxo2elTbyZmsPMeTrI+20QnCKATQwQvIHyZvIJN']) ->acceptJson() ->get('https://api.laposte.fr/suivi/v2/idships/' . $tracking->number, [ 'lang' => 'fr_FR', ]); if($response->successful()) { $event = collect($response->json()['shipment']['timeline'])->filter(fn ($item) => $item['status'] === true)->last(); $tracking->is_active = !$response->json()['shipment']['isFinal']; $tracking->save(); try { Notification::send($tracking->customer, new NotificationEmailTrackingLaPosteNumber( $tracking->number, $event )); } catch (\Exception $e) { Log::error($e); } $id = explode('_', $tracking->maileva_id); $c = new Carbon(); $order = Order::query()->where('customer_id', $id[1])->where('created_at', '<', $c->setTimestamp($id[2]))->orderByDesc('id')->first(); if(collect($order->options)->filter(fn($option) => $option->name === 'sms_notification')->count() >= 1) { Notification::send(Customer::find($id[1]), new NotificationSmsTrackingLaPosteNumber( $tracking->number, $event )); } } }); } }
import { forwardRef } from "@nextui-org/system"; import { CheckboxGroupProvider } from "./checkbox-group-context"; import { UseCheckboxGroupProps, useCheckboxGroup } from "./use-checkbox-group"; export interface CheckboxGroupProps extends UseCheckboxGroupProps {} const CheckboxGroup = forwardRef<"div", CheckboxGroupProps>((props, ref) => { const { children, context, label, description, errorMessage, getGroupProps, getLabelProps, getWrapperProps, getDescriptionProps, getErrorMessageProps, } = useCheckboxGroup({ ...props, ref }); // Updated dummy ValidationResult with a mock ValidityState const dummyValidationResult = { isInvalid: false, // or true, depending on your scenario validationErrors: [], // or an array of error messages validationDetails: { badInput: false, customError: false, patternMismatch: false, rangeOverflow: false, rangeUnderflow: false, stepMismatch: false, tooLong: false, tooShort: false, typeMismatch: false, valid: true, valueMissing: false, // ... add other properties of ValidityState as needed } }; return ( <div {...getGroupProps()}> {label && <span {...getLabelProps()}>{label}</span>} <div {...getWrapperProps()}> <CheckboxGroupProvider value={context}> {children} </CheckboxGroupProvider> </div> {errorMessage ? ( <div {...getErrorMessageProps()}> {typeof errorMessage === 'function' ? errorMessage(dummyValidationResult) : errorMessage} </div> ) : description ? ( <div {...getDescriptionProps()}>{description}</div> ) : null} </div> ); }); CheckboxGroup.displayName = "NextUI.CheckboxGroup"; export default CheckboxGroup;
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('fname'); $table->string('lname'); $table->string('email')->unique(); $table->string('role')->default('user'); $table->string('organization_name')->nullable(); $table->string('organization_type')->nullable(); $table->string('address'); $table->string('city'); $table->string('state'); $table->string('zip'); $table->string('phone'); $table->string('ssn'); $table->string('dl_front'); $table->string('dl_back'); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
package gitlet; import java.io.Serializable; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.TreeMap; public class Commit implements Serializable { /** * Constructor for a commit object. Assigns variables and * timestamp of commit. * * @param message log associated with the commit. * @param parent commit hash associated with the parent commit. * @param files Treemap of files that will be tracked by this commit * @param initial boolean, identifies if this commit is the initial commit */ Commit(String message, String parent, TreeMap<String, Blob> files, boolean initial) { _message = message; _parent = parent; if (files != null) { _files = files; } if (initial) { _timestamp = "Wed Dec 31 16:00:00 1969 -0800"; } else { _timestamp = setTimestamp(); } } /** * @return the message */ public String getMessage() { return _message; } /** * @return the parent identifier */ public String getParent() { return _parent; } /** * @return the timestamp of this commit */ public String getTimestamp() { return _timestamp; } /** * @return map of files this commit tracks */ public TreeMap<String, Blob> getCommittedFiles() { return _files; } /** * Creates a timestamp of the date/time this function * is called and formats it. * * @return formatted timestamp */ private String setTimestamp() { ZonedDateTime myDateObj = ZonedDateTime.now(); return DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss" + " yyyy xx").format(myDateObj); } /** Log associated with this commit. */ private String _message; /** Timestamp of current commit. */ private String _timestamp; /** SHA1 address hash of parent commit. */ private String _parent; /** Files in this commit. */ private TreeMap<String, Blob> _files = new TreeMap<>(); }
/* -------------------------------------------------------- On demand imports */ let viteModule; /* ------------------------------------------------------------------ Imports */ import { resolveConfigPath, resolveSrcPath, resolveLibPath, resolveDistPath, stripProjectPath, listLibNames } from "./paths.mjs"; import { getDefaultAliasesForVite } from "./aliases.mjs"; import { isFile } from "./fs.mjs"; import { asyncImport } from "./import.mjs"; /* ---------------------------------------------------------------- Internals */ const VITE_DEV_FILE_NAME = "vite.dev.mjs"; const VITE_BUILD_FILE_NAME = "vite.build.mjs"; const VITE_PREVIEW_FILE_NAME = "vite.preview.mjs"; const VITE_PUBLIC_FOLDER_PATH = "static"; /* ---------------------------------------------------------------- Functions */ /** * Watch for source code changes, auto build and run the project in * development mode * * @see configuration in config folder */ export async function viteRunInDevelopmentMode() { await importDependencies(); const config = await readViteConfig( VITE_DEV_FILE_NAME ); const server = await viteModule.createServer( config ); await server.listen(); server.printUrls(); } // -------------------------------------------------------------------- Function /** * Build a distribution version from the source * * @see configuration in config folder */ export async function viteBuildDist() { await importDependencies(); const config = await readViteConfig( VITE_BUILD_FILE_NAME ); await viteModule.build( config ); } // -------------------------------------------------------------------- Function /** * Preview a distribution version from the dist folder * * @see configuration in config folder */ export async function vitePreviewProjectFromDist() { await importDependencies(); const config = await readViteConfig( VITE_PREVIEW_FILE_NAME ); await viteModule.preview( config ); } // -------------------------------------------------------------------- Function /** * Get aliases for Vite from all libs in the libs folder * - @see viteGetAliasesFromLib for more info * * @returns {array} list of vite aliases */ export async function viteGetAliasesFromAllLibs() { const libNames = await listLibNames(); const allAliases = []; for( const libName of libNames ) { const entries = await viteGetAliasesFromLib( libName, false ); for( const entry of entries ) { allAliases.push( entry ); } } return allAliases; } // -------------------------------------------------------------------- Function /** * Get aliases for Vite from a lib in the libs folder * - The lib should contain a file [build-config/vite.aliases.mjs] * - That file should export a function called [generateAliases], which returns * an array of aliases that can be used by Vite. * - The function [generateAliases] receives a parameter [{resolveLibPath}], * that can be used to generate the correct paths for the aliases. * * @param {string} libName - Name of the lib * @param {boolean} [failOnMissing=true] * * @returns {array} list of vite aliases */ export async function viteGetAliasesFromLib( libName ) { await importDependencies(); try { const aliasConfigPath = resolveLibPath( libName, "config", "aliases.mjs" ); if( !await isFile( aliasConfigPath ) ) { console.log( `- Optional alias config file not found at ` + `[${stripProjectPath(aliasConfigPath)}].`); return []; } const module_ = await asyncImport( aliasConfigPath ); const resolveCurrentLibPath = resolveLibPath.bind( null, libName ); const displayPath = stripProjectPath( aliasConfigPath ); if( typeof module_.getCustomAliases !== "function" ) { throw new Error( `Alias configuration file [${displayPath}] does ` + `not export a function [getCustomAliases]`); } const viteEntries = []; const customAliases = await module_.getCustomAliases( { resolveCurrentLibPath } ); for( const key in customAliases ) { const path = customAliases[ key ]; if( typeof path !== "string" || !path.startsWith( resolveLibPath() ) ) { throw new Error( `Invalid value for alias [${key}] in alias configuration ` + `file [${displayPath}] (expected full path).`); } viteEntries.push( { find: key, replacement: path } ); } // end for } catch( e ) { if( e.code !== "ERR_MODULE_NOT_FOUND" ) { throw e; } } } /* ---------------------------------------------------------------- Internals */ /** * Read and process a vite config file * - Auto completes `config.root` * - Auto completes `config.publicDir` * - Auto completes `config.build.outDir` * * @param {string} configFileName - Name of a file in the config folder * * @returns {object} vite config */ async function readViteConfig( configFileName ) { let configFilePath = resolveConfigPath( configFileName ); let configFileURI = resolveConfigPath( configFileName, { returnURI: true } ); // console.log( { configFilePath } ); if( !await isFile( configFilePath ) ) { console.log(`- Missing config file [${configFilePath}].`); console.log(); /* eslint-disable-next-line no-undef */ process.exit(1); } await importDependencies(); // configFilePath = new URL( configFilePath ); const defaultExport = (await import( configFileURI )).default; let config; if( typeof defaultExport === "function" ) { config = await defaultExport(); } else { config = defaultExport; } // -- Auto complete config if( !config.root ) { config.root = resolveSrcPath(); } if( !config.publicDir ) { config.publicDir = resolveSrcPath( VITE_PUBLIC_FOLDER_PATH ); } if( config.build ) { if( !config.build.outDir ) { config.build.outDir = resolveDistPath(); } if( !("emptyOutDir" in config.build) && config.build.outDir.startsWith( resolveDistPath() ) ) { /* needed because outDir is outside project root */ config.build.emptyOutDir = true; } } // -- Debug: show main config properties const debugConfig = {}; if( config.server || config.preview ) { const server = config.server || config.preview; if( server.host ) { debugConfig.host = server.host; } if( server.port ) { debugConfig.port = server.port; } } if( config.resolve ) { const resolve = config.resolve; if( resolve.extensions instanceof Array ) { debugConfig.extensions = resolve.extensions.join(", "); } if( resolve.alias instanceof Array ) { const resolveAlias = resolve.alias; const debugAliases = []; for( const current of resolveAlias ) { if( typeof current === "function" ) { debugAliases.push(`(custom resolver)`); } else if( current instanceof Object ) { if( current.find && current.replacement ) { debugAliases.push( `${current.find} => ${stripProjectPath(current.replacement)}` ); } } else if( typeof current === "string" ) { debugAliases.push( `${stripProjectPath(current)}` ); } else { debugAliases.push(`unknown alias type (${typeof current})`); } } // end for debugConfig.aliases = debugAliases; } } if( config.root ) { debugConfig.sourceFolder = stripProjectPath( config.root ); } if( config.publicDir ) { debugConfig.staticFiles = stripProjectPath( config.publicDir ); } if( config.build ) { const build = config.build; if( build.outDir ) { debugConfig.distFolder = stripProjectPath( build.outDir ); } } // console.log("Full config", config); console.log(); console.log( "Main configuration:" ); console.log( debugConfig ); console.log(); return config; } // -------------------------------------------------------------------- Function /** * Generate config section `resolve` * * @see https://vitejs.dev/config/ * * @returns {object} config section */ export async function generateDefaultResolveConfig() { const configResolve = { extensions: [ '.mjs', '.js', // '.ts', '.jsx', '.tsx', '.json', '.css', '.scss' ], alias: [ ...await getDefaultAliasesForVite() ] }; // console.log( "configResolve", configResolve ); return configResolve; } // -------------------------------------------------------------------- Function /** * Dynamically import dependencies */ async function importDependencies() { if( viteModule ) { return; } viteModule = await import("vite"); }
from flask import Request, Response, jsonify from model.Model import Model from dao.DAO import DAO def model_post(model_object: Model, dao: DAO, request_json: dict[str, any]) -> Response: if dao.connect(): try: model_object.from_json(request_json) # Prepare the response data with default values response_data = { "id": dao.create(model_object), "message": f"{model_object.get_class_name()} row successfully created.", } response = jsonify(response_data) response.status = 201 return response except Exception as error: print(error) # Log the error for debugging purposes response_data = { "message": f"Empty or invalid parameters, unable to create {model_object.get_class_name()} object row." } response = jsonify(response_data) response.status = 400 # Set status to "Bad Request" (400) return response else: # If the DAO connection fails, return a service unavailable response (status 503) dao.is_connected = False response = jsonify({"message": "Service unavailable."}) response.status = 503 return response def model_get( model_object: Model, dao: DAO, conditions: str, values: list[any], ) -> Response: if dao.connect(): try: response_data = { "objects": [{}], "message": f"No conditions were received, unable to select {model_object.get_class_name()} objects.", } # Imediatly returns the function if there is no valid condition and values if not conditions and not values: response = jsonify(response_data) response.status = 400 return response objects_found = dao.read_with_condition(model_object, conditions, values) if len(objects_found) > 0: # If addresses are found, populate the addresses list and message response_data["objects"] = [ object_found.attributes_to_dict() for object_found in objects_found ] response_data[ "message" ] = f"{model_object.get_class_name()} data successfully found." status = 200 # Set status to success (200) else: # If no addresses are found, set a message and status accordingly response_data[ "message" ] = f"No {model_object.get_class_name()} data found with the specified condition." status = 404 # Set status to "Not Found" (404) # Create a JSON response with the response data and appropriate status response = jsonify(response_data) response.status = status return response except Exception as error: print(error) # Log the error for debugging purposes response = jsonify( {"message": "There was an internal error in the server."} ) response.status = 500 return response else: # If the DAO connection fails, return a service unavailable response (status 503) dao.is_connected = False response = jsonify({"message": "Service unavailable."}) response.status = 503 return response def model_put( model_object: Model, dao: DAO, request: Request, condition: str, values: list[any], ) -> Response: if dao.connect(): try: response_data = { "message": f"No condition or values were received, unable to update {model_object.get_class_name()} objects.", } status = 400 # Imediatly returns the function if there is no valid condition and values if not condition and not values: response = jsonify(response_data) response.status = status return response model_object.from_json(request.get_json()) if dao.update_with_condition(model_object, condition, values): response_data[ "message" ] = f"{model_object.get_class_name()} successfully updated." status = 200 # Set status to success (200) else: # If no addresses are found, set a message and status accordingly response_data[ "message" ] = f"No {model_object.get_class_name()} data found with the specified condition." status = 404 # Set status to "Not Found" (404) # Create a JSON response with the response data and appropriate status response = jsonify(response_data) response.status = status return response except Exception as error: print(error) # Log the error for debugging purposes else: # If the DAO connection fails, return a service unavailable response (status 503) dao.is_connected = False response = jsonify({"message": "Service unavailable."}) response.status = 503 return response def model_delete( model_object: Model, dao: DAO, condition: str, values: list[any], ) -> Response: if dao.connect(): try: response_data = { "message": f"No condition or values were received, unable to delete {model_object.get_class_name()} objects.", } status = 400 # Imediatly returns the function if there is no valid condition and values if not condition and not values: response = jsonify(response_data) response.status = status return response if dao.delete_with_condition(model_object, condition, values): response_data[ "message" ] = f"{model_object.get_class_name()} successfully deleted." status = 200 # Set status to success (200) else: # If no addresses are found, set a message and status accordingly response_data[ "message" ] = f"No {model_object.get_class_name()} data found with the specified condition." status = 404 # Set status to "Not Found" (404) # Create a JSON response with the response data and appropriate status response = jsonify(response_data) response.status = status return response except Exception as error: print(error) # Log the error for debugging purposes else: # If the DAO connection fails, return a service unavailable response (status 503) dao.is_connected = False response = jsonify({"message": "Service unavailable."}) response.status = 503 return response
<template> <layout-content header="Custom Resource Definitions"> <div style="float: left"> <el-button type="primary" size="small" :disabled="selects.length===0" @click="onDelete()" v-has-permissions="{scope:'namespace',apiGroup:'apiextensions.k8s.io',resource:'customresourcedefinitions',verb:'delete'}"> {{ $t("commons.button.delete") }} </el-button> </div> <complex-table :data="data" @search="search" :selects.sync="selects" v-loading="loading" :pagination-config="paginationConfig" :search-config="searchConfig"> <el-table-column type="selection" fix></el-table-column> <el-table-column label="Kind" show-overflow-tooltip> <template v-slot:default="{row}"> <span class="span-link" @click="openDetail(row)">{{ row.spec.names.kind }}</span> </template> </el-table-column> <el-table-column label="Group" prop="spec.group"> </el-table-column> <el-table-column label="Versions" prop="spec.versions"> <template v-slot:default="{row}"> <span v-for="(value, index) in row.spec.versions" v-bind:key="index"> {{value.name}} </span> </template> </el-table-column> <el-table-column :label="$t('commons.table.name')" prop="metadata.name"> </el-table-column> <el-table-column label="Scope" prop="spec.scope"> </el-table-column> <el-table-column :label="$t('commons.table.created_time')" prop="metadata.creationTimestamp" fix> <template v-slot:default="{row}"> {{ row.metadata.creationTimestamp | age }} </template> </el-table-column> <ko-table-operations :buttons="buttons" :label="$t('commons.table.action')"></ko-table-operations> </complex-table> </layout-content> </template> <script> import LayoutContent from "@/components/layout/LayoutContent" import ComplexTable from "@/components/complex-table" import {downloadYaml} from "@/utils/actions" import KoTableOperations from "@/components/ko-table-operations" import { deleteCustomResourceDefinition, getCustomResourceDefinition, listCustomResourceDefinitions, } from "@/api/customresourcedefinitions" import {checkPermissions} from "@/utils/permission" export default { name: "CRDList", components: { ComplexTable, LayoutContent, KoTableOperations }, data () { return { data: [], selects: [], loading: false, cluster: "", buttons: [ { label: this.$t("commons.button.edit_yaml"), icon: "el-icon-edit", click: (row) => { this.$router.push({ name: "CustomResourceDefinitionEdit", params: { name: row.metadata.name } }) }, disabled:()=>{ return !checkPermissions({scope:'namespace',apiGroup:"apiextensions.k8s.io",resource:"customresourcedefinitions",verb:"update"}) } }, { label: this.$t("commons.button.download_yaml"), icon: "el-icon-download", click: (row) => { downloadYaml(row.metadata.name + ".yml",getCustomResourceDefinition(this.cluster,row.metadata.name)) } }, { label: this.$t("commons.button.delete"), icon: "el-icon-delete", click: (row) => { this.onDelete(row) }, disabled:()=>{ return !checkPermissions({scope:'namespace',apiGroup:"apiextensions.k8s.io",resource:"customresourcedefinitions",verb:"delete"}) } }, ], paginationConfig: { currentPage: 1, pageSize: 10, total: 0, }, searchConfig: { keywords: "" } } }, methods: { search (resetPage) { this.loading = true if (resetPage) { this.paginationConfig.currentPage = 1 } listCustomResourceDefinitions(this.cluster, true, this.searchConfig.keywords, this.paginationConfig.currentPage, this.paginationConfig.pageSize).then(res => { this.data = res.items this.loading = false this.paginationConfig.total = res.total }) }, onDelete (row) { this.$confirm( this.$t("commons.confirm_message.delete"), this.$t("commons.message_box.prompt"), { confirmButtonText: this.$t("commons.button.confirm"), cancelButtonText: this.$t("commons.button.cancel"), type: "warning", }).then(() => { this.ps = [] if (row) { this.ps.push(deleteCustomResourceDefinition(this.cluster, row.metadata.name)) } else { if (this.selects.length > 0) { for (const select of this.selects) { this.ps.push(deleteCustomResourceDefinition(this.cluster, select.metadata.name)) } } } if (this.ps.length !== 0) { Promise.all(this.ps) .then(() => { this.search() this.$message({ type: "success", message: this.$t("commons.msg.delete_success"), }) }) .catch(() => { this.search() }) } }) }, openDetail (row) { this.$router.push({ name: "CustomResourceDefinitionDetail", params: { name: row.metadata.name }, query: { yamlShow: false } }) } }, created () { this.cluster = this.$route.query.cluster this.search() } } </script> <style scoped> </style>
#-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2024 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2013 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # 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. # # See COPYRIGHT and LICENSE files for more details. #++ require "spec_helper" RSpec.describe Capabilities::Scopes::Default do # we focus on the non current user capabilities to make the tests easier to understand subject(:scope) { Capability.default.where(principal_id: user.id) } shared_let(:project) { create(:project, enabled_module_names: []) } shared_let(:work_package) { create(:work_package, project:) } shared_let(:user) { create(:user) } let(:member_permissions) { %i[] } let(:global_permissions) { %i[] } let(:work_package_permissions) { %i[] } let(:non_member_permissions) { %i[] } let(:anonymous_permissions) { %i[] } let(:role) do create(:project_role, permissions: member_permissions) end let(:global_role) do create(:global_role, permissions: global_permissions) end let(:global_member) do create(:global_member, principal: user, roles: [global_role]) end let(:work_package_role) { create(:work_package_role, permissions: work_package_permissions) } let(:work_package_member) do create(:member, principal: user, project:, entity: work_package, roles: [work_package_role]) end let(:member) do create(:member, principal: user, roles: [role], project:) end let(:non_member_role) do create(:non_member, permissions: non_member_permissions) end let(:anonymous_role) do create(:anonymous_role, permissions: anonymous_permissions) end let(:members) { [] } shared_current_user do create(:admin) end shared_examples_for "consists of contract actions" do |with: "the expected actions"| it "includes #{with} for the scoped to user" do expect(scope.pluck(:action, :principal_id, :context_id)) .to match_array(expected) end end shared_examples_for "is empty" do it "is empty for the scoped to user" do expect(scope) .to be_empty end end describe ".default" do before do members end context "without any members and non member roles" do include_examples "is empty" end context "with a member without any permissions" do let(:members) { [member] } include_examples "is empty" context "with a module being activated with a public permission" do before do project.enabled_module_names = ["activity"] end include_examples "consists of contract actions", with: "the actions of the public permission" do let(:expected) do [ ["activities/read", user.id, project.id] ] end end end end context "with a global member without any permissions" do let(:members) { [global_member] } include_examples "is empty" end context "with a non member role without any permissions" do let(:members) { [non_member_role] } include_examples "is empty" context "with the project being public and having a module activated with a public permission" do before do project.update(public: true) project.enabled_module_names = ["activity"] end include_examples "consists of contract actions", with: "the actions of the public permission" do let(:expected) do [ ["activities/read", user.id, project.id] ] end end end end context "with a global member with a global permission" do let(:global_permissions) { %i[manage_user] } let(:members) { [global_member] } include_examples "consists of contract actions", with: "the actions of the global permission" do let(:expected) do [ ["users/read", user.id, nil], ["users/update", user.id, nil] ] end end context "with the user being locked" do before do user.locked! end include_examples "is empty" end end context "with a member with a project permission" do let(:member_permissions) { %i[manage_members] } let(:members) { [member] } include_examples "consists of contract actions", with: "the actions of the project permission" do let(:expected) do [["memberships/create", user.id, project.id], ["memberships/destroy", user.id, project.id], ["memberships/update", user.id, project.id]] end end context "with the user being locked" do before do user.locked! end include_examples "is empty" end end context "with the non member role with a project permission" do let(:non_member_permissions) { %i[view_members] } let(:members) { [non_member_role] } context "with the project being private" do include_examples "is empty" end context "with the project being public" do before do project.update(public: true) end include_examples "consists of contract actions", with: "the actions of the project permission" do let(:expected) do [ ["memberships/read", user.id, project.id] ] end end context "with the user being locked" do before do user.locked! end include_examples "is empty" end end end context "with the anonymous role having a project permission in a public project" do let(:anonymous_permissions) { %i[view_members] } let(:members) { [anonymous_role] } before do project.update(public: true) end include_examples "is empty" end context "with the anonymous user without any permissions with a public project" do let(:anonymous_permissions) { %i[] } let!(:user) { create(:anonymous) } let(:members) { [anonymous_role] } before do project.update(public: true) end include_examples "is empty" context "with the project having a module activated with a public permission" do before do project.enabled_module_names = ["activity"] end include_examples "consists of contract actions", with: "the actions of the public permission" do let(:expected) do [ ["activities/read", user.id, project.id] ] end end end end context "with the anonymous user with a project permission" do let(:anonymous_permissions) { %i[view_members] } let!(:user) { create(:anonymous) } let(:members) { [anonymous_role] } context "with the project being private" do include_examples "is empty" end context "with the project being public" do before do project.update(public: true) end include_examples "consists of contract actions", with: "the actions of the project permission" do let(:expected) do [ ["memberships/read", user.id, project.id] ] end end end end context "with a member without any permissions and with the non member having a project permission" do let(:non_member_permissions) { %i[view_members] } let(:members) { [member, non_member_role] } context "when the project is private" do include_examples "is empty" end context "when the project is public" do before do project.update(public: true) end include_examples "is empty" end end context "with a member with a project permission and with the non member having another project permission" do # This setup is not possible as having the manage_members permission requires to have view_members via the dependency # but it is convenient to test. let(:non_member_permissions) { %i[view_members] } let(:member_permissions) { %i[manage_members] } let(:members) { [member, non_member_role] } context "when the project is private" do include_examples "consists of contract actions", with: "the capabilities granted by the user`s membership" do let(:expected) do [ ["memberships/create", user.id, project.id], ["memberships/update", user.id, project.id], ["memberships/destroy", user.id, project.id] ] end end end context "when the project is public" do before do project.update(public: true) end include_examples "consists of contract actions", with: "the capabilities granted by the user`s membership" do let(:expected) do [ ["memberships/create", user.id, project.id], ["memberships/update", user.id, project.id], ["memberships/destroy", user.id, project.id] ] end end end end context "with an admin" do before do user.update(admin: true) end context "with modules activated" do before do project.enabled_module_names = OpenProject::AccessControl.available_project_modules end include_examples "consists of contract actions", with: "all actions of all permissions (project and global) grantable to admin" do let(:expected) do # This complicated and programmatic way is chosen so that the test can deal with additional actions being defined item = ->(namespace, action, global, module_name) { # We only expect contract actions for project modules that are enabled by default. In the # default edition the Bim module is not enabled by default for instance and thus it's contract # actions are not expected to be part of the default capabilities. return if module_name.present? && project.enabled_module_names.exclude?(module_name.to_s) ["#{API::Utilities::PropertyNameConverter.from_ar_name(namespace.to_s.singularize).pluralize.underscore}/#{action}", user.id, global ? nil : project.id] } OpenProject::AccessControl .contract_actions_map .select { |_, v| v[:grant_to_admin] } .map { |_, v| v[:actions].map { |vk, vv| vv.map { |vvv| item.call(vk, vvv, v[:global], v[:module_name]) } } } .flatten(2) .compact .uniq { |v| v.join(",") } end it "does not include actions of permissions non-grantable to admin" do expect(scope.pluck(:action)).not_to include("work_packages/assigned") end it "include actions from public permissions of activated modules" do expect(scope.pluck(:action)).to include("activities/read") end end end context "with modules deactivated" do before do project.enabled_modules = [] end include_examples "consists of contract actions", with: "all actions of all core permissions without the ones from modules" do let(:expected) do # This complicated and programmatic way is chosen so that the test can deal with additional actions being defined item = ->(namespace, action, global, module_name) { return if module_name.present? ["#{API::Utilities::PropertyNameConverter.from_ar_name(namespace.to_s.singularize).pluralize.underscore}/#{action}", user.id, global ? nil : project.id] } OpenProject::AccessControl .contract_actions_map .select { |_, v| v[:grant_to_admin] } .map { |_, v| v[:actions].map { |vk, vv| vv.map { |vvv| item.call(vk, vvv, v[:global], v[:module_name]) } } } .flatten(2) .compact .uniq { |v| v.join(",") } end end end context "with admin user being locked" do before do user.locked! end include_examples "is empty" end end context "without the current user being member in a project" do let(:member_permissions) { %i[manage_members] } let(:global_permissions) { %i[manage_user] } let(:members) { [member, global_member] } before do current_user.update(admin: false) end include_examples "is empty" end context "with the current user being member in a project" do let(:member_permissions) { %i[manage_members] } let(:global_permissions) { %i[manage_user] } let(:own_role) { create(:project_role, permissions: []) } let(:own_member) do create(:member, principal: current_user, roles: [own_role], project:) end let(:members) { [own_member, member, global_member] } before do current_user.update(admin: false) end include_examples "consists of contract actions" do let(:expected) do [ ["memberships/create", user.id, project.id], ["memberships/destroy", user.id, project.id], ["memberships/update", user.id, project.id], ["users/read", user.id, nil], ["users/update", user.id, nil] ] end end end context "with a member with an action permission that is not granted to admin" do let(:member_permissions) { %i[work_package_assigned] } let(:members) { [member] } before do project.enabled_module_names = ["work_package_tracking"] end include_examples "consists of contract actions", with: "the actions of the permission" do let(:expected) do [ ["work_packages/assigned", user.id, project.id] ] end end end context "with a member with a project permission and the project being archived" do let(:member_permissions) { %i[manage_members] } let(:members) { [member] } before do project.update(active: false) end include_examples "is empty" end context "with a work package membership" do before do project.enabled_module_names = ["work_package_tracking"] end let(:members) { [work_package_member] } context "when no permissions are associated with the role" do include_examples "is empty" end # TODO: This is temporary, we do not want the capabilities of the entity specific memberships to # show up in the capabilities API for now. This will change in the future context "when a permission is granted to the role" do let(:work_package_permissions) { [:view_work_packages] } include_examples "is empty" end context "for a public project" do let(:non_member_permissions) { %i[view_members] } let(:members) { [work_package_member, non_member_role] } before do project.update(public: true) end include_examples "consists of contract actions", with: "the actions of the non member role`s permission" do let(:expected) do [ ["memberships/read", user.id, project.id] ] end end end end end end
import React, { useState } from "react"; import { InputText } from "primereact/inputtext"; import { Button } from "primereact/button"; import { MdOutlineTitle } from "react-icons/md"; import { AiOutlineLink } from "react-icons/ai"; import { BiCategoryAlt, BiSolidImage } from "react-icons/bi"; import { Dropdown } from "primereact/dropdown"; import { GrStatusGoodSmall } from "react-icons/gr"; import { FaSortNumericDown } from "react-icons/fa"; import Image from "next/image"; export default function FormEditor({ category, setCategory, parentCategories, setParentCategories, formLoading, handleSubmitForm, btnLabel, }) { const statues = [ { id: 1, title: "Active", }, { id: 0, title: "In Active", }, ]; const [thumbnailImage, setThumbnailImage] = useState(category.icon); const handleChangeCategory = (e) => { const { name, value } = e.target; setCategory({ ...category, [name]: value, }); }; const handleChangeThumbnail = (e) => { const file = e.target.files[0]; setCategory({ ...category, icon: file, }); setThumbnailImage(URL.createObjectURL(file)); }; return ( <form method="POST" encType="multipart/form-data" onSubmit={handleSubmitForm} > <div className="my-2 row"> <div className="col-md-6 p-inputgroup flex-1"> <span className="p-inputgroup-addon"> <MdOutlineTitle /> </span> <InputText placeholder="Title" name="title" onChange={handleChangeCategory} value={category.title} required /> </div> <div className="col-md-6 p-inputgroup flex-1"> <span className="p-inputgroup-addon"> <AiOutlineLink /> </span> <InputText placeholder="Slug" name="slug" onChange={handleChangeCategory} value={category.slug} required /> </div> <div className="col-md-3 mt-2 p-inputgroup flex-1"> <span className="p-inputgroup-addon"> <FaSortNumericDown /> </span> <InputText placeholder="Order Number" name="order_number" onChange={handleChangeCategory} value={category.order_number} required /> </div> <div className="col-md-3 mt-2 p-inputgroup flex-1"> <span className="p-inputgroup-addon"> <GrStatusGoodSmall /> </span>{" "} <Dropdown options={statues} optionLabel="title" optionValue="id" placeholder="Status" className="w-full md:w-14rem" name="status" onChange={handleChangeCategory} value={category.status} required /> </div> <div className="col-md-3 mt-2 p-inputgroup flex-1"> <span className="p-inputgroup-addon"> <BiCategoryAlt /> </span>{" "} <Dropdown options={parentCategories} optionLabel="title" optionValue="id" placeholder="Parent Category" className="w-full md:w-14rem" name="parent_id" onChange={handleChangeCategory} value={category.parent_id} /> </div> <div className="col-md-3 mt-2 p-inputgroup flex-1"> <span className="p-inputgroup-addon"> <BiSolidImage /> </span> <div className="upload-thumbnail"> <label htmlFor="thumbnailUpload" className="p-button border-left-0" > Upload Icon <input id="thumbnailUpload" type="file" name="icon" onChange={handleChangeThumbnail} accept="image/png, image/jpg, image/jpeg" /> </label> </div> </div> </div> <div className="row"> <div className="col-md-3"> <Image src={ thumbnailImage ? thumbnailImage : "https://placehold.co/160x160/EEE/31343C" } className="thumbnail-image category" width={160} height={160} alt="thumbnail" /> </div> </div> <div className="text-right"> <Button label={btnLabel} icon="pi pi-save" type="submit" loading={formLoading} rounded={true} raised={true} /> </div> </form> ); }
from typing import Any import gradio as gr from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma from langchain.chains import RetrievalQA, ConversationalRetrievalChain from langchain.chat_models import ChatOpenAI from langchain.document_loaders import PyPDFLoader import fitz from PIL import Image import chromadb import re import uuid import os enable_box = gr.Textbox.update(value=None, placeholder='Upload your OpenAI API key', interactive=True) disable_box = gr.Textbox.update(value='OpenAI API key is Set', interactive=False) os.environ["OPENAI_API_KEY"] = "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" def set_apikey(api_key): app.OPENAI_API_KEY = api_key return disable_box def enable_api_box(): return enable_box def add_text(history, text): if not text: raise gr.Error('enter text') history = history + [(text, '')] return history class ChatBot: def __init__(self, OPENAI_API_KEY=None) -> None: self.OPENAI_API_KEY = OPENAI_API_KEY self.chain = None self.chat_history = [] self.N = 0 self.count = 0 def __call__(self, file) -> Any: if self.count == 0: print('This is here') self.build_chain(file) self.count += 1 return self.chain def chroma_client(self): # create a chroma client client = chromadb.Client() # create a collecyion collection = client.get_or_create_collection(name="my-collection") return client def process_file(self, file): loader = PyPDFLoader(file.name) documents = loader.load() pattern = r"/([^/]+)$" match = re.search(pattern, file.name) file_name = match.group(1) return documents, file_name def build_chain(self, file): documents, file_name = self.process_file(file) # Load embeddings model embeddings = OpenAIEmbeddings(openai_api_key=self.OPENAI_API_KEY) pdfsearch = Chroma.from_documents(documents, embeddings, collection_name=file_name, ) chain = ConversationalRetrievalChain.from_llm( ChatOpenAI(temperature=0.0, openai_api_key=self.OPENAI_API_KEY), retriever=pdfsearch.as_retriever(search_kwargs={"k": 1}), return_source_documents=True) return chain def get_response(history, query, file): if not file: raise gr.Error(message='Upload a PDF') chain = app(file) result = chain({"question": query, 'chat_history': app.chat_history}, return_only_outputs=True) app.chat_history += [(query, result["answer"])] app.N = list(result['source_documents'][0])[1][1]['page'] for char in result['answer']: history[-1][-1] += char yield history, '' def render_file(file): doc = fitz.open(file.name) page = doc[app.N] # Render the page as a PNG image with a resolution of 300 DPI pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72)) image = Image.frombytes('RGB', [pix.width, pix.height], pix.samples) return image def render_first(file): doc = fitz.open(file.name) page = doc[0] # Render the page as a PNG image with a resolution of 300 DPI pix = page.get_pixmap(matrix=fitz.Matrix(300 / 72, 300 / 72)) image = Image.frombytes('RGB', [pix.width, pix.height], pix.samples) return image, [] app = ChatBot() with gr.Blocks() as demo: state = gr.State(uuid.uuid4().hex) with gr.Column(): with gr.Row(): with gr.Column(scale=0.8): api_key = gr.Textbox(placeholder='Enter OpenAI API key', show_label=False, interactive=True).style( container=False) with gr.Column(scale=0.2): change_api_key = gr.Button('Change Key') with gr.Row(): chatbot = gr.Chatbot(value=[], elem_id='chatbot').style(height=650) show_img = gr.Image(label='Upload PDF', tool='select').style(height=680) with gr.Row(): with gr.Column(scale=0.60): txt = gr.Textbox( show_label=False, placeholder="Enter text and press enter", ).style(container=False) with gr.Column(scale=0.20): submit_btn = gr.Button('submit') with gr.Column(scale=0.20): btn = gr.UploadButton("📁 upload a PDF", file_types=[".pdf"]).style() api_key.submit(fn=set_apikey, inputs=[api_key], outputs=[api_key, ]) change_api_key.click(fn=enable_api_box, outputs=[api_key]) btn.upload(fn=render_first, inputs=[btn], outputs=[show_img, chatbot], ) submit_btn.click( fn=add_text, inputs=[chatbot, txt], outputs=[chatbot, ], queue=False ).success(fn=get_response, inputs=[chatbot, txt, btn], outputs=[chatbot, txt] ).success(fn=render_file, inputs=[btn], outputs=[show_img]) demo.queue() demo.launch()
import { AntDesign, Ionicons } from "@expo/vector-icons" import { NavigationProp, useNavigation } from "@react-navigation/native" import { Box, HStack, IconButton, Image, VStack, DeleteIcon } from "native-base" import * as React from "react" import { TouchableOpacity } from "react-native" import { IconProps } from "./icon.props" import { useQueryClient } from "react-query" import { apiSdk, getUserId } from "../../utils/api" import { Accordion, Button, Checkbox, Text } from "ui" import { Icon } from "../icon/icon" import { DELIVERY_ADDRESS, IMAGE_PLACEHOLDER_URL } from "../../config/constants" import { commaify } from "../../utils/format" import { CartShipment, LineItem, Product, Store } from "../../graphql/generated/graphql" import { ProductsParamList } from "../../navigators" import { useCartApi } from "../../stores/cart" import { makeDisplayString } from "../../utils/format" import { useStyles } from "../../utils/styles" import { useCart } from "../../stores/cart" import { useDeleteCartMutation, useGetCartByUserIdQuery, useGetCartQuery } from "../../graphql/generated/graphql" export interface CategorizedListProps { shipments: Array< Pick<CartShipment, "assignedStoreName" | "deliveryType" | "deliveryAddress"> & { lineItems?: Pick< LineItem, "productId" | "qtyPurchased" | "unitPrice" | "totalPrice" | "productName" >[] } > onCheckBoxToggle: (isActive: boolean, assignedStoreId: string, productId: string) => void } export const CategorizedList = (props: CategorizedListProps) => { const { shipments, onCheckBoxToggle } = props const navigation = useNavigation<NavigationProp<ProductsParamList, "productsSearch">>() const cart = useCart() const [activeSections, setActiveSections] = React.useState([]) const { processProduct } = useCartApi() const updateCart = ( product: Pick<Product, "id" | "prodFullName" | "prodShortDesc">, store: Pick<Store, "id" | "storeName">, newCount: number, ) => { processProduct({ product, quantity: newCount, assignedStoreId: store.id, assignedStoreName: store.storeName, }) } const styles = useStyles({ create: ({ colors }) => ({ textRed: { color: colors.primary } }), }) const queryClient = useQueryClient() const userId = getUserId() const { mutate, isLoading } = useDeleteCartMutation(apiSdk, { onSuccess: (data) => { queryClient.refetchQueries(useGetCartByUserIdQuery.getKey({ userId })) queryClient.refetchQueries(useGetCartQuery.getKey({ id: cart?.id, })) navigation.navigate("cart"); } }) const formattedShipments = React.useMemo( () => shipments.map((shipment) => { return { ...shipment, title: shipment?.assignedStoreName, } }), [shipments], ) return ( <Accordion variant="outline" expandMultiple activeSections={activeSections} sections={formattedShipments} renderAsFlatList onChange={setActiveSections} renderContent={(c, index, isActive) => { // @ts-ignore const content = c as CartShipment return ( <VStack borderWidth={1} borderColor="primary.200" rounded="lg" p={1} space={3}> {content?.lineItems?.map((item) => { const { productName, productId, qtyPurchased, unitPrice, totalPrice } = item return ( <Box> <HStack key={productId} space={3} alignItems={"flex-start"} p={2} borderBottomWidth={1} borderBottomColor="gray.400" > <Image source={{ uri: IMAGE_PLACEHOLDER_URL }} w={20} h={20} rounded={"lg"} alt={productName} bg="gray.600" /> <VStack flex={1} justifyContent={"space-between"}> <TouchableOpacity onPress={() => { navigation.navigate("productInfo", { product: { id: productId, title: productName, }, }) }} > <Text fontSize={"lg"} fontWeight={"normal"}> {productName} </Text> <HStack> <Text fontSize={"lg"} fontWeight={"Bold"}> Delivery By </Text> <Text fontSize={"lg"} fontWeight={"normal"} style={styles.textRed}> {" "} Fed Ex </Text> <Text style={{ marginLeft: 2, marginRight: 2 }}>{"|"} </Text> <Text ml="2" alignSelf="end" > {content?.deliveryType} </Text> </HStack> </TouchableOpacity> <HStack w="full" alignItems={"center"} space={2} p={2}> <Text ml="auto" fontSize={"lg"} fontWeight={"bold"} maxW={"lg"}> ${makeDisplayString(totalPrice)} </Text> <HStack alignItems={"center"} paddingLeft="100px"> <IconButton p={2} colorScheme="primary" rounded={"full"} color="white" variant={"outline"} onPress={() => { updateCart( { prodFullName: productName, prodShortDesc: "", id: productId, }, { id: content?.assignedStoreId, storeName: content?.assignedStoreName, }, qtyPurchased - 1, ) }} icon={<AntDesign name="minus" color="#000" />} /> <Box paddingLeft={2} paddingRight={2} > <Text fontSize={"md"} fontWeight={"bold"}> {qtyPurchased} </Text> </Box> <IconButton p={2} colorScheme="primary" rounded={"full"} color="white" variant={"outline"} onPress={() => { updateCart( { prodFullName: productName, prodShortDesc: "", id: productId, }, { id: content?.assignedStoreId, storeName: content?.assignedStoreName, }, qtyPurchased + 1, ) }} icon={<Ionicons name="add" color={"#000"} />} /> </HStack> </HStack> </VStack> {/* <Checkbox onValueChange={(value) => { onCheckBoxToggle(value, content.assignedStoreId, productId) }} /> */} {/* <Ionicons name="refresh" color={"green"} size={20} /> <Ionicons name="heart" style={styles.textRed} size={20} /> */} <TouchableOpacity> <DeleteIcon onPress={() => { // dispatch.cart?.discardProduct({ // product: { // id: productId, // }, // }) if (cart?.id?.length > 0) { mutate({ input: { id: cart?.id, }, }) } }} size="md" /> </TouchableOpacity> </HStack> <Text fontWeight="bold" style={styles.textRed}> {content?.assignedStoreName} </Text> <HStack> <Text fontWeight="bold"> Store Address:{' '} </Text> <Text> {commaify( content?.deliveryAddress?.addrLine1, content?.deliveryAddress?.addrLine2, content?.deliveryAddress?.city, content?.deliveryAddress?.state, content?.deliveryAddress?.country, )} </Text> </HStack> </Box> ) })} </VStack> ) }} /> ) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Tommy Comeau | Full Stack Developer</title> <link rel="stylesheet" href="style.css"> <script src="https://kit.fontawesome.com/91ced6fe6d.js" crossorigin="anonymous"></script> <script src="index.js" defer></script> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> </head> <body> <nav> <h3 class = "logo">Tommy Comeau</h3> <ul> <li> <a href="#home" class="nav-link">Home</a> </li> <li> <a href="#about" class="nav-link">About</a> </li> <li> <a href="#projects" class="nav-link">Projects</a> </li> <li> <a href="#contact" class="nav-link">Contact</a> </li> <li> <button class="mobile-nav-toggle"> <svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mobile-menu"> <path d="M4 6l16 0"></path> <path d="M4 12l16 0"></path> <path d="M4 18l16 0"></path> </svg> </button> </li> </ul> </nav> <div class="mobile-navigation"> <button> <span> <i class="fa-solid fa-xmark"></i> </span> </button> <ul> <li> <a href="#home" class="mobile-nav-link">Home</a> </li> <li> <a href="#about" class="mobile-nav-link">About</a> </li> <li> <a href="#projects" class="mobile-nav-link">Projects</a> </li> <li> <a href="#contact" class="mobile-nav-link">Contact</a> </li> </ul> </div> <section class="hero" id="home"> <div class="container"> <div class="content"> <div class="hero-main"> <div class="hero-text"> <h1>Junior Full-Stack Developer</h1> <img src="images/waving.png" alt="waving_hand"> <p>Hi, I'm Tommy Comeau. A passionate Full-Stack Developer based in San Jose, California. 📍</p> <span> <a class="icon" href="https://www.linkedin.com/?trk=seo-authwall-base_nav-header-logo" target="_blank"><ion-icon name="logo-linkedin"></ion-icon></a> <a class="icon" href="https://github.com/tommycomeau3" target="_blank"><ion-icon name="logo-github"></ion-icon></a> <a class="icon" href="https://www.instagram.com/tommy_comeau" target="_blank"><ion-icon name="logo-instagram"></ion-icon></a> <a class="icon" href="https://twitter.com/tommycomeausdsu" target="_blank"><ion-icon name="logo-twitter"></ion-icon></a> </span> </div> <div class="hero-img"></div> </div> <div class="skills"> <p>Tech Stack</p> <div class="logos"> <ul> <li> <img src="images/python.png" alt="python"> </li> <li> <img src="images/java.svg" alt="java"> </li> <li> <img src="images/html.png" alt="html"> </li> <li> <img src="images/css.png" alt="css"> </li> <li> <img src="images/javascript.svg" alt="javascript"> </li> </ul> </div> </div> </div> </div> </section> <section class="about" id="about"> <div class="about-container"> <div class="about-content"> <div class="img-side"> <img src="images/idk.jpg" alt="code" class="img-side__main-img"> </div> <div class="text-side"> <h3>About Me</h3> <h4>A dedicated Full Stack Developer<br>based in San Jose, California 📍</h4> <p>As a passionate computer science student at San Diego State, my journey into the world of technology is driven by a relentless curiosity and a commitment to continuous learning. With a solid foundation in Java, HTML, CSS, JavaScript, and Python, I thrive on the challenges of full-stack development. Beyond coding, my enthusiasm extends to problem-solving and creating innovative solutions. Eager to contribute my skills to real-world projects, I am dedicated to refining my abilities and embracing new technologies on the exciting path toward becoming a versatile and proficient developer. </p> </div> </div> </div> </section> <section class="projects" id="projects"> <div class="project-container"> <div class="project-content"> <p>Portfolio</p> <h3>Each project is a unique piece of development 🧩</h3> <div class="projects-grid"> <div class="pro pro__1 undefined"> <div class="pro__img"> <img src="images/v4.png" alt="website"> </div> <div class="pro__text"> <h3>WorkoutWizard<span class="date-class">(November 2023)</span>🏋️</h3> <p>An innovative web application that utilizes artificial intelligence to dynamically create personalized workout routines tailored to users' preferences and specific fitness goals</p> <div class="stack"> <p>HTML</p> <p>CSS</p> <p>JavaScript</p> </div> <div class="links"> <a href="https://github.com/tommycomeau3" target="_blank"> Code <i class="fa-solid fa-code"></i> </a> <a href="https://github.com/" target="_blank"> Live Demo <i class="fa-regular fa-share-from-square"></i> </a> </div> </div> </div> </div> </div> </div> </section> <section class="contact" id="contact"> <div class="contact-container"> <div class="contact_content"> <div class="contact_title"> <p>contact</p> <h3>Don't be shy! Hit me up! 👇</h3> </div> <div class="contact_icons"> <div class="contact_icon-box"> <span> <i class="fa-solid fa-location-dot dot"></i> </span> <div class="contact_info"> <h3>Location</h3> <p>San Jose, California</p> </div> </div> <div class="contact_icon-box"> <span> <i class="fa-regular fa-envelope mail"></i> </span> <div class="contact_info"> <h3>Mail</h3> <a href="mailto:tommycomeau28@gmail.com">tommycomeau28@gmail.com</a> </div> </div> </div> </div> </div> </section> <footer> <div class="footer-container"> <div class="footerc"> <h3>Copyright © 2023. All rights are reserved</h3> <div class="footerc_socials"> <a class="icon" href="https://www.linkedin.com/?trk=seo-authwall-base_nav-header-logo" target="_blank"><ion-icon name="logo-linkedin"></ion-icon></a> <a class="icon" href="https://github.com/tommycomeau3" target="_blank"><ion-icon name="logo-github"></ion-icon></a> </div> </div> </div> </footer> <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script> <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script> </body> </html>
<%= form_with(model: text) do |form| %> <% if text.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(text.errors.count, "error") %> prohibited this text from being saved:</h2> <ul> <% text.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= form.label :intro_title %> <%= form.text_field :intro_title %> </div> <div class="field"> <%= form.label :intro_description %> <%= form.text_area :intro_description %> </div> <div class="field"> <%= form.label :portfolio_title %> <%= form.text_field :portfolio_title %> </div> <div class="field"> <%= form.label :aboutme_title %> <%= form.text_field :aboutme_title %> </div> <div class="field"> <%= form.label :aboutme_description %> <%= form.text_area :aboutme_description %> </div> <div class="field"> <%= form.label :resume_link %> <%= form.text_field :resume_link %> </div> <div class="field"> <%= form.label :contact_title %> <%= form.text_field :contact_title %> </div> <div class="field"> <%= form.label :contact_description %> <%= form.text_field :contact_description %> </div> <div class="field"> <%= form.label :analytics %> <%= form.text_field :analytics %> </div> <div class="actions"> <%= form.submit %> </div> <% end %>
import React, { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import { useForm } from "react-hook-form"; import { Button, Checkbox, Form, Input, message, Select } from "antd"; import { getCategories } from "../../../api/category"; interface IProduct { id: number; name: string; price: string; desc: string; link: string; } interface ICategory { id: number; name: string; } interface IProps { onAdd: (product: IProduct) => void; categories: ICategory[]; } const AddProductPage = (props: IProps) => { const [categories, setCategories] = useState<ICategory[]>([]); const navigate = useNavigate(); useEffect(() => { getCategories() .then((response) => { setCategories(response.data); }) .catch((error) => { console.error(error); }); }, []); const onFinish = (values: any) => { console.log(values); props.onAdd(values); navigate("/admin/products"); message.success("Thêm sản phẩm thành công!", 2); }; const onFinishFailed = (errorInfo: any) => { console.log("Failed:", errorInfo); }; return ( <div> <Form name="basic" labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} style={{ width: 600, margin: "0 auto" }} initialValues={{ remember: true }} onFinish={onFinish} onFinishFailed={onFinishFailed} autoComplete="off" > <Form.Item label="Product Name" name="name" rules={[{ required: true, message: "Vui lòng nhập tên sản phẩm!" }]} > <Input /> </Form.Item> <Form.Item label="Product Link" name="link" rules={[{ required: true, message: "Vui lòng nhập link sản phẩm!" }]} > <Input /> </Form.Item> <Form.Item label="Product Description" name="desc" rules={[{ required: true, message: "Vui lòng nhập mô tả sản phẩm!" }]} > <Input /> </Form.Item> <Form.Item label="Product IMG" name="img" // rules={[{ required: true, message: "Vui lòng nhập mô tả sản phẩm!" }]} > <Input /> </Form.Item> <Form.Item label="Category" name="categoryID" // rules={[{ required: true, message: 'Vui lòng chọn danh mục!' }]} > <Select> {categories && categories.map((category) => ( <Select.Option key={category._id} value={category._id}> {category.name} </Select.Option> ))} </Select> </Form.Item> <Form.Item wrapperCol={{ offset: 8, span: 16 }}> <Button type="primary" htmlType="submit"> Thêm sản phẩm </Button> </Form.Item> </Form> </div> ); }; export default AddProductPage;
# Metatags I wrote this out of annoyance at all the other metatag generation gems there are out there. They all, or all that I could find, either mess the attributes you're providing or limit the tags that you can create. What the hell? I just want to create some open graph tags. Use add_meta and pass a hash of whatever attributes you want the metatag to have. The attributes are passed to Rails' tag helper to generate the meta tag. Simples. In your Gemfile... ```ruby gem 'metatags' ``` In your controller... ```ruby add_meta :property => 'og:title', :content => 'Lorem Ipsum' ``` In your layout... ```ruby <%= metatags %> ``` What you get... ``` <meta content="Lorem Ipsum" property="og:title" /> ``` #Lazy evaluation You can optionally pass a block to add_meta which will be evaluated in context of the view, this is useful when you need to access view helpers. ```ruby add_meta { {:property => 'og:image', :content => path_to_image('image.jpg')} } ``` This could also be written like: ```ruby add_meta({:property => 'og:image'}) { {:content => path_to_image('image.jpg')} } ``` The hash returned from the block gets merged with the set of attributes passed to the method.
# # This script was written by Tenable Network Security # # This script is released under Tenable Plugins License # desc["english"] = " Synopsis : Access the remote Windows Registry. Description : It was possible to access the remote Windows Registry using the login / password combination used for the Windows local checks (SMB tests). Risk factor : None"; desc_bad["english"] = " Synopsis : Access the remote Windows Registry. Description : It was not possible to connect to PIPE\winreg on the remote host. If you intend to use Nessus to perform registry-based checks, the registry checks will not work because the 'Remote Registry Access' service (winreg) has been disabled on the remote host or can not be connected to with the supplied credentials. Risk factor : None"; if(description) { script_id(10400); script_version ("$Revision: 1.30 $"); #script_bugtraq_id(6830); #script_cve_id("CVE-1999-0562"); name["english"] = "SMB accessible registry"; script_name(english:name["english"]); script_description(english:desc["english"]); summary["english"] = "Determines whether the remote registry is accessible"; script_summary(english:summary["english"]); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2005 Tenable Network Security"); family["english"] = "Windows"; script_family(english:family["english"]); script_dependencies("netbios_name_get.nasl", "smb_login.nasl"); script_require_keys("SMB/transport", "SMB/name", "SMB/login", "SMB/password"); script_exclude_keys("SMB/samba"); script_require_ports(139, 445); exit(0); } include("smb_func.inc"); port = get_kb_item("SMB/transport"); if(!port)port = 139; name = kb_smb_name(); if(!name)exit(0); login = kb_smb_login(); pass = kb_smb_password(); domain = kb_smb_domain(); port = kb_smb_transport(); if ( ! get_port_state(port) ) exit(0); soc = open_sock_tcp(port); if ( ! soc ) exit(0); logged = 0; session_init(socket:soc, hostname:name); r = NetUseAdd(login:login, password:pass, domain:domain, share:"IPC$"); if ( r == 1 ) { hklm = RegConnectRegistry(hkey:HKEY_LOCAL_MACHINE); if (! isnull(hklm) ) { RegCloseKey (handle:hklm); logged = 1; } NetUseDel(); } if (logged == 0) { security_note (port:port, data:desc_bad["english"]); } else { security_note (port); set_kb_item(name:"SMB/registry_access", value:TRUE); }
package com.project.board.post.controller; import com.project.board.post.dto.request.PostCreateRequestDto; import com.project.board.post.dto.request.PostGetListRequestDto; import com.project.board.post.dto.request.PostUpdateRequestDto; import com.project.board.post.dto.response.PostCreateResponseDto; import com.project.board.post.dto.response.PostGetListResponseDto; import com.project.board.post.dto.response.PostGetOneResponseDto; import com.project.board.post.service.PostService; import lombok.RequiredArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import jakarta.validation.Valid; import java.net.URI; @RestController @RequiredArgsConstructor public class PostController { private final PostService postService; @PostMapping("/posts") public ResponseEntity<Void> createPost(@RequestBody @Valid PostCreateRequestDto requestDto) { PostCreateResponseDto responseDto = postService.createPost(requestDto); URI location = ServletUriComponentsBuilder .fromCurrentRequest() .path("/{postId}") .buildAndExpand(responseDto.getCreatedId()) .toUri(); return ResponseEntity.created(location).build(); } @GetMapping("/posts") public ResponseEntity<PostGetListResponseDto> getPostList(PostGetListRequestDto requestDto) { return ResponseEntity.ok(postService.getPostList(requestDto)); } @GetMapping("/posts/{postId}") public ResponseEntity<PostGetOneResponseDto> getPost(@PathVariable Long postId) { return ResponseEntity.ok(postService.getPost(postId)); } @PatchMapping("/posts/{postId}") public ResponseEntity<Void> updatePost(@PathVariable Long postId, @RequestBody @Valid PostUpdateRequestDto requestDto) { postService.updatePost(postId, requestDto); return ResponseEntity.ok().build(); } @DeleteMapping("/posts/{postId}") public ResponseEntity<Void> deletePost(@PathVariable Long postId) { postService.deletePost(postId); return ResponseEntity.noContent().build(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Nunito&display=swap" rel="stylesheet"> <link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.14.0/css/all.css" integrity="sha384-HzLeBuhoNPvSl5KYnjx0BT+WB0QEEqLprO+NBkkk5gbc67FTaL7XIGa2w1L0Xbgc" crossorigin="anonymous" /> <title>AISHA CLOTHING</title> </head> <body> <nav class="nav__bar"> <div class="nav__container"> <a href="#home" id="nav__logo">AISHA</a> <div class="nav__toggle" id="mobile__menu"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </div> <ul class="nav__menu"> <li class="navbar__item"> <a id="home-page" href="#home" class="nav__link">Home<a></li> <li class="navbar__item"> <a id="products-page" href="#products" class="nav__link">Product</a></li> <li class="navbar__item"> <a id="contact-page" href="#contacts" class="nav__link">Contacts</a></li> <li class="navbar__item"> <a id="about-page" href="#about" class="nav__link">About</a></li> <li class="navbar__btn"> <a id="signup" href="#sign-up" class="btn">Sign Up</a> </li> </ul> </div> </nav> <!-- hero section --> <div class="hero" id="home"> <div class="hero__container"> <h1 class="hero__heading">Choose Your <span>Colors</span></h1> <p class="hero__description">Unlimited Possibilities</p> <button class="main__btn__heroserction"><a href="#">Explore</a></button> </div> </div> <!-- About Section --> <div class="main" id="about"> <div class="main__container"> <div class="main__img__container"> <div class="main__img__card"> <i class="fas fa-layer-group"></i> </div> </div> <div class="main__content"> <h1>What do we do ? </h1> <h2>We Help Businesses Scale</h2> <p>Schedule a call to learn more about our services</p> <button class="main__btn"><a href="#">Schedule Call</a></button> </div> </div> </div> <!-- Services section --> <div class="services" id="services"> <h1>Our services </h1> <div class="services_wrapper"> <div class="services__card"> <h2>Customer Colorways</h2> <p>AI Power Technology</p> <div class="services__btn"> <button>Get Started</button> </div> </div> <div class="services__card"> <h2>Are you Ready</h2> <p>Take the Lepa</p> <div class="services__btn"> <button>Get Started</button> </div> </div> <div class="services__card"> <h2>Infinite Choices</h2> <p>1000`s of Colors </p> <div class="services__btn"> <button>Get Started</button> </div> </div> </div> </div> <!-- Features Section --> <div class="main" id="sign-up"> <div class="main__container"> <div class="main__content"> <h1>Join Our Team</h1> <h2>Sign Up Today</h2> <p>See What Makes us Diferent</p> <button class="main__btn"><a href="#">Signup</a></button> </div> <div class="main__img__container"> <div class="main__img__card" id="card-2"> <i class="fas fa-users"></i> </div> </div> </div> </div> <div class="footer__container"> <div class="footer__links"> <div class="footer__link__wrapper"> <div class="footer_link_items"> <h2>About Us</h2> <a href="/sign__up">How it works</a> <a href="/">Testimonials</a> <a href="/">Careers</a> <a href="/">Terms of Service</a> </div> <div class="footer_link_items"> <h2>Contacts Us</h2> <a href="/">Contact</a> <a href="/">Support</a> <a href="/">Destinations</a> </div> </div> <div class="footer__link__wrapper"> <div class="footer_link_items"> <h2>Videos</h2> <a href="/">Submit Video</a> <a href="/">Ambassadors</a> <a href="/">Agency</a> </div> <div class="footer_link_items"> <h2>Social Media</h2> <a href="/">Instagram</a> <a href="/">Facebook</a> <a href="/">Youtube</a> <a href="/">Twitter</a> </div> </div> <section class="social__media"> <div class="social__media__wrap"> <div class="footer__logo"> <a href="/" id="footer__logo">AISHA</a> </div> <p class="website__rights">&copy; AISHA 2021. All Rights Reserved </p> <div class="social__icons"> <a href="" class="social__icon__link" target="_blank"> <i class="fab fa-facebook"></i></a> <a href="" class="social__icon__link" target="_blank"> <i class="fab fa-youtube"></i></a> <a href="" class="social__icon__link" target="_blank"> <i class="fab fa-instagram"></i></a> <a href="" class="social__icon__link" target="_blank"> <i class="fab fa-twitter"></i></a> </div> </div> </section> </div> </div> <script src="app.js"></script> </body> </html>
import {View} from 'react-native'; import type {Meta, StoryObj} from '@storybook/react'; import {MyButton} from './Button'; const MyButtonMeta: Meta<typeof MyButton> = { title: 'MyButton', component: MyButton, argTypes: { onPress: {action: 'pressed the button'} }, args: { text: 'Hello world' }, decorators: [ Story => ( <View style={{alignItems: 'center', justifyContent: 'center', flex: 1}}> <Story /> </View> ) ] }; export default MyButtonMeta; export const Basic: StoryObj<typeof MyButton> = {}; export const AnotherExample: StoryObj<typeof MyButton> = { args: { text: 'Another example' } };
import { Card, CardBody, Col, Row } from "reactstrap"; import Chart from "../../common_component/charts"; function Dashboard() { const data = [ { value: 1048, name: "Flexi Cap Fund 32.19%", color: "#75d6ff" }, { value: 735, name: "Small Cap Fund 26.40%", color: "#75ffff" }, { value: 580, name: "Sectoral Fund 26.40%", color: "#aa75ff" }, { value: 484, name: "ELSS 26.04%", color: "#ff7bf2" }, { value: 300, name: "Large & Mid Cap Fund 12.03%", color: "#ffd875" }, { value: 300, name: "Index Fund 12.03%", color: "#ffc46a" }, ]; const data1 = [ [ { name: "Flexi Cap Fund 32.19%", value: 30, itemStyle: { color: "#75d6ff", }, }, { name: "Small Cap Fund 26.40%", value: 50, itemStyle: { color: "#aa75ff", }, }, { name: "Sectoral Fund 26.40%", value: 80, itemStyle: { color: "#ff7bf2", }, }, ], [ { name: "ELSS 26.04%", value: 70, itemStyle: { color: "#75ffff", }, }, { name: "Large & Mid Cap Fund 12.03%", value: 50, itemStyle: { color: "#fc8c5c", }, }, { name: "Index Fund 12.03%", value: 20, itemStyle: { color: "#ffc46a", }, }, ], ]; return ( <> <Card className="mt-4 mx-4"> <CardBody> <Row> <Col md="4" sm="12" className="mb-4"> <Chart chartName="CategoryPieChart" title="Sub-Category" description="The assets are distributed between equity and cash & equivalents." data={data} /> </Col> <Col md="4" sm="12" className="mb-4"> <Chart chartName="DistributionLineChart" title="Fund Distribution" description="A mutual fund distribution represents the earnings of a fund being passed on to the individual investor or unit holder of the fund." data={data} /> </Col> <Col md="4" sm="12" className=""> <Chart chartName="SectorTreeChart" title="Top Sectors" description="The assets are distributed between equity and cash & equivalents." data={data1} /> </Col> </Row> </CardBody> </Card> </> ); } export default Dashboard;
import os import pickle from PIL import Image import numpy as np import torch from torch.utils.data import Dataset from torchvision import transforms ROOT_PATH = './data/tiered-imagenet-kwon' class TieredImageNet(Dataset): def __init__(self, split='train', size=84, transform=None): split_tag = split data = np.load(os.path.join( ROOT_PATH, '{}_images.npz'.format(split_tag)), allow_pickle=True)['images'] data = data[:, :, :, ::-1] with open(os.path.join( ROOT_PATH, '{}_labels.pkl'.format(split_tag)), 'rb') as f: label = pickle.load(f)['labels'] data = [Image.fromarray(x) for x in data] min_label = min(label) label = [x - min_label for x in label] self.data = data self.label = label self.n_classes = max(self.label) + 1 if transform is None: if split in ['train', 'trainval']: self.transform = transforms.Compose([ transforms.Resize(size+12), transforms.RandomCrop(size, padding=8), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) else: self.transform = transforms.Compose([ transforms.Resize(size), transforms.CenterCrop(size), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) else: self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, i): return self.transform(self.data[i]), self.label[i] class SSLTieredImageNet(Dataset): def __init__(self, split='train', args=None): split_tag = split data = np.load(os.path.join( ROOT_PATH, '{}_images.npz'.format(split_tag)), allow_pickle=True)['images'] data = data[:, :, :, ::-1] with open(os.path.join( ROOT_PATH, '{}_labels.pkl'.format(split_tag)), 'rb') as f: label = pickle.load(f)['labels'] data = [Image.fromarray(x) for x in data] min_label = min(label) label = [x - min_label for x in label] self.data = data self.label = label self.n_classes = max(self.label) + 1 color_jitter = transforms.ColorJitter(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1) self.augmentation_transform = transforms.Compose([transforms.RandomResizedCrop(size=(args.size, args.size)[-2:], scale=(0.5, 1.0)), transforms.RandomHorizontalFlip(p=0.5), transforms.RandomVerticalFlip(p=0.5), transforms.RandomApply([color_jitter], p=0.8), transforms.RandomGrayscale(p=0.2), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) # self.identity_transform = transforms.Compose([ transforms.Resize(args.size), transforms.CenterCrop(args.size), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) def __len__(self): return len(self.data) def __getitem__(self, i): img, label = self.data[i], self.label[i] image = [] for _ in range(1): image.append(self.identity_transform(img).unsqueeze(0)) for i in range(3): image.append(self.augmentation_transform(img).unsqueeze(0)) return dict(data=torch.cat(image)), label
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>putty - ai</title> <link rel="stylesheet" type="text/css" href="css/styles.css"> </head> <body> <header> <div class="navbar"> <nav> <a href="index.html">putty-ai</a> <a href="#about">about</a> <a href="#artists">artists</a> <a href="#contact">contact</a> </nav> </div> <div class="container"> <div class="row"> <div id="top-pic"> <img src="assets/puttyai.png" alt="logo"> </div> </div> </div> </header> <div class="image-container"> <img id="dynamicImage" src="assets/banner/1.png" alt="banner"> </div> <div id="about" class="hero"> <div> <h1>accelerating art and design with emerging technologies</h1> <p> in the past four years, we have witnessed a significant surge in image generation. pioneers like openai and midjourney have captivated the world with their innovations, demonstrating the vast potential of ai in creative fields. intrigued by these advancements, artists have eagerly adopted these tools, aiming to accelerate and enhance their creative processes. however, while initially impressive, many artists soon realize that these services, in their pursuit of universal applicability, often fall short in addressing the unique and diverse needs of individual creators. we are here to help.<br><br>recognizing that creativity is not a one-size-fits-all endeavor, our mission is to bridge the gap between the artist and image generation, ensuring that this powerful tool aligns perfectly with your vision and artistic process. <br><br>we collaborate closely with artists, crafting fine-tuned, bespoke models that not only resonate with their individual style but also amplify their creative potential. at putty-ai, we offer more than a service; we provide a partnership. a partnership where your artistic vision is central, and our technology is the means to realize it. this is not about replacing the artist's touch; it's about enhancing it with ai that understands and adapts to your unique style and needs. come see how we can assist you in harnessing this emerging technology. </p> </div> </div> <div id="artists" class="hero"> <div> <a href="#artists" onclick="changeImage('suki-iitsu'); return false;"><h1>suki iitsu</h1></a> <br> <a href="#artists" onclick="changeImage('dee-williams'); return false;"><h1>dee williams</h1></a> <br> <a href="#artists" onclick="changeImage('robert-dowel'); return false;"><h1>robert dowel</h1></a> <br> <a href="#artists" onclick="changeImage('spacecat'); return false;"><h1>spacecat</h1></a> <br> <a href="#artists" onclick="changeImage('raoul-agnel'); return false;"><h1>raoul agnel</h1></a> <br> </div> <div> <img id="workImage" src="assets/suki-iitsu/1.png" alt="work" onclick="nextImage()"> </div> </div> <div class="hero"> <div> <br><br><br> <a href="faq.html"><h1>click here to learn more</h1></a> <br> </div> </div> <div id="contact" class="hero"> <div> <h1>contact</h1> <br> <h3>email <br> putty-ai@proton.me</h3> <h3>x <br><a href="https://x.com/putty_ai">putty_ai</a></h3> </div> </div> <script> var currentArtist = 'suki-iitsu'; var currentImage = 1; var totalImages = 4; // Update this to the total number of images per artist function changeImage(artistName) { currentArtist = artistName; currentImage = 1; // Reset to the first image updateImage(); } function nextImage() { currentImage++; if (currentImage > totalImages) { currentImage = 1; // Loop back to the first image } updateImage(); } function updateImage() { var imagePath = "assets/" + currentArtist + "/" + currentImage + ".png"; document.getElementById("workImage").src = imagePath; } document.addEventListener('DOMContentLoaded', function() { var currentImage = 1; var totalImages = 10; // Total number of images you have (1.png to 5.png) setInterval(function() { currentImage++; if (currentImage > totalImages) { currentImage = 1; // Reset to first image } document.getElementById('dynamicImage').src = 'assets/banner/' + currentImage + '.png'; }, 2500); }); </script> </body> </html>
#pragma once #include "Sprite.h" #include "FrameCounter.h" /** * @file SelectCursor.h * @brief 選択中のカーソルを表示やアニメーションさせるためのファイル */ class SelectCursor { public: /** * @fn Initialize() * 初期化関数 */ void Initialize(); /** * @fn LoadResources() * リソース読み込み用関数 */ void LoadResources(); /** * @fn Update() * 更新処理関数 */ void Update(); /** * @fn Draw() * 描画処理関数 */ void Draw(); private: bool isActive_ = true; MNE::Sprite cursor_; const int32_t ANIME_TIME = 40; MNE::FrameCounter counter_; MyMath::Vector2D minSize_; MyMath::Vector2D maxSize_; // 選択中のモノのサイズ MyMath::Vector2D gapSize_ = MyMath::Vector2D(10.0f, 10.0f); int32_t easePawNum_ = 2; private: /** * @fn AnimationUpdate() * 拡縮アニメーション用更新処理関数 */ void AnimationUpdate(); public: #pragma region Setter /** * @fn SetCursorPosition(const Vector2D&, bool) * カーソルの表示位置変更用関数 * @param pos 選択位置の中心座標 * @param playMoveSound 移動音再生するか */ void SetCursorPosition(const MyMath::Vector2D& pos, bool playMoveSound = true); /** * @fn SetSize(const Vector2D&) * 選択中のモノのサイズ変更用関数 * @param size 選択中のモノのサイズ */ void SetButtonSize(const MyMath::Vector2D& size); /** * @fn SetIsActive(bool) * isActive_変更用関数 * @param isActive isActive変更後の値 */ void SetIsActive(bool isActive); #pragma endregion };
<head> <title>Wikinotes</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.0.0/semantic.min.css" /> <link rel="stylesheet" href="/static/styles.css" /> <meta name="viewport" content="width=device-width"> <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"> </script> <script type="text/x-mathjax-config"> MathJax.Hub.Config({ TeX: { extensions: ['cancel.js'] }, tex2jax: { inlineMath: [ ['$', '$'] ], processEscapes: true } }); </script> </head> <body> <div id="header" class="ui container"> <a href="/"> <img src="/static/img/logo-header.png" class="ui image" /> </a> </div> <div id="content"> <div class="ui container"> <div class="ui container"> <div class="ui secondary segment"> <div class="ui large breadcrumb"> <a class="section" href="/">Home</a> <i class="right chevron icon divider"></i> <a class="section" href="/GEOG_205/"> GEOG 205 </a> <i class="right chevron icon divider"></i> <span class="active section"> Wednesday, April 4, 2012 </span> </div> </div> <h1 class="ui header"> <div class="content"> Wednesday, April 4, 2012 <span> <a href="http://creativecommons.org/licenses/by-nc/3.0/"> <img src="/static/img/cc-by-nc.png" alt="CC-BY-NC" title="Available under a Creative Commons Attribution-NonCommercial 3.0 Unported License" /> </a> </span> <div class="sub header"> Lecture 24 </div> </div> </h1> <div class="ui icon list"> <div class="item"> <i class="user icon"></i> <div class="content"> <strong>Maintainer:</strong> admin </div> </div> </div> <div class="ui divider"></div> <div id="wiki-content"> <p>Terrestrial Vegetation Influences the Climate</p> <p>• The presence and characteristics of vegetation have a substantial impact on the climate, at all spatial scales: Locally, we can feel it, Regionally, empirical data shows it<br /> • The presence and characteristics of vegetation are not fixed, but constantly changing: naturally (ex: leaves fall from deciduous trees), due to human actions (ex: deforestation)<br /> • Dynamic Global Vegetation Models (DGVM) are the most advanced tools to simulate the two-way interactions between climate and terrestrial vegetation (two-way relationship)<br /> • DGVM Simulate<br /> • Quantities Computed by DGVM: carbon balance (take in CO2, give off O2, die and decompose), energy balance (some energy from the sun is reflected back), water balance (plants use roots to pump water from soil and transpire it back into atmosphere through leaves)<br /> • Purpose of DGVM is to compute two categories of variables: land-atmosphere exchanges (fluxes) and the status of different vegetation elements (ex: stocks) </p> <p>IBIS: Integrated Biosphere Simulator Model<br /> • IBIS: one of the many DGVM’s (integrated biosphere simulator model): wind speed, air humidity, precipitation<br /> • Hourly: Upper Canopy Transpiration <br /> • Daily: Snow Depth 1965-1966<br /> • Monthly: Upper Canopy Leaf Cover: January (Canada)<br /> • Canopy: Competition amoung vegetation for sunlight<br /> • Biomass: total mass of trees, shrubs, ect<br /> • Yearly: Total Biomass: After 1 Year (Canada), Remove all vegetation and then let it compete and grow, Light blue: small amount of vegetation, light blue: zero vegetation<br /> • After 5 Years, 25 Years: prairies (SW Canada) biomass is decreasing because it is so dry (grasses are thriving but they don’t weigh a lot), 50 years forests are maturing, 100 years see the same biomass pattern we see today in Canada, after 100 years the results don’t change that much if the climates remain constant<br /> • Huge trees and forests in BC are not shown in IBIS…because there was oversimplification when IBIS was made, they did not include certain kinds of trees in the program (huge coniferous trees which accumulate a lot of biomass over a long period of time)</p> <p>Research Questions Addressed with DGVM<br /> • Do boreal forests cool or warm the global climate? Carbon cycle cools the global climate, but vegetation also influences the climate in other ways. Reflection of solar radiation because of snow cover in the boreal region (albedo) warming effect<br /> • How fire and insect outbreaks might impact forests in the future?<br /> • What about crops productivity? How climate change will affect crops? Biofuel crops and essential crops (rice, wheat). Using DGVM to find impact of biofuels</p> <p>The Take Home Message<br /> • Climate models need to account for terrestrial vegetation<br /> • DGVM are sufficiently elaborate and accurate to: estimate the main land-atmosphere fluxes, and study some of the impact of climate on vegetation stocks<br /> • Many elements are not (well) represented yet…</p> <p>Permafrost Thaw Sensitivity: Detection and Assessment<br /> • Permafrost covers 50% of Canada</p> <p>Ground Ice in Permafrost<br /> • Massive ice at a thaw slump, half meter of soil and ice goes down 20 meters into the ground<br /> • Ice wedges<br /> • Ice lenses: thin strips of ice separated by soil<br /> • Massive ice core: moisture content of 250% and thickness of greater than 2 meters – amount of moisture exceeds saturation point<br /> • Building on top of ice can cause building, pipeline, and road problems<br /> • Can lift it above ground so warm oil doesn’t affect temperature of soil</p> <p>What Causes Permafrost Degration?<br /> • Geomorphic: excavating and removing insulating layers<br /> • Vegetation: impact amount of snow on surface, snow can buffer surface from atmosphere, peat changes thermo properties throughout year (quite colder compared to other terrains)<br /> • Climatic: climate changes</p> <p>Ground Thermal Regime<br /> • Trumpet<br /> • Diagonal line on bottom dictated from heat emanated from Earth’s core<br /> • Reach a point close enough to the surface, affected by surface heat<br /> • Sub-surface is no longer affected by weather patterns at surface<br /> • Permafrost starts at the depth at which the maximum temperature for the year is 0 C<br /> • Can have various shapes depending on type of environment we are in<br /> • Wide trumpet: area where there is a large temperature variation over an entire year<br /> • Snow would warm the permafrost because it is thermal insulation<br /> • Area with snow is much more suspectible to permafrost degradation</p> <p>How do we detect ground ice?<br /> • Coring<br /> • Drilling is expensive, time-consuming, and only provides point samples<br /> • Understanding conditions between boreholes is unreliable in areas of high variability<br /> • Geophysical investigations allow for cheap and rapid data acquisition in an environmentally-friendly manner<br /> • Ground-penetrating radar: when it encounters a boundary, a reflection is generated and it is captured by the receiver; done at multiple depths; can get a 2-D picture of subsurface structure; doesn’t tell you what the material is, just its geometry<br /> • Electrical resistivity: see how resistive different materials are; can adjust spacing between transmitter and receiver; the further away they are the deeper you can go</p> <p>Case Study at Parsons Lake, NWT<br /> • A lot of natural gas<br /> • Key site for proposed Mackenzie valley pipeline, 1500 km pipeline from North Canada to Southern Alberta<br /> • Objectives:<br /> • Construct thermal models that predict ground temperatures recorded in 2004<br /> • Project maximum active layer thickness (MALT) changes from 2011-2070<br /> • Access the spatial applicability of the MALT projections between the boreholes using geophysical data<br /> • Is it worth it to drill? Will the ice melt and water run??<br /> • Thermal Modelling Strategy: examine core at specific interval, assess unfrozen water content and melting temperature (fine grain materials can hold water below 0 C)<br /> • Want to know how much unfrozen water content you have at a specific temperature<br /> • Heat capacities of materials to parameterize layers<br /> • Geothermal heat flux: energy coming from the earth’s core<br /> • Pool information together, run model, see what we get (able to generate pretty accurate results)<br /> • Results vary due to amount of snowcover – have a good regional estimate of average snowcover<br /> • Silty clay causes ice to melt faster<br /> • Encountered massive ice body: <br /> • A lot of energy required for phase change in ice</p> <p>Key Conclusions from Case Study<br /> • 1D thermal models are accurate, we are confident in how the materials were parameterized, minimal lateral heat flow<br /> • anticipated climate warming effects (2011-2070): MALT will increase by a factor of 3 for the silty clay underlain by gravelly sand<br /> • Geophysics: the gravelly sand pocket is 90m in length and is therefore not insignificant, results shoe that multi-dimensional models are needed for long-term projections</p> </div> </div> </div> </div> <div id="footer" class="ui container"> <div class="ui stackable grid"> <div class="twelve wide column"> <p> Built by <a href="https://twitter.com/dellsystem"> @dellsystem</a>. Content is student-generated. <a href="https://github.com/dellsystem/wikinotes">See the old codebase on GitHub</a> </p> </div> <div class="four wide right aligned column"> <p><a href="#header">Back to top</a></p> </div> </div> </div> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-28456804-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
<template> <q-page> <q-card flat :class="{ 'big-margin': isDesktop }" class="first-card"> <q-card-section class="text-center"> <MainLogo /> <h1 class="text-primary text-weight-bold">{{ appName }}</h1> Любите читать? Смотреть фильмы?<br /> Храните свою личную историю?<br /> Строите планы на жизнь?<br /> Приложение «{{ appName }}» поможет вам делать это<br /> ещё более эффективно! <br /> С его помощью можно структурировать, систематизировать,<br /> выстраивать связи для большого количества сущностей. <br /> Приложение помогает планировать развитие, следить за собственным прогрессом, и даже - при желании - делиться им с другими участниками!<br /> Не переключайтесь, просто попробуйте! </q-card-section> <q-card-section class="text-center"> <LinkToLoginPage class="q-mb-sm" :is-show-always="false" /> <LinkToRegisterPage class="q-ml-sm q-mb-sm" :is-show-always="false" /> </q-card-section> </q-card> <q-card flat class="q-mb-xl"> <q-card-section horizontal> <q-card-section> <strong class="text-primary">Библиотека</strong> - это раздел для хранения списка прочитанных книг. <br /> Список ранжируется по годам прочтения, структурируется по авторам, тематикам, актуальности и значимости для Вас лично, а также по многим другим параметрам. <div class="row"> <q-btn type="a" outline no-caps size="md" icon-right="chevron_right" :to="helpLibsLink" class="q-pr-sm q-mt-sm text-primary" > Узнать больше </q-btn> </div> </q-card-section> <q-card-section class="q-px-lg"> <q-avatar size="125px" font-size="70px" color="primary" text-color="white" icon="o_library_books" /> </q-card-section> </q-card-section> </q-card> <q-card flat class="q-mb-xl"> <q-card-section horizontal> <q-card-section class="q-px-lg"> <q-avatar size="125px" font-size="70px" color="orange-9" text-color="white" icon="o_movie" /> </q-card-section> <q-card-section> <strong class="text-orange-9">Фильмотека</strong> - это раздел для хранения списка просмотренных фильмов, и других видеоматериалов. <br /> Список ранжируется по годам просмотра и выпуска, структурируется по авторам, актёрам, режиссёрам, жанрам, и так далее. <div class="row"> <q-btn type="a" outline no-caps size="md" icon-right="chevron_right" :to="helpFilmsLink" class="q-pr-sm q-mt-sm text-orange-9" > Узнать больше </q-btn> </div> </q-card-section> </q-card-section> </q-card> <q-card flat class="q-mb-xl"> <q-card-section horizontal> <q-card-section> <strong class="text-red-8">Картотека</strong> - это раздел для хранения ваших личных данных. <br /> Вместо разрозненных записей на бумаге, в блокноте, или даже в электронном виде, вы можете объединить данные из всех сфер своей жизни в одном месте, без боязни утечки, или потери информации. <br /> Всё что от вас требуется - это правильно их структурировать, и вовремя актуализировать. <div class="row"> <q-btn type="a" outline no-caps size="md" icon-right="chevron_right" :to="helpCardsLink" class="q-pr-sm q-mt-sm text-red-8" > Узнать больше </q-btn> </div> </q-card-section> <q-card-section class="q-px-lg"> <q-avatar size="125px" font-size="70px" color="red-8" text-color="white" icon="o_dashboard_customize" /> </q-card-section> </q-card-section> </q-card> <q-card flat class="q-mb-xl"> <q-card-section horizontal> <q-card-section class="q-px-lg"> <q-avatar size="125px" font-size="70px" color="teal-8" text-color="white" icon="o_assignment_ind" /> </q-card-section> <q-card-section> <strong class="text-teal-8">Биография</strong> - это раздел для записи и хранения структуры и, при необходимости, деталей Вашей биографии. <br /> Вы можете анализировать свою жизнь, открывать для себя ранее не замеченные связи, выявлять аналогии, оценивать и сравнивать жизненные периоды, заниматься перепросмотром, и многое другое. <br /> Настройками конфиденциальности записанной информации вы управляете сами, гибким и удобным способом. <div class="row"> <q-btn type="a" outline no-caps size="md" icon-right="chevron_right" :to="helpBiosLink" class="q-pr-sm q-mt-sm text-teal-8" > Узнать больше </q-btn> </div> </q-card-section> </q-card-section> </q-card> <q-card flat class="q-mb-xl"> <q-card-section horizontal> <q-card-section> <strong class="text-indigo-7">Планирование</strong> - это раздел для составления списка планов на жизнь. <br /> Вы можете планировать и ставить цели самого разного масштаба - начиная с ежедневных мелочей, продолжая планами на месяц и год, и заканчивая глобальными жизненными целями и мечтами. <br /> Вы - записываете и детализируете планы, а приложение - помогает их воплощать. <div class="row"> <q-btn type="a" outline no-caps size="md" icon-right="chevron_right" :to="helpPlansLink" class="q-pr-sm q-mt-sm text-indigo-7" > Узнать больше </q-btn> </div> </q-card-section> <q-card-section class="q-px-lg"> <q-avatar size="125px" font-size="70px" color="indigo-7" text-color="white" icon="o_moving" /> </q-card-section> </q-card-section> </q-card> </q-page> </template> <script setup> import LinkToLoginPage from "components/LinkToLoginPage.vue"; import LinkToRegisterPage from "components/LinkToRegisterPage.vue"; import MainLogo from "components/MainLogo.vue"; import { computed } from "vue"; import { useQuasar } from "quasar"; import { useRouter } from "vue-router"; /** * Константы. */ const appName = process.env.appName; // Имя приложения /** * Флаг размера экрана. */ const $q = useQuasar(); const isDesktop = computed(() => $q.screen.gt.sm); const router = useRouter(); const helpLibsLink = router.resolve({ name: "help-libs" }).path; const helpFilmsLink = router.resolve({ name: "help-films" }).path; const helpCardsLink = router.resolve({ name: "help-cards" }).path; const helpBiosLink = router.resolve({ name: "help-bios" }).path; const helpPlansLink = router.resolve({ name: "help-plans" }).path; </script> <style scoped lang="sass"> .q-card font-size: 17px &.first-card margin-bottom: 24px !important .q-card__section font-size: 18px .big-margin margin: auto 150px </style>
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class StudentStoreRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'name' => 'required|max:64', 'surname' => 'required|max:64', 'email' => 'required|max:64', 'phone' => 'required|max:32', ]; return $rules; } public function messages() { $messages = [ 'required' => 'Laukelis :attribute privalo buti uzpildytas' ]; return $messages; } }
import React, {useState, useEffect} from 'react'; import {api, getErrorMessage} from 'helpers/api'; import {useHistory} from 'react-router-dom'; import {Button} from 'components/ui/Button'; import 'styles/views/Login.scss'; import BaseContainer from "components/ui/BaseContainer"; import PropTypes from "prop-types"; import {Icon} from '@iconify/react'; import 'styles/views/Code.scss'; import {Alert} from "@mui/material"; import eyeClosedIcon from '@iconify-icons/ph/eye-closed-bold'; import eyeOpenIcon from '@iconify-icons/ph/eye-bold'; const MuteButton = ({ audio }) => { const [isMuted, setIsMuted] = useState(localStorage.getItem("isMuted") === "true" || false); const handleMuteClick = () => { if (isMuted) { audio.volume = 1; // Unmute the audio audio.muted = false; // Unmute the button sound } else { audio.volume = 0; // Mute the audio audio.muted = true; // Mute the button sound } setIsMuted(!isMuted); localStorage.setItem("isMuted", !isMuted); // Store the updated isMuted state in local storage }; useEffect(() => { // Set the initial mute state of the audio and button sound when the component mounts audio.volume = isMuted ? 0 : 1; audio.muted = isMuted; }, [audio, isMuted]); return ( <div className="mute-button" style={{ position: "absolute", top: "92vh", left: "1vw", backgroundColor: "transparent", border: "none" }}> <button onClick={handleMuteClick} style={{ backgroundColor: "transparent", border: "none" }}> {isMuted ? ( <Icon icon="ph:speaker-slash-bold" color="white" style={{ fontSize: '6vh' }} /> ) : ( <Icon icon="ph:speaker-high-bold" color="white" style={{ fontSize: '6vh' }} /> )} </button> </div> ); }; const FormField = props => { const [showPassword, setShowPassword] = useState(false); const handleTogglePassword = () => { setShowPassword(!showPassword); }; return ( <div className="login field"> <label className="login label">{props.label}</label> {props.password ? ( <div className="login password-field"> <input type={showPassword ? 'text' : 'password'} className="login input-password" placeholder={props.placeholder} value={props.value} onChange={e => props.onChange(e.target.value)} onKeyDown={e => props.onKeyPress(e)} /> <div className="login password-toggle" onClick={handleTogglePassword}> <Icon icon={showPassword ? eyeOpenIcon : eyeClosedIcon} color="gray" style={{ fontSize: '4vh'}} /> </div> </div> ) : ( <input type="text" className="login input-username" placeholder={props.placeholder} value={props.value} onChange={e => props.onChange(e.target.value)} onKeyDown={e => props.onKeyPress(e)} /> )} </div> ); }; FormField.propTypes = { label: PropTypes.string, value: PropTypes.string, onChange: PropTypes.func, password: PropTypes.string, onKeyPress: PropTypes.func }; const Login = () => { const history = useHistory(); const [password, setPassword] = useState(null); const [username, setUsername] = useState(null); const [audio] = useState(new Audio('https://drive.google.com/uc?export=download&id=1U_EAAPXNgmtEqeRnQO83uC6m4bbVezsF')); let [alert_message, setAlert_Message] = useState(<div className="login alert-message"></div>); const doLogin = async () => { try { audio.play(); } catch (e) { console.log("Failed to play sound.") } try { const response = await api.get('/users/login?username=' + username + '&pass=' + password); const token = response.headers.token; const id = response.headers.id; localStorage.setItem('token', token); localStorage.setItem('userId', id); localStorage.setItem("username", username); // Login successfully worked --> navigate to the route /game in the GameRouter history.push(`/home`); } catch (error) { let msg = getErrorMessage(error); console.log(msg); setAlert_Message(<Alert className="login alert-message" severity="error"><b>Something went wrong during login:</b> {msg}</Alert>); } }; function handleKeyPress(event) { if(event.key === "Enter" && username && password) { doLogin() } } return ( <BaseContainer> <div className="code left-field"> <Icon icon="ph:eye-closed-bold" color="white" style={{fontSize: '4vw'}}/> </div> <div className="base-container ellipse1"> </div> <div className="base-container ellipse2"> </div> <div className="base-container ellipse3"> </div> <div className="base-container ellipse4"> </div> <MuteButton audio={audio}/> <div className="login container"> <div className="login form"> <div className="login login-title"> Login </div> <FormField type="text" placeholder="Username" value={username} onChange={un => setUsername(un)} onKeyPress={handleKeyPress} /> <FormField password="password" placeholder="*******" value={password} onChange={n => setPassword(n)} onKeyPress={handleKeyPress} /> {alert_message} <div className="login button-container"> <Button className="login-button-loginpage" disabled={!username || !password} onClick={() => doLogin()} > <div className="login login-text"> Login </div> </Button> </div> <div className="login login-line"> </div> <div className="login register-text"> Don’t have an account yet? <a href="/Signup">Sign Up</a> </div> </div> </div> </BaseContainer> ); }; /** * You can get access to the history object's properties via the withRouter. * withRouter will pass updated match, location, and history props to the wrapped component whenever it renders. */ export default Login;
/* * $Id$ */ // $Workfile: ZipFile.h $ // $Archive: /ZipArchive_STL/ZipFile.h $ // $Date$ $Author$ // This source file is part of the ZipArchive library source distribution and // is Copyright 2000-2003 by Tadeusz Dracz (http://www.artpol-software.com/) // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // For the licensing details see the file License.txt #if ! defined( AFX_ZIPFILE_H__80609DE0_2C6D_4C94_A90C_0BE34A50C769__INCLUDED_ ) #define AFX_ZIPFILE_H__80609DE0_2C6D_4C94_A90C_0BE34A50C769__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "zipabstractfile.h" #include "zipstring.h" #include "ZipExport.h" #ifndef __GNUC__ #include <io.h> #else #include <unistd.h> #include <errno.h> #endif #if ( defined( __ICL ) || ( defined( _MSC_VER ) && _MSC_VER >= 1400 ) ) #define close _close #define write _write #define tell _tell #define read _read #define lseek _lseek #define chsize _chsize #endif class ZIP_API CZipFile : public CZipAbstractFile { void ThrowError() const; public: int m_hFile; operator HANDLE(); enum OpenModes { modeRead = 0x0001, modeWrite = 0x0002, modeReadWrite = modeRead | modeWrite, shareDenyWrite = 0x0004, shareDenyRead = 0x0008, shareDenyNone = 0x0010, modeCreate = 0x0020, modeNoTruncate = 0x0040, }; CZipFile( LPCTSTR lpszFileName, UINT openFlags ) { m_hFile = -1; Open( lpszFileName, openFlags, true ); } void Flush(); ZIP_ULONGLONG GetLength() const; CZipString GetFilePath() const { return m_szFileName; } bool IsClosed() const { return m_hFile == -1; } bool Open( LPCTSTR lpszFileName, UINT openFlags, bool bThrow ); void Close() { if( IsClosed() ) return; if( close( m_hFile ) != 0 ) ThrowError(); else { m_szFileName.empty(); m_hFile = -1; } } void Write( const void * lpBuf, UINT nCount ) { if( write( m_hFile, lpBuf, nCount ) != ( int ) nCount ) ThrowError(); } ZIP_ULONGLONG GetPosition() const { #ifndef __GNUC__ long ret = tell( m_hFile ); #else long ret = lseek( m_hFile, 0, SEEK_CUR ); #endif if( ret == -1L ) ThrowError(); return ret; } void SetLength( ZIP_ULONGLONG nNewLen ); UINT Read( void * lpBuf, UINT nCount ) { errno = 0; int ret = read( m_hFile, lpBuf, nCount ); if( ret < ( int ) nCount && errno != 0 ) ThrowError(); return ret; } ZIP_ULONGLONG Seek( ZIP_LONGLONG dOff, int nFrom ) { long ret = lseek( m_hFile, ( long ) dOff, nFrom ); if( ret == -1 ) ThrowError(); return ret; } CZipFile (); virtual ~CZipFile () { Close(); }; protected: CZipString m_szFileName; }; #endif // !defined(AFX_ZIPFILE_H__80609DE0_2C6D_4C94_A90C_0BE34A50C769__INCLUDED_)
#include "../../Google_tests/googletest-main/googletest/include/gtest/gtest.h" #include "pcb.hpp" using namespace PCB_dynamic; TEST(ContactConstructor, Default) { contact c; EXPECT_EQ(0, c.p.x); EXPECT_EQ(0, c.p.y); EXPECT_EQ(0, c.type_contact); } TEST(ContactConstructor, Init) { contact c(1, 2, (type) 1); point p(4, 8); EXPECT_EQ(1, c.p.x); EXPECT_EQ(2, c.p.y); EXPECT_EQ(1, c.type_contact); c = contact(p, (type) 1); EXPECT_EQ(4, c.p.x); EXPECT_EQ(8, c.p.y); EXPECT_EQ(1, c.type_contact); } TEST(ContactConstructor, TestException) { point p; EXPECT_THROW(contact(p, (type) 3), std::invalid_argument); EXPECT_THROW(contact(-1, 2, (type) -1), std::invalid_argument); } TEST(IO, Input) { std::istringstream istr_1("1 1\n0\n"); contact c, c2, c3; c.input_contact(istr_1); EXPECT_EQ(1, c.p.x); EXPECT_EQ(1, c.p.y); EXPECT_EQ(0, c.type_contact); std::istringstream istr_2("1 1\n4\n"); EXPECT_ANY_THROW(c2.input_contact(istr_2)); std::istringstream istr_3("1 a\n0\n"); EXPECT_ANY_THROW(c3.input_contact(istr_3)); } TEST(PCBConstructos, Init) { pcb circ1; contact c, c1(1, 1, (type) 1); EXPECT_EQ(0, circ1.len_()); circ1.add_contact(c), circ1.add_contact(c1); pcb circ2(circ1); EXPECT_EQ(2, circ2.len_()); } // -------- copy and swap idiom -------- // TEST(CopyAndSwap, CopyConstructor) { pcb pcb1, pcb2; pcb1.add_contact(contact (1, 1, input)); pcb2.add_contact(contact (1, 1, input)); pcb pcb3(pcb1); EXPECT_TRUE(pcb2.len_() == pcb3.len_()); EXPECT_TRUE(pcb1.len_() == pcb2.len_()); } TEST(CopyAndSwap, CopyAssignment) { pcb pcb1, pcb2, pcb3; pcb1.add_contact(contact (1, 1, input)); pcb2.add_contact(contact (1, 1, input)); pcb3 = pcb1; EXPECT_TRUE(pcb3.len_() == pcb2.len_()); EXPECT_TRUE(pcb1.len_() == pcb2.len_()); } TEST(CopyAndSwap, MoveConstructor) { pcb pcb1; pcb1.add_contact(contact (1, 1, output)); pcb old_pcb1 = pcb1; pcb pcb2(std::move(pcb1)); EXPECT_TRUE(pcb2.len_() == old_pcb1.len_()); EXPECT_TRUE(pcb1.len_() == pcb().len_()); } TEST(CopyAndSwap, MoveAssignment) { pcb pcb1; pcb1.add_contact(contact (1, 1, output)); pcb pcb2; pcb2.add_contact(contact (2, 2, output)); pcb2.add_contact(contact (7, 9, input)); pcb old_pcb1 = pcb1; pcb old_pcb2 = pcb2; pcb2 = std::move(pcb1); EXPECT_TRUE(pcb2.len_() == old_pcb1.len_()); EXPECT_TRUE(pcb1.len_() == old_pcb2.len_()); } // -------- old operations -------- // TEST(Operations, add_and_print) { pcb circ; contact c(0, 0, input), c6(0, 0, input), c1(1, 1, (type) 0), c2(2, 3, (type) 1), c3(10, 11, (type) 0); contact c4(100, 100, (type) 0); std::ostringstream ostr_0, ostr_1, ostr_2, ostr_3; circ.print_pcb(ostr_0); EXPECT_EQ(0, circ.len_()); EXPECT_EQ(ostr_0.str(), "Circuit broad is empty\n"); circ.add_contact(c); circ.print_pcb(ostr_1); EXPECT_EQ(1, circ.len_()); EXPECT_EQ(ostr_1.str(), "0 --> input, (0;0), -1;\n"); EXPECT_THROW(circ.add_contact(c6), std::invalid_argument); circ.add_contact(c1); circ.print_pcb(ostr_2); EXPECT_EQ(2, circ.len_()); EXPECT_EQ(ostr_2.str(), "0 --> input, (0;0), -1;\n1 --> output, (1;1), -1;\n"); circ.add_contact(c2), circ.add_contact(c3), circ.add_contact(c4); } TEST(Operations, Checkcorrectly) { pcb circ; contact c(0, 0, input), c1(1, 1, (type) 0); int t; EXPECT_THROW(t = circ.check_correctly(1), std::logic_error); circ.add_contact(c); circ.add_contact(c1); EXPECT_EQ(0, circ.check_correctly(0)); EXPECT_EQ(0, circ.check_correctly(1)); EXPECT_THROW(t = circ.check_correctly(3), std::invalid_argument); circ.add_link(0, 1); EXPECT_EQ(1, circ.check_correctly(1)); EXPECT_EQ(0, circ.check_correctly(0)); } TEST(Operations, add_link) { pcb circ; contact c(0, 0, input), c1(1, 1, (type) 0), c2(2, 3, (type) 0), c3(9, 9, (type) 0); circ.add_contact(c); circ.add_contact(c1); circ.add_link(0, 1); EXPECT_EQ(1, circ.check_correctly(1)); EXPECT_THROW(circ.add_link(2, 0), std::invalid_argument); EXPECT_THROW(circ.add_link(0, -1), std::invalid_argument); EXPECT_THROW(circ.add_link(1, 0), std::logic_error); EXPECT_THROW(circ.add_link(0, 1), std::logic_error); circ.add_contact(c2); circ.add_contact(c3); EXPECT_THROW(circ.add_link(2, 3), std::logic_error); EXPECT_THROW(circ.add_link(2, 1), std::logic_error); circ.add_link(1, 2); EXPECT_EQ(1, circ.check_correctly(2)); } TEST(Operations, contact_distance) { pcb circ; contact c(0, 0, input), c1(1, 1, (type) 0), c2(2, 3, (type) 0); circ.add_contact(c), circ.add_contact(c1), circ.add_contact(c2); circ.add_link(0, 2), circ.add_link(2, 1); int t; EXPECT_THROW(t = circ.contact_dist(-1, 2), std::invalid_argument); EXPECT_THROW(t = circ.contact_dist(0, 5), std::invalid_argument); EXPECT_THROW(t = circ.contact_dist(1, 0), std::logic_error); EXPECT_EQ(1, circ.contact_dist(0, 2)); EXPECT_EQ(2, circ.contact_dist(0, 1)); EXPECT_EQ(0, circ.contact_dist(1, 2)); } TEST(Operations, group_contacts) { pcb circ; contact c, c1(1, 1, (type) 1), c2(2, 3, (type) 1); pcb tst; EXPECT_THROW(tst = circ.group_cont((type) 0), std::logic_error); circ.add_contact(c); tst = circ.group_cont((type) 1); EXPECT_EQ(0, tst.len_()); circ.add_contact(c1), circ.add_contact(c2); tst = circ.group_cont((type) 0); EXPECT_EQ(1, tst.len_()); tst = circ.group_cont((type) 1); EXPECT_EQ(2, tst.len_()); EXPECT_THROW(tst = circ.group_cont((type) 2), std::invalid_argument); EXPECT_THROW(tst = circ.group_cont((type) -1), std::invalid_argument); } TEST(Operations, pop) { pcb circ; contact c, c1(1, 1, (type) 1), c2(2, 3, (type) 1); circ.add_contact(c); circ.add_contact(c1), circ.add_contact(c2); EXPECT_EQ(3, circ.len_()); circ.pcb_pop(); EXPECT_EQ(2, circ.len_()); circ.pcb_pop(); EXPECT_EQ(1, circ.len_()); circ.pcb_pop(); EXPECT_THROW(circ.pcb_pop(), std::invalid_argument); } TEST(Operators, element) { pcb circ; contact c, c1(1, 1, input), c2(2, 3, input), c3(10, 11, input); circ.add_contact(c); circ.add_contact(c1), circ.add_contact(c2); EXPECT_EQ(output, circ[0].type_contact); EXPECT_EQ(2, circ[2].p.x); EXPECT_THROW(circ[3], std::out_of_range); EXPECT_THROW(circ[-1], std::out_of_range); circ[2] = c3; EXPECT_EQ(10, circ[2].p.x); } TEST(Operators, decrement) { pcb circ; contact c, c1(1, 1, (type) 1), c2(2, 3, (type) 1); circ.add_contact(c); circ.add_contact(c1), circ.add_contact(c2); EXPECT_EQ(3, circ.len_()); int n0 = (circ--).len_(); EXPECT_EQ(3, n0); EXPECT_EQ(2, circ.len_()); EXPECT_EQ(1, (--circ).len_()); circ--; EXPECT_THROW(--circ, std::invalid_argument); } TEST(Operators, input_output) { pcb circ; std::ostringstream ostr_0, ostr_1; std::istringstream istr_1("3\n1 1 1\n2 3 1\n10 11 0\n"); ostr_0 << circ; EXPECT_EQ(ostr_0.str(), "Circuit broad is empty\n"); istr_1 >> circ; EXPECT_EQ(3, circ.len_()); ostr_1 << circ; EXPECT_EQ(ostr_1.str(), "0 --> input, (1;1), -1;\n1 --> input, (2;3), -1;\n2 --> output, (10;11), -1;\n"); std::istringstream istr_2("1\n1 1 1\n"); EXPECT_THROW(istr_2 >> circ, std::invalid_argument); std::istringstream istr_3("2\n2 3 1\n1 1 1\n"); EXPECT_THROW(istr_3 >> circ, std::invalid_argument); } TEST(Operators, invert) { pcb circ, inv_circ, inv_circ1; contact c(0, 0, (type) 1), c1(1, 1, (type) 0), c2(2, 3, (type) 0); circ.add_contact(c1); circ.add_contact(c), circ.add_contact(c2); circ.add_link(1, 2), circ.add_link(2, 0); std::ostringstream ostr_before, ostr_after, ostr_before1, ostr_after1; ostr_before << circ; EXPECT_EQ(ostr_before.str(), "0 --> output, (1;1), -1;\n1 --> input, (0;0), 2;\n2 --> output, (2;3), 0;\n"); inv_circ = !circ; ostr_after << inv_circ; EXPECT_EQ(ostr_after.str(), "0 --> input, (1;1), 2;\n1 --> output, (0;0), -1;\n2 --> output, (2;3), 1;\n"); contact c3(3, 4, (type) 1), c4(4, 5, (type) 0); inv_circ.add_contact(c3), inv_circ.add_contact(c4); inv_circ.add_link(3, 4); ostr_before1 << inv_circ; EXPECT_EQ(ostr_before1.str(), "0 --> input, (1;1), 2;\n1 --> output, (0;0), -1;\n2 --> output, (2;3), 1;\n3 --> input, (3;4), 4;\n4 --> output, (4;5), -1;\n"); inv_circ1 = !inv_circ; ostr_after1 << inv_circ1; EXPECT_EQ(ostr_after1.str(), "0 --> output, (1;1), -1;\n1 --> input, (0;0), 2;\n2 --> output, (2;3), 0;\n3 --> output, (3;4), -1;\n4 --> input, (4;5), 3;\n"); } TEST(Operators, modified_sum) { pcb circ, circ2; contact c(0, 0, input), c1(1, 1, (type) 0), c2(2, 3, (type) 0); circ.add_contact(c), circ.add_contact(c1), circ.add_contact(c2); circ.add_link(0, 2), circ.add_link(2, 1); contact c3(3, 4, (type) 1), c4(4, 5, (type) 0); circ2.add_contact(c3), circ2.add_contact(c4); circ2.add_link(0, 1); EXPECT_EQ(3, circ.len_()); EXPECT_EQ(2, circ2.len_()); std::ostringstream ostr_before, ostr_after, ostr_before1; ostr_before << circ; EXPECT_EQ(ostr_before.str(), "0 --> input, (0;0), 2;\n1 --> output, (1;1), -1;\n2 --> output, (2;3), 1;\n"); ostr_before1 << circ2; EXPECT_EQ(ostr_before1.str(), "0 --> input, (3;4), 1;\n1 --> output, (4;5), -1;\n"); circ += circ2; EXPECT_EQ(5, circ.len_()); ostr_after << circ; EXPECT_EQ(ostr_after.str(), "0 --> input, (0;0), 2;\n1 --> output, (1;1), -1;\n2 --> output, (2;3), 1;\n3 --> input, (3;4), 4;\n4 --> output, (4;5), -1;\n"); } TEST(Operators, sum) { pcb circ, circ2, res; contact c(0, 0, input), c1(1, 1, (type) 0), c2(2, 3, (type) 0); circ.add_contact(c), circ.add_contact(c1), circ.add_contact(c2); circ.add_link(0, 2), circ.add_link(2, 1); contact c3(3, 4, (type) 1), c4(4, 5, (type) 0); circ2.add_contact(c3), circ2.add_contact(c4); circ2.add_link(0, 1); EXPECT_EQ(3, circ.len_()); EXPECT_EQ(2, circ2.len_()); std::ostringstream ostr_before, ostr_after, ostr_before1; ostr_before << circ; EXPECT_EQ(ostr_before.str(), "0 --> input, (0;0), 2;\n1 --> output, (1;1), -1;\n2 --> output, (2;3), 1;\n"); ostr_before1 << circ2; EXPECT_EQ(ostr_before1.str(), "0 --> input, (3;4), 1;\n1 --> output, (4;5), -1;\n"); EXPECT_EQ(0, res.len_()); res = circ + circ2; EXPECT_EQ(5, res.len_()); ostr_after << res; EXPECT_EQ(ostr_after.str(), "0 --> input, (0;0), 2;\n1 --> output, (1;1), -1;\n2 --> output, (2;3), 1;\n3 --> input, (3;4), 4;\n4 --> output, (4;5), -1;\n"); } //TEST(Operators, comparator) { // pcb circ, circ2; // contact c, c1(1, 1, (type) 1), c2(2, 3, (type) 1); // // EXPECT_EQ( 0 <=> 0, circ <=> circ2); // circ.add_contact(c), circ.add_contact(c1), circ.add_contact(c2); // contact c3(3, 4, (type) 0), c4(4, 5, (type) 1); // circ2.add_contact(c3), circ2.add_contact(c4); // // EXPECT_EQ(3 <=> 2, circ <=> circ2); // EXPECT_EQ(3 > 2, circ > circ2); // EXPECT_EQ(3 <= 2, circ <= circ2); //} TEST(DynamicMemory, big_pcb) { pcb pcb1; for (int i = 0; i < 1000; ++i) { pcb1.add_contact(contact (i, i, (type) (i % 2))); } EXPECT_EQ(1000, pcb1.len_()); for (int i = 0; i < 6; ++i) { --pcb1; } EXPECT_EQ(994, pcb1.len_()); EXPECT_EQ(1005, pcb1.max_len()); EXPECT_EQ(995, (--pcb1).max_len()); for (int i = 0; i < 993; ++i) { --pcb1; } EXPECT_THROW(--pcb1, std::invalid_argument); } int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
"use client"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Carousel, CarouselContent, CarouselItem, } from "@/components/ui/carousel"; import messages from "@/messages.json"; import { Mail } from "lucide-react"; import Autoplay from "embla-carousel-autoplay" const Home = () => { return ( <> <main className="flex-grow flex flex-col items-center justify-center px-4 md:px-24 py-12 bg-gray-800 text-white"> <section className="text-center mb-8 md:mb-12"> <h1 className="text-3xl md:text-5xl font-bold"> Dive into the World of Anonymous Feedback </h1> <p className="mt-3 md:mt-4 text-base md:text-lg"> True Feedback - Where your identity remains a secret. </p> </section> <Carousel plugins={[Autoplay({ delay: 2000 })]} className="w-full max-w-lg md:max-w-xl" > <CarouselContent> {messages.map((message, index) => ( <CarouselItem key={index} className="p-4"> <Card> <CardHeader> <CardTitle>{message.title}</CardTitle> </CardHeader> <CardContent className="flex flex-col md:flex-row items-start space-y-2 md:space-y-0 md:space-x-4"> <Mail className="flex-shrink-0" /> <div> <p>{message.content}</p> <p className="text-xs text-muted-foreground"> {message.received} </p> </div> </CardContent> </Card> </CarouselItem> ))} </CarouselContent> </Carousel> </main> </> ); }; export default Home;
<?php namespace App\Models; use App\Concers\GenderEnum; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasOne; class Candidat extends Model { use HasFactory; protected $fillable =[ 'name', 'prenon', 'date_naissance', 'id_carte_electeur', 'photos', 'commune_id', 'user_id', 'gender' ]; protected $casts = [ 'date_naissance' => 'date', 'id_carte_electeur' => 'integer', 'gender' => GenderEnum::class, ]; public function commune(): BelongsTo { return $this->belongsTo(Commune::class); } public function user(): BelongsTo { return $this->belongsTo(User::class); } public function mariage(): HasOne { return $this->hasOne(Mariage::class); } }
package tester.srv.dao import io.github.gaelrenoux.tranzactio.doobie.{TranzactIO, tzio} import zio.schema.{DeriveSchema, Schema} import doobie.* import doobie.implicits.* import doobie.implicits.javasql.* import doobie.postgres.* import doobie.postgres.implicits.* import doobie.postgres.pgisimplicits.* import AbstractDao.* import ProblemDao.Problem import cats.syntax.all.catsSyntaxSeqs import otsbridge.ProblemScore.ProblemScore import java.time.Instant object ProblemDao extends AbstractDao[Problem] with ById[Problem] { type ScoreJsonString = String case class Problem(id: Int, courseId: Int, templateAlias: String, seed: Int, score: ScoreJsonString, scoreNormalized: Double, maxAttempts: Option[Int], deadline: Option[Instant], requireConfirmation: Boolean, addedAt: Instant) override val schema: Schema[Problem] = DeriveSchema.gen[Problem] override val tableName: String = "Problem" override val jsonbFields: Seq[String] = Seq("score") def byCourseAndTemplate(courseId: Int, templateAlias: String): TranzactIO[Option[Problem]] = selectWhereAndOption(fr"courseId = $courseId", fr"templateAlias = $templateAlias") def courseProblems(courseId: Int): TranzactIO[List[Problem]] = selectWhereList(fr"courseId = $courseId") def updateScore(problemId: Int, score: ProblemScore): TranzactIO[Boolean] = updateById(problemId, fr"scoreNormalized=${score.percentage}, score=${score.toJson}::jsonb") sealed trait ProblemFilter object ProblemFilter { case class ByUsers(userId: Int*) extends ProblemFilter case class FromGroupCourses(groupId: Int) extends ProblemFilter case class ByCourses(courseId: Int*) extends ProblemFilter case class ByCourseAliases(courseId: String*) extends ProblemFilter } def filterToFragment(f: ProblemFilter): Option[Fragment] = f match case ProblemFilter.ByUsers(userIds*) => userIds.toNeSeq.map(ids => Fragments.in(fr"C.userId", ids)) case ProblemFilter.FromGroupCourses(groupId) => None //todo user can have same courses from different groups, forbid that or add filter here case ProblemFilter.ByCourses(courseIds*) => courseIds.toNeSeq.map(cids => Fragments.in(fr"P.courseId", cids)) case ProblemFilter.ByCourseAliases(courseAliases*) => courseAliases.toNeSeq.map(as => Fragments.in(fr"C.templateAlias", as)) case class ProblemMeta(userId: Int, courseAlias: String, answers: Int, rejectedAnswers: Int, verifiedAnswers: Int, confirmed: Int, reviews: Int /*, confirmedNonRejected: Int*/) def queryProblems(filter: ProblemFilter*): TranzactIO[Seq[(Problem, ProblemMeta)]] = tzio { val q = Fragment.const( s"""SELECT ${fieldNames.map(n => s"P.$n").mkString(", ")}, C.userId, C.templateAlias, | COUNT(A.id), COUNT(R.answerId), COUNT(V.answerId), COUNT(VC.answerId), COUNT(Rev.answerId) |FROM $tableName as P |LEFT JOIN ${CourseDao.tableName} as C ON C.id = P.courseId |LEFT JOIN ${AnswerDao.tableName} as A ON A.problemId = P.id |LEFT JOIN ${AnswerRejectionDao.tableName} as R on R.answerId = A.id |LEFT JOIN ${AnswerVerificationDao.tableName} as V on V.answerId = A.id |LEFT JOIN ${AnswerVerificationConfirmationDao.tableName} as VC on VC.answerId = A.id |LEFT JOIN ${AnswerReviewDao.tableName} as Rev on Rev.answerId = A.id |""".stripMargin) ++ Fragments.whereAndOpt(filter.map(filterToFragment): _ *) ++ fr"GROUP BY P.id, C.userId, C.templateAlias" q.query[(Problem, ProblemMeta)].to[List] } }
import React, { useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { increaseLike, showSidebar } from "../utils/appSlice"; import { useSearchParams } from "react-router-dom"; import { VIDEO_DATA_URL, YOUTUBE_CHANNEL_URL, commentData, } from "../utils/constants"; import LiveComment from "./LiveComment"; import { subscribers } from "../utils/helper"; import Comments, { VideoComments } from "./Comments"; const WatchPage = () => { const [searchParams] = useSearchParams(); const params = searchParams.get("v"); const [videoData, setVideoData] = useState([]); const { snippet, statistics } = videoData; const [channelData, setChannelData] = useState([]); useEffect(() => { getVideoData(); }, []); async function getVideoData() { const response = await fetch(VIDEO_DATA_URL + params); const data = await response.json(); data?.items && setVideoData(data?.items[0]); } useEffect(() => { getChannelData(); }, [videoData]); async function getChannelData() { try { const response = await fetch(YOUTUBE_CHANNEL_URL + snippet?.channelId); const data = await response.json(); data?.items && setChannelData(data?.items[0]); } catch (error) { console.log(error); } } useEffect(() => { window.scrollTo(0, 0); }, []); return ( <div className="flex flex-col pl-8"> <div className="pt-20 flex h-[700px] "> <div> { <iframe width="900" height="500" // src={"https://www.youtube.com/embed/" + params + "?autoplay=1"} src={"https://www.youtube.com/embed/" + params} title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture;" allowFullScreen="allowFullScreen" className="rounded-2xl"></iframe> } <div className="w-full bg-white rounded-lg py-2"> <p className="text-xl font-medium ml-1 truncate"> {snippet?.title} </p> <div className="flex items-center pt-4"> <img src={ channelData?.snippet?.thumbnails?.default?.url || channelData?.snippet?.thumbnails?.medium?.url || channelData?.snippet?.thumbnails?.high?.url } className="w-12 h-12 rounded-full" alt="" /> <div className="mx-3 "> <p className="font-semibold ">{snippet?.channelTitle}</p> <p className="text-sm pt-0.5 text-slate-500"> {subscribers(channelData?.statistics?.subscriberCount)}{" "} subscribers </p> </div> <div className="mx-5"> <button className="w-28 h-10 bg-black text-white rounded-full"> Subscribe </button> </div> <div className="w-44 h-10 border flex justify-around rounded-full items-center ml-24 bg-slate-200 px-1"> <div className="flex items-center "> <img width="50" height="50" src={ statistics?.likeCount > 0 ? "https://img.icons8.com/ios-filled/50/343434/facebook-like.png" : "https://img.icons8.com/ios/50/facebook-like--v1.png" } alt="facebook-like--v1" className="h-7 w-7 cursor-pointer " /> </div> <p className="text-sm font-medium border-r border-slate-400 p-1 pl-0 pr-2"> {subscribers(statistics?.likeCount)} </p> <div className=""> <img width="50" height="50" src="https://img.icons8.com/ios/50/facebook-like--v1.png" alt="facebook-like--v1" className="h-7 w-7 cursor-pointer rotate-180 " /> </div> </div> <div className="w-24 h-10 border flex rounded-full items-center bg-slate-200 mx-3 pl-2"> <img width="26" height="50" src="https://img.icons8.com/ios/50/forward-arrow.png" alt="forward-arrow" /> <p className="font-md mx-1 text-sm">Share</p> </div> <div className="w-28 h-10 border flex rounded-full items-center bg-slate-200 "> <img width="25" height="32" src="https://img.icons8.com/small/32/download--v1.png" alt="download--v1" className="pl-1 ml-1" /> <p className="font-md mx-1 text-sm">Download</p> </div> </div> </div> </div> <div><LiveComment /></div> </div> <div className="mt-5 pb-5 w-[900px]"> <h1 className="text-xl font-semibold "> {statistics?.commentCount} Comments: </h1> <VideoComments videoId={params} /> </div> </div> ); }; export default WatchPage;
class Semaphore { constructor(count) { this.count = count; this.waiting = []; this.mutex = Promise.resolve(); } acquire() { if (this.count > 0) { this.count -= 1; return Promise.resolve(true); } // 현재 포크를 얻을 수 없으면, 대기 큐에 Promise를 추가합니다. let resolve; let promise = new Promise((r) => (resolve = r)); this.waiting.push(resolve); return promise; } release() { this.count += 1; if (this.waiting.length > 0) { // 대기중인 철학자가 있다면 하나를 깨웁니다. let resolve = this.waiting.shift(); resolve(true); } } async criticalSection(taskFn) { await this.acquire(); try { return await taskFn(); } finally { this.release(); } } } // 포크 클래스 (세마포어를 활용) class Fork extends Semaphore { constructor() { super(1); } } // 철학자 클래스 class Philosopher { constructor(name, leftFork, rightFork) { this.name = name; this.leftFork = leftFork; this.rightFork = rightFork; } async think() { console.log(`${this.name} is thinking.`); await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 1000))); } async eat() { console.log(`${this.name} started eating.`); await new Promise((resolve) => setTimeout(resolve, Math.floor(Math.random() * 1000))); console.log(`${this.name} finished eating.`); } async dine() { while (true) { await this.think(); await this.leftFork.criticalSection(async () => { await this.rightFork.criticalSection(async () => { await this.eat(); }); }); } } } // 철학자들과 포크들을 생성 const forks = Array.from({ length: 5 }, () => new Fork()); const philosophers = [ new Philosopher('Aristotle', forks[0], forks[1]), new Philosopher('Plato', forks[1], forks[2]), new Philosopher('Socrates', forks[2], forks[3]), new Philosopher('Descartes', forks[3], forks[4]), new Philosopher('Kant', forks[4], forks[0]), ]; // 모든 철학자가 동시에 식사를 시작 philosophers.forEach((philosopher) => philosopher.dine());
// // CoindeskAPIService.swift // Bitcoin Price // // Created by Juan carlos Faria santiago on 25/4/23. // import Combine import Foundation //http://api.coindesk.com/v1/bpi/currentprice.json struct CoindeskAPIService { public static let shared: CoindeskAPIService = CoindeskAPIService() public func fechBitcoinPrice() -> AnyPublisher <APIResponse, Error> { guard let url = URL(string: "http://api.coindesk.com/v1/bpi/currentprice.json") else { let error = URLError(.badURL) return Fail(error: error) .eraseToAnyPublisher() } return URLSession.shared.dataTaskPublisher(for: url) .tryMap({data, response in guard let httpResponse = response as? HTTPURLResponse else { throw URLError(.unknown) } guard httpResponse.statusCode == 200 else { let code = URLError.Code(rawValue: httpResponse.statusCode) throw URLError(code) } return data }) .decode(type: APIResponse.self, decoder: JSONDecoder()) .receive(on: DispatchQueue.main) .eraseToAnyPublisher() } } struct APIResponse: Decodable{ let time: APITime let bpi: APIBitcoinPriceIndex } struct APITime: Decodable{ let update: String } struct APIBitcoinPriceIndex: Decodable{ let USD: APIPriceData let GBP: APIPriceData let EUR: APIPriceData } struct APIPriceData: Decodable { let rate: String }
<#macro title></#macro> <#macro main> <html> <#import "spring.ftl" as spring /> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title><@title/></title> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700,800" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Poppins:300,300i,400,400i,500,600,600i,700,700i,800" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/plugins.css"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="css/plugins/owl.carousel.min.css"> <link rel="stylesheet" href="css/custom.css"> <script src="js/vendor/modernizr-3.5.0.min.js"></script> </head> <body onload=<@connect/>> <div class="wrapper" id="wrapper"> <header id="wn__header" class="header__area header__absolute sticky__header"> <div class="container-fluid"> <div class="row"> <div class="col-md-6 col-sm-6 col-6 col-lg-2"> <div class="logo"> <a href="/"> <img src="images/logo6.png" alt="logo image"> </a> </div> </div> <div class="col-lg-8 d-none d-lg-block"> <nav class="mainmenu__nav"> <ul class="meninmenu d-flex justify-content-start"> <li class="drop with--one--item"><a href="/houses"><@spring.message 'root.page.link_houses'/></a> </li> <li class="drop"><a href="/posts"><@spring.message 'root.page.link_posts'/></a> </li> <#if user?has_content> <li><a href="/create_house"><@spring.message 'root.page.link_create_house'/></a></li> <li><a href="/create_post"><@spring.message 'root.page.link_create_post'/></a></li> <li><a href="/flud"><@spring.message 'root.page.link_chat'/></a></li> </#if> </ul> </nav> </div> <#if user?has_content> <div class="col-md-6 col-sm-6 col-6 col-lg-2"> <ul class="header__sidebar__right d-flex justify-content-end align-items-center"> <li class="setting__bar__icon"><a class="setting__active" href="#"></a> <div class="searchbar__content setting__block"> <div class="content-inner"> <div class="switcher-currency"> <strong class="label switcher-label"> <span>${user.firstName}</span> <a href="/?lang=ru"><img src="images/icons/1200px-Flag_of_Russia.svg.png" height="16" width="24"></a> <a href="/?lang=en"><img src="images/icons/Flag_of_the_United_Kingdom.svg" height="16" width="24"></a> </strong> <div class="switcher-options"> <div class="switcher-currency-trigger"> <div class="setting__menu"> <span><a href="/profile"><@spring.message 'root.page.my_account'/></a></span> <span><a href="/logout"><@spring.message 'root.page.logout'/></a></span> </div> </div> </div> </div> </div> </div> </li> </ul> </div> <#else> <div class="col-md-6 col-sm-6 col-6 col-lg-2"> <ul class="header__sidebar__right d-flex justify-content-end align-items-center"> <li class="setting__bar__icon"><a class="setting__active" href="#"></a> <div class="searchbar__content setting__block"> <div class="content-inner"> <div class="switcher-currency"> <strong class="label switcher-label"> <div class="row"> <div class="col-md-8"> <span><@spring.message 'root.page.greeting'/></span> </div> <div class="col-md-4"> <a href="/?lang=ru"><img src="images/icons/1200px-Flag_of_Russia.svg.png" height="16" width="24"></a> <a href="/?lang=en"><img src="images/icons/Flag_of_the_United_Kingdom.svg" height="16" width="24"></a> </div> </div> </strong> <div class="switcher-options"> <div class="switcher-currency-trigger"> <div class="setting__menu"> <span><a href="/signIn"><@spring.message 'root.page.login'/></a></span> <span><a href="/signUp"><@spring.message 'root.page.sign_up'/></a></span> </div> </div> </div> </div> </div> </div> </li> </ul> </div> </#if> </div> </div> </header> <!-- Start Slider area --> <section class="best-seel-area pt--80"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="section__title text-center pb--50"> <h1 class="title__be--2"> <@spring.message 'root.page.app_name_first'/> <span class="color--theme"><a href="/houses"><@spring.message 'root.page.app_name_second'/></a> </span></h1> <p><@spring.message 'root.page.app_name_lower'/></p> </div> </div> </div> </div> </section> <@content/> <footer id="wn__footer" class="footer__area bg__cat--8 brown--color"> <div class="footer-static-top"> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="footer__widget footer__menu"> <div class="ft__logo"> <a href="https://ampl.ink/dV1Yx"> <img src="images/logo6.png" alt="logo"> </a> <p><a href="https://ampl.ink/dV1Yx"><@spring.message 'root.page.footer_text'/></a></p> </div> <div class="footer__content"> <ul class="mainmenu d-flex justify-content-center"> <li><a href="/houses"><@spring.message 'root.page.link_houses'/></a></li> <li><a href="/posts"><@spring.message 'root.page.link_posts'/></a></li> <#if user?has_content> <li><a href="/profile"><@spring.message 'root.page.my_account'/></a></li> </#if> </ul> </div> </div> </div> </div> </div> </div> <div class="copyright__wrapper"> <div class="container"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-12"> <div class="copyright"> <div class="copy__right__inner text-left"> <p>ITIS <i class="fa fa-copyright"></i> <a href="kpfu.ru">Kazan University.</a> Group 11-801, 13B class</p> </div> </div> </div> </div> </div> </div> </footer> </div> <script src="js/vendor/jquery-3.2.1.min.js"></script> <script src="js/popper.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/plugins.js"></script> <script src="js/active.js"></script> <script src="js/change_img.js"></script> <script src="js/validation.js"></script> </body> </html> </#macro>
import React, { useContext, useState } from "react"; import { Link } from "react-router-dom"; import logo from "../../../assets/logo.png"; import { AuthContext } from "../../../context/AuthProvider/AuthProvider"; export const Header = () => { const [isMenuOpen, setIsMenuOpen] = useState(false); const { user, logout } = useContext(AuthContext); const handleLogout = () => { logout() .then(() => {}) .catch((error) => console.log(error)); }; return ( <div className="px-4 py-5 mx-auto sm:max-w-xl md:max-w-full lg:max-w-screen-xl md:px-24 lg:px-8"> <div className="relative flex items-center justify-between"> <Link to="/" aria-label="Company" title="Company" className="inline-flex items-center" > <img src={logo} alt="" className="w-8" /> <span className="ml-2 text-xl font-bold tracking-wide text-gray-800 uppercase"> DOSOFY </span> </Link> <ul className="flex items-center hidden space-x-8 lg:flex"> <li> <Link to="/" aria-label="Home" title="Home" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > Home </Link> </li> <li> <Link to="/services" aria-label="services" title="services" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > Services </Link> </li> <li> { user?.uid && <Link to="/myreview" aria-label="Product pricing" title="Product pricing" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > My reviews </Link> } </li> <li> { user?.uid && <Link to="/addservice" aria-label="Product pricing" title="Product pricing" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > Add service </Link> } </li> <li> <Link to="/blog" aria-label="blog" title="blog" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > Blog </Link> </li> <li> {user?.uid ? ( <Link onClick={handleLogout} to="/" className="inline-flex items-center justify-center h-12 px-6 font-medium tracking-wide text-white transition duration-200 rounded shadow-md bg-sky-500/100 hover:bg-sky-700/100 focus:shadow-outline focus:outline-none" aria-label="Sign out" title="Sign out" > Sign out </Link> ) : ( <Link to="/login" className="inline-flex items-center justify-center h-12 px-6 font-medium tracking-wide text-white transition duration-200 rounded shadow-md bg-sky-500/100 hover:bg-sky-700/100 focus:shadow-outline focus:outline-none" aria-label="Sign in" title="Sign in" > Sign in </Link> )} </li> </ul> <div className="lg:hidden"> <button aria-label="Open Menu" title="Open Menu" className="p-2 -mr-1 transition duration-200 rounded focus:outline-none focus:shadow-outline hover:bg-purple-50 focus:bg-purple-50" onClick={() => setIsMenuOpen(true)} > <svg className="w-5 text-gray-600" viewBox="0 0 24 24"> <path fill="currentColor" d="M23,13H1c-0.6,0-1-0.4-1-1s0.4-1,1-1h22c0.6,0,1,0.4,1,1S23.6,13,23,13z" /> <path fill="currentColor" d="M23,6H1C0.4,6,0,5.6,0,5s0.4-1,1-1h22c0.6,0,1,0.4,1,1S23.6,6,23,6z" /> <path fill="currentColor" d="M23,20H1c-0.6,0-1-0.4-1-1s0.4-1,1-1h22c0.6,0,1,0.4,1,1S23.6,20,23,20z" /> </svg> </button> {isMenuOpen && ( <div className="absolute top-0 left-0 w-full z-10"> <div className="p-5 bg-white border rounded shadow-sm"> <div className="flex items-center justify-between mb-4"> <div> <Link href="/" aria-label="Company" title="Company" className="inline-flex items-center" > <img src={logo} alt="" className="w-8" /> <span className="ml-2 text-xl font-bold tracking-wide text-gray-800 uppercase"> DOSOFY </span> </Link> </div> <div> <button aria-label="Close Menu" title="Close Menu" className="p-2 -mt-2 -mr-2 transition duration-200 rounded hover:bg-gray-200 focus:bg-gray-200 focus:outline-none focus:shadow-outline" onClick={() => setIsMenuOpen(false)} > <svg className="w-5 text-gray-600" viewBox="0 0 24 24"> <path fill="currentColor" d="M19.7,4.3c-0.4-0.4-1-0.4-1.4,0L12,10.6L5.7,4.3c-0.4-0.4-1-0.4-1.4,0s-0.4,1,0,1.4l6.3,6.3l-6.3,6.3 c-0.4,0.4-0.4,1,0,1.4C4.5,19.9,4.7,20,5,20s0.5-0.1,0.7-0.3l6.3-6.3l6.3,6.3c0.2,0.2,0.5,0.3,0.7,0.3s0.5-0.1,0.7-0.3 c0.4-0.4,0.4-1,0-1.4L13.4,12l6.3-6.3C20.1,5.3,20.1,4.7,19.7,4.3z" /> </svg> </button> </div> </div> <nav> <ul className="space-y-4"> <li> <Link to="/" aria-label="Home" title="Home" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > Home </Link> </li> <li> <Link href="/" aria-label="services" title="services" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > Services </Link> </li> <li> { user?.uid && <Link to="/myreview" aria-label="Product pricing" title="Product pricing" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > My reviews </Link> } </li> <li> { user?.uid && <Link to="/addservice" aria-label="Product pricing" title="Product pricing" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > Add service </Link> } </li> <li> <Link to="/blog" aria-label="blog" title="blog" className="font-medium tracking-wide text-gray-700 transition-colors duration-200 hover:text-sky-500/100" > Blog </Link> </li> <li> {user?.uid ? ( <Link onClick={handleLogout} to="/" className="inline-flex items-center justify-center h-12 px-6 font-medium tracking-wide text-white transition duration-200 rounded shadow-md bg-sky-500/100 hover:bg-sky-700/100 focus:shadow-outline focus:outline-none" aria-label="Sign out" title="Sign out" > Sign out </Link> ) : ( <Link to="/login" className="inline-flex items-center justify-center h-12 px-6 font-medium tracking-wide text-white transition duration-200 rounded shadow-md bg-sky-500/100 hover:bg-sky-700/100 focus:shadow-outline focus:outline-none" aria-label="Sign in" title="Sign in" > Sign in </Link> )} </li> </ul> </nav> </div> </div> )} </div> </div> </div> ); }; export default Header;
<div class="container"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-12"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">{{ TEXTS.PAGES.INVOICE.INVOICE }}</h1> </div> <form class="user" (ngSubmit)="!additiveForm.invalid && saveAdditive()" #additiveForm="ngForm"> <div class="form-group row"> <div class="col-sm-4"> <div class="row"> <div class="col-sm-6"> <mat-form-field style="width:100%"> <mat-label>{{ TEXTS.MODELS.ADDITIVE.PAYMENT_DUE_DATE }}</mat-label> <input matInput [matDatepicker]="paymentDueDatePicker" [(ngModel)]="additive.paymentDueDate" required="required" name="paymentDueDate" #paymentDueDate="ngModel"> <mat-datepicker-toggle matSuffix [for]="paymentDueDatePicker"></mat-datepicker-toggle> <mat-datepicker #paymentDueDatePicker></mat-datepicker> <mat-error *ngIf="paymentDueDate.invalid">{{ TEXTS.MODELS.FORMS.INVOICE.PAYMENT_DUE_DATE_REQUIRED }}</mat-error> </mat-form-field> </div> <div class="col-sm-6"> <mat-form-field style="width:100%"> <mat-label>{{ TEXTS.MODELS.ADDITIVE.INVOICED_AT }}</mat-label> <input matInput [matDatepicker]="invoicedAtDatePicker" [(ngModel)]="additive.invoicedAt" name="invoicedAt" #invoicedAt="ngModel"> <mat-datepicker-toggle matSuffix [for]="invoicedAtDatePicker"></mat-datepicker-toggle> <mat-datepicker #invoicedAtDatePicker></mat-datepicker> </mat-form-field> </div> </div> </div> <div class="col-sm-4 mb-3 mb-sm-0"> <mat-form-field style="width:100%"> <mat-label>{{ TEXTS.MODELS.ADDITIVE.PAYMENT_TYPE }}</mat-label> <mat-select [(ngModel)]="additive.paymentType" required id="additiveStatus" name="status" #status="ngModel"> <mat-option value="Boleto">Boleto</mat-option> <mat-option value="Depósito">Depósito</mat-option> <mat-option value="Cartão de Crédito">Cartão de Crédito</mat-option> <mat-option value="PIX">PIX</mat-option> </mat-select> </mat-form-field> </div> <div class="col-sm-2"> <mat-form-field style="width:100%"> <mat-label>{{ TEXTS.MODELS.ADDITIVE.INSTALLMENTS }}</mat-label> <mat-select [(ngModel)]="additive.installments" required id="installments" name="installments" #installments="ngModel"> <mat-option value="1">À Vista</mat-option> <mat-option value="2">2x</mat-option> <mat-option value="3">3x</mat-option> <mat-option value="4">4x</mat-option> <mat-option value="5">5x</mat-option> <mat-option value="6">6x</mat-option> <mat-option value="7">7x</mat-option> <mat-option value="8">8x</mat-option> <mat-option value="9">9x</mat-option> <mat-option value="10">10x</mat-option> <mat-option value="11">11x</mat-option> <mat-option value="12">12x</mat-option> </mat-select> </mat-form-field> </div> <div class="col-sm-2"> <mat-form-field style="width:100%"> <mat-label>Entrada</mat-label> <input matInput type="text" mask="separator.2" thousandSeparator="." prefix="R$" [(ngModel)]="additive.entryValue" id="additiveEntryValue" name="entryValue" #entryValue="ngModel"> </mat-form-field> </div> </div> <div class="form-group row"> <div class="col-sm-2"> <mat-form-field style="width:100%"> <mat-label>{{ TEXTS.MODELS.ADDITIVE.TOTAL_VALUE }}</mat-label> <input matInput type="text" mask="separator.2" thousandSeparator="." prefix="R$" [(ngModel)]="additive.value" id="additiveTotalValue" name="totalValue" required="required" #totalValue="ngModel"> <mat-error *ngIf="totalValue.invalid">{{ TEXTS.MODELS.FORMS.ADDITIVE.TOTAL_VALUE_REQUIRED }}</mat-error> </mat-form-field> </div> <div class="col-sm-2"> <mat-form-field style="width:100%"> <mat-label>{{ TEXTS.MODELS.ADDITIVE.INVOICE }}</mat-label> <input matInput type="number" [(ngModel)]="additive.invoiceNumber" id="additiveFiscalNote" name="invoiceNumber"> </mat-form-field> </div> <div class="col-sm-4"> <mat-form-field style="width:100%"> <mat-label>{{ TEXTS.MODELS.ADDITIVE.PURCHASE_ORDER_NUMBER }}</mat-label> <input matInput type="text" [(ngModel)]="additive.purchaseOrderNumber" id="additivePurchaseOrderNumber" name="purchaseOrderNumber"> </mat-form-field> </div> <div class="col-sm-4"> <mat-form-field style="width:100%"> <mat-label>{{ TEXTS.MODELS.ADDITIVE.INVOICE_COMMENT }}</mat-label> <input matInput type="text" [(ngModel)]="additive.invoiceComment" id="additiveInvoiceComment" name="invoiceComment"> </mat-form-field> </div> </div> <button type="submit" mat-raised-button color="primary">{{ TEXTS.GENERAL.ACTIONS.SAVE }}</button> <button type="button" mat-raised-button color="basic" (click)="onCancel()">{{ TEXTS.GENERAL.ACTIONS.CANCEL }}</button> <button type="button" mat-raised-button color="basic" [disabled]="additiveForm.invalid" (click)="onExport(additive.id)"> <mat-icon>picture_as_pdf</mat-icon> {{ TEXTS.GENERAL.ACTIONS.EXPORT }} </button> </form> <hr> </div> </div> </div> </div> </div> </div>
<i18n> en: id: 'BlankDeckFrame' de: id: 'BlankDeckFrame' </i18n> <template lang="pug"> .deck-frame(:class="{'hide-thumbnail': !thumbnail}" oncontextmenu="return false") xy-hex-deck-map.hex-layer( v-if="!thumbnail && isLoaded" :props="mapProps" @hexClick="handleHexClick" @emptyClick="handleEmptyClick" ) .left-side(v-if="isLoaded && !thumbnail") collapsible-panel(direction="left") .panel-items .right-side(v-if="isLoaded && !thumbnail") collapsible-panel(direction="right") .panel-items .message(v-if="!thumbnail && myState.statusMessage") p.status-message {{ myState.statusMessage }} </template> <script lang="ts"> import { Vue, Component, Prop, Watch } from 'vue-property-decorator' import YAML from 'yaml' import { spawn, Worker, Thread, ModuleThread } from 'threads' import util from '@/util/util' import globalStore from '@/store' import CollapsiblePanel from '@/components/CollapsiblePanel.vue' import { ColorScheme, FileSystemConfig, VisualizationPlugin, Status } from '@/Globals' import BlankDeckMap from './BlankDeckMap2.vue' import HTTPFileSystem from '@/util/HTTPFileSystem' interface VizDetail { title: string description?: string thumbnail?: string } @Component({ components: { CollapsiblePanel, BlankDeckMap, } as any, }) class DeckFrame extends Vue { @Prop({ required: true }) private root!: string @Prop({ required: true }) private subfolder!: string @Prop({ required: false }) private yamlConfig!: string @Prop({ required: false }) private thumbnail!: boolean private globalState = globalStore.state private vizDetails: VizDetail = { title: '', description: '', thumbnail: '', } public myState = { statusMessage: '', fileApi: undefined as HTTPFileSystem | undefined, fileSystem: undefined as FileSystemConfig | undefined, subfolder: this.subfolder, yamlConfig: this.yamlConfig, thumbnail: this.thumbnail, } private get mapProps() { return { dark: this.$store.state.isDarkMode, data: [], } } public buildFileApi() { const filesystem = this.getFileSystem(this.root) this.myState.fileApi = new HTTPFileSystem(filesystem) this.myState.fileSystem = filesystem // console.log('built it', this.myState.fileApi) } private thumbnailUrl = "url('assets/thumbnail.jpg') no-repeat;" private get urlThumbnail() { return this.thumbnailUrl } private getFileSystem(name: string) { const svnProject: FileSystemConfig[] = this.$store.state.svnProjects.filter( (a: FileSystemConfig) => a.slug === name ) if (svnProject.length === 0) { console.log('no such project') throw Error } return svnProject[0] } private async getVizDetails() { if (!this.myState.fileApi) return console.log(this.myState.yamlConfig) // first get config try { const text = await this.myState.fileApi.getFileText( this.myState.subfolder + '/' + this.myState.yamlConfig ) this.vizDetails = YAML.parse(text) } catch (e) { console.log('failed') // // maybe it failed because password? // if (this.myState.fileSystem && this.myState.fileSystem.need_password && e.status === 401) { // this.$store.commit('requestLogin', this.myState.fileSystem.slug) // } else { // this.$store.commit('setStatus', { // type: Status.WARNING, // msg: `Could not find: ${this.myState.subfolder}/${this.myState.yamlConfig}`, // }) // } } const t = this.vizDetails.title ? this.vizDetails.title : 'BlankMap' this.$emit('title', t) } private async buildThumbnail() { if (!this.myState.fileApi) return if (this.thumbnail && this.vizDetails.thumbnail) { try { const blob = await this.myState.fileApi.getFileBlob( this.myState.subfolder + '/' + this.vizDetails.thumbnail ) const buffer = await blob.arrayBuffer() const base64 = util.arrayBufferToBase64(buffer) if (base64) this.thumbnailUrl = `center / cover no-repeat url(data:image/png;base64,${base64})` } catch (e) { console.error(e) } } } private jumpToCenter() { // Only jump in camera is not yet set if (!this.$store.state.viewState.initial) return // // jump! // const currentView = this.$store.state.viewState // const jumpView = { // jump: true, // longitude: x, // latitude: y, // bearing: currentView.bearing, // pitch: currentView.pitch, // zoom: currentView.zoom, // } // console.log({ jumpView }) // this.$store.commit('setMapCamera', jumpView) } private async mounted() { this.buildFileApi() await this.getVizDetails() if (this.thumbnail) return this.myState.statusMessage = `${this.$i18n.t('loading')}` this.buildThumbnail() } private beforeDestroy() {} } // !register plugin! globalStore.commit('registerPlugin', { kebabName: 'blank-deck-frame', prettyName: 'Blank Frame', description: '', filePatterns: ['viz-blank*.y?(a)ml'], component: DeckFrame, } as VisualizationPlugin) export default DeckFrame </script> <style scoped lang="scss"> @import '~vue-slider-component/theme/default.css'; @import '@/styles.scss'; .deck-frame { display: grid; min-height: $thumbnailHeight; background: url('assets/thumbnail.jpg') center / cover no-repeat; grid-template-columns: auto 1fr min-content; grid-template-rows: auto 1fr auto; grid-template-areas: 'leftside . rightside' '. . rightside' '. . rightside'; } .deck-frame.hide-thumbnail { background: none; } .message { z-index: 5; grid-column: 1 / 4; grid-row: 1 / 4; box-shadow: 0px 2px 10px #22222222; display: flex; flex-direction: row; margin: auto auto 0 0; background-color: var(--bgPanel); padding: 0.5rem 1.5rem; a { color: white; text-decoration: none; &.router-link-exact-active { color: white; } } p { margin: auto 0.5rem auto 0; font-weight: normal; padding: 0 0; color: var(--textFancy); } } .status-message { font-size: 1.5rem; line-height: 1.75rem; font-weight: bold; } .big { padding: 0.5rem 0; font-size: 1.5rem; line-height: 1.7rem; font-weight: bold; } .left-side { grid-area: leftside; display: flex; flex-direction: column; font-size: 0.8rem; pointer-events: auto; margin: 0 0 0 0; } .right-side { grid-area: rightside; display: flex; flex-direction: column; font-size: 0.8rem; pointer-events: auto; margin-top: auto; // margin-bottom: 3rem; } .playback-stuff { flex: 1; } .bottom-area { display: flex; flex-direction: row; margin-bottom: 2rem; grid-area: playback; padding: 0rem 1rem 1rem 2rem; pointer-events: auto; } .settings-area { z-index: 20; pointer-events: auto; background-color: $steelGray; color: white; font-size: 0.8rem; padding: 0.25rem 0; margin: 1.5rem 0rem 0 0; } .hex-layer { grid-column: 1 / 4; grid-row: 1 / 4; pointer-events: auto; } .speed-label { font-size: 0.8rem; font-weight: bold; } p.speed-label { margin-bottom: 0.25rem; } .tooltip { padding: 5rem 5rem; background-color: #ccc; } .panel-items { margin: 0.5rem 0.5rem; } .panel-item { margin-bottom: 1rem; } input { border: none; background-color: #235; color: #ccc; } .row { display: 'grid'; grid-template-columns: 'auto 1fr'; } label { margin: auto 0 auto 0rem; text-align: 'left'; } .toggle { margin-bottom: 0.25rem; margin-right: 0.5rem; } .aggregation-button { width: 100%; } @media only screen and (max-width: 640px) { .message { padding: 0.5rem 0.5rem; } .right-side { font-size: 0.7rem; } .big { padding: 0 0rem; margin-top: 0.5rem; font-size: 1.3rem; line-height: 2rem; } } </style>
#include <iostream> #include <vector> #include <string> using namespace std; // DO NOT CHANGE CODE ABOVE /** * Name: printArray * Print each element of the generic vector on a new line. Do not return anything. * @param A generic vector **/ // Write your code here // generic T data type template <typename T> void printArray(vector<T> vec) { // loop through items in array and print for(T item : vec) { cout << item << endl; } } // DO NOT CHANGE CODE BELOW int main() { int n; cin >> n; vector<int> int_vector(n); for (int i = 0; i < n; i++) { int value; cin >> value; int_vector[i] = value; } cin >> n; vector<string> string_vector(n); for (int i = 0; i < n; i++) { string value; cin >> value; string_vector[i] = value; } printArray<int>(int_vector); printArray<string>(string_vector); return 0; }
# create river network and measure distances among sampling locations. Stream # network "epsg3722_minnesota_stream_dispersal_5km2.shp" was created to connect # all sites with corridor for dispersal # setup ------------------------------------------------------------------- # clean objects rm(list = ls()) # load libaries source(here::here("code/library.R")) # read site and stream data -------------------------------------------------------------------- # read occurrence data wgs_sf_outlet <- readRDS(file = "data_fmt/data_minnesota_stream_dummy_real_occurrence.rds") # transform to utm utm_sf_outlet <- st_transform(wgs_sf_outlet, crs = 3722) # data frame for sampling site coordinates df_coord <- utm_sf_outlet %>% mutate(X = st_coordinates(.)[,1], Y = st_coordinates(.)[,2]) %>% as_tibble() X <- df_coord$X Y <- df_coord$Y # read in stream network strnet <- line2network(path = "data_fmt/vector", layer = "epsg3722_minnesota_stream_dispersal_5km2") # prep stream network and sites -------------------------------------------------- # clean up network: dissolve - y, split segment - n, insert vertices - y, # distance - 1, examine figure for mouth questions, remove additional segments - n, # build segment routes - y strnet_fixed <- cleanup(rivers = strnet) # snap sites to stream network site_snap <- xy2segvert(x = X, y = Y, rivers = strnet_fixed) # export fixed stream network --------------------------------------------- # save file #saveRDS(strnet_fixed, file = "data_fmt/riverdist_minnesota_stream_network.rds") #strnet_fixed <- readRDS(file = "data_fmt/riverdist_minnesota_stream_network.rds") # create distance matrices -------------------------------------------------------- # distance matrix: total, m_x m_x <- riverdistancemat(site_snap$seg, site_snap$vert, strnet_fixed, ID = site_snap$segment) %>% data.matrix() m_x <- round(m_x / 1000, 2) # convert to km # distance matrix: net upstream, m_y m_y <- upstreammat(seg = site_snap$seg, vert = site_snap$vert, rivers = strnet_fixed, ID = site_snap$segment, net = TRUE) %>% data.matrix() m_y <- round(m_y / 1000, 2) # convert to km # distance matrix: up and downstream distance (m_u & m_d) m_u <- (m_x + m_y) / 2 m_d <- (m_x - m_y) / 2 # total distance m_td <- round(m_u + m_d, 2) # check if m_td = m_x identical(m_td, m_x) # make data list to save multipule objects on one RDS file datalist <- list(m_u = m_u, m_d = m_d) # export saveRDS(datalist, file = "data_fmt/data_minnesota_distance_matrix_dummy_real.rds")
<!DOCTYPE html> <html> <head> <title>aboutGPT</title> <link rel="shortcut icon" type="image/x-icon" href="gpt.ico"> <meta charset="utf-8"> <style> a{ color: black; text-decoration: none; } h1 { font-size: 45px; text-align: center; border-bottom: 1px solid gray; margin: 0px; padding: 20px; } #active{ color:blue; } .saw{ color: gray; } #grid ol{ border-right: 1px solid gray; width: 100px; margin: 0; padding: 20px; } #grid{ display: grid; grid-template-columns: 150px 1fr; } #article{ padding-left: 25px; } @media(max-width:800px){ #grid{ display:block; } #grid ol{ border-right:none; } h1{ border-bottom:none; } } </style> </head> <body> <h1><a href="index.html">챗 GPT로 변화하는 세상</a></h1> <style> h1 { text-shadow: 2px 2px 5px green; } </style> <div id="grid"> <ol> <li><a href="what.html" class="saw"> 챗 GPT란 무엇인가?</a></li> <li><a href="where.html" class="saw" id="active"> 챗 GPT 사용방법</a></li> <li><a href="change.html" class="saw">챗 GPT로 인한 세상의 변화 </a></li> <li><a href="use.html" class="saw">챗 GPT 활용방안</a></li> </ol> <div id="article"> <h2>챗 GPT '잘' 사용하는 방법</h2> <p>ChatGPT는 몇 가지 특성을 가지고 있다. ChatGPT의 특성을 충분히 이해해야 ChatGPT에게 제대로 질문하고 제대로 요청할 수 있고, ChatGPT도 우리에게 제대로 대답할 수 있다. 3가지 특성을 알아보자.</p> <p><strong>첫째, ChatGPT는 2021년까지의 데이터만 학습했다.</strong> 앞으로 나오는 시 는 실시간으로 인터넷에 등록되는 데이터를 학습하겠지만, ChatGPT는 2021 년까지의 데이터만 학습했다. 따라서 ChatGPT에게 최근 지식이나 데이터를 물어보면 대답을 못 하거나 과거의 사실을 현재 사실처럼 얘기한다. 오피스 업무 자동화에 대해서는 오피스의 최신 버전을 모를 수 있다. 예를 들어 올해 새로 나온 엑셀 버전을 ChatGPT는 전혀 몰라서 대꾸하지 못할 수 도 있다. 올해 새로 추가된 파이썬 라이브러리 같은 것도 모를 수 있다. 하지 만 새로운 출시 내용이 2021년 9월 이전에 인터넷에 올라왔거나 ChatGPT가 최신 데이터를 학습했다면 어떻게든 대답할 것이다.</p> <p><strong>둘째, ChatGPT는 사용자와 지금 나누고 있는 대화를 기억한다.</strong> ChatGPT는 대화형 거대 언어 모델이다. 사람과 대화하면서 사람이 묻거나 요청한 것을 계속 기억한다. 더 정확히는 기억이라기보다는 사람이 앞에서 물었던 것을 다시 입력값으로 계산한다. 여기에 더해, ChatGPT가 대답했던 것도 입력값으로 계산한다. ChatGPT와 자연스럽게 대화를 주고받을 수 있다 는 말이다. 오피스 업무 자동화도 이것 때문에 가능하다. 오류가 났을 때 해결하는 방법인 디버깅(Debbuging)을 ChatGPT와 할 수 있다. ChatGPT가 제시한 코드가 작동이 안 될 때 오류 메시지만 ChatGPT에게 물어도 ChatGPT가 알아 서 앞에서 대답한 코드에서 문제를 찾아 해법을 내놓는다.</p> <p><strong>셋째, ChatGPT는 어떤 식으로든 대답한다.</strong> 이것은 양날의 검이다. 사람 을 대신해서 인터넷의 모든 곳을 뒤졌다는 의미이기도 하면서, 동시에 허풍이나 거짓을 말할 수도 있다는 의미이기 때문이다. 이는 물론 ChatGPT가 일부러 거짓말하거나 허풍을 떠는 것이 아니라, 데이터와 알고리즘, 물리적 한계 등으로 A에게 어쩔 수 없이 나타나는 현상이다. 오피스 업무 자동화에 대해서는 잘못된 코드를 만들어주거나 없는 함수나 기능을 설명할 수도 있다. ChatGPT도 최대한 제대로 된 코드, 작동하는 코드, 오류 없는 코드를 알려주려고 노력하겠지만, 어느 정도 한계는 인정해야 마음 편히 사용할 수 있다. ChatGPT가 주는 코드를 어느 신입 개발자가 짜서 주는 코드 정도로 생각하고, 틀린 부분이 있을 수 있다는 것을 인정하고 보자.</p> <image src="gpt2.jpg" width="30%"> <p><u>ChatGPT의 특성을 고려하면 ChatGPT에게 어떻게 질문하고 요청해야 하는지 알 수 있다.</u></p><p>일단 ChatGPT에게 질문하고 요청하기 위해 사람이 입력하는 텍스트를 프롬프트(Prompt)라고 한다. 프롬프트가 뭔지 ChatGPT에게 물어보자.</p> <p>프롬프트(Prompt)는 컴퓨터에서 명령어를 입력할 수 있는 인터페이스를 제공하는 텍스트 상자 또는 라인입니다. 일반적으로 명령어를 입력하기 위해 사용자에게 대기 상태를 표시하며, 컴퓨터가 입력을 받을 준비가 되었음을 나타내기 위해 사용됩니다. 예를 들어, 명령 프롬프트(command prompt)는 사용자가 명령어를 입력할 수 있는 텍스트 상자를 의미합니다. 명령 프롬프트는 일반적으로 운영 체제에서 사용되며, 사용자가 명령을 입력하고 실행할 수 있는 CLI(Command Line Interface)를 제공합니다.</P> <p>이렇게 보면 구글 검색도 일종의 프롬프트라고 볼 수 있다. 사용자가 컴퓨터에 무엇인가 요청하거나 질문하거나 하는 것은 모두 프롬프트라고 봐도 무방하다. 다만, 여기서 프롬프트는 ChatGPT 같은 언어 모델에 대한 입력으로 한정하자. 이때 언어 모델로부터 구체적이고 사용 가능한 응답을 얻기 위 해 프롬프트를 적절하게 만들어야 하는데, 이 과정을 프롬프트 엔지니어링 (Prompt Engineering)이라고 한다. 정말 '이과스러운' 용어다. 아무튼 프롬프트를 잘 써야 ChatGPT가 잘 알아듣고 사용자가 원하는 대 답을 해준다. 그러면 프롬프트를 어떻게 써야 할까?</p> <p><strong>첫째, 일상적인 대화 방식으로 프롬프트를 쓰면 된다.</strong> ChatGPT는 일상 적인 대화는 웬만하면 다 알아듣는다. 예를 들어 우리가 외국에 여행 가서 호텔이나 식당에서 예약하고 주문할 때를 생각해 보자. 대충 핵심 단어 몇 개를 얘기하면 그쪽에서 어느 정도 알아듣는다. 상대방이 못 알아들으면 우리에게 다시 질문하고, 우리는 또 몇 마디 단어로 대답하면 된다. ChatGPT가 딱 그 외국인이다. 예를 들어 "엑셀의 버전별 차이를 알려줘" 라는 표현도 알아듣고, "엑셀 버전 차이"라고 해도 알아듣고 대답한다.</p> <p><strong>둘째, 오피스 툴이나 프로그래밍 언어를 얘기하면 그에 맞게 대답해 준다.</strong> 예를 들어 어떤 단어를 바꾸는 기능을 알려달라고 할 때 엑셀인지 파워포인트인지 한글인지를 밝히면 그 툴로 설명한다. 프로그래밍 언어도 마찬가지 여서 Python인지 VBA인지 구글 앱스 스크립트인지 알려주면 그에 맞춰 코드를 내놓는다.</p> <p><strong>셋째, 한 번에 완벽한 질문이나 요청을 하기 어렵다면 대충 생각나는 대 로 적으면 된다.</strong> ChatGPT는 사람의 프롬프트가 복잡하다 싶으면 1문제 1프롬프트로 분석해서 대응한다. 즉, 1문제 1프롬프트는 바로 처리하지만, 여러 문제가 한 프롬프트에 있을 때는 사람에게 일단 확인해서 처리하려고 한다. 그러니 사람이 스스로 완벽하게 프롬프트를 짤 필요가 없다.</p> <p><strong>넷째, 원하는 상황이나 형식이 있다면 정확히 지정해야 한다.</strong> 예를 들어 코드에서 주석(코드 안에서 코드를 설명하는 문구)을 원하면 상세한 주석을 달아서 코드를 짜 달라고 해야 한다. 이때 주의할 것이 있다. 상세한 주석을 달라고 하는 순간 코드가 조금 달라진다. 주석을 달아 쉽게 설명하기 위해 코드를 조금 더 정밀하게 만들어주기 때문이다. 출력 형식도 정확히 지정하면 그렇게 출력해 준다. 예를 들어 표로 출력해 달라고 할 수 있다.</p> </div> </div> </body> </html>
import "./assets/styles/index.css"; import { Item } from "./components/Item"; import { List } from "./components/List"; import { useRef, useState } from "react"; import { ToastContainer, toast } from "react-toastify"; import "react-toastify/dist/ReactToastify.css"; const App = () => { const inputValue = useRef(); const [todos, setTodo] = useState( JSON.parse(localStorage.getItem("todos")) || [] ); const handleSubmit = (evt) => { evt.preventDefault(); setTodo([ ...todos, { id: todos.at(-1)?.id + 1 || 1, isComplate: false, text: inputValue.current.value, }, ]); inputValue.current.value = ""; toast.success("Todo qo'shildi"); }; localStorage.setItem("todos", JSON.stringify(todos)); return ( <div className="container"> <h1 className="display-2 fw-bold text-center my-3 mt-5">Todo App</h1> <form onSubmit={handleSubmit} className="w-75 mx-auto shadow p-5 mt-5 "> <div className="input-group"> <input ref={inputValue} className="form-control" type="text" placeholder="Todo..." /> <button className="btn btn-primary" type="submit"> SEND </button> </div> </form> {todos.length ? ( <List> {todos.map((todo) => ( <Item key={todo.id} todos={todos} setTodo={setTodo} text={todo.text} isComplate={todo.isComplate} id={todo.id} /> ))} </List> ) : ( <h2 className="text-center mt-5">Todolar kiritilmagan</h2> )} <ToastContainer position="bottom-right" autoClose={3000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover theme="dark" /> </div> ); }; export default App;
--- title: 'La Cryogénisation' description: 'La cryogénisation, souvent perçue comme un concept de science-fiction...' tags: ["Cryogénisation", "science-fiction", "organisme", "humain"] slug: 'article3' thumbnail: '/img/cryogenisation.webp' date: '2024-06-26' draft: false --- # La Cryogénisation : Une Exploration de l'Avenir ## Introduction La cryogénisation, souvent perçue comme un concept de science-fiction, est une technique médicale qui vise à conserver des organismes humains ou animaux à très basse température dans l'espoir de les ramener à la vie dans le futur. Cet article explore les bases de la cryogénisation, son histoire, les technologies utilisées, et les perspectives futures. ## Qu'est-ce que la Cryogénisation ? La cryogénisation est le processus de conservation de corps ou de cellules à des températures extrêmement basses, généralement autour de -196°C, à l'aide de l'azote liquide. Le but est de préserver les structures biologiques de manière à minimiser les dommages causés par le temps. ## Histoire de la Cryogénisation ### Les Débuts Le concept de cryogénisation a été popularisé dans les années 1960. Le premier corps humain à être cryogénisé fut celui du professeur de psychologie James Bedford en 1967. Depuis lors, plusieurs centaines de personnes ont choisi cette méthode dans l'espoir de bénéficier des avancées futures en médecine. ### Avancées Technologiques Les techniques de cryogénisation ont évolué avec le temps. Des méthodes plus sophistiquées, comme la vitrification, ont été développées pour éviter la formation de cristaux de glace qui peuvent endommager les cellules. La vitrification transforme les tissus en un état vitreux et solide sans formation de glace. ## Les Technologies de la Cryogénisation ### Azote Liquide L'azote liquide est le principal agent de refroidissement utilisé dans la cryogénisation. Sa température extrêmement basse permet de conserver les tissus biologiques sans les altérer. ### Vitrification La vitrification est une méthode avancée qui permet de congeler les tissus sans formation de cristaux de glace. Cette technique utilise des cryoprotecteurs pour prévenir les dommages cellulaires. ### Stockage et Maintenance Les corps cryogénisés sont stockés dans des cryostats, des conteneurs spécialement conçus pour maintenir des températures ultra-basses. Une surveillance constante est nécessaire pour assurer que les conditions de stockage restent optimales. ## Perspectives Futures ### Réanimation La possibilité de réanimer les corps cryogénisés dépend de futurs progrès médicaux et technologiques. La science moderne n'a pas encore trouvé un moyen de réverser la cryogénisation, mais les avancées en nanotechnologie et en biologie cellulaire offrent des perspectives prometteuses. ### Éthique et Législation La cryogénisation soulève des questions éthiques et légales importantes. Les débats portent sur le consentement, la propriété des corps cryogénisés, et les implications morales de ramener les gens à la vie dans un futur inconnu. ### Popularité Croissante De plus en plus de personnes considèrent la cryogénisation comme une option viable pour l'avenir. Des organisations comme l'Alcor Life Extension Foundation et la Cryonics Institute proposent des services de cryogénisation et continuent de faire avancer la recherche dans ce domaine. ## Conclusion La cryogénisation reste un domaine de la science à la frontière entre la réalité et la science-fiction. Bien que de nombreux défis techniques et éthiques subsistent, les avancées continues dans les technologies de conservation et les sciences médicales pourraient un jour réaliser le rêve de la cryogénisation : surmonter les limites du temps et de la mort. --- Rédigé par [Wilfred ADJOVI]
import React, { useEffect, useState } from 'react'; import { MDBCol, MDBContainer, MDBRow, MDBCard, MDBCardText, MDBCardBody, MDBCardImage, MDBBtn, MDBTypography } from 'mdb-react-ui-kit'; import { Link } from 'react-router-dom'; export default function Profile() { const [item,setItem] = useState([]); const [Post,setPost] = useState([]) const getPostData = async()=>{ const post = await fetch(`https://jsonplaceholder.typicode.com/posts`,{ method: 'GET', headers: { 'Accept': 'application/json', } }); const postList = await post.json(); // Filter posts where userId === id const filteredPosts = postList.filter((post) => post.userId === parseInt(item.id)); const filters = filteredPosts.slice(0,4); setPost(filters); } useEffect(()=>{ const token = localStorage.getItem('item'); const itm = JSON.parse(token); setItem(itm); },[]) useEffect(()=>{ getPostData(); },[item]) return ( <div className="gradient-custom-2" style={{ backgroundColor: '#9de2ff' }}> <MDBContainer className="py-5 h-100"> <MDBRow className="justify-content-center align-items-center h-100"> <MDBCol lg="9" xl="7"> <MDBCard> <div className="rounded-top text-white d-flex flex-row" style={{ backgroundColor: '#000', height: '200px' }}> <div className="ms-4 mt-5 d-flex flex-column" style={{ width: '150px' }}> <MDBCardImage src="https://mdbcdn.b-cdn.net/img/Photos/new-templates/bootstrap-profiles/avatar-1.webp" alt="Generic placeholder image" className="mt-4 mb-2 img-thumbnail" fluid style={{ width: '150px', zIndex: '1' }} /> <MDBBtn outline color="dark" style={{height: '36px', overflow: 'visible'}}> Edit profile </MDBBtn> </div> <div className="ms-3" style={{ marginTop: '130px' }}> <MDBTypography tag="h5">{item.name}</MDBTypography> <MDBCardText>{item.address?.city}</MDBCardText> </div> </div> <div className="p-4 text-black" style={{ backgroundColor: '#f8f9fa' }}> <div className="d-flex justify-content-end text-center py-1"> <div> <MDBCardText className="mb-1 h5">10</MDBCardText> <MDBCardText className="small text-muted mb-0">Posts</MDBCardText> </div> </div> </div> <MDBCardBody className="text-black p-4"> <div className="mb-5"> <p className="lead fw-normal mb-1">About</p> <div className="p-4" style={{ backgroundColor: '#f8f9fa' }}> <MDBCardText className="font-italic mb-1"><span style={{fontWeight:'bolder'}}>Email: </span>{item.email}</MDBCardText> <MDBCardText className="font-italic mb-1"><span style={{fontWeight:'bolder'}}>Website: </span>{item.website}</MDBCardText> <MDBCardText className="font-italic mb-0"><span style={{fontWeight:'bolder'}}>Phone: </span>{item.phone}</MDBCardText> </div> </div> <div className="d-flex justify-content-between align-items-center mb-4"> <MDBCardText className="lead fw-normal mb-0">Recent posts</MDBCardText> <MDBCardText className="mb-0"><Link to={`/mypost/${item.id}`} className="text-muted">Show all</Link></MDBCardText> </div> <MDBRow> {Post.map((val)=>( <MDBCol className="mb-2" key={val.id}> <div className='card' style={{objectFit:'contain',height:'100%',width:'250px',backgroundColor:'#fff',display:'flex',alignItems:'center'}}> <h3 style={{fontSize:'1.1rem',fontWeight:'700'}}>{val.title}</h3> <p style={{justifyContent:'space-evenly'}}>{val.body}</p> </div> </MDBCol> ))} </MDBRow> </MDBCardBody> </MDBCard> </MDBCol> </MDBRow> </MDBContainer> </div> ); }
import React from 'react'; import { useMemo, useEffect } from 'react'; import TextField from '@mui/material/TextField'; import Autocomplete from '@mui/material/Autocomplete'; import Box from '@mui/material/Box'; import DynamicIcon from '../mui/DynamicIcon.jsx' import config from '../../config.json' export default function MeterSelect({meterNames, meters, onChange}) { let meterOptions = []; meterOptions = useMemo(() => { return meterNames.map((meterName) => { let optionLabel = meterName; const prefix = meterName.split('.', 1)[0]; if (meters[meterName]) { return {value: meterName, label: optionLabel, prefix: prefix, type: meters[meterName]["type"]}; } else { return {value: meterName, label: meterName, prefix: prefix}; } }) }, [meterNames, meters]); if (meterNames) { return ( <> <Autocomplete options={meterOptions} id="current-meter" onChange={(event, newValue) => { onChange(newValue); }} isOptionEqualToValue={(option, value) => option.value === value.value} renderInput={(params) => ( <TextField {...params} label="Meter"/> )} renderOption={(props, option) => ( <Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}> <DynamicIcon iconNameSupplier={() => config.meter.type[option.type].icon}/> &nbsp; {option.label} </Box> )} groupBy={(option) => option.prefix} /> </> ); } }
"use client"; import { Disclosure } from "@headlessui/react"; import Image from "next/image"; import { FaRegStar, FaStar } from "react-icons/fa"; import { FaAngleUp, FaEllipsisVertical } from "react-icons/fa6"; import Rating from "react-rating"; const FeedbackSmallView = ({ feedbackData }) => { return ( <> <div className="lg:hidden overflow-x-auto"> {feedbackData.map((feedback) => ( <div key={feedback._id} className="mx-auto w-full mb-4 py-3 shadow-lg hover:shadow-2xl duration-300 " style={{ boxShadow: "0 0 10px rgba(0, 0, 0, 0.2)" }} > <Disclosure> {({ open }) => ( <> <Disclosure.Button className="flex w-full justify-between items-center rounded-lg px-4 text-left font-medium focus:outline-none focus:border-none "> <div className=" px-1 text-left flex gap-2 items-center justify-center"> <div className="h-6 w-6 overflow-hidden object-contain rounded"> <Image style={{ objectFit: "contain" }} src={feedback.customer_image} alt="product image" width={40} height={40} /> </div> <p>{feedback.customer_name}</p> </div> <p> <span className="mr-2">{feedback._id}</span> <FaAngleUp className={`${ open ? "rotate-180 transform duration-500" : "rotate-360 transform duration-500" } h-5 w-5 text-green-500 font-bold inline`} /> </p> </Disclosure.Button> <Disclosure.Panel className="px-4 pt-4 pb-2 !text-sm w-full"> <table className="w-full"> <tbody className="w-full"> <tr> <td className="font-semibold px-4 py-4 text-left border border-gray-300 "> Feedback </td> <td className=" px-4 py-4 text-left border border-gray-300 text-green-500 text-sm"> {feedback._id} </td> </tr> <tr> <td className="font-semibold px-4 py-4 text-left border border-gray-300 "> User </td> <td className=" px-4 py-4 text-left border border-gray-300 "> <div className="flex gap-2 items-center justify-left"> <div className="h-10 w-10 overflow-hidden object-contain rounded"> <Image style={{ objectFit: "contain" }} src={feedback.customer_image} alt="product image" width={100} height={100} /> </div> <span>{feedback.customer_name}</span> <br /> <span>{feedback.customer_email}</span> </div> </td> </tr> <tr> <td className="font-semibold px-4 py-4 text-left border border-gray-300 "> Rating </td> <td className=" px-4 py-4 text-left border border-gray-300 "> <Rating fractions={true} placeholderRating={feedback.rating} emptySymbol={ <FaRegStar className="text-yellow-400" /> } placeholderSymbol={ <FaStar className="text-yellow-400" /> } fullSymbol={ <FaStar className="text-yellow-400" /> } readonly /> </td> </tr> <tr> <td className=" font-semibold px-4 py-4 text-left border border-gray-300 "> Message </td> <td className=" px-4 py-4 text-left border border-gray-300 font-semibold"> {feedback.feedback.length > 100 ? ( <> {feedback.feedback.slice(0, 100)}{" "} <span>...</span>{" "} </> ) : ( feedback.feedback )} </td> </tr> <tr> <td className=" font-semibold px-4 py-4 text-left border border-gray-300 "> Actions </td> <td className=" px-4 py-4 text-left border border-gray-300 font-semibold"> <FaEllipsisVertical size={30} className="text-green-500 cursor-pointer" /> </td> </tr> </tbody> </table> </Disclosure.Panel> </> )} </Disclosure> </div> ))} </div> </> ); }; export default FeedbackSmallView;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <title>@yield('title')</title> @include('frontend.layout.styles') <!-- All Javascripts --> @include('frontend.layout.scripts') <link href="https://fonts.googleapis.com/css2?family=Maven+Pro:wght@400;500;600;700&display=swap" rel="stylesheet"> <script type="text/javascript" src="//s7.addthis.com/{{ asset('/') }}frontend/assets/js/300/addthis_widget.js#pubid=ra-6212352ed76fda0a"></script> <!-- Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-84213520-6"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-84213520-6'); </script> </head> <body> <div class="top"> <div class="container"> <div class="row"> <div class="col-md-6"> <ul> <li class="today-text">Today: January 20, 2022</li> <li class="email-text">contact@arefindev.com</li> </ul> </div> <div class="col-md-6"> <ul class="right"> @if($global_pages->faq_status == 'show') <li class="menu"><a href="{{ route('front_faq') }}">FAQ</a></li> @endif @if($global_pages->about_status == 'show') <li class="menu"><a href="{{ route('front_about') }}">About</a></li> @endif @if($global_pages->contact_status == 'show') <li class="menu"><a href="{{ route('front_contact') }}">Contact</a></li> @endif @if($global_pages->login_status == 'show') <li class="menu"><a href="{{ route('front_login') }}">Login</a></li> @endif <li> <div class="language-switch"> <select name=""> <option value="">English</option> <option value="">Hindi</option> <option value="">Arabic</option> </select> </div> </li> </ul> </div> </div> </div> </div> <div class="heading-area"> <div class="container"> <div class="row"> <div class="col-md-4 d-flex align-items-center"> <div class="logo"> <a href="{{ route('front_home') }}"> <img src="{{ asset('/') }}frontend/assets/uploads/logo.png" alt=""> </a> </div> </div> <div class="col-md-8"> @if($global_top_add_data->top_search_ad_status == 'show') <div class="ad-section-1"> @if($global_top_add_data->top_search_ad_url=='') <img src="{{ asset('frontend/assets/uploads/'.$global_top_add_data->top_search_ad) }}" alt=""> @else <a href="{{ $global_top_add_data->top_search_ad_url }}"><img src="{{ asset('frontend/assets/uploads/'.$global_top_add_data->top_search_ad) }}" alt=""></a> @endif </div> @endif </div> </div> </div> </div> @include('frontend.menu') @yield('main_content') @include('frontend.footer') <div class="copyright"> Copyright 2022, ArefinDev. All Rights Reserved. </div> <div class="scroll-top"> <i class="fas fa-angle-up"></i> </div> @include('frontend.layout.script_footer') @if(session()->has('error')) <script> iziToast.error({ title: 'Error', position:'topRight', message: '{{ session()->get('error') }}', }); </script> @endif @if(session()->has('success')) <script> iziToast.success({ title: '', position:'topRight', message:'{{ session()->get('success') }}' }); </script> @endif </body> </html>
# Simple Docker ## Part 1. Готовый докер В качестве конечной цели своей небольшой практики вы сразу выбрали написание докер образа для собственного веб сервера, а потому в начале вам нужно разобраться с уже готовым докер образом для сервера. Ваш выбор пал на довольно простой **nginx**. **== Задание ==** #### Взять официальный докер образ с **nginx** и выкачать его при помощи `docker pull` ![docker](screenshots/001.png) #### Проверить наличие докер образа через `docker images` ![docker](screenshots/002.png) #### Запустить докер образ через `docker run -d [image_id|repository]` ![docker](screenshots/003.png) #### Проверить, что образ запустился через `docker ps` ![docker](screenshots/004.png) #### Посмотреть информацию о контейнере через `docker inspect [container_id|container_name]` ![docker](screenshots/005.png) #### По выводу команды определить и поместить в отчёт размер контейнера, список замапленных портов и ip контейнера ![docker](screenshots/006.png) #### Остановить докер образ через `docker stop [container_id|container_name]` ![docker](screenshots/007.png) #### Проверить, что образ остановился через `docker ps` ![docker](screenshots/008.png) #### Запустить докер с замапленными портами 80 и 443 на локальную машину через команду *run* ![docker](screenshots/019.png) #### Проверить, что в браузере по адресу *localhost:80* доступна стартовая страница **nginx** ![docker](screenshots/010.png) #### Перезапустить докер контейнер через `docker restart [container_id|container_name]` ![docker](screenshots/111.png) #### Проверить любым способом, что контейнер запустился ![docker](screenshots/012.png) ## Part 2. Операции с контейнером #### Прочитать конфигурационный файл *nginx.conf* внутри докер образа через команду *exec* ![docker](screenshots/101.png) #### Создать на локальной машине файл *nginx.conf* и настроить в нем по пути */status* отдачу страницы статуса сервера **nginx** ![docker](screenshots/203.png) #### Скопировать созданный файл *nginx.conf* внутрь докер образа через команду `docker cp` ![docker](screenshots/104.png) #### Перезапустить **nginx** внутри докер образа через команду *exec* ![docker](screenshots/105.png) #### Проверить, что по адресу *localhost:80/status* отдается страничка со статусом сервера **nginx** ![docker](screenshots/106.png) #### Экспортировать контейнер в файл *container.tar* через команду *export* ![docker](screenshots/107.png) #### Остановить контейнер ![docker](screenshots/108.png) #### Удалить образ через `docker rmi [image_id|repository]`, не удаляя перед этим контейнеры ![docker](screenshots/109.png) #### Импортировать контейнер обратно через команду *import* ![docker](screenshots/110.png) #### Запустить импортированный контейнер ![docker](screenshots/112.png)
interface Item { name: string; price: number; img: string; } const Cards = ({ item, handleClick, }: { item: Item, handleClick: (item: Item) => void, }) => { const { name, price, img } = item; return ( <> <section className="flex flex-row px-6 py-4 lg:w-1/4 w-full"> <div className="p-1 md:w-1/3 w-1/2 lg:w-full mb-4"> <div className="h-full border-2 border-gray-200 border-opacity-60 rounded-lg overflow-auto"> <img className="lg:h-72 md:h-36 h-48 w-full object-cover object-center" src={img} alt="item" /> <div className="px-3 py-2"> <h1 className="text-xl font-bold mb-3">{name}</h1> <div className="flex flex-wrap justify-between mb-2 mt-4"> <p className="leading-relaxed mt-4 text-lg">Price: ₦{price}</p> <button onClick={() => handleClick(item)} className="bg-yellow-400 py-2 px-2 text-white rounded hover:border-2 hover:bg-white hover:text-yellow-400 hover:border-brandColor" > Add to Cart </button> </div> </div> </div> </div> </section> </> ); }; export default Cards;
import { PiecePropValueSchema, Property, createTrigger, } from '@activepieces/pieces-framework'; import { TriggerStrategy } from '@activepieces/pieces-framework'; import { DedupeStrategy, Polling, pollingHelper, } from '@activepieces/pieces-common'; import { sftpAuth } from '../..'; import dayjs from 'dayjs'; import Client from 'ssh2-sftp-client'; const polling: Polling< PiecePropValueSchema<typeof sftpAuth>, { path: string; ignoreHiddenFiles?: boolean } > = { strategy: DedupeStrategy.TIMEBASED, items: async ({ auth, propsValue, lastFetchEpochMS }) => { const host = auth.host; const port = auth.port; const username = auth.username; const password = auth.password; const sftp = new Client(); try { await sftp.connect({ host, port, username, password, }); let files = await sftp.list(propsValue.path); await sftp.end(); files = files.filter( (file) => dayjs(file.modifyTime).valueOf() > lastFetchEpochMS ); if ((propsValue.ignoreHiddenFiles ?? false) === true) files = files.filter((file) => !file.name.startsWith('.')); return files.map((file) => ({ data: { ...file, path: `${propsValue.path}/${file.name}`, }, epochMilliSeconds: dayjs(file.modifyTime).valueOf(), })); } catch (err) { return []; } }, }; export const newOrModifiedFile = createTrigger({ auth: sftpAuth, name: 'new_file', displayName: 'New File', description: 'Trigger when a new file is created or modified.', props: { path: Property.ShortText({ displayName: 'Path', description: 'The path to watch for new files', required: true, defaultValue: './', }), ignoreHiddenFiles: Property.Checkbox({ displayName: 'Ignore hidden files', description: 'Ignore hidden files', required: false, defaultValue: false, }), }, type: TriggerStrategy.POLLING, onEnable: async (context) => { await pollingHelper.onEnable(polling, { auth: context.auth, store: context.store, propsValue: context.propsValue, }); }, onDisable: async (context) => { await pollingHelper.onDisable(polling, { auth: context.auth, store: context.store, propsValue: context.propsValue, }); }, run: async (context) => { return await pollingHelper.poll(polling, { auth: context.auth, store: context.store, propsValue: context.propsValue, }); }, test: async (context) => { return await pollingHelper.test(polling, { auth: context.auth, store: context.store, propsValue: context.propsValue, }); }, sampleData: {}, });
import RestraurantCard from "./RestraurantCard"; // import restrautList from "../utils/mockData"; import { useContext, useEffect, useState } from "react"; import Shimmer from "./Shimmer"; import { Link } from "react-router-dom"; import useOnlineStatus from "../utils/useOnline"; import WhatOnMind from "./WhatOnMind"; import UserContext from "../utils/UserContext"; import uesRestrauntData from "../utils/useRestrauntData"; import { generateProxyUrl } from "../utils/constants"; import Login from "./Login"; import { useDispatch, useSelector } from "react-redux"; import { onAuthStateChanged } from "firebase/auth"; import { addUser, removeUser } from "../utils/redux/userSlice"; import { auth } from "../utils/firebase"; import GetLocation from "./GetLocation"; import LocationContext from "../utils/context/LocationContext"; import { stringify } from "postcss"; import Filters from "./Filters"; const Body = () => { //Local State Variables - Super powerful variable const [restraunt, setRestraunt] = useState([]); //here it did array destruturing // const arr = useState(resList); // const [restraunt,setRestraunt] =arr; // these are he same thing const [filteredRestraunt, setFilteredRestraunt] = useState([]); const [searchText, setSearchText] = useState(""); const [whatsOnYourMind, setWhatsOnYourMind] = useState(); const [topRestraunt, setTopRestraunt] = useState(); const [current, setCurrent] = useState(0); const [onCloseModal, setOnCloseModal] = useState(false); const { location, dataFromLocal } = useContext(LocationContext); const [filteredData, setFilteredData] = useState(null); console.log(location, "locationssss"); const dispatch = useDispatch(); // whenever state variables update, react triggers a reconciliation cycle(RE - render component) //console.log("body rendered"); const { logggdInUser, setUserName } = useContext(UserContext); const isModalOpen = useSelector((state) => state.modal.isMenuOpen); console.log(isModalOpen, "isModalOpen"); useEffect(() => { onAuthStateChanged(auth, (user) => { if (user) { // User is signed in, see docs for a list of available properties // https://firebase.google.com/docs/reference/js/auth.user const { uid, email, displayName, photoURL } = user; dispatch( addUser({ uid: uid, email: email, displayName: displayName, photoURL: photoURL, isLoggedIn: true, }) ); // ... } else { // User is signed out // ... dispatch(removeUser()); } }); }, []); useEffect(() => { getData(); }, [location]); useEffect(() => { const storedData = JSON.parse(localStorage.getItem("address:")); }, []); // const resData = uesRestrauntData(); //console.log(resData, "data from custom hook"); async function getData() { try { if (location !== null) { // const resource = generateProxyUrl( // `https://www.swiggy.com/dapi/restaurants/list/v5?lat=${location.lat}&lng=${location.lng}&is-seo-homepage-enabled=true` // ); const data = await fetch( `https://thingproxy.freeboard.io/fetch/https://www.swiggy.com/dapi/restaurants/list/v5?lat=${location.lat}&lng=${location.lng}&is-seo-homepage-enabled=true` ); const json = await data.json(); //console.log( console.log("🚀 ~ file: Body.js:89 ~ getData ~ data:", data); // json?.data?.cards[4]?.card?.card?.gridElements?.infoWithStyle ?.restaurants // ); const restruntList = json.data.cards.filter((res) => { return res.card.card.id === "restaurant_grid_listing"; }); setFilteredData( json.data?.cards?.filter((res) => { return ( res?.card?.card?.["@type"] === "type.googleapis.com/swiggy.gandalf.widgets.v2.InlineViewFilterSortWidget" ); }) ); setWhatsOnYourMind( json.data?.cards?.filter((res) => { return res?.card?.card?.id === "whats_on_your_mind"; }) ); setTopRestraunt(json.data?.cards[1]?.card?.card); //console.log(whatsOnYourMind, "in mind"); setRestraunt( restruntList[0]?.card?.card?.gridElements?.infoWithStyle?.restaurants ); // const card setFilteredRestraunt( restruntList[0]?.card?.card?.gridElements?.infoWithStyle?.restaurants ); console.log(json.data); //console.log(filteredRestraunt, "filterr"); console.log(topRestraunt, "restrauntList"); } else { const resource = generateProxyUrl( `https://www.swiggy.com/dapi/restaurants/list/v5?lat=26.1157917&lng=91.7085933&is-seo-homepage-enabled=true` ); const data = await fetch( `https://thingproxy.freeboard.io/fetch/https://www.swiggy.com/dapi/restaurants/list/v5?lat=26.1157917&lng=91.7085933&is-seo-homepage-enabled=true` ); const json = await data.json(); //console.log( console.log("🚀 ~ file: Body.js:133 ~ getData ~ data:", data); // json?.data?.cards[4]?.card?.card?.gridElements?.infoWithStyle ?.restaurants // ); const restruntList = json.data.cards.filter((res) => { return res.card.card.id === "restaurant_grid_listing"; }); setWhatsOnYourMind( json.data?.cards?.filter((res) => { return res?.card?.card?.id === "whats_on_your_mind"; }) ); setFilteredData( json.data?.cards?.filter((res) => { return ( res?.card?.card?.["@type"] === "type.googleapis.com/swiggy.gandalf.widgets.v2.InlineViewFilterSortWidget" ); }) ); setTopRestraunt(json.data?.cards[1]?.card?.card); //console.log(whatsOnYourMind, "in mind"); setRestraunt( restruntList[0]?.card?.card?.gridElements?.infoWithStyle?.restaurants ); // const card setFilteredRestraunt( restruntList[0]?.card?.card?.gridElements?.infoWithStyle?.restaurants ); console.log(json.data); //console.log(filteredRestraunt, "filterr"); console.log(topRestraunt, "restrauntList"); } // https://www.swiggy.com/mapi/restaurants/list/v5?offset=0&is-seo-homepage-enabled=true&lat=26.1157917&lng=91.7085933&carousel=true&third_party_vendor=1 // } catch (err) { console.log(err); } } const onlineStatus = useOnlineStatus(); console.log(filteredData, "filtered"); //Early return if (!onlineStatus) { return ( <h1 className="p-10 font-semibold text-xl"> Looks like you are offline please check your internet connection </h1> ); } function handleSearchInput(e) { setSearchText(e.target.value); // //console.log(searchText) } //conditional rendering // if(restraunt.length===0) // { // return <Shimmer/> // } function prevSlide() { if (current === 0) { setCurrent( topRestraunt?.gridElements?.infoWithStyle?.restaurants.length - 1 - 7 ); } else { setCurrent(current - 4); } } function nextSlide() { //console.log("clicked"); if ( current >= topRestraunt?.gridElements?.infoWithStyle?.restaurants.length - 1 - 7 ) { setCurrent(0); } else { setCurrent(current + 4); } } return restraunt?.length === 0 ? ( <Shimmer /> ) : ( <div className=" w-[20rem] sm:min-w-[600px] md:min-w-[670px] lg:min-w-[961px] mx-auto"> {whatsOnYourMind.length !== 0 && ( <div className="overflow-hidden my-10 pb-2 border-b "> <WhatOnMind whatsOnYourMind={whatsOnYourMind} /> </div> )} {topRestraunt?.gridElements?.infoWithStyle?.restaurants.length !== 0 && ( <div className=" overflow-hidden border-b pb-2"> <div> <div className="flex justify-between mb-6"> <h1 className="font-medium text-xs md:text-xl lg:text-2xl"> {topRestraunt?.header?.title} </h1> <div> <button className="px-2 sm:px-1 hover:bg-sky-100" onClick={prevSlide} > ⬅ </button> <button className="px-2 sm:px-1 hover:bg-slate-100" onClick={nextSlide} > ➡ </button> </div> </div> <div className="flex w-[7000px] transition ease-out duration-40" style={{ transform: `translateX(-${current * 4}%)` }} > {topRestraunt?.gridElements?.infoWithStyle?.restaurants?.map( (restraunt) => ( <Link to={"/restraunts/" + restraunt.info.id} key={restraunt.info.id} > {" "} <RestraurantCard resData={restraunt} />{" "} </Link> ) )} </div> </div> </div> )} {/* <div className="flex justify-center items-center mx-auto mt-6 mb-4"> <input className="mr-4 mt-1 p-1 w-24 text-[6px] sm:text-[8px] md:text-[10px] lg:text-[15px] md:w-44 lg:w-60 border rounded outline-none " type="text" placeholder="Search" onChange={handleSearchInput} ></input> <div> <button className="bg-green-300 rounded p-1 px-2 mr-2 md:text-[10px] sm:text-[8px] lg:text-[15px] text-[8px] " onClick={() => { const filterData = restraunt.filter((res) => { return res.info.name .toLowerCase() .includes(searchText.toLowerCase()); }); setFilteredRestraunt(filterData); //console.log(filterData, "fill"); }} > Search </button> <button className="bg-rose-300 rounded p-1 px-2 mr-6 md:text-[10px] sm:text-[8px] lg:text-[15px] text-[8px]" onClick={() => { let filterRes = restraunt.filter( (res) => res.info.avgRating > 4.2 ); setFilteredRestraunt(filterRes); //console.log("button clicked", filterRes); }} > Top rated restraunts </button> {/* <input className=" " value={logggdInUser} onChange={(e) => { setUserName(e.target.value); }} */} {/* /> */} {/* </div> */} {/* </div> */} {/* <div> <Filters filteredData={filteredData} /> </div> */} <div className="flex flex-wrap "> {/* //componenet */} {filteredRestraunt?.map((restraunt) => ( <Link to={"/restraunts/" + restraunt.info.id} key={restraunt.info.id}> {" "} <RestraurantCard resData={restraunt} /> </Link> ))} </div> <div> <Login isModalOpen={isModalOpen} />{" "} </div> </div> ); }; export default Body;
const express = require('express') const app = express() const router = express.Router() const mongoose = require("mongoose") const Student = require("./models/student-mongo") const cors = require('cors') app.use(express.json()) app.use(express.urlencoded({extended: true})) app.use(cors()) mongoose.connect("mongodb://localhost:27017/studentdb", (err)=>{ if(err){ throw err } else { console.log(`Connected to mongodb successfully !!!`) } }) router.get("/", (req, res) => { res.json('Welcome to Student API using MongoDB') }) router.get("/students", (req, res) => { Student.getStudents(function(err, data){ if(err){ throw err } res.json(data) }) }) router.get("/students/:id", (req, res) => { const studentId = req.params.id Student.getStudentById(studentId, (err, data)=>{ if(err){ throw err } res.json(data) }) }) router.post("/students", (req, res) => { const student = req.body Student.createStudent(student, (err, data)=>{ if(err){ throw err } res.json(data) }) }) router.put("/students/:id", (req, res)=>{ const studentId = req.params.id const student = req.body Student.updateStudent(studentId, student, (err, data)=>{ if(err){ throw err } res.json(data) }) }) router.delete("/students/:id", (req, res)=>{ const studentId = req.params.id Student.deleteStudent(studentId, function(err, data){ if(err){ throw err } res.json(data) }) }) app.use("/api", router) const PORT = 3001 app.listen(PORT, () => { console.log(`Server listening at PORT ${PORT}`) })
/* Scan Tailor - Interactive post-processing tool for scanned pages. Copyright (C) 2007-2008 Joseph Artsimovich <joseph_a@mail.ru> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef PAGE_SPLIT_DEPENDENCIES_H_ #define PAGE_SPLIT_DEPENDENCIES_H_ #include <QSize> #include "LayoutType.h" #include "OrthogonalRotation.h" class QString; class QDomDocument; class QDomElement; namespace page_split { class Params; /** * \brief Dependencies of a page parameters. * * Once dependencies change, the stored page parameters are no longer valid. */ class Dependencies { // Member-wise copying is OK. public: Dependencies(); explicit Dependencies(const QDomElement& el); Dependencies(const QSize& image_size, OrthogonalRotation rotation, LayoutType layout_type); void setLayoutType(LayoutType type); const OrthogonalRotation& orientation() const; bool compatibleWith(const Params& params) const; bool isNull() const; QDomElement toXml(QDomDocument& doc, const QString& tag_name) const; private: QSize m_imageSize; OrthogonalRotation m_rotation; LayoutType m_layoutType; }; } // namespace page_split #endif // ifndef PAGE_SPLIT_DEPENDENCIES_H_
import assert from 'assert'; import { ArrayType, generalizeType, SourceUnit, StructDefinition, TypeNode, UserDefinedType, } from 'solc-typed-ast'; import { AST } from '../../ast/ast'; import { CairoImportFunctionDefinition } from '../../ast/cairoNodes'; import { CairoFunctionDefinition } from '../../export'; import { printTypeNode } from '../../utils/astPrinter'; import { CairoType, MemoryLocation, TypeConversionContext } from '../../utils/cairoTypeSystem'; import { TranspileFailedError } from '../../utils/errors'; import { getElementType, getPackedByteSize, isAddressType, isDynamicallySized, isDynamicArray, isStruct, safeGetNodeType, } from '../../utils/nodeTypeProcessing'; import { uint256 } from '../../warplib/utils'; import { delegateBasedOnType, GeneratedFunctionInfo, mul } from '../base'; import { MemoryReadGen } from '../memory/memoryRead'; import { AbiBase, removeSizeInfo } from './base'; const IMPLICITS = '{bitwise_ptr : BitwiseBuiltin*, range_check_ptr : felt, warp_memory : DictAccess*}'; /** * It is a special class used for encoding of indexed arguments in events. * More info at: https://docs.soliditylang.org/en/v0.8.14/abi-spec.html#encoding-of-indexed-event-parameters */ export class IndexEncode extends AbiBase { protected override functionName = 'index_encode'; protected memoryRead: MemoryReadGen; constructor(memoryRead: MemoryReadGen, ast: AST, sourceUnit: SourceUnit) { super(ast, sourceUnit); this.memoryRead = memoryRead; } public getOrCreate(types: TypeNode[]): GeneratedFunctionInfo { const [params, encodings, functionsCalled] = types.reduce( ([params, encodings, functionsCalled], type, index) => { const cairoType = CairoType.fromSol(type, this.ast, TypeConversionContext.Ref); params.push({ name: `param${index}`, type: cairoType.toString() }); const [paramEncoding, paramFuncCalls] = this.generateEncodingCode( type, 'bytes_index', `param${index}`, false, ); encodings.push(paramEncoding); return [params, encodings, functionsCalled.concat(paramFuncCalls)]; }, [ new Array<{ name: string; type: string }>(), new Array<string>(), new Array<CairoFunctionDefinition>(), ], ); const cairoParams = params.map((p) => `${p.name} : ${p.type}`).join(', '); const funcName = `${this.functionName}${this.generatedFunctionsDef.size}`; const code = [ `func ${funcName}${IMPLICITS}(${cairoParams}) -> (result_ptr : felt){`, ` alloc_locals;`, ` let bytes_index : felt = 0;`, ` let (bytes_array : felt*) = alloc();`, ...encodings, ` let (max_length256) = felt_to_uint256(bytes_index);`, ` let (mem_ptr) = wm_new(max_length256, ${uint256(1)});`, ` felt_array_to_warp_memory_array(0, bytes_array, 0, mem_ptr, bytes_index);`, ` return (mem_ptr,);`, `}`, ].join('\n'); const importedFuncs = [ this.requireImport('starkware.cairo.common.alloc', 'alloc'), this.requireImport('starkware.cairo.common.cairo_builtins', 'BitwiseBuiltin'), this.requireImport('starkware.cairo.common.uint256', 'Uint256'), this.requireImport('warplib.maths.utils', 'felt_to_uint256'), this.requireImport('warplib.memory', 'wm_new'), this.requireImport('warplib.dynamic_arrays_util', 'felt_array_to_warp_memory_array'), ]; const cairoFunc = { name: funcName, code: code, functionsCalled: [...importedFuncs, ...functionsCalled], }; return cairoFunc; } /** * Given a type generate a function that abi-encodes it * @param type type to encode * @returns the name of the generated function */ public getOrCreateEncoding(type: TypeNode, padding = true): CairoFunctionDefinition { const unexpectedType = () => { throw new TranspileFailedError(`Encoding ${printTypeNode(type)} is not supported yet`); }; return delegateBasedOnType<CairoFunctionDefinition>( type, (type) => type instanceof ArrayType ? this.createDynamicArrayHeadEncoding(type) : padding ? this.createStringOrBytesHeadEncoding() : this.createStringOrBytesHeadEncodingWithoutPadding(), (type) => isDynamicallySized(type, this.ast.inference) ? this.createStaticArrayHeadEncoding(type) : this.createArrayInlineEncoding(type), (type, def) => isDynamicallySized(type, this.ast.inference) ? this.createStructHeadEncoding(type, def) : this.createStructInlineEncoding(type, def), unexpectedType, () => this.createValueTypeHeadEncoding(), ); } /** * Given a type it generates the function to encodes it, as well as all other * instructions required to use it. * @param type type to encode * @param newIndexVar cairo var where the updated index should be stored * @param varToEncode variable that holds the values to encode * @returns instructions to encode `varToEncode` */ public generateEncodingCode( type: TypeNode, newIndexVar: string, varToEncode: string, padding = true, ): [string, CairoFunctionDefinition[]] { const func = this.getOrCreateEncoding(type, padding); if (isDynamicallySized(type, this.ast.inference) || isStruct(type)) { return [ [ `let (${newIndexVar}) = ${func.name}(`, ` bytes_index,`, ` bytes_array,`, ` ${varToEncode}`, `);`, ].join('\n'), [func], ]; } // Static array with known compile time size if (type instanceof ArrayType) { assert(type.size !== undefined); return [ [ `let (${newIndexVar}) = ${func.name}(`, ` bytes_index,`, ` bytes_array,`, ` 0,`, ` ${type.size},`, ` ${varToEncode},`, `);`, ].join('\n'), [func], ]; } // Is value type const size = getPackedByteSize(type, this.ast.inference); const instructions: string[] = []; const importedFunc = []; // packed size of addresses is 32 bytes, but they are treated as felts, // so they should be converted to Uint256 accordingly if (size < 32 || isAddressType(type)) { instructions.push(`let (${varToEncode}256) = felt_to_uint256(${varToEncode});`); importedFunc.push(this.requireImport(`warplib.maths.utils`, 'felt_to_uint256')); varToEncode = `${varToEncode}256`; } instructions.push( ...[ `${func.name}(bytes_index, bytes_array, 0, ${varToEncode});`, `let ${newIndexVar} = bytes_index + 32;`, ], ); return [instructions.join('\n'), importedFunc]; } private createDynamicArrayHeadEncoding(type: ArrayType): CairoFunctionDefinition { const key = 'head ' + type.pp(); const existing = this.auxiliarGeneratedFunctions.get(key); if (existing !== undefined) return existing; const tailEncoding = this.createDynamicArrayTailEncoding(type); const name = `${this.functionName}_head_dynamic_array_spl${this.auxiliarGeneratedFunctions.size}`; const code = [ `func ${name}${IMPLICITS}(`, ` bytes_index: felt,`, ` bytes_array: felt*,`, ` mem_ptr : felt`, `) -> (final_bytes_index : felt){`, ` alloc_locals;`, ` let (length256) = wm_dyn_array_length(mem_ptr);`, ` let (length) = narrow_safe(length256);`, ` // Storing the element values encoding`, ` let (new_index) = ${tailEncoding.name}(`, ` bytes_index,`, ` bytes_array,`, ` 0,`, ` length,`, ` mem_ptr`, ` );`, ` return (`, ` final_bytes_index=new_index,`, ` );`, `}`, ].join('\n'); const importedFuncs = [ this.requireImport('warplib.memory', 'wm_dyn_array_length'), this.requireImport('warplib.maths.utils', 'felt_to_uint256'), this.requireImport('warplib.maths.utils', 'narrow_safe'), ]; const funcInfo = { name, code, functionsCalled: [...importedFuncs, tailEncoding] }; const auxFunc = this.createAuxiliarGeneratedFunction(funcInfo); this.auxiliarGeneratedFunctions.set(key, auxFunc); return auxFunc; } private createDynamicArrayTailEncoding(type: ArrayType): CairoFunctionDefinition { const key = 'tail ' + type.pp(); const existing = this.auxiliarGeneratedFunctions.get(key); if (existing !== undefined) return existing; const elementT = getElementType(type); const elementTSize = CairoType.fromSol(elementT, this.ast).width; const [readElement, readFunc] = this.readMemory(elementT, 'elem_loc'); const [headEncodingCode, functionsCalled] = this.generateEncodingCode( elementT, 'bytes_index', 'elem', ); const name = `${this.functionName}_tail_dynamic_array_spl${this.auxiliarGeneratedFunctions.size}`; const code = [ `func ${name}${IMPLICITS}(`, ` bytes_index : felt,`, ` bytes_array : felt*,`, ` index : felt,`, ` length : felt,`, ` mem_ptr : felt`, `) -> (final_index : felt){`, ` alloc_locals;`, ` if (index == length){`, ` return (final_index=bytes_index);`, ` }`, ` let (index256) = felt_to_uint256(index);`, ` let (elem_loc) = wm_index_dyn(mem_ptr, index256, ${uint256(elementTSize)});`, ` let (elem) = ${readElement};`, ` ${headEncodingCode}`, ` return ${name}(bytes_index, bytes_array, index + 1, length, mem_ptr);`, `}`, ].join('\n'); const importedFuncs = [ this.requireImport('warplib.memory', 'wm_index_dyn'), this.requireImport('warplib.maths.utils', 'felt_to_uint256'), ]; const funcInfo = { name, code, functionsCalled: [...importedFuncs, ...functionsCalled, readFunc], }; const auxFunc = this.createAuxiliarGeneratedFunction(funcInfo); this.auxiliarGeneratedFunctions.set(key, auxFunc); return auxFunc; } private createStaticArrayHeadEncoding(type: ArrayType): CairoFunctionDefinition { assert(type.size !== undefined); const key = 'head ' + type.pp(); const existing = this.auxiliarGeneratedFunctions.get(key); if (existing !== undefined) return existing; const inlineEncoding = this.createArrayInlineEncoding(type); const name = `${this.functionName}_head_static_array_spl${this.auxiliarGeneratedFunctions.size}`; const code = [ `func ${name}${IMPLICITS}(`, ` bytes_index : felt,`, ` bytes_array : felt*,`, ` mem_ptr : felt,`, `) -> (final_bytes_index : felt){`, ` alloc_locals;`, ` let length = ${type.size};`, ` // Storing the data values encoding`, ` let (bytes_index) = ${inlineEncoding}(`, ` bytes_index,`, ` bytes_array,`, ` 0,`, ` length,`, ` mem_ptr`, ` );`, ` return (`, ` final_bytes_index=new_bytes_index,`, ` );`, `}`, ].join('\n'); const importedFunc = this.requireImport('warplib.maths.utils', 'felt_to_uint256'); const funcInfo = { name, code, functionsCalled: [importedFunc] }; const auxFunc = this.createAuxiliarGeneratedFunction(funcInfo); this.auxiliarGeneratedFunctions.set(key, auxFunc); return auxFunc; } private createArrayInlineEncoding(type: ArrayType): CairoFunctionDefinition { const key = 'inline ' + removeSizeInfo(type); const existing = this.auxiliarGeneratedFunctions.get(key); if (existing !== undefined) return existing; const elementTWidth = CairoType.fromSol(type.elementT, this.ast).width; const [readElement, readFunc] = this.readMemory(type.elementT, 'elem_loc'); const [headEncodingCode, functionsCalled] = this.generateEncodingCode( type.elementT, 'bytes_index', 'elem', ); const name = `${this.functionName}_inline_array_spl${this.auxiliarGeneratedFunctions.size}`; const code = [ `func ${name}${IMPLICITS}(`, ` bytes_index : felt,`, ` bytes_array : felt*,`, ` mem_index : felt,`, ` mem_length : felt,`, ` mem_ptr : felt,`, `) -> (final_bytes_index : felt){`, ` alloc_locals;`, ` if (mem_index == mem_length){`, ` return (final_bytes_index=bytes_index);`, ` }`, ` let elem_loc = mem_ptr + ${mul('mem_index', elementTWidth)};`, ` let (elem) = ${readElement};`, ` ${headEncodingCode}`, ` return ${name}(`, ` bytes_index,`, ` bytes_array,`, ` mem_index + 1,`, ` mem_length,`, ` mem_ptr`, ` );`, `}`, ].join('\n'); const funcInfo = { name, code, functionsCalled: [...functionsCalled, readFunc] }; const auxFunc = this.createAuxiliarGeneratedFunction(funcInfo); this.auxiliarGeneratedFunctions.set(key, auxFunc); return auxFunc; } private createStructHeadEncoding( type: UserDefinedType, def: StructDefinition, ): CairoFunctionDefinition { const key = 'struct head ' + type.pp(); const existing = this.auxiliarGeneratedFunctions.get(key); if (existing !== undefined) return existing; const inlineEncoding = this.createStructInlineEncoding(type, def); const name = `${this.functionName}_head_spl_${def.name}`; const code = [ `func ${name}${IMPLICITS}(`, ` bytes_index : felt,`, ` bytes_array : felt*,`, ` mem_ptr : felt,`, `) -> (final_bytes_index : felt){`, ` alloc_locals;`, ` // Storing the data values encoding`, ` let (bytes_index) = ${inlineEncoding}(`, ` bytes_index,`, ` bytes_array,`, ` mem_ptr`, `);`, ` return (bytes_index,);`, `}`, ].join('\n'); const importedFunction = this.requireImport('warplib.maths.utils', 'felt_to_uint256'); const funcInfo = { name, code, functionsCalled: [importedFunction, inlineEncoding] }; const auxFunc = this.createAuxiliarGeneratedFunction(funcInfo); this.auxiliarGeneratedFunctions.set(key, auxFunc); return auxFunc; } private createStructInlineEncoding( type: UserDefinedType, def: StructDefinition, ): CairoFunctionDefinition { const key = 'struct inline ' + type.pp(); const existing = this.auxiliarGeneratedFunctions.get(key); if (existing !== undefined) return existing; const encodingInfo: [string, CairoFunctionDefinition[]][] = def.vMembers.map( (member, index) => { const type = generalizeType(safeGetNodeType(member, this.ast.inference))[0]; const elemWidth = CairoType.fromSol(type, this.ast).width; const [readElement, readFunc] = this.readMemory(type, 'mem_ptr'); const [encoding, functionsCalled] = this.generateEncodingCode( type, 'bytes_index', `elem${index}`, ); return [ [ `// Encoding member ${member.name}`, `let (elem${index}) = ${readElement};`, `${encoding}`, `let mem_ptr = mem_ptr + ${elemWidth};`, ].join('\n'), [...functionsCalled, readFunc], ]; }, ); const [instructions, functionsCalled] = encodingInfo.reduce( ([instructions, functionsCalled], [currentInstruction, currentFuncs]) => [ [...instructions, currentInstruction], [...functionsCalled, ...currentFuncs], ], [new Array<string>(), new Array<CairoFunctionDefinition>()], ); const name = `${this.functionName}_inline_struct_spl_${def.name}`; const code = [ `func ${name}${IMPLICITS}(`, ` bytes_index : felt,`, ` bytes_array : felt*,`, ` mem_ptr : felt,`, `) -> (final_bytes_index : felt){`, ` alloc_locals;`, ...instructions, ` return (bytes_index,);`, `}`, ].join('\n'); const funcInfo = { name, code, functionsCalled }; const auxFunc = this.createAuxiliarGeneratedFunction(funcInfo); this.auxiliarGeneratedFunctions.set(key, auxFunc); return auxFunc; } private createStringOrBytesHeadEncoding(): CairoImportFunctionDefinition { const funcName = 'bytes_to_felt_dynamic_array_spl'; return this.requireImport('warplib.dynamic_arrays_util', funcName); } private createStringOrBytesHeadEncodingWithoutPadding(): CairoImportFunctionDefinition { const funcName = 'bytes_to_felt_dynamic_array_spl_without_padding'; return this.requireImport('warplib.dynamic_arrays_util', funcName); } private createValueTypeHeadEncoding(): CairoImportFunctionDefinition { const funcName = 'fixed_bytes256_to_felt_dynamic_array_spl'; return this.requireImport('warplib.dynamic_arrays_util', funcName); } protected readMemory(type: TypeNode, arg: string): [string, CairoFunctionDefinition] { const func = this.memoryRead.getOrCreateFuncDef(type); const cairoType = CairoType.fromSol(type, this.ast); const args = cairoType instanceof MemoryLocation ? [arg, isDynamicArray(type) ? uint256(2) : uint256(0)] : [arg]; return [`${func.name}(${args.join(',')})`, func]; } }
import { PropsWithChildren } from 'react'; import { Link as LinkComponent } from 'react-router-dom'; import styled from 'styled-components'; const Contents = styled.div` color: ${props => props.theme.railfg2}; font-weight: 500; font-size: 15px; text-align: center; margin: 0.25rem 0; cursor: pointer; transition: color 200ms; &:hover { color: ${props => props.theme.primary}; } `; const Link = styled(LinkComponent)` color: inherit; text-decoration: inherit; `; type Props = { to?: string; onClick?(): void; title?: string; }; export default function RailLink({ to, onClick, children, title, }: PropsWithChildren<Props>) { return ( <Contents onClick={onClick}> {to ? ( <Link to={to} title={title}> {children} </Link> ) : ( <a title={title}>{children}</a> )} </Contents> ); }
import React, { useEffect, useState } from "react"; import "./weatherApp.css"; const WeatherApp = () => { const [weatherData, setWeatherData] = useState({}); const [cityName, setCityName] = useState("Karachi"); const [locationCity, setLocationCity] = useState({}); const [searchCityState, setSearchCityState] = useState("Karachi"); useEffect(() => { function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( function (position) { console.log(position); setLocationCity(position); setCityName(""); }, function (error) { console.log("error", error); setSearchCityState(cityName); } ); } else { alert("Geolocation is not supported by this browser."); } } getLocation(); }, []); useEffect(() => { let searchQuery = locationCity && locationCity.coords ? `lat=${locationCity.coords.latitude}&lon=${locationCity.coords.longitude}` : `q=${searchCityState ? searchCityState : cityName}`; fetch( `https://api.openweathermap.org/data/2.5/weather?${searchQuery}&appid=aeea4a77412d6c1856df8675ff429df6&units=metric` ) .then((res) => res.json()) .then((result) => { console.log(result); setWeatherData(result); }) .catch((err) => { console.log("0rrr", err); }); }, [searchCityState, locationCity]); const searchCity = (e) => { if(cityName === ''){ alert('Enter City') } else{ setSearchCityState(cityName); setLocationCity({}); } }; return ( <div> <div className="d-flex flex-column align-items-center justify-content-center my-5" > <h1 style={{color: "white", marginBottom: '50px'}}>WeatherApp</h1> <input type="text" value={cityName} className="form-group form-control media" placeholder="Enter City name" onChange={(e) => setCityName(e.target.value)} /> <button onClick={searchCity} className="btn btn-info my-5"> Search </button> </div> <div className="listBox"> <li className="list-unstyled font-weight-bold text-warning h5" >City: {weatherData && weatherData.name} </li> <li className="list-unstyled font-weight-bold text-warning h5" >Temp: {weatherData && weatherData.main && weatherData.main.temp} </li> <li className="list-unstyled font-weight-bold text-warning h5" > Condition:{" "} {weatherData && weatherData.weather && weatherData.weather[0] && weatherData.weather[0].main} </li> </div> </div> ); }; export default WeatherApp;
<template> <div class="login-element forgot-page"> <img class="logo-login cursor-pointer" src="/assets/images/logo_white.svg" alt="" @click="changeLink('/')"> <div> <div class="login-title">{{ $t('forgot_pass.title') }}</div> <div id="forgot-des" class="text-center"> <div class="text-mobile">{{ $t('forgot_pass.description') }}</div> <div class="text-mobile">{{ $t('forgot_pass.description_second') }}</div> </div> <el-form ref="accountForm" :model="accountForm" :rules="accountRules" autocomplete="off" label-position="left" @submit.native.prevent > <el-form-item class="email-login" prop="email" :error="(error.key === 'email') ? error.value : ''"> <div class="label">{{ $t('login.email') }}</div> <el-input ref="email" v-model.trim="accountForm.email" :placeholder="$t('login.email')" name="email" type="text" tabindex="2" maxlength="255" @focus="resetValidate('email')" /> </el-form-item> <el-form-item class="button-login"> <div :class="{'disabled' : disabledButton}"> <el-button v-loading.fullscreen.lock="fullscreenLoading" :loading="loading" type="danger" @click.native.prevent="login" > {{ $t('register.send') }} </el-button> </div> </el-form-item> <div class="link-register"> <span class="underline-hover register-button" @click="changeLink('register')">{{ $t('login.create_new_account') }}</span> </div> </el-form> </div> </div> </template> <script> import { INDEX_SET_LOADING, INDEX_SET_SUCCESS, INDEX_SET_ERROR, USER_FORGOT_PASS } from '../../store/store.const' import { validEmail, validHalfWidth } from '@/utils/validate' export default { name: 'ForgotElement', data() { const validFormEmail = (rule, value, callback) => { if (value && value.length > 255) { callback(new Error(this.$t('validation.max_length', { _field_: this.$t('login.email') }))) } if (!validHalfWidth(value)) { callback(new Error(this.$t('validation.halfwidth_length', { _field_: this.$t('login.email') }))) } if (!validEmail(value)) { callback(new Error(this.$t('validation.email', { _field_: this.$t('login.email') }))) } else { callback() } } return { accountForm: { email: '', errors: {} }, error: { key: null, value: '' }, accountRules: { email: [ { required: true, message: this.$t('validation.required', { _field_: this.$t('login.email') }), trigger: 'blur' }, { validator: validFormEmail, trigger: 'blur' } ] }, valid: false, loading: false, fullscreenLoading: false } }, computed: { disabledButton() { return this.accountForm.email === '' || !validEmail(this.accountForm.email) || !validHalfWidth(this.accountForm.email) } }, created() { if (this.$refs.accountForm !== undefined) { this.resetValidate('accountForm') } }, methods: { resetValidate(ref) { if (ref === this.error.key) { this.error = { key: null, value: '' } } this.$refs.accountForm.fields.find((f) => f.prop === ref).clearValidate() this.accountForm.errors[ref] = '' }, login() { this.error = { key: null, value: '' } this.$refs.accountForm.validate(async valid => { if (valid) { try { await this.$store.commit(INDEX_SET_LOADING, true) const dto = { email: this.accountForm.email } const data = await this.$store.dispatch(USER_FORGOT_PASS, { ...dto }) switch (data.status_code) { case 200: await this.$store.commit(INDEX_SET_SUCCESS, { show: true, text: data.messages }) this.$router.push('/login') break case 422: for (const [key] of Object.entries(data.data)) { this.error = { key, value: data.data[key][0] } } break case 500: await this.$store.commit(INDEX_SET_ERROR, { show: true, text: this.$t('content.EXC_001') }) break default: await this.$store.commit(INDEX_SET_ERROR, { show: true, text: data.messages }) break } } catch (err) { await this.$store.commit(INDEX_SET_ERROR, { show: true, text: this.$t('message.message_error') }) } await this.$store.commit(INDEX_SET_LOADING, false) } }) }, changeLink(state) { this.$router.push(state) } } } </script>
#= Exercice de traitement d'image: Conversion Vert-Rouge Ton objectif pour cette mission verte est de transformer les pixels verts d'une image en rouge, enflamme cette verdure et fais-nous une belle tomate pixelisée! Voici ta mission photo-synthétique (sans code, pour préserver l'aventure) : Importation de l'image : Trouve une belle image colorée qui te servira de terrain de jeu pixelisé pour cette expérience chromatique. Repérage du vert : Chaque pixel possède trois composants : rouge (R), vert (G) et bleu (B). Tu devras identifier ceux où le green règne en maître. Transformation verte : Chacun de ces pixels verts détectés doit muter en rouge. Tu vas devoir ajuster les niveaux de rouge et de vert en conséquence. Ajustement précis : Tu peux choisir d'appliquer cette métamorphose uniquement aux pixels d'une certaine intensité de vert ou à tous ceux qui contiennent une touche de cette couleur. Enregistrement de la nouvelle création : Une fois que tu as fait voir rouge à tous ces pixels verts, il est temps de sauvegarder ton œuvre pour l'immortaliser. Prends en compte le fait que la manière dont tu détectes et modifies la couleur verte peut varier. Tu pourrais choisir un seuil spécifique pour définir ce qui est "assez vert" ou travailler avec une plage de valeurs. =# using Images using ImageMagick # la fonction qui change les pixels verts en rouges function changer_pixel_vert_en_rouge(img::Array{RGBA{N0f8}, 2}) for index in CartesianIndices(img) i, j = Tuple(index) pixel = img[i, j] if pixel.g > pixel.r && pixel.g > pixel.b img[i, j] = RGB(1, 0, 0) end end end # dossier de l'image dossier = "images/" # Charger l'image img = load("$dossier/test.png") # Pas besoin de convertir en RGB # if eltype(img) == RGBA{N0f8} # img = RGB.(img) # end # Appliquer la fonction sur l'image changer_pixel_vert_en_rouge(img) # Sauvegarder l'image modifiée save("$dossier/vert_to_rouge.png", img)
###################################################### # Solved on Friday, 26 - 11 - 2021. ###################################################### ###################################################### # Runtime: 52ms - 92.02% # Memory: 14.1MB - 99.61% ###################################################### class Solution: def convert(self, s: str, numRows: int) -> str: if numRows == 1: return s strings = [""] * numRows # direction determines whether to add 1 to index or subtract 1 from index direction = 1 # index will be the index of strings array to which we should add the next char index = 0 for char in s: # Adding current char to particular index of strings array strings[index] += char # Moving index to next position index += direction # If index became -1, we went out of the left bounds of strings array # That means previously we added char to 0th index, so in next iteration # we should add to index 1. And we should go downwards. So we make # index = 1 and direction = 1 if index == -1: index = 1 direction = 1 # If index became numRows, we went out of the right bounds of strings array # That means previously we added char to last index of strings array, so # in next iteration we should add to last but one index which is # numRows - 2. And we should go upwards. So we make # index = numRows - 1 and direction = -1 elif index == numRows: index = numRows - 2 direction = -1 # Concatenating all strings in strings array, separated by empty string return "".join(strings)
import React from 'react' import { useState, useEffect } from 'react'; import './Register.css'; import { Link, useNavigate } from 'react-router-dom'; import { toast } from 'react-toastify'; import axios from 'axios'; import { ApiRegister } from '../Utils/ApiRoutes'; const Register = () => { const navigate = useNavigate(); const [data, setData] = useState({ username: '', email: '', password: '', confirmpassword: '' }); useEffect(() => { if (localStorage.getItem('user')) { navigate('/'); } }, []); const formvalidation = () => { if (data.username.length < 3) { alert('Username must be atleast 3 characters long'); return false; } if (data.password.length < 6) { alert('Password must be atleast 6 characters long'); return false; } if (data.password !== data.confirmpassword) { alert('Passwords do not match'); return false; } return true; } const changeHandler = (e) => { setData({ ...data, [e.target.name]: e.target.value }); } const submitHandler = async (e) => { e.preventDefault(); console.log(data); if (formvalidation()) { let res = await axios.post(ApiRegister, data); if (res.data.status === 400) { toast.error(res.data.message); return; } if (res.data.status === 200) { localStorage.setItem('user', JSON.stringify(res.data.user)); toast.success('Account created successfully'); navigate('/setAvatar'); return; } } } return ( <div className='register'> <form onSubmit={submitHandler} className='form'> <h2>C-Chat</h2> <input type="text" name="username" placeholder="Your Name" value={data.username} onChange={(e) => { changeHandler(e); }} /> <input type="email" name="email" placeholder="Email" value={data.email} onChange={(e) => { changeHandler(e); }} /> <input type="password" name="password" placeholder="Password" value={data.password} onChange={(e) => { changeHandler(e); }} /> <input type="password" name='confirmpassword' placeholder='Confirm password' value={data.confirmpassword} onChange={(e) => { changeHandler(e); }} /> <button type='submit'>Create Account</button> <h2>Already have an account? <Link to='/login'>Login</Link></h2> </form> </div> ) } export default Register