text
stringlengths
184
4.48M
import { StyleSheet, Text, TouchableOpacity, View } from "react-native"; import React from "react"; import { COLORS, TEXT, SIZES } from "../../constants/theme"; import NetworkImage from "./NetworkImage"; import WidthSpacer from "../Reusable/WidthSpacer"; import HeightSpacer from "../Reusable/HeightSpacer"; import ReusableText from "./ReusableText"; import Rating from "./Rating"; const ReusableTile = ({ item, onPress }) => { return ( <TouchableOpacity onPress={onPress} style={styles.container}> <View style={{ flexDirection: "row", justifyContent: "flex-start", alignItems: "center", }} > <NetworkImage source={item.imageUrl} width={90} height={90} radius={12} ></NetworkImage> <WidthSpacer width={15}></WidthSpacer> <View> <ReusableText text={item.title} family={"medium"} size={SIZES.medium} color={COLORS.black} ></ReusableText> <HeightSpacer height={8}></HeightSpacer> <ReusableText text={item.location} family={"medium"} size={14} color={COLORS.gray} ></ReusableText> <HeightSpacer height={8}></HeightSpacer> <View style={{ flexDirection: "row", justifyContent: "flex-start", alignItems: "center", }} > <Rating rating={item.rating}></Rating> <WidthSpacer width={10}></WidthSpacer> <ReusableText text={`(${item.review})`} family={"medium"} size={14} color={COLORS.gray} ></ReusableText> </View> </View> </View> </TouchableOpacity> ); }; const styles = StyleSheet.create({ container: { padding: 10, backgroundColor: COLORS.lightWhite, borderRadius: 12, }, }); export default ReusableTile;
import { ref, onMounted, onUnmounted } from "vue"; import { useStore } from "vuex"; import { useRouter } from "vue-router"; import { AppAlert } from "src/plugins/app-alert"; export default function () { const router = useRouter(); const popup = ref(null); const isPopup = ref(false); const popupContent = ref({ popup_name: undefined, id: undefined, }); const store = useStore(); const scollWindow = (e) => { if (isPopup.value) { isPopup.value = false; popupContent.value = { popup_name: undefined, id: undefined, }; } }; const popupAction = async (value, { resetForm }) => { if (popupContent.value.popup_name === "widthdrawal") { try { await store.dispatch("profile/widthdrawalIndex", { ...value, inder_id: popupContent.value.id, }); resetForm(); isPopup.value = false; } catch (e) { throw e; } } if (popupContent.value.popup_name === "buy") { const obj = { ...value, inder_id: popupContent.value.id, }; try { const data = await store.dispatch("profile/buyIndex", obj); resetForm(); isPopup.value = false; if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) { window.location.href = data.payment_url; } else { var newWin = window.open(data.payment_url, "_blank"); if (!newWin || newWin.closed || typeof newWin.closed == "undefined") { window.location.href = data.payment_url; } router.push({ name: "history" }); } } catch (e) { if (!e.response) throw e; if (e.response.status === 422) { const { errors } = await e.response.json(); AppAlert({ message: () => errors.amount[0], type: "negative", }); } else throw e; } } }; const targetClick = (e) => { let currentElem = e.target; let open = false; while (currentElem) { if (currentElem.hasAttribute("data-index")) { open = true; break; } else currentElem = currentElem.parentElement; } if (!open && isPopup.value && !e.composedPath().includes(popup.value)) { isPopup.value = false; popupContent.value = { popup_name: undefined, id: undefined, }; } }; const targetPopup = (e) => { let currentElem = e.target; let open = false; while (currentElem) { if (currentElem.hasAttribute("data-index")) { isPopup.value = true; break; } else currentElem = currentElem.parentElement; } if (isPopup.value) { const pageHeight = window.innerHeight + window.pageYOffset; const windowHeight = currentElem.getBoundingClientRect().height + currentElem.getBoundingClientRect().top + window.pageYOffset; const positionY = currentElem.getBoundingClientRect().top + window.pageYOffset; popup.value.style.display = "block"; setTimeout(() => { if (window.innerWidth > 1024) { const popupHeight = popup.value.offsetHeight; popup.value.style.top = positionY - currentElem.getBoundingClientRect().height - popupHeight + "px"; } else { popup.value.style.position = 'fixed' popup.value.style.top = '50%'; popup.value.style.transform = 'translateY(-50%)'; } }, 0); } }; const buy = (e, id) => { popupContent.value = { popup_name: "buy", id: id }; targetPopup(e); }; const widthdrawal = (e, id) => { popupContent.value = { popup_name: "widthdrawal", id: id }; targetPopup(e); }; onMounted(async () => { window.addEventListener("click", targetClick); }); onUnmounted(() => { window.removeEventListener("click", targetClick); }); return { popup, isPopup, popupContent, buy, widthdrawal, targetClick, popupAction, }; }
// Parallel Fold (Reduce) Operation List(1, 3, 8).foldLeft(100)((s, x) => s - x) == ((100 - 1) - 3) - 8 List(1, 3, 8).foldRight(100)((s, x) => s - x) == 1 - (3 - (8 - 100)) List(1, 3, 8).reduceLeft((s, x) => s - x) == (1 - 3) - 8 List(1, 3, 8).reduceRight((s, x) => s - x) == 1 - (3 - 8) // Associative operation // f(x, f(y, z)) = f(f(x, y), z) sealed abstract class Tree[A] case class Leaf[A](value: A) extends Tree[A] case class Node[A](left: Tree[A], right: Tree[A]) extends Tree[A] def reduce[A](t: Tree[A], f: (A, A) => A): A = t match { case Leaf(v) => v case Node(l, r) => f(reduce[A](l, f), reduce[A](r, f)) } def tree = Node(Leaf(1), Node(Leaf(3), Leaf(8))) def fMinus = (x: Int, y: Int) => x - y def res = reduce[Int](tree, fMinus) // how to make that tree reduce parallel? /* def reduce[A](t: Tree[A], f: (A, A) => A): A = t match { case Leaf(v) => v case Node(l, r) => { val (lV, rV) = parallel(reduce[A](l, f), reduce[A](r, f)) f(lV, rV) } } */ //reduce(Node(Leaf(x), Node(Leaf(y), Leaf(z))), f) == //reduce(Node(Node(Leaf(x), Leaf(y)), Leaf(z)), f) == def toList[A](t: Tree[A]): List[A] = t match { case Leaf(v) => List(v) case Node(l, r) => toList[A](l) ++ toList[A](r) } def map[A, B](t: Tree[A], f: A => B): Tree[B] = t match { case Leaf(v) => Leaf(f(v)) case Node(l, r) => Node(map[A, B](l, f), map[A, B](r, f)) } //toList(t) == reduce(map(t, List(_)), _ ++ _) // if toList(t1) == toList(t2) // then, reduce(t1, f) == reduce(t2, f) /* def reduceSeg[A](inp: Array[A], left: Int, right: Int, f: (A, A) => A): A = { if ( right - left < threshold ) { var res = inp(left); var i = left + 1 while ( i < right ) { res = f(res, inp(i)); i = i + 1 } res } else { val mid = left + (right - left) / 2 val (a1, a2) = parallel(reduceSeg(inp, left, mid, f), reduceSeg(inp, mid, right, f)) f(a1, a2) } } def reduce[A](inp: Array[A], f: (A, A) => A): A = reduceSeg(inp, 0, inp.length, f) */
import React, { useContext, useState, useEffect, useRef } from "react"; import { Text, TextInput, TouchableOpacity, View, Pressable } from 'react-native'; import { Box, AspectRatio, Image, Center, Heading, DeleteIcon, ChevronDownIcon, ChevronUpIcon, Stack, HStack} from 'native-base'; import { Button, Input, InputLeftAddon, InputGroup, InputRightAddon, Select, CheckIcon } from 'native-base'; import { useExerciseLogs } from "../../services/exerciseLogService"; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; const WEIGHT_UNITS = "lbs" const ExerciseSimpleCard = ({exercise, navigation }) => { // when a card is pressed navigate to the corresponding screen const onCardPress = () => { navigation.navigate("Exercise", { exData: exercise}); } return ( <View style={{}}> <Box alignItems="center"> <Pressable onPress={onCardPress} style={{overflow: 'hidden', borderRadius: 25, borderWidth: 1, borderColor: 'lightgrey', shadow: 3}}> <Box w="80" rounded="lg" overflow="hidden" borderRadius="25" borderColor="coolGray.200" borderWidth="0" _dark={{ borderColor: "coolGray.600", backgroundColor: "gray.700" }} _light={{ backgroundColor: "gray.50" }}> <Stack p="4" space={3}> <Stack space={2}> <View style={{display: 'flex', flexDirection: "row", alignItems: "center", justifyContent: 'space-between'}}> <Heading size="md" ml="-1" display="flex" flexWrap="wrap" marginLeft={1} flexDirection="row" width="75%"> {exercise?.name} </Heading> </View> <Text fontSize="xs" _light={{ color: "violet.500" }} _dark={{ color: "violet.400" }} fontWeight="500" ml="-0.5" mt="-1"> {exercise.muscleGroup} </Text> </Stack> <Text fontWeight="400"> {exercise?.description} </Text> <HStack alignItems="center" space={4} justifyContent="space-between"> <HStack alignItems="center"> <Text color="coolGray.600" _dark={{ color: "warmGray.200" }} fontWeight="400"> {exercise?.sets?.length ? exercise?.sets?.length : "0"} sets </Text> </HStack> </HStack> </Stack> </Box> </Pressable> </Box> </View> ); } export { ExerciseSimpleCard };
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:timezone/timezone.dart' as tz; class LocalNotifications { //initialize notification static final _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); static Future init() async { const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher'); const InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, ); _flutterLocalNotificationsPlugin.initialize(initializationSettings, onDidReceiveNotificationResponse: (details) => null); } //show simple notif static Future showNotification( {int id = 0, String? title, String? body, String? payload}) async { const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails('your channel id', 'medicines', channelDescription: 'your channel description', importance: Importance.max, priority: Priority.high, ticker: 'ticker'); const NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails); await _flutterLocalNotificationsPlugin .show(0, title, body, notificationDetails, payload: payload); } //periodic notifications static Future showPeriodicNotifications( {int id = 0, String? title, String? body, String? payload}) async { const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails('channel 2', 'medicines', channelDescription: 'your channel description', importance: Importance.max, priority: Priority.high, ticker: 'ticker'); const NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails); await _flutterLocalNotificationsPlugin.periodicallyShow( 1, title, body, RepeatInterval.everyMinute, notificationDetails); } //schedule notifications //first we should initilaize timezone in main function //by import 'package:timezone/data/latest.dart' as tz; //and put tz.initializeTimeZones(); in main function static Future showScheduleNotifications( {int id = 0, String? title, String? body, String? payload, required DateTime scheduleDate}) async { const AndroidNotificationDetails androidNotificationDetails = AndroidNotificationDetails('channel 3', 'medicines', channelDescription: 'your channel description', importance: Importance.max, priority: Priority.high, ticker: 'ticker'); const NotificationDetails notificationDetails = NotificationDetails(android: androidNotificationDetails); await _flutterLocalNotificationsPlugin.zonedSchedule( id, title, body, tz.TZDateTime.from( tz.TZDateTime.now(tz.local).add(const Duration(seconds: 10)), tz.local), notificationDetails, androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle, uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime); } }
% Description: This function computes a similarity matrix between each % vertex in a network. It accepts and adjacency matrix as well as a % parameter for which local similarity score should be used. These scores % are defined in the paper: "Uncovering Missing Links with Cold Ends" and % currently available ones include: % - AA: Adamic Adar % - CN: Common Neighbors % - HD: Hub Depressed % - HP: Hub Promoted % - JC: Jaccard % - LHN: Leicht-Holme-Newman % - PA: Preferential Attachment % - RS: Resource Allocation % - SA: Salton % - SO: Sorensen % See: https://drive.google.com/file/d/1TsXGWMqqt5euCtxnEQBodo3FM74gyvzO/view function similarity=local_similarity(adj, index) similarity = zeros(size(adj)); for i=1:height(adj) for j=i+1:height(adj) % i_j_similarity = 0; switch index case 'AA' i_j_similarity = adamicAdar_index(adj, i, j); case 'CN' i_j_similarity = commonNeighbors_index(adj, i, j); case 'HD' i_j_similarity = hubDepressed_index(adj, i, j); case 'HP' i_j_similarity = hubPromoted_index(adj, i, j); case 'JC' i_j_similarity = jaccard_index(adj, i, j); case 'LHN' i_j_similarity = leichtHolmeNewman_index(adj, i, j); case 'PA' i_j_similarity = preferentialAttachment(adj, i, j); case 'RS' i_j_similarity = resourceAllocation(adj, i, j); case 'SA' i_j_similarity = salton_index(adj, i, j); case 'SO' i_j_similarity = sorensen_index(adj, i,j); end similarity(i, j) = i_j_similarity; similarity(j, i) = i_j_similarity; end end end
class LoginResponse { String? token; String? fbToken; String? type; String? message; User? user; Null? vehicle; Null? vendor; LoginResponse( {this.token, this.fbToken, this.type, this.message, this.user, this.vehicle, this.vendor}); LoginResponse.fromJson(Map<String, dynamic> json) { token = json['token']; fbToken = json['fb_token']; type = json['type']; message = json['message']; user = json['user'] != null ? new User.fromJson(json['user']) : null; vehicle = json['vehicle']; vendor = json['vendor']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['token'] = this.token; data['fb_token'] = this.fbToken; data['type'] = this.type; data['message'] = this.message; if (this.user != null) { data['user'] = this.user!.toJson(); } data['vehicle'] = this.vehicle; data['vendor'] = this.vendor; return data; } } class User { int? id; String? code; String? name; String? email; String? phone; String? countryCode; int? commission; Null? emailVerifiedAt; Null? vendorId; int? isActive; int? isOnline; Null? creatorId; String? language; String? createdAt; String? updatedAt; Null? deletedAt; bool? hasMultipleVendors; String? roleName; int? roleId; String? formattedDate; String? photo; String? rating; int? assignedOrders; String? rawPhone; bool? isTaxiDriver; bool? documentRequested; bool? pendingDocumentApproval; List<Roles>? roles; List<Null>? media; User( {this.id, this.code, this.name, this.email, this.phone, this.countryCode, this.commission, this.emailVerifiedAt, this.vendorId, this.isActive, this.isOnline, this.creatorId, this.language, this.createdAt, this.updatedAt, this.deletedAt, this.hasMultipleVendors, this.roleName, this.roleId, this.formattedDate, this.photo, this.rating, this.assignedOrders, this.rawPhone, this.isTaxiDriver, this.documentRequested, this.pendingDocumentApproval, this.roles, this.media}); User.fromJson(Map<String, dynamic> json) { id = json['id']; code = json['code']; name = json['name']; email = json['email']; phone = json['phone']; countryCode = json['country_code']; commission = json['commission']; emailVerifiedAt = json['email_verified_at']; vendorId = json['vendor_id']; isActive = json['is_active']; isOnline = json['is_online']; creatorId = json['creator_id']; language = json['language']; createdAt = json['created_at']; updatedAt = json['updated_at']; deletedAt = json['deleted_at']; hasMultipleVendors = json['has_multiple_vendors']; roleName = json['role_name']; roleId = json['role_id']; formattedDate = json['formatted_date']; photo = json['photo']; rating = json['rating']; assignedOrders = json['assigned_orders']; rawPhone = json['raw_phone']; isTaxiDriver = json['is_taxi_driver']; documentRequested = json['document_requested']; pendingDocumentApproval = json['pending_document_approval']; if (json['roles'] != null) { roles = <Roles>[]; json['roles'].forEach((v) { roles!.add(new Roles.fromJson(v)); }); } if (json['media'] != null) { media = <Null>[]; json['media'].forEach((v) { }); } } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['code'] = this.code; data['name'] = this.name; data['email'] = this.email; data['phone'] = this.phone; data['country_code'] = this.countryCode; data['commission'] = this.commission; data['email_verified_at'] = this.emailVerifiedAt; data['vendor_id'] = this.vendorId; data['is_active'] = this.isActive; data['is_online'] = this.isOnline; data['creator_id'] = this.creatorId; data['language'] = this.language; data['created_at'] = this.createdAt; data['updated_at'] = this.updatedAt; data['deleted_at'] = this.deletedAt; data['has_multiple_vendors'] = this.hasMultipleVendors; data['role_name'] = this.roleName; data['role_id'] = this.roleId; data['formatted_date'] = this.formattedDate; data['photo'] = this.photo; data['rating'] = this.rating; data['assigned_orders'] = this.assignedOrders; data['raw_phone'] = this.rawPhone; data['is_taxi_driver'] = this.isTaxiDriver; data['document_requested'] = this.documentRequested; data['pending_document_approval'] = this.pendingDocumentApproval; if (this.roles != null) { data['roles'] = this.roles!.map((v) => v.toJson()).toList(); } if (this.media != null) { } return data; } } class Roles { int? id; String? name; String? guardName; String? createdAt; String? updatedAt; Pivot? pivot; Roles( {this.id, this.name, this.guardName, this.createdAt, this.updatedAt, this.pivot}); Roles.fromJson(Map<String, dynamic> json) { id = json['id']; name = json['name']; guardName = json['guard_name']; createdAt = json['created_at']; updatedAt = json['updated_at']; pivot = json['pivot'] != null ? new Pivot.fromJson(json['pivot']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['id'] = this.id; data['name'] = this.name; data['guard_name'] = this.guardName; data['created_at'] = this.createdAt; data['updated_at'] = this.updatedAt; if (this.pivot != null) { data['pivot'] = this.pivot!.toJson(); } return data; } } class Pivot { String? modelType; int? modelId; int? roleId; Pivot({this.modelType, this.modelId, this.roleId}); Pivot.fromJson(Map<String, dynamic> json) { modelType = json['model_type']; modelId = json['model_id']; roleId = json['role_id']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['model_type'] = this.modelType; data['model_id'] = this.modelId; data['role_id'] = this.roleId; return data; } }
import React, { useState, useEffect } from 'react'; import { Searchbar } from '../Searchbar/Searchbar'; import { ImageGallery } from '../ImageGallery/ImageGallery'; import { Loader } from '../Loader/Loader'; import { Button } from '../Button/Button'; import { Modal } from '../Modal/Modal'; import css from './App.module.css'; const BASE_URL = 'https://pixabay.com/api/'; const API_KEY = '34756481-ec8746fc3857b8c268e985924'; const searchParams = new URLSearchParams({ image_type: 'photo', orientation: 'horizontal', per_page: 12, }); export const App = () => { const [images, setImages] = useState([]); const [searchQuery, setSearchQuery] = useState(''); const [page, setPage] = useState(1); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [showModal, setShowModal] = useState(false); const [imageModal, setImageModal] = useState(''); useEffect(() => { if (searchQuery) { setLoading(true); fetch( `${BASE_URL}?q=${searchQuery}&page=${page}&key=${API_KEY}&${searchParams}` ) .then(response => { if (response.ok) { return response.json(); } return Promise.reject( new Error('There is no results for {this.state.searchQuery}') ); }) .then(images => { setImages(prev => [...prev, ...images.hits]); }) .catch(error => setError(error)) .finally(() => setLoading(false)); } }, [searchQuery, page]); const toggleModal = () => setShowModal(prev => !prev); const formSubmitHandler = value => { if (searchQuery !== value) { setImages([]); setSearchQuery(value); setPage(1); } else { alert(`You are already viewing the results on request "${searchQuery}"`); } }; const onPageChange = () => setPage(prev => prev + 1); const onChoseImage = large => { setImageModal(large); toggleModal(); }; return ( <div className={css.App}> <Searchbar onSubmit={formSubmitHandler} /> {error && <h1>There is no results for {searchQuery}</h1>} {loading && <Loader />} {images && <ImageGallery images={images} onChoseImage={onChoseImage} />} {images.length !== 0 && !loading && ( <Button onPageChange={onPageChange} /> )} {showModal && <Modal largeImage={imageModal} onClose={toggleModal} />} </div> ); };
package com.service.notificationservice.Email; import java.io.IOException; import com.amazonaws.regions.Regions; import com.amazonaws.services.simpleemail.AmazonSimpleEmailService; import com.amazonaws.services.simpleemail.AmazonSimpleEmailServiceClientBuilder; import com.amazonaws.services.simpleemail.model.Body; import com.amazonaws.services.simpleemail.model.Content; import com.amazonaws.services.simpleemail.model.Destination; import com.amazonaws.services.simpleemail.model.Message; import com.amazonaws.services.simpleemail.model.SendEmailRequest; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; @Component public class AmazonSES { private final TemplateEngine templateEngine; public AmazonSES(TemplateEngine templateEngine) { this.templateEngine = templateEngine; } // Official Insidoor's email that is verified with Amazon SES. static final String FROM = "[email protected]"; // The email body for recipients with non-HTML email clients. static final String TEXTBODY = "Please check the task management system for the new case that is assigned to you."; public String sendEmail(String name, String recipientEmail, String subject, String severity, String incidentTitle, String taskId) throws IOException { try { AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.standard() .withRegion(Regions.AP_SOUTHEAST_2).build(); SendEmailRequest request = new SendEmailRequest() .withDestination( new Destination().withToAddresses(recipientEmail)) .withMessage(new Message() .withBody(new Body() .withHtml(new Content() .withCharset("UTF-8").withData(setContent(name, severity, incidentTitle, taskId))) .withText(new Content() .withCharset("UTF-8").withData(TEXTBODY))) .withSubject(new Content() .withCharset("UTF-8").withData(subject))) .withSource(FROM); client.sendEmail(request); System.out.println("Email sent!"); } catch (Exception ex) { System.out.println("The email was not sent. Error message: " + ex.getMessage()); return null; } return "Email sent"; } public String setContent(String name, String severity, String incidentTitle, String taskId){ // Create a context object and set the input variables in the context object. Context context = new Context(); context.setVariable("name", name); context.setVariable("severity", severity); context.setVariable("incidentTitle", incidentTitle); context.setVariable("taskId", taskId); // ClassPathResource image = new ClassPathResource("icon.png"); // context.setVariable("imageCid", "image001"); // System.out.println("Image path: " + image.getPath()); // Process the HTML file using the template engine and the context object. String htmlContent = templateEngine.process("email-template", context); return htmlContent; } }
@extends('cms.layouts.app') @section('content') @include('cms.modals.confirmation_modal', ['id' => 'delete_confirmation_modal', 'title' => 'Confirm', 'text' => 'You are about to delete this product!', 'action' => 'Confirm', 'function' => 'deleteSeriesCategory()',]) @include('cms.alerts.success-alert') <div class="panel panel-default"> <div class="panel-heading"> <h3 style="font-weight: bold; color: #337ab7;" class="pull-left"> Series Categories: </h3> <a href="{{ route('series_categories.create') }}" class="pull-right" title="add series category"> <i class="fa fa-plus-circle fa-2x text-primary" style="cursor: pointer;"></i> </a> <div class="clearfix"></div> </div> <div class="panel-body"> <div id="seriesCategoriesTable" class="table-responsive"> <table id="myTable" class="table table-hover"> <thead> <th>No.</th> <th>Name</th> <th>Action</th> </thead> <tbody> @foreach($categories as $category) <tr class="{{($loop->index % 2 == 0) ? 'active' : ''}}"> <td>{{$loop->iteration}}</td> <td>{{$category->name}}</td> <td> <div class="btn-group"> <a class="btn btn-warning" title="edit category" href="{{route('series_categories.edit', ['seriesCategory' => $category->id])}}"> <span class="fa fa-pencil"></span> </a> <button class="btn btn-danger" title="delete category" onclick="showDeleteModal({{$category}})"> <span class="fa fa-trash-o"></span> <form id="delete{{$category->id}}" action="{{route('series_categories.destroy', ['seriesCategory' => $category->id])}}" method="POST" style="display: none;"> {{ csrf_field() }} {{ method_field('DELETE') }} </form> </button> </div> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> @endsection @section('scripts') <script src="{{ asset('js/series_categories.js') }}"></script> @endsection
package com.flab.funding.repository; import com.flab.funding.application.ports.output.MemberPort; import com.flab.funding.domain.model.Member; import com.flab.funding.domain.model.MemberGender; import com.flab.funding.domain.model.MemberLinkType; import com.flab.funding.infrastructure.adapters.output.persistence.MemberPersistenceAdapter; import com.flab.funding.infrastructure.adapters.output.persistence.repository.MemberRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.LocalDate; import java.util.List; import static com.flab.funding.data.MemberTestData.getMember; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; @ExtendWith(SpringExtension.class) @DataJpaTest public class MemberPersistenceAdapterTest { private final MemberPort memberPort; @Autowired public MemberPersistenceAdapterTest(MemberRepository memberRepository) { this.memberPort = new MemberPersistenceAdapter(memberRepository); } @Test @DisplayName("회원가입") public void saveMember() { //given Member member = getMember().activate(); //when Member savedMember = memberPort.saveMember(member); //then assertNotNull(savedMember.getId()); assertNotNull(savedMember.getUserKey()); assertEquals(MemberLinkType.NONE, savedMember.getLinkType()); assertEquals("[email protected]", savedMember.getEmail()); assertEquals("홍길순", savedMember.getUserName()); assertEquals("테스터", savedMember.getNickName()); assertEquals("010-1111-2222", savedMember.getPhoneNumber()); assertEquals(MemberGender.FEMALE, savedMember.getGender()); assertEquals(LocalDate.of(1998, 1, 30), savedMember.getBirthday()); assertEquals("", savedMember.getPassword()); } @Test @DisplayName("회원 키로 회원조회") public void getMemberByUserKey() { //given Member member = getMember().activate(); Member savedMember = memberPort.saveMember(member); // when Member findMember = memberPort.getMemberByUserKey(savedMember.getUserKey()); //then assertNotNull(savedMember.getUserKey()); assertEquals(savedMember.getUserKey(), findMember.getUserKey()); assertEquals(savedMember.getEmail(), findMember.getEmail()); } @Test @DisplayName("이메일로 회원조회") public void getMemberByEmail() { //given Member member = getMember().activate(); Member savedMember = memberPort.saveMember(member); // when List<Member> findMember = memberPort.getMemberByEmail(savedMember.getEmail()); //then assertNotNull(savedMember.getUserKey()); assertEquals(1, findMember.size()); } }
import React, { useRef, useEffect, useState } from "react"; import styles from "./dropdown.module.css"; import { MdOutlineKeyboardArrowDown } from "react-icons/md"; import DropDownOption from "./dropDownOption"; import { useSelector } from "react-redux"; const DropDown = () => { const [showOption, setShowOption] = useState(false); const dropDownRef = useRef(null); const iconRef = useRef(null); const activeFrameType = useSelector((state) => state.frame.activeFrameType); const handleDropDownClick = () => { setShowOption((prev) => !prev); }; useEffect(() => { const handleClickOutside = (event) => { if ( dropDownRef.current && !dropDownRef.current.contains(event.target) && iconRef.current && !iconRef.current.contains(event.target) ) { setShowOption(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, []); return ( <> <div className={styles.mainContainer}> <div> Mockup</div> <div className={styles.container}> <div className={styles.imageContainer}> <div className={styles.imaginnerContainer}> <img src="/icons/maxbook3.png" alt="" /> </div> </div> <div className={styles.text}> <div>{activeFrameType.label}</div> <div className={styles.mutedtext}>{activeFrameType.ratio}</div> </div> <div className={styles.icon} onClick={handleDropDownClick} ref={iconRef} > <div className={styles.iconContainer}> <MdOutlineKeyboardArrowDown /> </div> </div> </div> </div> {showOption && ( <div className={styles.dropdownContainer} ref={dropDownRef}> <DropDownOption prop={showOption} /> </div> )} </> ); }; export default DropDown;
# 从 Docker 开始 > 原文:<https://medium.com/analytics-vidhya/starting-with-docker-bfd74021d5c7?source=collection_archive---------9-----------------------> 一个 Docker 帖子已经永远在我的待办事项列表上了:现在是时候了! ![](img/cc33928621dd06b962d57bc03fcd267f.png) 照片由 [Nilantha Ilangamuwa](https://unsplash.com/@ilangamuwa?utm_source=medium&utm_medium=referral) 在 [Unsplash](https://unsplash.com?utm_source=medium&utm_medium=referral) 上拍摄 ## 为什么是 Docker 呢? * 如果你曾经不得不使用一个虚拟的*机器*,你就会知道它们有多慢多重——它们占据了太多的空间!Docker 更快更轻! * 如果您曾经在您的本地机器虚拟环境(您的代码在其中工作)和将它部署到其他地方(甚至是*与*相同的环境)之间遇到过问题,在那里它突然不再工作了,Docker 可以提供一个工作空间,它在您的本地机器上运行将与在远程机器上运行完全相同,因为它实际上是同一个“机器”!变量更少,故障排除更简单。 使用`Dockerfile`文件中的指令,Docker 将您的环境——库、任何依赖项、环境变量和配置文件等——和*代码* *一起*打包成一个`image`,您可以与任何人共享。然后他们可以在他们的机器上`run`图像,无论你发送给他们什么都可以工作!💥 ## 那么,我们如何开始? 1. 创建一个码头中心账户:[https://hub.docker.com](https://hub.docker.com) 2. 从 docker hub 下载 docker。 3. 下载完成后(如果你用的是 Mac 的话,会被拖到应用程序中),点击它,等待 docker 启动(需要一些时间)。启动后,docker 符号应该会出现在电池和 wifi 符号旁边的状态栏顶部。 4. 打开一个终端,从任何目录中键入`docker run hello-world`,它将从 Docker Hub 获取 Hello World 映像,构建它,并打印一条消息。或者,更简单地说,你也可以只输入`docker info`,你就会得到你机器上所有 Docker 信息的打印结果😁 5. 希望这行得通! ## 一些可以尝试的事情: **探索你正在做的事情—** * `docker images`查看您有哪些图像。目前可能没有。 * `docker ps`或`docker ps -a`查看哪些容器是或曾经是活动的。如果你什么都没有,做`docker run busybox`然后再试`docker ps -a`。您应该会看到新的一行。记下`<IMAGE>`图像名称,以及`<CONTAINER ID>`、`<STATUS>`和`<NAMES>`,因为这些可以在命令行中引用,以执行诸如删除、停止或运行特定的操作。 **跑步—** * `docker run <IMAGE>`启动 docker 容器并在其中运行您的程序。 * 如果你没有要运行的图像,试试`docker run busybox`,它会在你的机器上显示,然后搜索 [Docker Hub](https://hub.docker.com) 找到它,下载它,并在一个容器中运行它。您还可以使用`docker pull <IMAGE>`从 Docker Hub 获取图像。你可以在[中心点击](https://hub.docker.com/search?&q=)查看更多图片。 * `docker run -it <IMAGE> sh`运行图像,并打开一个 shell 以便可以直接与容器交互。如果容器已经在运行,执行`docker exec -it <CONTAINER ID> sh`在容器中得到一个 shell 提示。 **停止并移除 docker 物件—** * `docker stop <CONTAINER ID>`以优雅的方式停止容器运行。但是容器仍然存在,所以在某个时候你需要移除它。 * `docker system prune -a` ***删除你机器上的每个图像和每个容器!*** 😱然而,在执行这个请求之前,*会要求*确认,这很好🎉 * 更明智的`rm`命令包括:`docker rm <CONTAINER ID>`删除特定的容器,`docker container prune`仅删除停止的容器,`docker rmi`删除图像。 * 提示:在输入<container id="">时,你只需要输入前几个值,它就会知道你指的是哪一个。✨</container> * 有关移除图像、容器和卷的更多信息,请查看数字海洋的[这篇文章。](https://www.digitalocean.com/community/tutorials/how-to-remove-docker-images-containers-and-volumes) * `docker -h`查看还有哪些命令可用。 ## **制作自己的<形象>** 为了创建你自己的图像,你需要打一个 order 文件。如果您当前的文本编辑器还没有安装语法荧光笔,安装语法荧光笔会有助于提高可读性。我使用 Atom,有几个 Docker 语法高亮器可供安装👍要在 Atom 中找到它们,打开 Atom,选择`Packages`->-`Settings View`->-`Install Packages/Themes`,然后在搜索栏中键入类似`Docker highlighter`的内容。 ![](img/b7283c9ae00c08cec5045d984e24f0bb.png) 如何在 Atom 文本编辑器中安装附加包?可以帮助安装一个 Docker 语法荧光笔。上面的代码显示了 Dockerfile 语法高亮显示。 ## `Dockerfile` 这是指令文件。通常,我们将 Dockerfile 建立在一个已经存在的映像上,这样我们就不必从头开始构建映像。例如,如果您想在您的容器中运行 python 代码,那么您可以将您的 docker 文件基于一个[现有的 python 映像](https://hub.docker.com/_/python/)。为此,第一行将是`FROM <IMAGE>`,其中`<IMAGE>`是预先存在的图像。下面的截图显示了一个基于[官方 Python3 图片](https://hub.docker.com/_/python/)的 Dockerfile。 ![](img/7110cb2992ae9a0d02ae0da430798515.png) 从如何在 Docker Hub 上使用 [Python 映像的示例中复制到 Atom 中的示例 Docker 文件的屏幕截图](https://hub.docker.com/_/python/?tab=description) **第 1 行:**标签`:3`指定使用哪个版本的图像。对于 python 2 版本,这也可以读作`FROM python:2`。对于所有不同的版本或标签,请查看 python Docker Hub 页面上的[支持的标签。](https://hub.docker.com/_/python/) **第 3 行:**指定容器的工作目录`WORKDIR` **第 5 行&第 6 行:**将`reqiuirements.txt`从本地机器上的当前目录复制到`WORDKDIR`容器中,然后`RUN`安装文件中列出的所有库。 **第 8 行:**所有内容都从本地机器上的当前目录复制到容器中的`WORKDIR` **第 10 行:**`CMD`命令在新容器中启动 python 脚本💥 **提示!**用`FROM python:3-onbuild`写更少的行,这将包括复制文件部分和来自`requirements.txt`的需求的安装。上面的 Dockerfile 文件变成: ![](img/beb11c473ccd1a374684a5b5fdabb334.png) 最后,构建映像,共享并运行: * `docker build -t <TAG NAME> .`将从这个 docker 文件构建图像,给它一个对你有意义的`-t`标记名。`.`表示 Dockerfile 文件是当前位置。 * `docker run -it <TAG NAME>`将在`-i`交互模式下运行新图像。 如果您想使用 Docker Hub 或其他地方的图像,而不需要额外的库或环境变量等,并使用它运行一个脚本,该怎么办?一定要写 Dockerfile,建立新形象吗? 相反,我们可以运行下面的命令来启动一个直接基于图像`<TAG NAME>`的容器,比如官方的 python 图像,并在其中运行脚本`my-new-python-script.py`: ![](img/ce3b49bc5ef204c4e94dda4ad1d56f5b.png) 运行不包含在映像构建中的脚本的命令 * `docker run -it`和以前一样,在脚本所在的目录下运行。 * `-v "$PWD":/usr/src/myapp`将本地目录——或`-v`卷——直接挂载到容器,这意味着所需的脚本必须在当前的本地目录中。 * `-w /usr/src/myapp`定义工作目录。即使在构建映像的 Dockerfile 文件中指定了`WORKDIR`,这也是必要的。 * `<TAG NAME> python my-new-python-script.py`正在指定要使用的图像,然后调用 python 脚本。 如果您想从同一个映像运行几个容器,并且不想使用随机生成的容器名,可以用标志`--name`指定一个容器名。 ![](img/e08d4c0ab85bc5b8513e87affec690cf.png) 命令来运行不包含在映像构建中的脚本,并将容器命名为“new-script” 在上面的终端代码中,容器被命名为“new-script ”,所以我知道哪个脚本在那个容器中运行。然而,容器名必须是唯一的,记住这一点。 目前就这些。要记的东西太多了,很容易让人不知所措。一些方便的资源包括: * 命令行参考[https://docs . docker . com/engine/reference/command line/docker/](https://docs.docker.com/engine/reference/commandline/docker/) * 码头工人自己的课程【https://docker-curriculum.com 现在,不要忘记清理你退出的容器!!!👋
import streamlit as st from PIL import Image def get_main_dir(depth: int = 0): # nopep8 """Get the main directory of the project.""" import os import sys from os.path import dirname as up main_dir = os.path.dirname(os.path.abspath(__file__)) for _ in range(depth): sys.path.append(up(main_dir)) main_dir = up(main_dir) return main_dir MAIN_DIR_PATH = get_main_dir(0) # nopep8 from models.groq_llm import GroqLLM from models.local_gguf_llm import LocalGgufLLM from models.rag import RAG from models.simple_rag import SimpleRAG from models.metadata_rag import MetadataRAG from utils.custom_utils import get_filename, load_yaml, get_extensions_paths from evaluation.test_dataset import questions, answers st.set_page_config(page_title="MOLE", layout="wide") def display_messages(): st.subheader("Chat") with st.session_state["container_message"]: for i, element in enumerate(st.session_state["messages"]): msg, user, stream = element if user == "user": st.chat_message( user).write(msg) elif user == "assistant" and msg != "": if not stream: st.chat_message( user).write(msg) elif stream: placeholder = st.empty() streamed_messages = "" for message in msg: # Iterate over the generator if message != None: try: streamed_messages += message.encode( 'utf-8').decode('utf-8') except: try: streamed_messages += message.encode( 'latin1').decode('utf-8') except: streamed_messages += message.encode( 'utf-8', 'ignore').decode('utf-8', 'ignore') with placeholder.chat_message(user): st.write(streamed_messages) st.session_state["messages"][i] = ( streamed_messages, "assistant", False) st.session_state["thinking_spinner"] = st.empty() def process_input(): if (st.session_state["user_input"] and len(st.session_state["user_input"].strip()) > 0): user_text = st.session_state["user_input"].strip() st.session_state["messages"].append((user_text, "user", False)) if st.session_state["llm"] and st.session_state["llm"].loaded: with st.session_state["thinking_spinner"], st.spinner(f"Thinking"): if st.session_state["toggle_rag"]: agent_text, stream = st.session_state["rag"].ask_stream( user_text, False), True else: agent_text, stream = st.session_state["llm"].ask_stream( user_text, False), True st.session_state["messages"].append( (agent_text, "assistant", stream)) else: st.session_state["messages"].append( ("Please load a model first.", "assistant", False)) def llm_loader(): st.subheader("LLM Loader") with st.spinner(f"Loading"): st.toggle("Use Local LLM", key="toggle_local_llm") if st.session_state["llm"]: print("Current LLM is : ", st.session_state["llm"].name) else: print("No model loaded") if st.session_state["toggle_local_llm"]: if type(st.session_state["llm"]) != LocalGgufLLM: st.session_state["messages"] = [] st.session_state["llm"] = LocalGgufLLM( st.session_state["config"]) gguf_paths = get_extensions_paths( st.session_state["config"]["model_directory"], "gguf") st.selectbox("Select a LLM model", gguf_paths, format_func=get_filename, key="selectbox_local_llm", label_visibility="collapsed") load_col, unload_col = st.columns((1, 3)) load_col.button(label="Load", on_click=load_local_llm) unload_col.button(label="Unload", on_click=unload_local_llm) if st.session_state["llm"].loaded and st.session_state["llm"].name == get_filename(st.session_state["selectbox_local_llm"]): st.write("LLM loaded \u2705") else: st.session_state["load_model_spinner"] = st.empty() else: if type(st.session_state["llm"]) == LocalGgufLLM: st.session_state["llm"].unload_model() if type(st.session_state["llm"]) != GroqLLM: st.session_state["messages"] = [] st.session_state["llm"] = GroqLLM( st.session_state["config"]) st.session_state["llm"].load_model(0) st.selectbox("Select a LLM model", list( range(len(st.session_state["llm"].available_models))), key="selectbox_groqchat_llm", format_func=lambda k: st.session_state["llm"].available_models[k], on_change=change_groq_llm, label_visibility="collapsed") if st.session_state["llm"].loaded: st.write("LLM loaded \u2705") else: st.session_state["load_model_spinner"] = st.empty() def rag_loader(): st.subheader("RAG Loader") with st.spinner(f"Loading"): st.toggle("Use RAG", key="toggle_rag") if st.session_state["toggle_rag"] and st.session_state["rag"] is None: st.session_state["messages"] = [] st.session_state["rag"] = MetadataRAG( st.session_state["llm"], st.session_state["config"] ) st.session_state["rag"].load_collection("256_1000") elif not st.session_state["toggle_rag"] and st.session_state["rag"] is not None: st.session_state["messages"] = [] del st.session_state["rag"] st.session_state["rag"] = None if st.session_state["toggle_rag"]: st.write("Number of chunks:", st.session_state["rag"].collection.count()) def load_local_llm(): st.session_state["messages"] = [] gguf_path = st.session_state["selectbox_local_llm"] gguf_paths = get_extensions_paths( st.session_state["config"]["model_directory"], "gguf") with st.session_state["load_model_spinner"], st.spinner(f"Loading"): st.session_state["llm"].load_model(gguf_paths.index(gguf_path)) print("Changed LLM to : ", st.session_state["llm"].name) def unload_local_llm(): st.session_state["messages"] = [] st.session_state["llm"].unload_model() def change_groq_llm(): st.session_state["messages"] = [] llm_number = st.session_state["selectbox_groqchat_llm"] st.session_state["llm"].load_model(llm_number) print("Changed LLM to : ", st.session_state["llm"].name) def display_questions(questions, answers): st.write("# Questions and Answers") for i, (question, answer) in enumerate(zip(questions, answers)): st.write(f"## Question {i+1}: {question}") st.write(f"Correct Answer: {answer}") st.write("---") def page_chat(): if len(st.session_state) == 0: st.session_state["messages"] = [] st.session_state["llm"] = None st.session_state["rag"] = None st.session_state["config"] = load_yaml(MAIN_DIR_PATH + "./config.yaml") st.header("MOLE") with st.sidebar: logo = Image.open(MAIN_DIR_PATH + r"\assets\logo.png") st.image(logo, width=300) llm_loader() rag_loader() st.session_state["container_message"] = st.container(height=600) display_messages() st.chat_input("Message", key="user_input", on_submit=process_input) def page_questions(): st.header("MOLE") st.write("### Questions and Answers") for i, (question, answer) in enumerate(zip(questions, answers)): st.write(f"Question {i+1}: {question}") st.write(f"Correct Answer: {answer}") st.write("---") def main(): st.sidebar.title("Navigation") page = st.sidebar.radio("Go to", ["Chat", "Questions"]) if page == "Chat": page_chat() elif page == "Questions": page_questions() if __name__ == "__main__": main()
<h1 align="center"> <a href="https://github.com/CirculatoryHealth/LoFTK"> <img src="/docs/images/LoFTK_logo2.png" alt="Logo" width="300" height="150"> </a> </h1> LOFTK (Loss-of-Function ToolKit) [![DOI](https://img.shields.io/badge/DOI-10.1101%2F2021.08.09.455694-lightgrey)](https://doi.org/10.1101/2021.08.09.455694) [![License](https://img.shields.io/badge/license-CC--BY--SA--4.0-orange)](https://choosealicense.com/licenses/cc-by-sa-4.0) [![Version](https://img.shields.io/badge/Version-1.0.0-blue)](https://github.com/CirculatoryHealth/LoFTK) [![zenodo_DOI](https://zenodo.org/badge/274101242.svg)](https://zenodo.org/badge/latestdoi/274101242) #### This readme > This readme accompanies the paper _"LOFTK: a framework for fully automated calculation of predicted Loss-of-Function variants."_ by [Alasiri A. *et al*. **bioRxiv 2021**](https://doi.org/10.1101/2021.08.09.455694). -------------- ## Background Predicted Loss-of-Function (LoF) variants in human genes are important due to their impact on clinical phenotypes and frequent occurrence in the genomes of healthy individuals. Current approaches predict high-confidence LoF variants without identifying the specific genes or the number of copies they affect. Here we present an open source tool, the **Loss-of-Function ToolKit (LoFTK)**, which allows efficient and automated prediction of LoF variants from both genotyped and sequenced genomes, identifying genes that are inactive in one or two copies, and providing summary statistics for downstream analyses. **LoFTK** is a pipeline written in the `BASH` and `Perl` languages to identify loss-of function (LoF) variants using [`VEP`](https://github.com/Ensembl/ensembl-vep) and [`LOFTEE`](https://github.com/konradjk/loftee) efficiently. It will aid in annotating LoF variants, select high confidence (HC) variants, state the homozygous and heterozygous LoF variants, and calculate statistics. **The Loss-of-Function ToolKit Workflow: finding knockouts using genotyped and sequenced genomes.** ![The Loss-of-Function ToolKit Workflow: finding knockouts using genotyped and sequenced genomes.](docs/images/workflow.png) -------------- ## Installation and Requirements ### Install LoFTK LoFTK has been developed to work under the environment of two cluster managers; Simple Linux Utility for Resource Management (SLURM) and Sun Grid Engine (SGE). Each cluster manager (SLURM/SGE) has LoFTK verison for installation. Look at [Instillation and Requirements](https://github.com/CirculatoryHealth/LoFTK/wiki/Instillation-and-Requirements) in the [wiki](https://github.com/CirculatoryHealth/LoFTK/wiki). ### Requirements All scripts are annotated for debugging purposes - and future reference. The scripts will work within the context of a certain Linux environment - in this case we have tested **LoFTK** on CentOS7 with a SLURM Grid Engine background. - `Perl >= 5.10.1` - `Bash` - [Ensembl Variant Effect Predictor (VEP)](https://github.com/Ensembl/ensembl-vep) - [`LOFTEE`](https://github.com/konradjk/loftee) for GRCh37 - Ancestral sequence [`(human_ancestor.fa[.gz|.rz])`](https://github.com/konradjk/loftee#:~:text=slow%29.%20Default%3A%20fast.-,human_ancestor_fa,-Location%20of%20human_ancestor) - PhyloCSF database [`(phylocsf.sql)`](https://github.com/konradjk/loftee#:~:text=checked%20and%20filtered.-,conservation_file,-The%20required%20SQL) for conservation filters - [`LOFTEE`](https://github.com/konradjk/loftee/tree/grch38) for GRCh38 - GERP scores bigwig [`(gerp_bigwig)`](https://github.com/konradjk/loftee/tree/grch38#:~:text=contain%20this%20path.-,gerp_bigwig,-Location%20of%20GERP) - Ancestral sequence [`(human_ancestor_fa)`](https://github.com/konradjk/loftee/tree/grch38#:~:text=download%20for%20GRCh38.-,human_ancestor_fa,-Location%20of%20human_ancestor) - PhyloCSF database [`(loftee.sql.gz)`](https://github.com/konradjk/loftee/tree/grch38#:~:text=checked%20and%20filtered.-,conservation_file,-Location%20of%20file) - [`samtools`](https://github.com/samtools/samtools) ([must be on path](https://github.com/CirculatoryHealth/LoFTK/wiki/Instillation-and-Requirements#samtools-must-be-on-path)) -------------- ## Usage The only script the user should use is the `run_loftk.sh` script in conjunction with a configuration file `LoF.config`. It is required to set up the configuration file `LoF.config` before run any analysis, follow the [instruction](https://github.com/CirculatoryHealth/LoFTK/wiki/Configuration) in the [wiki](https://github.com/CirculatoryHealth/LoFTK/wiki). You can run **LoFTK** using the following command: ``` bash run_loftk.sh $(pwd)/LoF.config ``` **Always Remember** 1. To set all options in the `LoF.config` file before the run 2. To use the _full path_ to the configuration file, e.g. use `$(pwd)`. 2. You can run LoFTK steps all in one run or separately by setting **analysis type** in the `LoF.config` file. 3. VEP and LOFTEE options can be added and modified in one of these configuration files in `./bin/`: - [VEP_LOFTEE_GRCh37.config](bin/VEP_LOFTEE_GRCh37.config) - [VEP_LOFTEE_GRCh38.config](bin/VEP_LOFTEE_GRCh38.config) ### Description of files File | Description | Usage --------------------------------- | -------------------------------- | -------------- README.md | Description of project | Human editable LICENSE | User permissions | Read only LoF.config | Configuration file | Human editable run_loftk.sh | Main LoFTK script | Read only LoF_annotation.sh | Annotation of LoF variants/genes | Read only allele_to_vcf.sh | Converting IMPUT2 format to VCF | Read only descriptive_stat.sh | Descriptive analysis | Read only -------------- ## Post LoFTK ### Merge the counts files of multiple cohorts This scripts allows you to merge the counts files of different cohorts. By default it only includes genes that were present in both files but you can use the `union` function to include genes that are present in at least 1 cohort. This means that for the other cohorts, the gene LoF counts will be set to 0 for every individual (which is tricky if the gene was not tested), or to a self-specified value ```bash perl merge_gene_lof_counts.pl -i cohortX.counts,cohortY.counts,cohortZ.counts -o merged_cohorts.counts -c ``` Run the the following to know how to use options: ```bash perl merge_gene_lof_counts.pl --help ``` ### Mismatched genes between samples This script can be used to determine ‘mismatched’ genes between samples; these are genes that are active in one or two copies in one sample and completely inactive (two-copy loss) in the other sample. This feature helps study interactions between human genomes, for instance during pregnancy (maternal vs fetal genome) and after stem cell or solid organ transplantation (donor vs recipient genome). - You must create a file `pairs_file.txt` with two columns (tab-separated), where both columns have list of individual IDs and each line has paired subjects. - The first column must contain individual IDs for which you want to examine the mismatch of knocked out genes with the 1 or 2 active copies in the other pair. - Output file contains encodings for individuals (from 1st column in `pairs_file.txt`), where `1` for mismatch `0` for not mismatch. - `1`: mismatch where sample in the 2nd column has active gene. - `0`: not mismatch where paired samples either having both a knocked out gene or none of them carry LoF gene. **Run the below command:** ```bash perl gene_lof_counts_to_dyad_lofs.pl pairs_file.txt input_file.counts output_file.dyads ``` -------------- ## Inputs **LoFTK** permits two common file formats as an input: 1. **Variant Call Format (VCF)** You can find VCF specification [here](https://samtools.github.io/hts-specs/VCFv4.2.pdf). 2. **IMPUTE2 output format** Four files with the following extensions are needed as an input; `.haps.gz`, `.allele_probs.gz`, `.info` and `.sample` :warning: The input data have to be phased to annotate compound heterozygous LoF variants, which result in LoF genes with two copies losses. For more details and [examples](data/) about [**input files**](https://github.com/CirculatoryHealth/LoFTK/wiki/Input-files) are explained in the [wiki](https://github.com/CirculatoryHealth/LoFTK/wiki). -------------- ## Outputs **LoFTK** will generate four files as an output at the end of the analysis. The [LoFTK outputs](https://github.com/CirculatoryHealth/LoFTK/wiki/LoFTK-outputs) in the [wiki](https://github.com/CirculatoryHealth/LoFTK/wiki) contains more explanation. 1. [[project_name]_snp.counts](https://github.com/CirculatoryHealth/LoFTK/wiki/LoFTK-outputs): LoF variants and individuals. 2. [[project_name]_gene.counts](https://github.com/CirculatoryHealth/LoFTK/wiki/LoFTK-outputs): LoF genes and individuals. 3. [[project_name]_gene.lof.snps](https://github.com/CirculatoryHealth/LoFTK/wiki/LoFTK-outputs): list of LoF variants allele frequencies. 4. [[project_name]_output.info](https://github.com/CirculatoryHealth/LoFTK/wiki/LoFTK-outputs): report descriptive statistics on LoF variants and genes. -------------- #### Changes log _Version:_ v1.0.0</br> _Last update:_ 2021-06-08</br> * v1.0.0 Initial version. * v1.0.1 - Add post LoFTK analysis - [Merge](https://github.com/CirculatoryHealth/LoFTK#merge-the-counts-files-of-multiple-cohorts) and [Mismatched genes](https://github.com/CirculatoryHealth/LoFTK#mismatched-genes-between-samples). * v1.0.2 - separate stat description from annotation script * v1.0.3 - Run each step in LoFTK separately - Add configuration file to modify VEP and LOFTEE options ### Contact If you have any suggestions for improvement, discover bugs, etc. please create an [issues](https://github.com/CirculatoryHealth/LoFTK/issues). For all other questions, please refer to the last author: Jessica van Setten, PhD | j.vansetten [at] umcutrecht.nl -------------- #### CC-BY-SA-4.0 License <table> <tr> <td> ##### Copyright (c) 2020 University Medical Center Utrecht Creative Commons Attribution-ShareAlike 4.0 International Public License By exercising the Licensed Rights (defined in the [LICENSE](LICENSE)), you accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, you are granted the Licensed Rights in consideration of your acceptance of these terms and conditions, and the Licensor grants you such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Reference: https://choosealicense.com/licenses/cc-by-sa-4.0/#. </td> </tr> </table>
package haxe.ds; @:coreApi class IntMap<T> implements haxe.Constraints.IMap<Int, T> { var _m:dart.core.Map<Int, T>; public function new() _m = new dart.core.Map(); public function set(key:Int, value:T):Void untyped _m[key] = value; public function get(key:Int):Null<T> return untyped _m[key]; public function exists(key:Int):Bool return _m.containsKey(key); public function remove(key:Int):Bool return _m.remove(key) != null; public function keys():Iterator<Int> return new dart.HaxeIterator(_m.keys.iterator); public function iterator():Iterator<T> return new dart.HaxeIterator(_m.values.iterator); public function keyValueIterator():KeyValueIterator<Int, T> return new haxe.iterators.MapKeyValueIterator(this); public function copy():IntMap<T> { final result = new IntMap(); result._m = dart.core.Map.of(_m); return result; } public function toString():String return untyped _m.toString(); public function clear():Void return _m.clear(); }
[![SonarCloud](https://sonarcloud.io/images/project_badges/sonarcloud-white.svg)](https://sonarcloud.io/summary/new_code?id=Arthur-Maskalenkas_bora-marcar) [![Coverage Status](https://coveralls.io/repos/github/Arthur-Maskalenkas/bora-marcar/badge.svg)](https://coveralls.io/github/Arthur-Maskalenkas/bora-marcar) # Seja bem vindo ao Bora Marcar! --- # Sobre ## O que é o Bora Marcar? O Bora Marcar é um projeto que visa facilitar a vida de quem gosta de criar e participar de eventos. Com ele você pode criar um evento, convidar seus amigos e marcar a data. ## Como funciona? Funciona a base de microsserviços, onde cada serviço é responsável por uma funcionalidade específica. O projeto é composto por 4 serviços: - [Bora Marcar API](xxx): Responsável por gerenciar os eventos e convidados. - [Bora Marcar Auth](xxx): Responsável por gerenciar a autenticação dos usuários. - [Bora Marcar Front](xxx): Responsável por disponibilizar a interface gráfica para o usuário. - [Bora Marcar Gateway](xxx): Responsável por disponibilizar uma API única para os serviços. ## O que foi criado até o momento? - 🟡 API de eventos - Em andamento... - 🔴 API Gateway - Aguardando a tarefa acima ser concluída. - 🔴 API de autenticação - Aguardando a tarefa acima ser concluída. - 🔴 Frontend - Aguardando a tarefa acima ser concluída. --- # Utilidades ## No projeto você vai encontrar diversos principios e metodologias, como: ### Principios: - Liskov Substitution Principle (LSP) - Open Closed Principle (OCP) - Interface Segregation Principle (ISP) - Single Responsibility Principle (SRP) - Dependency Inversion Principle (DIP) - Separation of Concerns (SOC) - Don't Repeat Yourself (DRY) - Keep It Simple, Silly (KISS) - You Aren't Gonna Need It (YAGNI) - Composition Over Inheritance - Small Commits ### Metodologias: - Continuous Integration - Continuous Delivery - Continuous Deployment - TDD - Clean Architecture - DDD - GitFlow - Use Cases --- # Rodando o projeto ### Antes de mais nada, você precisa ter instalado em sua maquina: - [Docker](https://www.docker.com/) ### Para rodar o projeto você precisa seguir os seguintes passos: 1. Clone o projeto 2. Crie um .env na raiz do projeto e preencha com as variaveis de ambiente do projeto mencionadas no arquivo .env.example 3. Rode o comando `npm install` para instalar as dependencias 4. Rode `npm run build:watch` observar as mudanças nos arquivos 5. Levante os containers com o comando `npm run docker:up` - O container vai levantar tanto a api quanto o banco de dados :D 6. Acesse a api através do endereço `http://127.0.0.1:5050/api` 7. Utilize o [manual da API](xxx) para testar as rotas
package org.sportradar.soccer.worldcup; import static org.junit.jupiter.api.Assertions.*; import static org.sportradar.soccer.worldcup.Fixtures.TEAM_A; import static org.sportradar.soccer.worldcup.Fixtures.TEAM_B; import static org.sportradar.soccer.worldcup.Fixtures.TEAM_C; import static org.sportradar.soccer.worldcup.Fixtures.TEAM_D; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class LiveScoreboardTest { private LiveScoreboard liveScoreboard; @BeforeEach void beforeEach() { liveScoreboard = LiveScoreboard.getInstance(); } @Nested @DisplayName("start match") class StartMatch { @ParameterizedTest @DisplayName("fails with exception when null objects are passed as parameters") @MethodSource("provideNullTeamNames") void throwsException_whenNullParametersArePassed( String teamA, String teamB, String expectedMessage) { Exception exception = assertThrows( IllegalArgumentException.class, () -> liveScoreboard.startMatch(teamA, teamB)); String actualMessage = exception.getMessage(); assertEquals(actualMessage, expectedMessage); } @ParameterizedTest @DisplayName("fails with exception when team is already playing in another match") @MethodSource("provideTeamsAlreadyInAMatch") void throwsException_whenTeamIsAlreadyInAMatch( String homeTeamInAMatch, String awayTeamInAMatch, String teamA, String teamB, String expectedMessage) { liveScoreboard.startMatch(homeTeamInAMatch, awayTeamInAMatch); Exception exception = assertThrows(IllegalStateException.class, () -> liveScoreboard.startMatch(teamA, teamB)); String actualMessage = exception.getMessage(); assertEquals(actualMessage, expectedMessage); } private static Stream<Arguments> provideNullTeamNames() { return getNullTeamNames(); } private static Stream<Arguments> provideTeamsAlreadyInAMatch() { String expectedExceptionMessage = "There is already ongoing match for a team on the scoreboard: %s"; Stream<Arguments> argumentsStream = Stream.of( Arguments.of( TEAM_A, TEAM_B, TEAM_A, TEAM_C, String.format(expectedExceptionMessage, TEAM_A)), Arguments.of( TEAM_A, TEAM_B, TEAM_C, TEAM_B, String.format(expectedExceptionMessage, TEAM_B))); return argumentsStream; } } @Nested @DisplayName("finish match") class FinishMatch { @ParameterizedTest @DisplayName("fails with exception when null objects are passed as parameters") @MethodSource("provideNullTeamNames") void throwsException_whenNullParametersArePassed( String teamA, String teamB, String expectedMessage) { Exception exception = assertThrows( IllegalArgumentException.class, () -> liveScoreboard.finishMatch(teamA, teamB)); String actualMessage = exception.getMessage(); assertEquals(actualMessage, expectedMessage); } private static Stream<Arguments> provideNullTeamNames() { return getNullTeamNames(); } } @Nested @DisplayName("update score") class UpdateScore { @ParameterizedTest @DisplayName("fails with exception when null objects are passed as parameters") @MethodSource("provideNullTeamNames") void throwsException_whenNullParametersArePassed( String teamA, String teamB, String expectedMessage) { Exception exception = assertThrows( IllegalArgumentException.class, () -> liveScoreboard.updateScore(teamA, 1, teamB, 1)); String actualMessage = exception.getMessage(); assertEquals(actualMessage, expectedMessage); } @Test @DisplayName("fails with exception when match is not on the scoreboard") void throwsException_whenMatchIsNotOnScoreboard() { Exception exception = assertThrows( IllegalStateException.class, () -> liveScoreboard.updateScore(TEAM_A, 1, TEAM_B, 1)); String expectedMessage = String.format( "There is no match on the scoreboard for home team: %s and away team: %s", TEAM_A, TEAM_B); String actualMessage = exception.getMessage(); assertEquals(actualMessage, expectedMessage); } private static Stream<Arguments> provideNullTeamNames() { return getNullTeamNames(); } } @Nested @DisplayName("get summary") class GetSummary { @Test @DisplayName("provides expected summary for exemplary World Cup conditions") void succeeds_forExemplaryWorldCupConditions() { // given /* Following matches are started in the specified order and their scores respectively updated Mexico 0 - Canada 5 Spain 10 - Brazil 2 Germany 2 - France 2 Uruguay 6 - Italy 6 Argentina 3 - Australia 1 */ liveScoreboard.startMatch("Mexico", "Canada"); liveScoreboard.startMatch("Spain", "Brazil"); liveScoreboard.startMatch("Germany", "France"); liveScoreboard.startMatch("Uruguay", "Italy"); liveScoreboard.startMatch("Argentina", "Australia"); liveScoreboard.updateScore("Spain", 10, "Brazil", 2); liveScoreboard.updateScore("Uruguay", 6, "Italy", 6); liveScoreboard.updateScore("Mexico", 0, "Canada", 5); liveScoreboard.updateScore("Argentina", 3, "Australia", 1); liveScoreboard.updateScore("Germany", 2, "France", 2); // when Summary actualSummary = liveScoreboard.getSummary(); // then /* The summary should be as follows: 1. Uruguay 6 - Italy 6 2. Spain 10 - Brazil 2 3. Mexico 0 - Canada 5 4. Argentina 3 - Australia 1 5. Germany 2 - France 2 */ Summary expectedSummary = Summary.of( new Summary.Score("Uruguay", 6, "Italy", 6), new Summary.Score("Spain", 10, "Brazil", 2), new Summary.Score("Mexico", 0, "Canada", 5), new Summary.Score("Argentina", 3, "Australia", 1), new Summary.Score("Germany", 2, "France", 2)); assertEquals(expectedSummary, actualSummary); } @Test @DisplayName("provides empty summary when all matches were already finished") void providesEmptyList_whenAllMatchesWereFinished() { // given liveScoreboard.startMatch(TEAM_A, TEAM_B); liveScoreboard.updateScore(TEAM_A, 1, TEAM_B, 0); liveScoreboard.startMatch(TEAM_C, TEAM_D); liveScoreboard.updateScore(TEAM_C, 1, TEAM_D, 2); liveScoreboard.finishMatch(TEAM_A, TEAM_B); liveScoreboard.finishMatch(TEAM_C, TEAM_D); // when Summary actualSummary = liveScoreboard.getSummary(); liveScoreboard.startMatch(TEAM_A, TEAM_B); // then assertTrue(actualSummary.getScores().isEmpty()); } @Test @DisplayName("provides properly sorted summary when match was finished and stared again") void providesProperlyOrderList_whenMatchWasFinishedAndStartedAgain() { // given liveScoreboard.startMatch(TEAM_A, TEAM_B); liveScoreboard.updateScore(TEAM_A, 1, TEAM_B, 1); liveScoreboard.startMatch(TEAM_C, TEAM_D); liveScoreboard.updateScore(TEAM_C, 1, TEAM_D, 1); // finish match A,B liveScoreboard.finishMatch(TEAM_A, TEAM_B); // start match A,B again liveScoreboard.startMatch(TEAM_A, TEAM_B); liveScoreboard.updateScore(TEAM_A, 1, TEAM_B, 1); // when Summary actualSummary = liveScoreboard.getSummary(); // then Summary expectedSummary = Summary.of( new Summary.Score(TEAM_A, 1, TEAM_B, 1), new Summary.Score(TEAM_C, 1, TEAM_D, 1)); assertEquals(expectedSummary, actualSummary); } } private static Stream<Arguments> getNullTeamNames() { String expectedExceptionMessage = "Provided team names cannot be null, provided home team: %s away team: %s"; return Stream.of( Arguments.of(null, null, String.format(expectedExceptionMessage, null, null)), Arguments.of(TEAM_A, null, String.format(expectedExceptionMessage, TEAM_A, null)), Arguments.of(null, TEAM_A, String.format(expectedExceptionMessage, null, TEAM_A))); } }
package com.example.gmailclone import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView class MyCustomAdapter (val items: ArrayList<ItemModel>): BaseAdapter() { override fun getCount(): Int { return items.size } override fun getItem(p0: Int): Any { return items[p0] } override fun getItemId(p0: Int): Long { return p0.toLong() } override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View { val row : View = LayoutInflater.from(p2?.context).inflate(R.layout.custom_row_icon_label, p2, false) val textView = row.findViewById<TextView>(R.id.caption) val imageView = row.findViewById<ImageView>(R.id.icon) val contentView = row.findViewById<TextView>(R.id.content) textView.text = items[p0].caption imageView.setImageResource(items[p0].imageResource) contentView.text = items[p0].content return row } }
<script> import rules from "@/services/rules/index.js"; export default { data: () => ({ model: {}, rules }), async mounted() { await this.loadData(); }, methods: { async loadData() { try { const response = await this.$API .categories() .getForEdit(this.$route.params.id); this.model = response.data; } catch (e) { console.log(e); } }, async submit() { try { const form = this.$refs.form; if (form.valdiate()) { await this.$API.categories().edit(this.$route.params.id, this.model); await this.$router.push("/categories"); } } catch (e) { console.log(e); } }, }, }; </script> <template> <div class="d-flex align-center justify-center" style="width: 100%"> <v-card min-width="900" class="mt-5"> <v-card-title>Edit category</v-card-title> <v-card-text> <v-row> <v-col cols="12"> <v-form ref="form" lazy-validation> <v-text-field label="Name RO" :rules="[rules.required, rules.minLength(3)]" v-model="model.name_ro" /> <v-text-field label="Name EN" :rules="[rules.required, rules.minLength(3)]" v-model="model.name_en" /> <v-text-field label="Name RU" :rules="[rules.required, rules.minLength(3)]" v-model="model.name_ru" /> </v-form> </v-col> </v-row> </v-card-text> <v-card-actions> <v-spacer /> <v-btn depressed small text link to="/categories"> Cancel </v-btn> <v-btn depressed small outlined color="primary" @click="submit()"> Save </v-btn> </v-card-actions> </v-card> </div> </template> <style scoped></style>
package com.example.springlearnrediscluster.controller; import com.example.springlearnrediscluster.model.User; import com.example.springlearnrediscluster.service.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/cache") public class CacheController { private final UserService userService; public CacheController(UserService userService) { this.userService = userService; } @PostMapping("/user") public ResponseEntity<String> saveUser(@RequestBody User user) { boolean result = userService.saveUser(user); if (result) return ResponseEntity.ok("User created successfully!"); else return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } @GetMapping("/user") public ResponseEntity<List<User>> getAllUsers() { List<User> users = userService.getAllUsers(); return ResponseEntity.ok(users); } @GetMapping("/user/{id}") public ResponseEntity<User> getUserById(@PathVariable("id") Long id) { User user = userService.getUserById(id); return ResponseEntity.ok(user); } @DeleteMapping("/user/{id}") public ResponseEntity<String> deleteUser(@PathVariable("id") Long id) { boolean result = userService.deleteUser(id); if (result) return ResponseEntity.ok("User deleted successfully!"); else return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } @PutMapping("/user/{id}") public ResponseEntity<String> updateUser(@PathVariable("id") Long id, @RequestBody User user) { boolean result = userService.updateUser(id, user); if (result) return ResponseEntity.ok("User updated successfully!"); else return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); } }
from scipy.integrate import odeint from numpy import linspace, exp, sqrt, pi import matplotlib.pyplot as plt #Function retunring dphi/dx and dE/dx def dfdx(phiE, x, vs=1): #parameters passed from odient in result variable #Unpack values for variables phi and E phi = phiE[0] ; E = phiE[1] # Equation for ion density ni = (vs/(sqrt(vs**2 - 2*phi))) ne = exp(phi) #Calculate the x derivatives dEdx = ni - ne dphidx = -E return [dphidx, dEdx] def run(E0, phi0, vs): x=linspace(0,40,100) #Define x-axis coordinates f0 = [phi0, E0] #Initial values for phi and E result = odeint(dfdx, f0, x, args=(vs,)) #assigns values from using odeint to variable x_of_t = result[:,0] # Draws out values of phi from result j = sqrt(1840/(2*pi))*exp(x_of_t) - 1 #the normalised equation for current #Plots Potential against x plt.figure(1) plt.plot(x, x_of_t, label = 'Potential') plt.xlabel("Distance [Debye lengths]") plt.ylabel("Potential [Normalised]") plt.title('Potential with respect to Distance') plt.legend(loc='best') plt.grid() #Plots current against x plt.figure(2) plt.plot(x,j, label = 'Current') plt.xlabel("Distance [Debye lengths]") plt.ylabel("Current [Normalised]") plt.title('Current with respect to the distance') plt.legend(loc='best') plt.grid() if __name__ == "__main__": #Allows other programs to use the function run(0.001, 0., 1.0) #passes initial conditions #(Electric field, Potential, velocity of sheath ions)
const path = require("path") const fs = require("fs") const http= require("http") const server=http.createServer((req,res)=>{ // if(req.url==='/'){ // fs.readFile(path.join(__dirname,"public","home.html"),"utf8",function(err,data){ // if(err) throw err; // res.writeHead(200,{"Content-type": "text/html"}); // res.end(data); // }); // } // //console.log(req); // else if(req.url==="/about"){ // fs.readFile(path.join(__dirname,"public","about.html"),"utf8",function(err,data){ // if(err) throw err; // res.writeHead(200,{"Content-type": "text/html"}); // res.end(data); // }); // } let filePath = path.join( __dirname, "public", req.url === "/" ? "home.html" : req.url ); // Extension of file let extname = path.extname(filePath); // Initial content type let contentType = "text/html"; // Check ext and set content type switch (extname) { case ".js": contentType = "text/javascript"; break; case ".css": contentType = "text/css"; break; case ".json": contentType = "application/json"; break; case ".png": contentType = "image/png"; break; case ".jpg": contentType = "image/jpg"; break; } // Check if contentType is text/html but no .html file extension if (contentType == "text/html" && extname == "") filePath += ".html" fs.readFile(filePath, (err, content) => { if (err) { if (err.code == "ENOENT") { // Page not found fs.readFile( path.join(__dirname, "public", "error.html"), (err, content) => { res.writeHead(404, { "Content-Type": "text/html" }); res.end(content, "utf8"); } ); } else { // Some server error res.writeHead(500); res.end(`Server Error: ${err.code}`); } } else { // Success res.writeHead(200, { "Content-Type": contentType }); res.end(content, "utf8"); } }); }); const PORT = process.env.PORT || 5000; server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
@page "/pendingLeaves" @using BlazorProject.Service.IService @using System.Security.Policy; @if(PendingLeaveList == null) { <h2 class="text-center text-danger">No Data Found...</h2> } else { <table class="table table-bordered table-striped table-active m-2 p-2"> <thead> <tr> <th>User Name</th> <th>Leave Type</th> <th>Start Date</th> <th>End Date</th> <th>Contact</th> <th>Reason</th> <th>File</th> <th>To</th> <th>CC</th> </tr> </thead> <tbody> @foreach (var leave in PendingLeaveList) { <tr style="font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;"> <td>@leave.LeaveBalance.ApplicationUser.Name</td> <td>@leave.LeaveBalance.LeaveType.Name</td> <td>@leave.StartDate.ToShortDateString()</td> <td>@leave.EndDate.ToShortDateString()</td> <td>@leave.Contact</td> <td>@leave.Reason</td> <td> <button class="btn-primary" @onclick="(() => Preview(leave))">Preview</button> </td> <td>@leave.To</td> <td>@leave.CC</td> </tr> } </tbody> </table> @if (Extension == "image/jpeg") { <img src="@DataURL" alt="File Not Found" style="height:70vh;width:70vw" /> } else if (Extension == "text/plain") { <iframe src="@DataURL" style="height:70vh;width:70vw"></iframe> } else if (Extension == "application/pdf") { <iframe src="@DataURL" style="height:70vh;width:70vw"></iframe> } } @code { [Inject] protected ILeaveService leaveService { get; set; } [Parameter] public IEnumerable<Models.Leave> PendingLeaveList { get; set; } protected string Extension { get; set; } protected string DataURL { get; set; } protected override async Task OnInitializedAsync() { GetPendingLeaveList(); } public void GetPendingLeaveList() { PendingLeaveList = leaveService.GetUserPendingLeaves(); } public void Preview(Models.Leave file) { DataURL = string.Format($"data:{file.FileExtension};base64,{file.File}"); Extension = file.FileExtension; } }
import express from 'express'; import { CommentStore,comment } from '../models/comment'; const store = new CommentStore(); const index = async (req : express.Request , res : express.Response)=>{ try{ const comments = await store.index(); res.json(comments); }catch(err){ res.status(400) res.json(`error is : ${err}`) } } const show = async (req : express.Request , res : express.Response)=>{ try{ const comment = await store.show(req.params.id); res.json(comment); }catch(err){ res.status(400) res.json(`error is : ${err}`) } } const destroy = async (req : express.Request , res : express.Response)=>{ try{ const comment = await store.delete(req.params.id); res.json(comment); }catch(err){ res.status(400) res.json(`error is : ${err}`) } } const create = async (req : express.Request , res : express.Response)=>{ try{ const sentComment : comment ={ userId : req.body.userId, commentTitle : req.body.commentTitle, commentBody : req.body.commentBody, rating : req.body.rating } const createdComment = await store.create(sentComment); res.json(createdComment); }catch(err){ res.status(400); res.json(`error is : ${err}`); } } const update = async (req : express.Request , res : express.Response)=>{ try{ const originalComment = await store.show(req.params.id); const updatedComment : comment ={ userId : req.body.userId ? req.body.userId : originalComment.userId, commentTitle : req.body.commentTitle ? req.body.commentTitle : originalComment.commentTitle, commentBody : req.body.commentBody ? req.body.commentBody : originalComment.commentBody, rating : req.body.rating ? req.body.rating : originalComment.rating } const updatecomment = await store.update(req.params.id,updatedComment); res.json(updatecomment); }catch(err){ res.status(400); res.json(`error is : ${err}`); } } const commentsHandler = (app : express.Application)=>{ app.get('/comments' , index); app.get('/comments/:id' , show); app.post('/comments' , create); app.put('/comments/:id' , update); app.delete('/comments/:id' , destroy); } export default commentsHandler;
// SPDX-License-Identifier: LGPL-3.0-only pragma solidity 0.8.23; // Internal Interfaces import { IOrchestrator_v1, IFundingManager_v1, IPaymentProcessor_v1, IAuthorizer_v1, IGovernor_v1 } from "src/orchestrator/interfaces/IOrchestrator_v1.sol"; import {IModule_v1} from "src/modules/base/IModule_v1.sol"; import {IModuleManagerBase_v1} from "src/orchestrator/interfaces/IModuleManagerBase_v1.sol"; // Internal Dependencies import {ModuleManagerBase_v1} from "src/orchestrator/abstracts/ModuleManagerBase_v1.sol"; // External Interfaces import {IERC20} from "@oz/token/ERC20/IERC20.sol"; // External Libraries import {ERC165Checker} from "@oz/utils/introspection/ERC165Checker.sol"; /** * @title Orchestrator * * @dev This Contract is the center and connecting block of all Modules in a * Inverter Network Workflow. It contains references to the essential contracts * that make up a workflow. By inheriting the ModuleManager it allows for managing * which modules make up the workflow. * * An orchestrator is composed of a funding mechanism * and a set of modules. * * The token being accepted for funding is non-changeable and set during * initialization. Authorization is performed via calling a non-changeable * {IAuthorizer_v1} instance. Payments, initiated by modules, are processed * via a non-changeable {IPaymentProcessor_v1} instance. * * Each orchestrator has a unique id set during initialization. * * @custom:security-contact [email protected] * In case of any concerns or findings, please refer to our Security Policy * at security.inverter.network or email us directly! * * @author Inverter Network */ contract Orchestrator_v1 is IOrchestrator_v1, ModuleManagerBase_v1 { function supportsInterface(bytes4 interfaceId) public view virtual override(ModuleManagerBase_v1) returns (bool) { return interfaceId == type(IOrchestrator_v1).interfaceId || super.supportsInterface(interfaceId); } //-------------------------------------------------------------------------- // Modifiers /// @notice Modifier to guarantee function is only callable by the admin of the workflow /// address. modifier onlyOrchestratorAdmin() { bytes32 adminRole = authorizer.getAdminRole(); if (!authorizer.hasRole(adminRole, _msgSender())) { revert Orchestrator__CallerNotAuthorized(adminRole, _msgSender()); } _; } modifier onlyLogicModules(address module_) { // Revert given module to be removed is equal to current authorizer if (module_ == address(authorizer)) { revert Orchestrator__InvalidRemovalOfAuthorizer(); } // Revert given module to be removed is equal to current fundingManager if (module_ == address(fundingManager)) { revert Orchestrator__InvalidRemovalOfFundingManager(); } // Revert given module to be removed is equal to current paymentProcessor if (module_ == address(paymentProcessor)) { revert Orchestrator__InvalidRemovalOfPaymentProcessor(); } _; } //-------------------------------------------------------------------------- // Storage /// @inheritdoc IOrchestrator_v1 uint public override(IOrchestrator_v1) orchestratorId; /// @inheritdoc IOrchestrator_v1 IFundingManager_v1 public override(IOrchestrator_v1) fundingManager; /// @inheritdoc IOrchestrator_v1 IAuthorizer_v1 public override(IOrchestrator_v1) authorizer; /// @inheritdoc IOrchestrator_v1 IPaymentProcessor_v1 public override(IOrchestrator_v1) paymentProcessor; /// @inheritdoc IOrchestrator_v1 IGovernor_v1 public override(IOrchestrator_v1) governor; // Storage gap for future upgrades uint[50] private __gap; //-------------------------------------------------------------------------- // Constructor & Initializer constructor(address _trustedForwarder) ModuleManagerBase_v1(_trustedForwarder) { _disableInitializers(); } /// @inheritdoc IOrchestrator_v1 function init( uint orchestratorId_, address moduleFactory_, address[] calldata modules, IFundingManager_v1 fundingManager_, IAuthorizer_v1 authorizer_, IPaymentProcessor_v1 paymentProcessor_, IGovernor_v1 governor_ ) external override(IOrchestrator_v1) initializer { // Initialize upstream contracts. __ModuleManager_init(moduleFactory_, modules); // Set storage variables. orchestratorId = orchestratorId_; fundingManager = fundingManager_; authorizer = authorizer_; paymentProcessor = paymentProcessor_; governor = governor_; // Add necessary modules. // Note to not use the public addModule function as the factory // is (most probably) not authorized. _enforcePrivilegedModuleInterfaceCheck( address(fundingManager_), type(IFundingManager_v1).interfaceId ); __ModuleManager_addModule(address(fundingManager_)); _enforcePrivilegedModuleInterfaceCheck( address(authorizer_), type(IAuthorizer_v1).interfaceId ); __ModuleManager_addModule(address(authorizer_)); _enforcePrivilegedModuleInterfaceCheck( address(paymentProcessor_), type(IPaymentProcessor_v1).interfaceId ); __ModuleManager_addModule(address(paymentProcessor_)); emit OrchestratorInitialized( orchestratorId_, address(fundingManager_), address(authorizer_), address(paymentProcessor_), modules, address(governor_) ); } //-------------------------------------------------------------------------- // Module search functions /// @notice verifies whether a orchestrator with the title `moduleName` has been used in this orchestrator /// @dev The query string and the module title should be **exactly** same, as in same whitespaces, same capitalizations, etc. /// @param moduleName Query string which is the title of the module to be searched in the orchestrator /// @return uint256 index of the module in the list of modules used in the orchestrator /// @return address address of the module with title `moduleName` function _isModuleUsedInOrchestrator(string calldata moduleName) private view returns (uint, address) { address[] memory moduleAddresses = listModules(); uint moduleAddressesLength = moduleAddresses.length; string memory currentModuleName; uint index; for (; index < moduleAddressesLength;) { currentModuleName = IModule_v1(moduleAddresses[index]).title(); if (bytes(currentModuleName).length == bytes(moduleName).length) { if ( keccak256(abi.encodePacked(currentModuleName)) == keccak256(abi.encodePacked(moduleName)) ) { return (index, moduleAddresses[index]); } } unchecked { ++index; } } return (type(uint).max, address(0)); } /// @inheritdoc IOrchestrator_v1 function findModuleAddressInOrchestrator(string calldata moduleName) external view returns (address) { (uint moduleIndex, address moduleAddress) = _isModuleUsedInOrchestrator(moduleName); if (moduleIndex == type(uint).max) { revert Orchestrator__DependencyInjection__ModuleNotUsedInOrchestrator(); } return moduleAddress; } //-------------------------------------------------------------------------- // Upstream Function Implementations /// @dev Only addresses authorized via the {IAuthorizer_v1} instance can manage /// modules. function __ModuleManager_isAuthorized(address who) internal view override(ModuleManagerBase_v1) returns (bool) { return authorizer.hasRole(authorizer.getAdminRole(), who); } //-------------------------------------------------------------------------- // onlyOrchestratorAdmin Functions /// @inheritdoc IOrchestrator_v1 function initiateSetAuthorizerWithTimelock(IAuthorizer_v1 authorizer_) external onlyOrchestratorAdmin { address authorizerContract = address(authorizer_); bytes4 authorizerInterfaceId = type(IAuthorizer_v1).interfaceId; _enforcePrivilegedModuleInterfaceCheck( authorizerContract, authorizerInterfaceId ); _initiateAddModuleWithTimelock(authorizerContract); _initiateRemoveModuleWithTimelock(address(authorizer)); } /// @inheritdoc IOrchestrator_v1 function executeSetAuthorizer(IAuthorizer_v1 authorizer_) external onlyOrchestratorAdmin updatingModuleAlreadyStarted(address(authorizer_)) whenTimelockExpired(address(authorizer_)) { _executeRemoveModule(address(authorizer)); // set timelock to inactive moduleAddressToTimelock[address(authorizer_)].timelockActive = false; // Use _commitAddModule directly as it doesnt need the authorization of the by now none existing Authorizer _commitAddModule(address(authorizer_)); authorizer = authorizer_; emit AuthorizerUpdated(address(authorizer_)); } /// @inheritdoc IOrchestrator_v1 function cancelAuthorizerUpdate(IAuthorizer_v1 authorizer_) external onlyOrchestratorAdmin { _cancelModuleUpdate(address(authorizer_)); } /// @inheritdoc IOrchestrator_v1 function initiateSetFundingManagerWithTimelock( IFundingManager_v1 fundingManager_ ) external onlyOrchestratorAdmin { address fundingManagerContract = address(fundingManager_); bytes4 fundingManagerInterfaceId = type(IFundingManager_v1).interfaceId; _enforcePrivilegedModuleInterfaceCheck( fundingManagerContract, fundingManagerInterfaceId ); if (fundingManager.token() != fundingManager_.token()) { revert Orchestrator__MismatchedTokenForFundingManager( address(fundingManager.token()), address(fundingManager_.token()) ); } else { _initiateAddModuleWithTimelock(fundingManagerContract); _initiateRemoveModuleWithTimelock(address(fundingManager)); } } /// @inheritdoc IOrchestrator_v1 function executeSetFundingManager(IFundingManager_v1 fundingManager_) external onlyOrchestratorAdmin { _executeRemoveModule(address(fundingManager)); _executeAddModule(address(fundingManager_)); fundingManager = fundingManager_; emit FundingManagerUpdated(address(fundingManager_)); } /// @inheritdoc IOrchestrator_v1 function cancelFundingManagerUpdate(IFundingManager_v1 fundingManager_) external onlyOrchestratorAdmin { _cancelModuleUpdate(address(fundingManager_)); } /// @inheritdoc IOrchestrator_v1 function initiateSetPaymentProcessorWithTimelock( IPaymentProcessor_v1 paymentProcessor_ ) external onlyOrchestratorAdmin { address paymentProcessorContract = address(paymentProcessor_); bytes4 paymentProcessorInterfaceId = type(IPaymentProcessor_v1).interfaceId; _enforcePrivilegedModuleInterfaceCheck( paymentProcessorContract, paymentProcessorInterfaceId ); _initiateAddModuleWithTimelock(paymentProcessorContract); _initiateRemoveModuleWithTimelock(address(paymentProcessor)); } /// @inheritdoc IOrchestrator_v1 function executeSetPaymentProcessor(IPaymentProcessor_v1 paymentProcessor_) external onlyOrchestratorAdmin { _executeRemoveModule(address(paymentProcessor)); _executeAddModule(address(paymentProcessor_)); paymentProcessor = paymentProcessor_; emit PaymentProcessorUpdated(address(paymentProcessor_)); } /// @inheritdoc IOrchestrator_v1 function cancelPaymentProcessorUpdate( IPaymentProcessor_v1 paymentProcessor_ ) external onlyOrchestratorAdmin { _cancelModuleUpdate(address(paymentProcessor_)); } /// @inheritdoc IOrchestrator_v1 function cancelModuleUpdate(address module_) external { _cancelModuleUpdate(module_); } /// @inheritdoc IOrchestrator_v1 function initiateAddModuleWithTimelock(address module_) external { _initiateAddModuleWithTimelock(module_); } /// @inheritdoc IOrchestrator_v1 function initiateRemoveModuleWithTimelock(address module_) external onlyLogicModules(module_) { _initiateRemoveModuleWithTimelock(module_); } /// @inheritdoc IOrchestrator_v1 function executeAddModule(address module_) external { _executeAddModule(module_); } /// @inheritdoc IOrchestrator_v1 function executeRemoveModule(address module_) external onlyLogicModules(module_) { _executeRemoveModule(module_); } /// @inheritdoc IOrchestrator_v1 function executeTx(address target, bytes memory data) external onlyOrchestratorAdmin returns (bytes memory) { bool ok; bytes memory returnData; (ok, returnData) = target.call(data); if (ok) { return returnData; } else { revert Orchestrator__ExecuteTxFailed(); } } // Enforces that the address is in fact a Module of the required type function _enforcePrivilegedModuleInterfaceCheck( address _contractAddr, bytes4 _privilegedInterfaceId ) internal view { bytes4 moduleInterfaceId = type(IModule_v1).interfaceId; if ( !ERC165Checker.supportsInterface(_contractAddr, moduleInterfaceId) || !ERC165Checker.supportsInterface( _contractAddr, _privilegedInterfaceId ) ) { revert Orchestrator__InvalidModuleType(_contractAddr); } } //-------------------------------------------------------------------------- // View Functions /// @inheritdoc IOrchestrator_v1 function version() external pure returns (string memory) { return "1"; } // IERC2771Context // @dev Because we want to expose the isTrustedForwarder function from the ERC2771Context Contract in the IOrchestrator_v1 // we have to override it here as the original openzeppelin version doesnt contain a interface that we could use to expose it. function isTrustedForwarder(address forwarder) public view virtual override(IModuleManagerBase_v1, ModuleManagerBase_v1) returns (bool) { return ModuleManagerBase_v1.isTrustedForwarder(forwarder); } function trustedForwarder() public view virtual override(IModuleManagerBase_v1, ModuleManagerBase_v1) returns (address) { return ModuleManagerBase_v1.trustedForwarder(); } }
/* eslint-disable react/prop-types */ import { useState } from "react"; const RecentSales = ({ data = [], itemsPerPage = 3 }) => { const [currentPage, setCurrentPage] = useState(1); // calculate index of items to show current page const indexOfLastItem = currentPage * itemsPerPage; const indexOfFirstItem = indexOfLastItem - itemsPerPage; const currentItems = data.slice(indexOfFirstItem, indexOfLastItem); const handlePageChange = (pageNumber) => { setCurrentPage(pageNumber); }; const totalPages = Math.ceil(data.length / itemsPerPage); return ( <div className="sold-products border rounded py-6 flex flex-col"> <h2 className="text-lg font-bold text-slate-800 mb-6 px-4"> Recently Sold </h2> <div className="overflow-x-auto"> <table className="table table-zebra"> <thead className="text-center"> <tr> <th>Name</th> <th>Selling Date</th> <th>Profit</th> </tr> </thead> <tbody> {currentItems?.map((sale, index) => ( <tr key={index + 1}> <td> {sale.productName} </td> <td> {sale.soldAt ? new Date(sale.soldAt).toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric", }) : "Date Missing"} </td> <td> ${parseInt(sale.sellingPrice - sale.productCost)} </td> </tr> ))} </tbody> </table> </div> <div className="flex-grow"></div> <div className="divider"></div> <div className="flex justify-center w-full"> <div className="join"> <button className="join-item btn" disabled={currentPage - 1 <= 0} onClick={() => { if (currentPage - 1 > 0) { setCurrentPage((curr) => curr - 1); } }} > « </button> {Array.from({ length: totalPages }).map((_, idx) => ( <input key={idx} className="join-item btn btn-square" type="radio" name="options" aria-label={idx + 1} checked={currentPage === idx + 1} readOnly onClick={() => handlePageChange(idx + 1)} /> ))} <button className="join-item btn" disabled={currentPage + 1 > totalPages} onClick={() => { if (currentPage + 1 <= totalPages) { setCurrentPage((curr) => curr + 1); } }} > » </button> </div> </div> </div> ); }; export default RecentSales;
import * as React from "react"; import { SiSpotify } from "react-icons/si"; import useSWR from "swr"; export interface SpotifyData { isPlaying: boolean; title: string; album: string; artist: string; albumImageUrl: string; songUrl: string; } export default function Spotify() { const { data } = useSWR<SpotifyData>("/api/spotify"); return data?.isPlaying ? ( <> <div className="flex-1"> <p className="text-sm font-medium">{data.title}</p> <p className="mt-1 text-xs text-gray-600 dark:text-gray-300"> {data.artist} </p> </div> <div className="absolute bottom-1.5 right-1.5"> <SiSpotify size={20} color="#1ED760" /> </div> </> ) : null; }
class ExchangesController < ApplicationController def index @exchanges = Exchange.all @exchanges_demands = Exchange.where(user_2_id: current_user.id) @exchanges_resquests = Exchange.where(user_1_id: current_user.id) end def create @exchange = Exchange.new(exchange_params) if @exchange.save flash[:notice] = "Demande d'échange envoyée" else flash[:alert] = @exchange.errors.full_messages.join(", ") end redirect_to timeslots_path end def update @exchange = Exchange.find(params[:id]) @status = params[:status] booking = Booking.find(@exchange.booking_2_id) if @exchange.update(status: params[:status]) if @status == "Accepté" flash[:notice] = "Échange accepté" booking.update(user_id: @exchange.user_1_id) elsif @status == "Refusé" flash[:notice] = "Échange refusé" end else flash[:alert] = @exchange.errors.full_messages.join(", ") redirect_to exchanges_path end end def destroy @exchange = Exchange.find(params[:id]) @exchange.destroy redirect_to exchanges_path end private def exchange_params params.permit(:user_1_id, :booking_2_id, :user_2_id, :status) end end
# 【Q089】为什么需要 webpack ::: tip Issue 欢迎在 Gtihub Issue 中回答此问题: [Issue 89](https://github.com/kangyana/daily-question/issues/89) ::: ::: tip Author 回答者: [kangyana](https://github.com/kangyana) ::: ## 1. 为什么需要 webpack ? 想要理解为什么要使用 `webpack`,我们先回顾下历史,在打包工具出现之前,我们是如何在 web 中使用 JavaScript 的。 在浏览器中运行 JavaScript 有两种方法: - 引用一些脚本来存放每个功能。此解决方案很难扩展,因为加载太多脚本会导致网络瓶颈。 - 使用一个包含所有项目代码的大型 .js 文件。但是这会导致作用域、文件大小、可读性和可维护性方面的问题。 ### 立即调用函数表达式(IIFE) - Immediately invoked function expressions `IIFE` 解决大型项目的作用域问题。 当脚本文件被封装在 `IIFE` 内部时,你可以安全地拼接或安全地组合所有文件,而不必担心作用域冲突。 `IIFE` 使用方式产生出 `Make`, `Gulp`, `Grunt`, `Broccoli` 或 `Brunch` 等工具。 这些工具称为任务执行器,它们将所有项目文件拼接在一起。 但是,修改一个文件意味着必须重新构建整个文件。 拼接可以做到很容易地跨文件重用脚本,但是却使构建结果的优化变得更加困难。 如何判断代码是否实际被使用? 即使你只用到 `lodash` 中的某个函数,也必须在构建结果中加入整个库,然后将它们压缩在一起。 如何 `treeshake` 代码依赖? 难以大规模地实现延迟加载代码块,这需要开发人员手动地进行大量工作。 ### 感谢 Node.js,JavaScript 模块诞生了 Node.js 是一个 JavaScript 运行时,可以在浏览器环境之外的计算机和服务器中使用。 `webpack` 运行在 Node.js 中。 当 Node.js 发布时,一个新的时代开始了,它带来了新的挑战。 既然不是在浏览器中运行 JavaScript,现在已经没有了可以添加到浏览器中的 html 文件和 script 标签。 那么 Node.js 应用程序要如何加载新的代码 `chunk` 呢? `CommonJS` 问世并引入了 `require` 机制,它允许你在当前文件中加载和使用某个模块。 导入需要的每个模块,这一开箱即用的功能,帮助我们解决了作用域问题。 ### npm + Node.js + modules - 大规模分发模块 JavaScript 已经成为一种语言、一个平台和一种快速开发和创建快速应用程序的方式,接管了整个 JavaScript 世界。 但 `CommonJS` 没有浏览器支持。 没有 [live binding(实时绑定)](https://medium.com/webpack/the-state-of-javascript-modules-4636d1774358)。 循环引用存在问题。 同步执行的模块解析加载器速度很慢。 虽然 `CommonJS` 是 Node.js 项目的绝佳解决方案,但浏览器不支持模块, 因而产生了 **RequireJS**, `Browserify` 和 `SystemJS` 等打包工具,允许我们编写能够在浏览器中运行的 `CommonJS` 模块。 ### ESM - ECMAScript 模块 来自 Web 项目的好消息是,模块正在成为 ECMAScript 标准的官方功能。 然而,浏览器支持不完整,版本迭代速度也不够快,目前还是推荐上面那些早期模块实现。 ### 依赖自动收集 传统的任务构建工具基于 Google 的 Closure 编译器都要求你手动在顶部声明所有的依赖。 然而像 `webpack` 一类的打包工具自动构建并基于你所引用或导出的内容推断出[依赖图谱](https://webpack.docschina.org/concepts/dependency-graph/)。 这个特性与其它的如[plugins](https://webpack.docschina.org/concepts/plugins/) and [loaders](https://webpack.docschina.org/concepts/loaders/)一道让开发者的体验更好。 ### 看起来都不是很好…… 是否可以有一种方式,不仅可以让我们编写模块,而且还支持任何模块格式(至少在我们到达 ESM 之前),并且可以同时处理资源和资产? **这就是 `webpack` 存在的原因。** 它是一个工具,可以打包你的 JavaScript 应用程序(支持 ESM 和 CommonJS),可以扩展为支持许多不同的静态资源,例如:`images`, `fonts` 和 `stylesheets`。 `webpack` 关心性能和加载时间;它始终在改进或添加新功能,例如:异步地加载 `chunk` 和预取,以便为你的项目和用户提供最佳体验。 ::: tip Author 回答者: [kangyana](https://github.com/kangyana) ::: ## 2. webpack `webpack` 是一个模块的 **打包器**。 它的主要目的是打包 JavaScript 文件以便在浏览器中使用,但它也能够转换、打包或包装几乎所有的资源或资产。 `webpack` 的主要功能: - 捆绑 `ES` 模块、`CommonJS` 和 `AMD` 模块(甚至合并)。 - 可以创建一个或多个模块文件,在运行时异步加载(以减少初始加载时间)。 - 依赖关系在编译过程中被解决,减少了运行时的大小。 - `Loaders` 可以在编译时预处理文件,例如 TypeScript 到 JavaScript,Handlebars 字符串到编译的函数,图像到 Base64 等。 - 高度模块化的插件系统可以做任何你的应用程序需要的其他事情。
/* ! tailwindcss v3.3.3 | MIT License | https://tailwindcss.com */ /* 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) */ *, ::before, ::after { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ border-color: #e5e7eb; /* 2 */ } ::before, ::after { --tw-content: ''; } /* 1. Use a consistent sensible line-height in all browsers. 2. Prevent adjustments of font size after orientation changes in iOS. 3. Use a more readable tab size. 4. Use the user's configured `sans` font-family by default. 5. Use the user's configured `sans` font-feature-settings by default. 6. Use the user's configured `sans` font-variation-settings by default. */ html { line-height: 1.5; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ -moz-tab-size: 4; /* 3 */ -o-tab-size: 4; tab-size: 4; /* 3 */ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */ font-feature-settings: normal; /* 5 */ font-variation-settings: normal; /* 6 */ } /* 1. Remove the margin in all browsers. 2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. */ body { margin: 0; /* 1 */ line-height: inherit; /* 2 */ } /* 1. Add the correct height in Firefox. 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) 3. Ensure horizontal rules are visible by default. */ hr { height: 0; /* 1 */ color: inherit; /* 2 */ border-top-width: 1px; /* 3 */ } /* Add the correct text decoration in Chrome, Edge, and Safari. */ abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } /* Remove the default font size and weight for headings. */ h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } /* Reset links to optimize for opt-in styling instead of opt-out. */ a { color: inherit; text-decoration: inherit; } /* Add the correct font weight in Edge and Safari. */ b, strong { font-weight: bolder; } /* 1. Use the user's configured `mono` font family by default. 2. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */ font-size: 1em; /* 2 */ } /* Add the correct font size in all browsers. */ small { font-size: 80%; } /* Prevent `sub` and `sup` elements from affecting the line height in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) 3. Remove gaps between table borders by default. */ table { text-indent: 0; /* 1 */ border-color: inherit; /* 2 */ border-collapse: collapse; /* 3 */ } /* 1. Change the font styles in all browsers. 2. Remove the margin in Firefox and Safari. 3. Remove default padding in all browsers. */ button, input, optgroup, select, textarea { font-family: inherit; /* 1 */ font-feature-settings: inherit; /* 1 */ font-variation-settings: inherit; /* 1 */ font-size: 100%; /* 1 */ font-weight: inherit; /* 1 */ line-height: inherit; /* 1 */ color: inherit; /* 1 */ margin: 0; /* 2 */ padding: 0; /* 3 */ } /* Remove the inheritance of text transform in Edge and Firefox. */ button, select { text-transform: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Remove default button styles. */ button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; /* 1 */ background-color: transparent; /* 2 */ background-image: none; /* 2 */ } /* Use the modern Firefox focus style for all focusable elements. */ :-moz-focusring { outline: auto; } /* Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) */ :-moz-ui-invalid { box-shadow: none; } /* Add the correct vertical alignment in Chrome and Firefox. */ progress { vertical-align: baseline; } /* Correct the cursor style of increment and decrement buttons in Safari. */ ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } /* 1. Correct the odd appearance in Chrome and Safari. 2. Correct the outline style in Safari. */ [type='search'] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /* Remove the inner padding in Chrome and Safari on macOS. */ ::-webkit-search-decoration { -webkit-appearance: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Add the correct display in Chrome and Safari. */ summary { display: list-item; } /* Removes the default spacing and border for appropriate elements. */ blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } fieldset { margin: 0; padding: 0; } legend { padding: 0; } ol, ul, menu { list-style: none; margin: 0; padding: 0; } /* Reset default styling for dialogs. */ dialog { padding: 0; } /* Prevent resizing textareas horizontally by default. */ textarea { resize: vertical; } /* 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) 2. Set the default placeholder color to the user's configured gray 400 color. */ input::-moz-placeholder, textarea::-moz-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input::placeholder, textarea::placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } /* Set the default cursor for buttons. */ button, [role="button"] { cursor: pointer; } /* Make sure disabled buttons don't get the pointer cursor. */ :disabled { cursor: default; } /* 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) This can trigger a poorly considered lint error in some tools but is included by design. */ img, svg, video, canvas, audio, iframe, embed, object { display: block; /* 1 */ vertical-align: middle; /* 2 */ } /* Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) */ img, video { max-width: 100%; height: auto; } /* Make elements with the HTML hidden attribute stay hidden by default */ [hidden] { display: none; } *, ::before, ::after { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } ::backdrop { --tw-border-spacing-x: 0; --tw-border-spacing-y: 0; --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-gradient-from-position: ; --tw-gradient-via-position: ; --tw-gradient-to-position: ; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border-width: 0; } .pointer-events-none { pointer-events: none; } .fixed { position: fixed; } .absolute { position: absolute; } .relative { position: relative; } .-inset-0 { inset: -0px; } .-inset-0\.5 { inset: -0.125rem; } .-inset-1 { inset: -0.25rem; } .-inset-1\.5 { inset: -0.375rem; } .inset-0 { inset: 0px; } .inset-y-0 { top: 0px; bottom: 0px; } .left-0 { left: 0px; } .right-0 { right: 0px; } .top-0 { top: 0px; } .z-10 { z-index: 10; } .-m-1 { margin: -0.25rem; } .m-1 { margin: 0.25rem; } .m-4 { margin: 1rem; } .m-\[10px\] { margin: 10px; } .m-0 { margin: 0px; } .m-3 { margin: 0.75rem; } .m-96 { margin: 24rem; } .m-40 { margin: 10rem; } .m-80 { margin: 20rem; } .m-6 { margin: 1.5rem; } .m-60 { margin: 15rem; } .m-10 { margin: 2.5rem; } .m-14 { margin: 3.5rem; } .m-56 { margin: 14rem; } .m-5 { margin: 1.25rem; } .m-52 { margin: 13rem; } .m-44 { margin: 11rem; } .mx-auto { margin-left: auto; margin-right: auto; } .mb-2 { margin-bottom: 0.5rem; } .mb-3 { margin-bottom: 0.75rem; } .ml-3 { margin-left: 0.75rem; } .mr-4 { margin-right: 1rem; } .mt-10 { margin-top: 2.5rem; } .mt-2 { margin-top: 0.5rem; } .mt-4 { margin-top: 1rem; } .mr-1 { margin-right: 0.25rem; } .mr-10 { margin-right: 2.5rem; } .ml-1 { margin-left: 0.25rem; } .ml-16 { margin-left: 4rem; } .mr-16 { margin-right: 4rem; } .mt-12 { margin-top: 3rem; } .mr-52 { margin-right: 13rem; } .ml-52 { margin-left: 13rem; } .ml-5 { margin-left: 1.25rem; } .ml-4 { margin-left: 1rem; } .ml-48 { margin-left: 12rem; } .mt-14 { margin-top: 3.5rem; } .mt-16 { margin-top: 4rem; } .ml-\[\] { margin-left: ; } .ml-\[50px\] { margin-left: 50px; } .mt-1 { margin-top: 0.25rem; } .mt-\[\] { margin-top: ; } .mt-\[56\] { margin-top: 56; } .mt-\[56px\] { margin-top: 56px; } .ml-\[190px\] { margin-left: 190px; } .ml-\[200px\] { margin-left: 200px; } .ml-\[199px\] { margin-left: 199px; } .mt-11 { margin-top: 2.75rem; } .mt-\[48px\] { margin-top: 48px; } .mt-\[49px\] { margin-top: 49px; } .mt-\[px\] { margin-top: px; } .mt-\[52px\] { margin-top: 52px; } .mt-\[47px\] { margin-top: 47px; } .mt-\[4px\] { margin-top: 4px; } .mt-\[47\.9px\] { margin-top: 47.9px; } .mt-\[47\.5px\] { margin-top: 47.5px; } .mt-52 { margin-top: 13rem; } .mt-36 { margin-top: 9rem; } .mr-5 { margin-right: 1.25rem; } .mr-14 { margin-right: 3.5rem; } .mr-12 { margin-right: 3rem; } .mt-20 { margin-top: 5rem; } .mt-24 { margin-top: 6rem; } .mt-28 { margin-top: 7rem; } .mt-\[9\] { margin-top: 9; } .mt-\[98px\] { margin-top: 98px; } .mt-\[102px\] { margin-top: 102px; } .mt-0 { margin-top: 0px; } .mt-48 { margin-top: 12rem; } .mb-24 { margin-bottom: 6rem; } .block { display: block; } .flex { display: flex; } .inline-flex { display: inline-flex; } .grid { display: grid; } .hidden { display: none; } .h-0 { height: 0px; } .h-1 { height: 0.25rem; } .h-14 { height: 3.5rem; } .h-16 { height: 4rem; } .h-6 { height: 1.5rem; } .h-8 { height: 2rem; } .h-auto { height: auto; } .h-full { height: 100%; } .h-10 { height: 2.5rem; } .h-\[\] { height: ; } .h-\[100vh\] { height: 100vh; } .h-\[1\] { height: 1; } .h-2 { height: 0.5rem; } .h-9 { height: 2.25rem; } .h-72 { height: 18rem; } .h-\[\[\]\] { height: []; } .min-h-screen { min-height: 100vh; } .w-44 { width: 11rem; } .w-48 { width: 12rem; } .w-6 { width: 1.5rem; } .w-8 { width: 2rem; } .w-auto { width: auto; } .w-full { width: 100%; } .w-4 { width: 1rem; } .w-3\/6 { width: 50%; } .w-\[\] { width: ; } .w-\[40\] { width: 40; } .w-\[40h\] { width: 40h; } .w-\[40hw\] { width: 40hw; } .w-\[40vh\] { width: 40vh; } .w-96 { width: 24rem; } .w-\[70\] { width: 70; } .w-\[70\%\] { width: 70%; } .w-\[30\%\] { width: 30%; } .w-2 { width: 0.5rem; } .w-1 { width: 0.25rem; } .w-\[10\%\] { width: 10%; } .w-3 { width: 0.75rem; } .w-\[30\] { width: 30; } .w-\[3\\10\%\] { width: 3\10%; } .w-20 { width: 5rem; } .w-72 { width: 18rem; } .w-\[80\%\] { width: 80%; } .w-\[60\%\] { width: 60%; } .max-w-6xl { max-width: 72rem; } .max-w-7xl { max-width: 80rem; } .max-w-sm { max-width: 24rem; } .max-w-lg { max-width: 32rem; } .flex-1 { flex: 1 1 0%; } .flex-shrink-0 { flex-shrink: 0; } .flex-grow { flex-grow: 1; } .origin-top-right { transform-origin: top right; } .transform { transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .cursor-pointer { cursor: pointer; } .flex-col { flex-direction: column; } .flex-wrap { flex-wrap: wrap; } .content-center { align-content: center; } .items-center { align-items: center; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .gap-6 { gap: 1.5rem; } .space-x-2 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(0.5rem * var(--tw-space-x-reverse)); margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse))); } .space-x-4 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(1rem * var(--tw-space-x-reverse)); margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse))); } .space-y-1 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.25rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.25rem * var(--tw-space-y-reverse)); } .overflow-hidden { overflow: hidden; } .rounded-2xl { border-radius: 1rem; } .rounded-full { border-radius: 9999px; } .rounded-md { border-radius: 0.375rem; } .rounded-\[100\%\] { border-radius: 100%; } .rounded-xl { border-radius: 0.75rem; } .rounded-3xl { border-radius: 1.5rem; } .rounded-\[24px\] { border-radius: 24px; } .rounded { border-radius: 0.25rem; } .rounded-\[\[\]\] { border-radius: []; } .rounded-s-full { border-start-start-radius: 9999px; border-end-start-radius: 9999px; } .rounded-s-3xl { border-start-start-radius: 1.5rem; border-end-start-radius: 1.5rem; } .rounded-e-3xl { border-start-end-radius: 1.5rem; border-end-end-radius: 1.5rem; } .rounded-t-3xl { border-top-left-radius: 1.5rem; border-top-right-radius: 1.5rem; } .rounded-r-3xl { border-top-right-radius: 1.5rem; border-bottom-right-radius: 1.5rem; } .rounded-b-3xl { border-bottom-right-radius: 1.5rem; border-bottom-left-radius: 1.5rem; } .rounded-l-3xl { border-top-left-radius: 1.5rem; border-bottom-left-radius: 1.5rem; } .rounded-b-none { border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; } .rounded-b { border-bottom-right-radius: 0.25rem; border-bottom-left-radius: 0.25rem; } .rounded-t { border-top-left-radius: 0.25rem; border-top-right-radius: 0.25rem; } .rounded-tl-3xl { border-top-left-radius: 1.5rem; } .rounded-tl-none { border-top-left-radius: 0px; } .rounded-tr { border-top-right-radius: 0.25rem; } .rounded-tr-none { border-top-right-radius: 0px; } .rounded-bl { border-bottom-left-radius: 0.25rem; } .rounded-bl-none { border-bottom-left-radius: 0px; } .rounded-bl-3xl { border-bottom-left-radius: 1.5rem; } .rounded-tr-3xl { border-top-right-radius: 1.5rem; } .rounded-br-3xl { border-bottom-right-radius: 1.5rem; } .border-2 { border-width: 2px; } .border { border-width: 1px; } .border-b-4 { border-bottom-width: 4px; } .border-b { border-bottom-width: 1px; } .border-solid { border-style: solid; } .border-white { --tw-border-opacity: 1; border-color: rgb(255 255 255 / var(--tw-border-opacity)); } .border-yellow-400 { --tw-border-opacity: 1; border-color: rgb(250 204 21 / var(--tw-border-opacity)); } .border-black { --tw-border-opacity: 1; border-color: rgb(0 0 0 / var(--tw-border-opacity)); } .border-red-500 { --tw-border-opacity: 1; border-color: rgb(239 68 68 / var(--tw-border-opacity)); } .bg-blue-500 { --tw-bg-opacity: 1; background-color: rgb(59 130 246 / var(--tw-bg-opacity)); } .bg-gray-800 { --tw-bg-opacity: 1; background-color: rgb(31 41 55 / var(--tw-bg-opacity)); } .bg-gray-900 { --tw-bg-opacity: 1; background-color: rgb(17 24 39 / var(--tw-bg-opacity)); } .bg-purple-600 { --tw-bg-opacity: 1; background-color: rgb(147 51 234 / var(--tw-bg-opacity)); } .bg-slate-950 { --tw-bg-opacity: 1; background-color: rgb(2 6 23 / var(--tw-bg-opacity)); } .bg-transparent { background-color: transparent; } .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .bg-red-900 { --tw-bg-opacity: 1; background-color: rgb(127 29 29 / var(--tw-bg-opacity)); } .bg-black { --tw-bg-opacity: 1; background-color: rgb(0 0 0 / var(--tw-bg-opacity)); } .bg-red-400 { --tw-bg-opacity: 1; background-color: rgb(248 113 113 / var(--tw-bg-opacity)); } .bg-red-800 { --tw-bg-opacity: 1; background-color: rgb(153 27 27 / var(--tw-bg-opacity)); } .bg-gray-400 { --tw-bg-opacity: 1; background-color: rgb(156 163 175 / var(--tw-bg-opacity)); } .bg-slate-400 { --tw-bg-opacity: 1; background-color: rgb(148 163 184 / var(--tw-bg-opacity)); } .bg-slate-500 { --tw-bg-opacity: 1; background-color: rgb(100 116 139 / var(--tw-bg-opacity)); } .bg-slate-700 { --tw-bg-opacity: 1; background-color: rgb(51 65 85 / var(--tw-bg-opacity)); } .bg-slate-800 { --tw-bg-opacity: 1; background-color: rgb(30 41 59 / var(--tw-bg-opacity)); } .bg-red-300 { --tw-bg-opacity: 1; background-color: rgb(252 165 165 / var(--tw-bg-opacity)); } .object-cover { -o-object-fit: cover; object-fit: cover; } .p-1 { padding: 0.25rem; } .p-10 { padding: 2.5rem; } .p-2 { padding: 0.5rem; } .p-4 { padding: 1rem; } .p-14 { padding: 3.5rem; } .p-20 { padding: 5rem; } .px-10 { padding-left: 2.5rem; padding-right: 2.5rem; } .px-14 { padding-left: 3.5rem; padding-right: 3.5rem; } .px-2 { padding-left: 0.5rem; padding-right: 0.5rem; } .px-3 { padding-left: 0.75rem; padding-right: 0.75rem; } .px-4 { padding-left: 1rem; padding-right: 1rem; } .py-1 { padding-top: 0.25rem; padding-bottom: 0.25rem; } .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; } .pb-2 { padding-bottom: 0.5rem; } .pb-3 { padding-bottom: 0.75rem; } .pb-\[56\.25\%\] { padding-bottom: 56.25%; } .pr-2 { padding-right: 0.5rem; } .pr-4 { padding-right: 1rem; } .pt-2 { padding-top: 0.5rem; } .pl-24 { padding-left: 6rem; } .pt-12 { padding-top: 3rem; } .pt-64 { padding-top: 16rem; } .pt-4 { padding-top: 1rem; } .pt-40 { padding-top: 10rem; } .pt-3 { padding-top: 0.75rem; } .pt-36 { padding-top: 9rem; } .text-center { text-align: center; } .font-\[Poppins\2c sans-serif\] { font-family: Poppins,sans-serif; } .font-serif { font-family: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; } .text-2xl { font-size: 1.5rem; line-height: 2rem; } .text-3xl { font-size: 1.875rem; line-height: 2.25rem; } .text-5xl { font-size: 3rem; line-height: 1; } .text-base { font-size: 1rem; line-height: 1.5rem; } .text-lg { font-size: 1.125rem; line-height: 1.75rem; } .text-sm { font-size: 0.875rem; line-height: 1.25rem; } .text-xs { font-size: 0.75rem; line-height: 1rem; } .text-xl { font-size: 1.25rem; line-height: 1.75rem; } .font-\[750\] { font-weight: 750; } .font-bold { font-weight: 700; } .font-medium { font-weight: 500; } .font-semibold { font-weight: 600; } .leading-tight { line-height: 1.25; } .text-gray-100 { --tw-text-opacity: 1; color: rgb(243 244 246 / var(--tw-text-opacity)); } .text-gray-200 { --tw-text-opacity: 1; color: rgb(229 231 235 / var(--tw-text-opacity)); } .text-gray-300 { --tw-text-opacity: 1; color: rgb(209 213 219 / var(--tw-text-opacity)); } .text-gray-400 { --tw-text-opacity: 1; color: rgb(156 163 175 / var(--tw-text-opacity)); } .text-gray-500 { --tw-text-opacity: 1; color: rgb(107 114 128 / var(--tw-text-opacity)); } .text-gray-700 { --tw-text-opacity: 1; color: rgb(55 65 81 / var(--tw-text-opacity)); } .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .text-slate-300 { --tw-text-opacity: 1; color: rgb(203 213 225 / var(--tw-text-opacity)); } .text-slate-200 { --tw-text-opacity: 1; color: rgb(226 232 240 / var(--tw-text-opacity)); } .text-slate-500 { --tw-text-opacity: 1; color: rgb(100 116 139 / var(--tw-text-opacity)); } .antialiased { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .shadow-lg { --tw-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); --tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color); box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow); } .ring-1 { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .ring-black { --tw-ring-opacity: 1; --tw-ring-color: rgb(0 0 0 / var(--tw-ring-opacity)); } .ring-opacity-5 { --tw-ring-opacity: 0.05; } .transition { transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, -webkit-backdrop-filter; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter; transition-property: color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .duration-150 { transition-duration: 150ms; } .duration-700 { transition-duration: 700ms; } .ease-in-out { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } .ease-out { transition-timing-function: cubic-bezier(0, 0, 0.2, 1); } .hover\:scale-105:hover { --tw-scale-x: 1.05; --tw-scale-y: 1.05; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .hover\:bg-blue-600:hover { --tw-bg-opacity: 1; background-color: rgb(37 99 235 / var(--tw-bg-opacity)); } .hover\:bg-gray-700:hover { --tw-bg-opacity: 1; background-color: rgb(55 65 81 / var(--tw-bg-opacity)); } .hover\:bg-purple-700:hover { --tw-bg-opacity: 1; background-color: rgb(126 34 206 / var(--tw-bg-opacity)); } .hover\:bg-white:hover { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .hover\:font-bold:hover { font-weight: 700; } .hover\:text-gray-100:hover { --tw-text-opacity: 1; color: rgb(243 244 246 / var(--tw-text-opacity)); } .hover\:text-slate-950:hover { --tw-text-opacity: 1; color: rgb(2 6 23 / var(--tw-text-opacity)); } .hover\:text-white:hover { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .focus\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; } .focus\:ring-2:focus { --tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color); --tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color); box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000); } .focus\:ring-inset:focus { --tw-ring-inset: inset; } .focus\:ring-white:focus { --tw-ring-opacity: 1; --tw-ring-color: rgb(255 255 255 / var(--tw-ring-opacity)); } .focus\:ring-offset-2:focus { --tw-ring-offset-width: 2px; } .focus\:ring-offset-gray-800:focus { --tw-ring-offset-color: #1f2937; } .group:hover .group-hover\:translate-x-0 { --tw-translate-x: 0px; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .group:hover .group-hover\:translate-y-0 { --tw-translate-y: 0px; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } @media (min-width: 640px) { .sm\:static { position: static; } .sm\:inset-auto { inset: auto; } .sm\:ml-6 { margin-left: 1.5rem; } .sm\:block { display: block; } .sm\:hidden { display: none; } .sm\:items-stretch { align-items: stretch; } .sm\:justify-start { justify-content: flex-start; } .sm\:px-10 { padding-left: 2.5rem; padding-right: 2.5rem; } .sm\:px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .sm\:pr-0 { padding-right: 0px; } } @media (min-width: 768px) { .md\:mt-3 { margin-top: 0.75rem; } .md\:mt-16 { margin-top: 4rem; } .md\:ml-\[199px\] { margin-left: 199px; } .md\:mt-11 { margin-top: 2.75rem; } .md\:ml-48 { margin-left: 12rem; } .md\:mt-52 { margin-top: 13rem; } .md\:block { display: block; } .md\:flex { display: flex; } .md\:hidden { display: none; } .md\:max-w-none { max-width: none; } .md\:-translate-y-2 { --tw-translate-y: -0.5rem; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .md\:translate-x-4 { --tw-translate-x: 1rem; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .md\:translate-y-2 { --tw-translate-y: 0.5rem; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .md\:grid-cols-2 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .md\:flex-row { flex-direction: row; } .md\:gap-8 { gap: 2rem; } .md\:px-10 { padding-left: 2.5rem; padding-right: 2.5rem; } .md\:px-7 { padding-left: 1.75rem; padding-right: 1.75rem; } .md\:pb-\[75\%\] { padding-bottom: 75%; } .md\:text-4xl { font-size: 2.25rem; line-height: 2.5rem; } .md\:text-xl { font-size: 1.25rem; line-height: 1.75rem; } } @media (min-width: 1024px) { .lg\:gap-12 { gap: 3rem; } .lg\:px-8 { padding-left: 2rem; padding-right: 2rem; } .lg\:pb-\[56\.25\%\] { padding-bottom: 56.25%; } .lg\:text-3xl { font-size: 1.875rem; line-height: 2.25rem; } } @media (min-width: 1280px) { .xl\:-translate-y-4 { --tw-translate-y: -1rem; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .xl\:translate-x-8 { --tw-translate-x: 2rem; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .xl\:translate-y-4 { --tw-translate-y: 1rem; transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y)); } .xl\:gap-16 { gap: 4rem; } } .timeline { list-style: none; padding: 0; margin: 0; } .timeline-item { margin-bottom: 1rem; } .timeline-icon { width: 6rem; height: 6rem; border-radius: 50%; background-color: var(--primary); color: white; text-align: center; font-size: 2rem; } .timeline-content { padding: 1rem; }
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct Node { int elem; struct Node* prev, * next; }Node; typedef struct List { int n; Node* H = NULL; Node* T = NULL; int isEmpty() { if (n == 0) return 1; else return 0; } int size() { return n; } int get(int r) { Node* p = H; for (int i = 0; i < r; i++) p = p->next; return p->elem; } void init() { H = (Node*)malloc(sizeof(Node)); T = (Node*)malloc(sizeof(Node)); H->next = T; T->prev = H; H->prev = NULL; T->next = NULL; n = 0; } void addNodeBefore(Node* p, int e) { Node* q = (Node*)malloc(sizeof(Node)); q->elem = e; q->prev = p->prev; q->next = p; (p->prev)->next = q; p->prev = q; } void addNodeAfter(Node* p, int e) { Node* q = (Node*)malloc(sizeof(Node)); q->elem = e; q->prev = p; q->next = p->next; (p->next)->prev = q; p->next = q; } void add(int r, int e) { Node* p = H; for (int i = 0; i < r; i++) { p = p->next; addNodeBefore(p, e); n++; } } void addLast(int e) { Node* p = T; addNodeBefore(p, e); n++; } void addFirst(int e) { Node* p = H; addNodeAfter(p, e); n++; } void addElem(int e) { addLast(e); } int removeNode(Node* p) { int e = p->elem; (p->prev)->next = p->next; (p->next)->prev = p->prev; free(p); p = NULL; return e; } int remove(int r) { Node* p = H; for (int i = 0; i < r; i++) p = p->next; int e = removeNode(p); n--; return e; } void removeLast() { remove(n); } void removeFirst() { remove(1); } void removeElem() { removeFirst(); } void visit(int e) { printf(" %d", e); } void trav() { Node* p = H->next; while (p != T) { visit(p->elem); p = p->next; } printf("\n"); } int member(int e) { if (n == 0) return 0; Node* p = H->next; while (1) { int a = p->elem; if (a < e) { if (p->next == NULL) return 0; else p = p->next; } else if (a > e) return 0; else return 1; } } }Set; Set uni(Set A, Set B) { Set X; X.init(); while (!A.isEmpty() && !B.isEmpty()) { int a = A.get(1); int b = B.get(1); if (a < b) { X.addLast(a); A.removeFirst(); } else if (a > b) { X.addLast(b); B.removeFirst(); } else { X.addLast(a); A.removeFirst(); B.removeFirst(); } } while (!A.isEmpty()) { int a = A.get(1); X.addLast(a); A.removeFirst(); } while (!B.isEmpty()) { int b = B.get(1); X.addLast(b); B.removeFirst(); } return X; } Set intsec(Set A, Set B) { Set X; X.init(); while (!A.isEmpty() && !B.isEmpty()) { int a = A.get(1); int b = B.get(1); if (a < b) A.removeFirst(); else if (a > b) B.removeFirst(); else { X.addLast(a); A.removeFirst(); B.removeFirst(); } } while (!A.isEmpty()) A.removeFirst(); while (!B.isEmpty()) B.removeFirst(); return X; } int main() { int n, e; Set A, a, B, b, C, c; A.init(); a.init(); B.init(); b.init(); scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &e); A.addElem(e); a.addElem(e); } scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &e); B.addElem(e); b.addElem(e); } C = uni(A, B); if (C.isEmpty() == 1) printf(" 0\n"); else C.trav(); c = intsec(a, b); if (c.isEmpty() == 1) printf(" 0\n"); else c.trav(); return 0; }
""" 2272. Substring With Largest Variance Hard The variance of a string is defined as the largest difference between the number of occurrences of any 2 characters present in the string. Note the two characters may or may not be the same. Given a string s consisting of lowercase English letters only, return the largest variance possible among all substrings of s. A substring is a contiguous sequence of characters within a string. Example 1: Input: s = "aababbb" Output: 3 Explanation: All possible variances along with their respective substrings are listed below: - Variance 0 for substrings "a", "aa", "ab", "abab", "aababb", "ba", "b", "bb", and "bbb". - Variance 1 for substrings "aab", "aba", "abb", "aabab", "ababb", "aababbb", and "bab". - Variance 2 for substrings "aaba", "ababbb", "abbb", and "babb". - Variance 3 for substring "babbb". Since the largest possible variance is 3, we return it. Example 2: Input: s = "abcde" Output: 0 Explanation: No letter occurs more than once in s, so the variance of every substring is 0. Constraints: 1 <= s.length <= 104 s consists of lowercase English letters. """ class Solution: def solve_one(self, a, b, s): var, max_var = 0, 0 has_b, first_b = False, False for c in s: if c == a: var += 1 elif c == b: has_b = True if first_b and var >= 0: # shift b, first was b and encountered another, 'baab' first_b = False elif (var - 1) < 0: # restart subarray, 'bbaaa' max var is 2, not 1 first_b = True var = -1 else: var -= 1 # var is always >=0 if has_b and var > max_var: max_var = var return max_var def largestVariance(self, s: str) -> int: # https://leetcode.com/problems/substring-with-largest-variance/discuss/2579146/%22Weird-Kadane%22-or-Intuition-%2B-Solution-Explained # kadane's algorithm application # time O(26*26*n) - two words a-z, kadane's on n length of string # space O(26) - freq counter max_variance = 0 unique_ch = set(s) print(unique_ch) for major_ch in unique_ch: for minor_ch in unique_ch: if major_ch == minor_ch: continue major_vs_minor_variance = self.solve_one(major_ch, minor_ch, s) max_variance = max(max_variance, major_vs_minor_variance) return max_variance
import './App.css'; import mapboxgl from 'mapbox-gl'; import 'mapbox-gl/dist/mapbox-gl.css'; import React, { useEffect, useState } from 'react'; function App() { const [mapStyle, setMapStyle] = useState('mapbox://styles/mapbox/dark-v10'); useEffect(() => { mapboxgl.accessToken = 'pk.eyJ1Ijoid2lkc29uIiwiYSI6ImNrbXZyZHlpdjA3dWYycHFzcTF6Z2txYTgifQ.dfzOBZeGLBKSD6lLW8uwPA'; const map = new mapboxgl.Map({ container: 'map', style: mapStyle, center: [15.8277, -13.1339], zoom: 4 }); // Define a function to fly to a new location const flyToAngola = () => { map.flyTo({ center: [17.8739, -11.2027], zoom: 5, }); }; // Call the flyToAngola function after the map loads map.on('load', flyToAngola); }, [mapStyle]); // Function to handle changing the map style const handleMapStyleChange = (style) => { setMapStyle(style); }; return ( <div> <div id="map" style={{ width: '100%', height: '90vh' }}></div> <div className="map-styles"> <button onClick={() => handleMapStyleChange('mapbox://styles/mapbox/dark-v10')}> Dark </button> <button onClick={() => handleMapStyleChange('mapbox://styles/mapbox/light-v10')}> Light </button> <button onClick={() => handleMapStyleChange('mapbox://styles/mapbox/satellite-streets-v11')}> Satellite </button> <button onClick={() => handleMapStyleChange('mapbox://styles/mapbox/satellite-streets-v11')}> Satellite streets </button> </div> </div> ); } export default App;
package co.com.certificacion.falabella.tasks; import net.serenitybdd.screenplay.Actor; import net.serenitybdd.screenplay.Task; import net.serenitybdd.screenplay.actions.Enter; import net.serenitybdd.screenplay.waits.WaitUntil; import org.openqa.selenium.Keys; import static co.com.certificacion.falabella.userinterfaces.Falabella.TXT_SEARCH_FALABELLA; import static co.com.certificacion.falabella.utils.Constantes.TIEMPO; import static net.serenitybdd.screenplay.Tasks.instrumented; import static net.serenitybdd.screenplay.matchers.WebElementStateMatchers.isVisible; public class ConsultarProducto implements Task { private String producto; public ConsultarProducto(String producto) { this.producto = producto; } @Override public <T extends Actor> void performAs(T actor) { actor.attemptsTo(WaitUntil.the(TXT_SEARCH_FALABELLA, isVisible()).forNoMoreThan(TIEMPO).seconds(), Enter.theValue(producto).into(TXT_SEARCH_FALABELLA) .thenHit(Keys.ENTER)); } public static ConsultarProducto enFalabella(String producto) { return instrumented(ConsultarProducto.class, producto); } }
import { Injectable } from '@angular/core'; import { Subject } from 'rxjs'; import { InvestmentService } from '../shared/investment.service'; import { Stock } from '../shared/stock.model'; @Injectable({ providedIn: 'root' }) export class StockService { stocksChanged = new Subject<Stock[]>(); private stocks: Stock[] = []; constructor(private investmentService: InvestmentService) { } loadStocks() { this.investmentService.getAvailableStocks() .subscribe( resData => { console.log('Available Stocks'); console.log(resData); this.setStocks(resData); }, errorMessage => { console.log(errorMessage); } ); } setStocks(stocks: Stock[]) { this.stocks = stocks; this.stocksChanged.next(this.stocks.slice()); } getStocks() { return this.stocks.slice(); } getStock(index: number) { return this.stocks[index]; } addStock(stock: Stock) { this.stocks.push(stock); this.stocksChanged.next(this.stocks.slice()); } updateStock(index: number, newStock: Stock) { this.stocks[index] = newStock; this.stocksChanged.next(this.stocks.slice()); } deleteStock(index: number) { this.stocks.splice(index, 1); this.stocksChanged.next(this.stocks.slice()); } }
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'login_page.dart'; class SignUpPage extends StatefulWidget { @override _RegistryPageState createState() => _RegistryPageState(); } class _RegistryPageState extends State<SignUpPage> { final formKey = GlobalKey<FormState>(); final TextEditingController tfEmail = TextEditingController(); final TextEditingController tfSifre = TextEditingController(); late String email, sifre; final firebaseAuth = FirebaseAuth.instance; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Üye Ol'), centerTitle: true, automaticallyImplyLeading: false, ), body: Center( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16.0), child: Form( key: formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon(Icons.person, size: 80), const SizedBox(height: 8), TextFormField( controller: tfEmail, decoration: const InputDecoration( labelText: "Email", hintText: "Email", border: OutlineInputBorder( borderSide: BorderSide( width: 1, ), ), ), validator: (value) { if (value!.isEmpty) { return "Email boş olamaz!"; } if (!RegExp( r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+") .hasMatch(value)) { return "Geçerli bir Email giriniz!"; } return null; }, onSaved: (value) { email = value!; }, ), const SizedBox(height: 8), TextFormField( controller: tfSifre, obscureText: true, decoration: const InputDecoration( labelText: "Şifre", hintText: "Şifre", border: OutlineInputBorder( borderSide: BorderSide( width: 1, ), ), ), validator: (value) { if (value!.isEmpty) { return "Şifre boş olamaz!"; } if (value.length < 6) { return "Şifre 6 karakterden az olamaz!"; } return null; }, onSaved: (value) { sifre = value!; }, ), const SizedBox(height: 8), ElevatedButton( onPressed: signIn, child: const Text("Üye Ol"), ), TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => LoginPage()), ); }, child: const Text( "Giriş yapmak için tıklayınız", style: TextStyle( color: Colors.grey, ), ), ), ], ), ), ), ), ), ); } void signIn() async { bool kontrol = formKey.currentState!.validate(); if (kontrol) { formKey.currentState!.save(); try { var userResult = await firebaseAuth.createUserWithEmailAndPassword( email: email, password: sifre); print(userResult.user!.uid); } catch (e) { print(e.toString()); } formKey.currentState!.reset(); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Üye olundu.'), ), ); Navigator.pop(context); } } }
<?php require_once "classes/DBAccess.php"; require_once "classes/Authentication.php"; require_once "classes/ShoppingCart.php"; $title = "Update"; $pageHeading = "Items"; session_start(); if(isset($_SESSION["theme"])) { $theme = $_SESSION["theme"]. ".css"; } else { $theme = "plain.css"; } Authentication::protect(); //get database settings include "settings/db.php"; //create database object $db = new DBAccess($dsn, $username, $password); //connect to database $pdo = $db->connect(); //get categories to populate drop down list $sql = "SELECT Category_Id, Category_name from category"; $stmt = $pdo->prepare($sql); //execute SQL query $categoryRows = $db->executeSQL($stmt); $message = ""; //update the category when the button is clicked if(isset($_POST["submit"])) { //check if checkbox for discontinued is ticked if (isset($_POST["Featured"]) && $_POST["Featured"] == "on") { $Featured = 1; } else { $Featured = 0; } //Last Edit point //check if a product name was supplied if(!empty($_POST["Item_name"]) && !empty($_POST["Item_id"])) { $sql = "update item set Item_name = :Item_Name, Price = :Price, Sale_price = :Sale_price, Description = :Description, Featured = :Featured, Category_Id = :Category_Id, PhotoPath = :PhotoPath WHERE Item_id = :Item_id"; $stmt = $pdo->prepare($sql); $stmt->bindValue(":Item_Name" , $_POST["Item_name"], PDO::PARAM_STR); $stmt->bindValue(":Price" , $_POST["Price"], PDO::PARAM_STR); $stmt->bindValue(":Sale_price" , $_POST["Sale_price"], PDO::PARAM_STR); $stmt->bindValue(":Description" , $_POST["Description"], PDO::PARAM_STR); $stmt->bindValue(":Featured" , $Featured, PDO::PARAM_INT); $stmt->bindValue(":Category_Id" , $_POST["Category_Id"], PDO::PARAM_STR); $stmt->bindValue(":PhotoPath" , $_POST["PhotoPath"], PDO::PARAM_STR); $stmt->bindValue(":Item_id" , $_POST["Item_id"], PDO::PARAM_STR); //execute SQL query $id = $db->executeNonQuery($stmt, false); $message = "The item was updated, id:" . " ". $id; } } //display the product to be updated //get the category id from the query string or from the posted data if the submit button was pressed if(isset($_GET["id"])) { $prodId = $_GET["id"]; } elseif (isset($_POST["Item_id"])) { $prodId = $_POST["Item_id"]; } else { $prodId = 0; } $sql = "SELECT * FROM item WHERE Item_id = :Item_id"; $stmt = $pdo->prepare($sql); $stmt->bindValue(":Item_id" , $prodId, PDO::PARAM_INT); $rows = $db->executeSQL($stmt); //select all items to display in a table $sql = "SELECT Item_id, Item_name, Price, Sale_price, Description, Featured, Category_Id, PhotoPath from item"; $stmt = $pdo->prepare($sql); $itemRows = $db->executeSQL($stmt); //start buffer ob_start(); //display categories include "templates/displayAllItems.html.php"; //display form include "templates/display-updateItem.html.php"; $output = ob_get_clean(); include "templates/layout.html.php"; ?>
<div class="card card-primary"> <div class="card-header"> <h3 class="card-title fw-bold fs-4">Create Doctor</h3> </div> <form method="POST" action="{{ route('doctors.store') }}" enctype="multipart/form-data"> @csrf <div class="card-body"> <div class="form-group"> <label for="exampleInputEmail1">Name</label> <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter Name" name="name"> @error('name') <span style="color: red">{{ $message }}</span> @enderror </div> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="email"> @error('email') <span style="color: red">{{ $message }}</span> @enderror </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" name="password"> @error('password') <span style="color: red">{{ $message }}</span> @enderror </div> <div class="form-group"> <label for="exampleInputEmail1">National ID </label> <input type="text" class="form-control" id="exampleInputEmail1" placeholder="Enter email" name="national_id"> @error('national_id') <span style="color: red">{{ $message }}</span> @enderror </div> <div class="form-group"> <label for="exampleInputFile">Avatar Image</label> <div class="input-group"> <div class="custom-file"> <input type="file" class="custom-file-input" id="exampleInputFile" name="avatar_image"> <label class="custom-file-label" for="exampleInputFile">Choose file</label> </div> <div class="input-group-append"> <span class="input-group-text">Upload</span> </div> </div> </div> </div> <!-- /.card-body --> <div class="card-footer"> <button type="submit" class="btn btn-primary fw-bold">Submit</button> </div> </form> </div>
const createError = require("http-errors"); const { v4: uuidv4 } = require("uuid"); const { newsletterValidationSchema, } = require("../../helpers/validation_schema"); const Newsletter = require("../../models/newsletter/newsletter.model"); const Email = require("./../../utils/email/email"); const newsletter = async (req, res, next) => { try { const result = await newsletterValidationSchema.validateAsync(req.body); const token = uuidv4(); const url = `${req.protocol}://${req.hostname}/`; const unsubscribeUrl = `${req.protocol}://${process.env.UNSUBSCRIBE_URL}/unsubscribe/${token}`; // Check if the email already exists const existingEmail = await Newsletter.findOne({ email: result.email, subscribeStatus: true, }); if (existingEmail) { throw createError.Conflict( `${result.name} you already subscribed to our newsletter.` ); } // Check if the email already exists and is unsubscribed const unsubscribedEmail = await Newsletter.findOne({ email: result.email, subscribeStatus: false, }); if (unsubscribedEmail) { const token2 = uuidv4(); unsubscribedEmail.name = result.name; unsubscribedEmail.subscribeStatus = true; unsubscribedEmail.token = token2; await unsubscribedEmail.save(); const newNewsletterToken = { name: result.name, email: result.email, }; const unsubscribeUrl2 = `${req.protocol}://${process.env.UNSUBSCRIBE_URL}/unsubscribe/${token2}`; await new Email( newNewsletterToken, url, unsubscribeUrl2 ).sendNewsletter(); return res.status(200).json({ message: `${result.name}, thanks for subscribing to our newsletter again!`, }); } // Create a new newsletter instance const newNewsletter = new Newsletter({ name: result.name, email: result.email, token: token, subscribeStatus: true, }); // Save the new newsletter await newNewsletter.save(); const newNewsletterToken = { name: result.name, email: result.email, }; await new Email(newNewsletterToken, url, unsubscribeUrl).sendNewsletter(); return res.status(200).json({ message: `${result.name}, thanks for subscribing to our newsletter!`, }); } catch (error) { console.error("Error creating newsletter:", error); if (error.isJoi === true) { return res.status(501).json({ message: error.message }); } next(error); } }; const unsubscribeNewletter = async (req, res, next) => { try { const token = req.params.token; // Check if the token exists in the URL if (!token) { return res.status(404).send({ message: "Token does not exist" }); } const subscriberToken = await Newsletter.findOne({ token: token }); if (!subscriberToken) { return res.status(404).json({ message: "Token not found" }); } subscriberToken.subscribeStatus = false; await subscriberToken.save(); return res.status(200).json({ message: "while we hate to see you leave, we say thanks for the time you have spent with us.", }); } catch (error) { console.error("Error unsubscribing:", error, req.params.token); return res .status(500) .json({ message: "An error occurred while unsubscribing" }); } }; module.exports = { newsletter, unsubscribeNewletter, };
/* * @Author: your name * @Date: 2021-03-03 20:22:17 * @LastEditTime: 2021-08-27 13:32:36 * @LastEditTime: 2021-06-21 18:18:05 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \WN-ATOM\src\components\NavBar\LeftBar.jsx */ import React, { useEffect, Fragment, useState } from "react"; import { observer, inject } from "mobx-react"; import { DownOutlined } from "@ant-design/icons"; import { Radio, Dropdown, Menu, Badge } from "antd"; import FlightTableColumnConfigModal from "components/FlightTableColumnConfigModal/FlightTableColumnConfigModal"; import ATOMConfigModal from "components/ATOMConfigModal/ATOMConfigModal"; import NTFMConfigModal from "components/NTFMConfigModal/NTFMConfigModal"; import ATOMConfigInit from "components/ATOMConfigModal/ATOMConfigInit"; import PositionModal from "components/Position/PositionModal"; import ProhibitedNav from "components/Prohibited/ProhibitedNav"; import ScoreModal from "components/Score/ScoreModal"; import ColumnDataInit from "./ColumnDataInit"; //参数配置页面 function ParameterConfiguration({ ATOMConfigFormData, NTFMConfigFormData, columnConfig, prohibitedData, systemPage, }) { const [positionModalVisible, setPositionModalVisible] = useState(false); const [scoreModalVisible, setScoreModalVisible] = useState(false); const menu = function () { return ( <Menu> <Menu.Item key="FlightTableColumnConfig" value="FlightTableColumnConfig" onClick={showFlightTableColumnConfigModal} > 表格列序配置 </Menu.Item> <Menu.Item key="ATOMConfig" value="ATOMConfig" onClick={showATOMConfigurationModal} > 各地CDM引接应用配置 </Menu.Item> <Menu.Item key="NTFMConfig" value="NTFMConfig" onClick={showNTFMConfigurationModal} > NTFM引接应用配置 </Menu.Item> {systemPage.userHasAuth(12523) && ( <Menu.Item key="Position" value="Position" onClick={showPositionModal} > 备降停机位 </Menu.Item> )} {systemPage.userHasAuth(12524) && ( <Menu.Item key="score" value="score" onClick={showScoreModal}> 贡献值与诚信值管理 </Menu.Item> )} {/* 禁航信息 */} {systemPage.userHasAuth(12525) && ( <Menu.Item key="Prohibited" value="Prohibited" onClick={showProhibitedModal} > <span> 禁航信息管理 {/* {prohibitedData.dataList.length > 0 && ( <Badge count={prohibitedData.dataList.length} style={{ backgroundColor: "rgb(61, 132, 36)" }} /> )} */} </span> </Menu.Item> )} </Menu> ); }; // 显示表格列序配置模态框 const showFlightTableColumnConfigModal = () => { columnConfig.toggleModalVisible(true); }; // 显示ATOM引接应用配置模态框 const showATOMConfigurationModal = () => { ATOMConfigFormData.toggleModalVisible(true); }; // 显示NTFM引接应用配置模态框 const showNTFMConfigurationModal = () => { NTFMConfigFormData.toggleModalVisible(true); }; // 显示禁航信息模态框 const showProhibitedModal = () => { prohibitedData.setProhibitedListModalVisible(true); }; // 显示备降停机位模态框 const showPositionModal = () => { setPositionModalVisible(true); }; // 显示贡献值与诚信值管理模态框 const showScoreModal = () => { setScoreModalVisible(true); }; return ( <Fragment> <Dropdown overlay={menu}> <Radio.Group buttonStyle="solid" value=""> <Radio.Button value="system"> 参数配置 <DownOutlined /> </Radio.Button> </Radio.Group> </Dropdown> {columnConfig.modalVisible && <FlightTableColumnConfigModal />} {/* 表格列配置数据初始化组件 */} <ColumnDataInit /> <ATOMConfigInit /> <ATOMConfigModal /> <NTFMConfigModal /> {systemPage.userHasAuth(12523) && <PositionModal visible={positionModalVisible} setPositionModalVisible={setPositionModalVisible} />} {/* 贡献值与诚信值管理 */} {systemPage.userHasAuth(12524) &&<ScoreModal visible={scoreModalVisible} setScoreModalVisible={setScoreModalVisible} />} {/* 禁航信息相关 */} {systemPage.userHasAuth(12525) && <ProhibitedNav />} </Fragment> ); } export default inject( "systemPage", "ATOMConfigFormData", "NTFMConfigFormData", "columnConfig", "prohibitedData" )(observer(ParameterConfiguration));
package org.example.program2; import javafx.scene.control.Alert; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; /** * The Target class represents a geographical target with a name, latitude, longitude, and moving speed. * It provides methods to calculate the distance from the target, the bearing to the target, and the time to reach the target. */ public class Target { final double RADIUS_EARTH = 6371.01; private String targetName; private double targetLatitude; private double targetLongitude; // Hard coding my latitude and longitude as Delta College private double myLatitude = 43.559; private double myLongitude = -83.986; private double movingSpeed; /** * No-argument constructor for the Target class. */ public Target() { } /** * Parameterized constructor for the Target class. * * @param targetName the name of the target * @param targetLatitude the latitude of the target * @param targetLongitude the longitude of the target * @param myLatitude the latitude of the current location * @param myLongitude the longitude of the current location * @param movingSpeed the speed at which the target is moving */ public Target(String targetName,double targetLatitude, double targetLongitude, double myLatitude, double myLongitude, double movingSpeed) { this.targetName = targetName; this.targetLatitude = targetLatitude; this.targetLongitude = targetLongitude; this.myLatitude = myLatitude; this.myLongitude = myLongitude; this.movingSpeed = movingSpeed; } // Getters and setters /** * Gets the name of the target. * * @return the name of the target */ public String getTargetName() { return targetName; } /** * Sets the name of the target. * * @param targetName the name of the target */ public void setTargetName(String targetName) { this.targetName = targetName; } /** * Gets the latitude of the target. * * @return the latitude of the target */ public double getTargetLatitude() { return targetLatitude; } /** * Sets the latitude of the target. * * @param targetLatitude the latitude of the target * @throws IllegalArgumentException if the latitude is not between -90.0 and 90.0 degrees */ public void setTargetLatitude(double targetLatitude) throws IllegalArgumentException { validateLatitude(targetLatitude); this.targetLatitude = targetLatitude; } /** * Validates the latitude of the target. * * @param latitude the latitude of the target * @throws IllegalArgumentException if the latitude is not between -90.0 and 90.0 degrees */ private void validateLatitude(double latitude) throws IllegalArgumentException { if (latitude < -90.0 || latitude > 90.0) { throw new IllegalArgumentException("Latitude must be between -90.0 and 90.0 degrees."); } } /** * Gets the longitude of the target. * * @return the longitude of the target */ public double getTargetLongitude() { return targetLongitude; } /** * Sets the longitude of the target. * * @param targetLongitude the longitude of the target * @throws IllegalArgumentException if the longitude is not between -180.0 and 180.0 degrees */ public void setTargetLongitude(double targetLongitude) throws IllegalArgumentException { validateLongitude(targetLongitude); this.targetLongitude = targetLongitude; } /** * Validates the longitude of the target. * * @param longitude the longitude of the target * @throws IllegalArgumentException if the longitude is not between -180.0 and 180.0 degrees */ private void validateLongitude(double longitude) throws IllegalArgumentException { if (longitude < -180.0 || longitude > 180.0) { throw new IllegalArgumentException("Longitude must be between -180.0 and 180.0 degrees."); } } /** * Gets the latitude of the current location. * * @return the latitude of the current location */ public double getMyLatitude() { return myLatitude; } /** * Sets the latitude of the current location. * * @param myLatitude the latitude of the current location */ public void setMyLatitude(double myLatitude) { this.myLatitude = myLatitude; } /** * Gets the longitude of the current location. * * @return the longitude of the current location */ public double getMyLongitude() { return myLongitude; } /** * Sets the longitude of the current location. * * @param myLongitude the longitude of the current location */ public void setMyLongitude(double myLongitude) { this.myLongitude = myLongitude; } /** * Gets the moving speed of the target. * * @return the moving speed of the target */ public double getMovingSpeed() { return movingSpeed; } /** * Sets the moving speed of the target. * * @param movingSpeed the moving speed of the target * @throws IllegalArgumentException if the moving speed is negative */ public void setMovingSpeed(double movingSpeed) throws IllegalArgumentException { validateMovingSpeed(movingSpeed); this.movingSpeed = movingSpeed; } /** * Validates the moving speed of the target. * * @param speed the moving speed of the target * @throws IllegalArgumentException if the moving speed is negative */ private void validateMovingSpeed(double speed) throws IllegalArgumentException { if (speed < 0) { throw new IllegalArgumentException("Speed cannot be negative."); } } /** * Calculates the distance from the current location to the target. * * @return the distance from the current location to the target */ public double distanceFrom() { // Convert coordinates to radians double lat1 = Math.toRadians(targetLatitude); double lon1 = Math.toRadians(targetLongitude); double lat2 = Math.toRadians(myLatitude); double lon2 = Math.toRadians(myLongitude); return RADIUS_EARTH * Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)); } /** * Calculates the bearing from the current location to the target in degrees. * * @return the bearing from the current location to the target in degrees */ public double bearingToDegrees() { double latitude1 = Math.toRadians(myLatitude); double longitude1 = Math.toRadians(myLongitude); double latitude2 = Math.toRadians(targetLatitude); double longitude2 = Math.toRadians(targetLongitude); double longDiff = longitude2 - longitude1; double y = Math.sin(longDiff) * Math.cos(latitude2); double x = Math.cos(latitude1) * Math.sin(latitude2) - Math.sin(latitude1) * Math.cos(latitude2) * Math.cos(longDiff); double bearing = Math.atan2(y, x); return (Math.toDegrees(bearing) + 360) % 360; } /** * Converts the bearing from the current location to the target to an ordinal direction. * * @return the bearing from the current location to the target as an ordinal direction */ public String bearingToOrdinal() { double bearing = bearingToDegrees(); String[] compassPoints = {"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"}; // Convert bearing to index of compassPoints array int index = (int) ((bearing / 22.5) + 0.5) % 16; if (index < 0) { index += 16; } return compassPoints[index]; } /** * Calculates the time to reach the target from the current location. * * @return the time to reach the target from the current location * @throws IllegalArgumentException if the moving speed is zero */ public double timeToTarget() { double distance = distanceFrom(); double speed = getMovingSpeed(); if (speed == 0) { throw new IllegalArgumentException("Speed cannot be zero."); } return distance / speed; } /** * Validates the data of the target. * * @return true if the data of the target is valid, false otherwise */ public boolean dataValid() { if (getTargetName() == null || getTargetName().trim().isEmpty()) { return false; } if (getTargetLatitude() < -90.0 || getTargetLatitude() > 90.0) { return false; } if (getTargetLongitude() < -180.0 || getTargetLongitude() > 180.0) { return false; } if (getMovingSpeed() < 0) { return false; } return true; } /** * Gets the current date and time. * * @return the current date and time as a string */ public String getDateTime() { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return now.format(formatter); } /** * Displays the data of the target in an alert. * If the data is invalid, an error alert is shown with a message to enter valid data. * If the data is valid, an information alert is shown with the target's name, distance from the current location, bearing to the target in degrees and as an ordinal direction, current date and time, and time to reach the target. */ public void showTargetData() { if (!dataValid()) { Alert errorAlert = new Alert(Alert.AlertType.ERROR); errorAlert.setTitle("Error"); errorAlert.setHeaderText("Invalid Data"); errorAlert.setContentText("Please enter valid data."); errorAlert.showAndWait(); return; } Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Navigation Report"); alert.setHeaderText(null); alert.setContentText(toString()); alert.showAndWait(); } /** * Returns a string representation of the target. * The string includes the target's name, distance from the current location, bearing to the target in degrees and as an ordinal direction, current date and time, and time to reach the target. * * @return a string representation of the target */ @Override public String toString() { StringBuilder targetAlert = new StringBuilder(); targetAlert.append("Target: ").append(targetName).append("\n"); targetAlert.append("Distance: ").append(String.format("%.2f", distanceFrom())).append(" km").append("\n"); targetAlert.append("Bearing: ").append(String.format("%.0f", bearingToDegrees())).append(" degrees (").append(bearingToOrdinal()).append(")").append("\n"); targetAlert.append("Currently: ").append(getDateTime()).append("\n"); targetAlert.append("Time to target: ").append(String.format("%.2f", timeToTarget())).append(" hours"); return targetAlert.toString(); } }
import { Component } from '@angular/core'; import { MenuItem } from './menu-item'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Menu'; Menu: MenuItem[] = [ { name: "Cheese Pizza", category: "Pizza", price: 10 }, { name: "BBQ Wings", category: "Wings", price: 8 }, { name: "Meat Pizza", category: "Pizza", price: 12 }, { name: "Lemon Pepper Wings", category: "Wings", price: 8 }, { name: "Breadsticks", category: "Sides", price: 6 }, { name: "Garlic Knots", category: "Sides", price: 7 } ]; getByCategory(cat:string):MenuItem[]{ let Result: MenuItem[] = []; this.Menu.forEach((i:MenuItem) => { if(i.category == cat){ Result.push(i); } }) return Result; } }
/* James Huynh Ms. Krasteva ICS4U0 Evaluation Exercise 1 Feb 9, 2022 This program creates 3 instances of the classes Animal, Car, House, and Student, and runs all the methods in them. */ public class Main{ public static void main(String[] args){ Animal hippo = new Animal("Ursa", 1000.0); Animal cat = new Animal("Oscar", 10.0); Animal dog = new Animal("Shoob",25.0); cat.feed("meat"); cat.sleep(); hippo.feed("vegetables"); hippo.sleep(); dog.feed("meat"); dog.sleep(); House small = new House(123, "Cat Street", "Toronto", "Ontario", "A1A1A1", 1400.0, false, 1); House mansion = new House(444, "Luxury Avenue", "Toronto", "Ontario", "B2B2B2", 9999999.0, true, 7); House basic = new House(111, "House Lane", "Toronto", "Ontario", "C3C3C3", 2400.0, true, 2); small.displayAddress(); mansion.displayAddress(); basic.displayAddress(); Car smal = new Car("Toyota", "Corrola", 0.0, 240.0); Car big = new Car("Tesla","CyberTruck",523.0,10000.0); Car delor = new Car("DeLorean", "DMC", 10.0, 1000.0); smal.drive(100.0); big.drive(1000.0); delor.drive(10.0); smal.gasUp(); big.gasUp(); delor.gasUp(); Student jim = new Student("Jim"); Student cas = new Student("Cassandra"); Student jam = new Student("James"); cas.setMarks(70,95); jim.setMarks(80,90); jam.setMarks(100,100); cas.calcAverage(); jim.calcAverage(); jam.calcAverage(); System.out.println(cas.message()); System.out.println(jim.message()); System.out.println(jam.message()); } }
/* AULA 130 - AMPLITUDE DE UM DATASET */ SELECT qtd, COUNT(*) AS "Moda" FROM maquinas GROUP BY qtd ORDER BY "Moda" DESC; SELECT maquina, MAX(qtd) AS "Qtd Máxima", MIN(qtd) AS "Qtd Mínima", MAX(qtd)-MIN(qtd) AS "Amplitude" FROM maquinas GROUP BY maquina ORDER BY 1 ASC; -- Incluindo a Média da qtd produzida por máquina SELECT maquina, MAX(qtd) AS "Qtd Máxima", MIN(qtd) AS "Qtd Mínima", MAX(qtd)-MIN(qtd) AS "Amplitude", ROUND(AVG(qtd),2) AS "Média" FROM maquinas GROUP BY maquina ORDER BY 1 ASC; /* DESVIO PADRÃO e VARIÂNCIA */ SELECT MAQUINA AS "Máquina", ROUND(AVG(qtd),2) AS "Média", ROUND(STDDEV_POP(qtd),2) AS "Desv. Padrão", ROUND(VAR_POP(qtd),2) AS "Variância" FROM MAQUINAS GROUP BY MAQUINA ORDER BY 1 ASC; /* Em suma, o desvio padrão é a "distância" do valor -- em relação a média. Ele nos ajuda a compreender o -- grau de dispersão ou variabilidade dos valores. -- OBS: A variância e o desvio padrão se assemelhão, -- são métricas que nos fornece insights sobre a -- variabilidade e dispersão dos dados. */
fun main() { val car = Car("Subaru","F200","blue",7) car.carry(12) car.identity() var result =car.calculateParkingFees(7) println(result) var bus = Bus("Scania","V8","yellow",30) var new = bus.maxTripFare(170.00) println(new) var all = bus.calculateParkingFees(6) println(all) } open class Car( var make:String, var model:String,var color:String,var capacity:Int){ fun carry(people:Int){ var x = (people - capacity) if (people<=capacity){ println("carrying $people passengers") } else if (people>capacity){ println("over capacity by $x people") } } fun identity(){ println("I am a $color $make $model") } open fun calculateParkingFees(hours:Int): Int{ var Calc = hours * 20 return Calc } } class Bus( make:String, model:String, color:String,capacity:Int):Car(make,model,color,capacity){ fun maxTripFare(fare: Double):Double{ var calculate = capacity * fare return calculate } override fun calculateParkingFees(hours: Int): Int { var fees = hours * capacity return fees } } //override fun calculatepackingFees(hours: Int): Int { // var w= hours*capacity // return w
const express = require("express"); const bodyParser = require("body-parser"); const multer = require("multer"); const cors = require("cors"); const db = require("./db"); const appRouter = require("./router/app-router"); const app = express(); const apiPort = 3100; var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, "./uploads"); }, filename: function (req, file, cb) { cb(null, req.body.filename + ".mp4"); }, }); var upload = multer({ storage: storage }).single("file"); app.use(bodyParser.urlencoded({ extended: true })); app.use(cors()); app.use(bodyParser.json()); app.use("/uploads", express.static("uploads")); db.on("error", console.error.bind(console, "MongoDB connection error:")); app.get("/", (req, res) => { res.send("Server is running!"); }); app.post("/upload", function (req, res) { upload(req, res, function (err) { if (err instanceof multer.MulterError) { return res.status(500).json(err); } else if (err) { return res.status(500).json(err); } return res.status(200).send(req.file); }); }); app.use("/api", appRouter); app.listen(apiPort, () => console.log(`Server running on port ${apiPort}`));
// // ClasesModelo.swift // PrepaNet // // Created by Emilio Y Martinez on 13/10/22. // import Foundation import Alamofire struct curso: Decodable{ // let id : Int // let nombre: String // let orden: Int // let description : String // let duracion : Int // let approved: Bool // let status : String let approved: Bool let description: String let duracion:Int let estatus:String let id : Int let nombre:String let orden: Int } struct ModelClases{ let id : Int let nombre: String let orden: Int let description : String let duracion : Int let approved: Bool let status : String } class ClasesModelo: ObservableObject{ @Published var result = [ModelClases]() @Published var cursosInactivos=[ModelClases]() func loadData(url:String,token:String)async ->([ModelClases],[ModelClases],[ModelClases])? { let (modelos,modelosNo,modeloPasado) = await loaddata(Url: url,token: token) ?? ([ModelClases(id: 0, nombre: "''", orden: 0, description: "", duracion: 0, approved: true, status: "")],[ModelClases(id: 0, nombre: "''", orden: 0, description: "", duracion: 0, approved: true, status: "")],[ModelClases(id: 0, nombre: "''", orden: 0, description: "", duracion: 0, approved: true, status: "")]) return (modelos,modelosNo,modeloPasado) } func loaddata(Url:String,token:String)async -> ([ModelClases],[ModelClases],[ModelClases])?{ let headers = ["x-auth-token":token] let url = URL(string: Url)! var request = URLRequest(url: url) request.httpMethod = "GET" for(key,value) in headers{ request.setValue(value, forHTTPHeaderField: key) } do{ // let session = URLSession(configuration: .default) var temp = [ModelClases]() var temp2 = [ModelClases]() var temp3 = [ModelClases]() let (data,_) = try await URLSession.shared.data(for: request) let respuestas = try JSONDecoder().decode([curso].self, from: data ) // print(respuestas) for respuesta in respuestas{ let id = respuesta.id let nombre = respuesta.nombre let orden = respuesta.orden let description = respuesta.description let approved = respuesta.approved let status = respuesta.estatus let duracion = respuesta.duracion print(status) if status == "Sin Cursar"{ temp2.append(ModelClases(id: id, nombre: nombre, orden: orden, description: description,duracion: duracion, approved: approved, status: status)) }else if status == "Cursando"{ temp.append(ModelClases(id: id, nombre: nombre, orden: orden, description: description,duracion: duracion, approved: approved, status: status)) }else{ temp3.append(ModelClases(id: id, nombre: nombre, orden: orden, description: description,duracion: duracion, approved: approved, status: status)) } } return (temp,temp2,temp3) as! ([ModelClases], [ModelClases],[ModelClases]) }catch{ print("error") return nil } // let (data,_) = session.dataTask(with: request){(data,response,error) in // if error != nil { // print("existio un error\(error?.localizedDescription)") // } // if let safeData = data{ // if let cursos = await self.parsearDatos_Json(cursosData: safeData){ // print(cursos) // DispatchQueue.main.async { // self.result = cursos // self.cursosInactivos = self.getCursosInactivos(cursoM: cursos) // // } // } // } // return data // // } // return } // func loadData(Url: String){ // let headers : HTTPHeaders = ["x-auth-token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOjEsImlhdCI6MTY2ODcxNjkxNH0.U7GiSmP6TKwoWfRU5SvJaPDcsDOvjl3yluZfOkdVOXs"] // DispatchQueue.main.async { // // // AF.request(Url,method: .get,parameters: [:],encoding: URLEncoding.queryString,headers: headers).validate().responseJSON {response ->Void in // print(response.value) // do{ // let json = try JSONDecoder().decode([curso].self, from: response.data!) // // }catch let erro{ // print(erro) // } // // // if let safeData = response.data{ // // if let curso = self.parsearDatos_Json(cursosData:safeData){ // // self.result = curso // // return // // // // } // // } // // } // } // } // func getCursosInactivos(temp:[ModelClases])async-> [ModelClases]?{ // var t=[ModelClases]() // for curso in temp { // if curso.status == "Sin Cursar"{ // t.append(ModelClases(id: curso.id, nombre: curso.nombre, orden: curso.orden, description: curso.description, duracion: curso.duracion, approved: curso.approved, status: curso.status)) // } // } // // return t // } func parsearDatos_Json(cursosData:Data) -> [ModelClases]?{ let json = JSONDecoder() var temp = [ModelClases]() print(cursosData) do { let respuestas = try json.decode([curso].self, from: cursosData ) print(respuestas) for respuesta in respuestas{ let id = respuesta.id let nombre = respuesta.nombre let orden = respuesta.orden let description = respuesta.description let approved = respuesta.approved let status = respuesta.estatus let duracion = respuesta.duracion temp.append(ModelClases(id: id, nombre: nombre, orden: orden, description: description,duracion: duracion, approved: approved, status: status)) } return temp }catch{ return nil } } }
import 'package:admin/controllers/nav_controller.dart'; import 'package:admin/core/helpers/responsive.dart'; import 'package:flutter/material.dart'; import 'package:admin/models/stats_info_model.dart'; import 'package:get/get.dart'; import '../../../core/config/constants.dart'; import 'feature_info_card.dart'; class StatsCardGrid extends StatelessWidget { const StatsCardGrid({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final Size size = MediaQuery.of(context).size; return Column( children: [ const SizedBox(height: defaultPadding), Responsive( mobile: InfoCardGridView( crossAxisCount: size.width < 650 ? 2 : 4, childAspectRatio: size.width < 650 ? 1.3 : 1, ), tablet: const InfoCardGridView(), desktop: InfoCardGridView( childAspectRatio: size.width < 1400 ? 1.1 : 1.5, ), ), ], ); } } class InfoCardGridView extends StatelessWidget { const InfoCardGridView({ Key? key, this.crossAxisCount = 4, this.childAspectRatio = 1, }) : super(key: key); final int crossAxisCount; final double childAspectRatio; @override Widget build(BuildContext context) { return GridView.builder( physics: const NeverScrollableScrollPhysics(), shrinkWrap: true, itemCount: dashboardPanelsList.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: crossAxisCount, crossAxisSpacing: defaultPadding, mainAxisSpacing: defaultPadding, childAspectRatio: childAspectRatio, ), itemBuilder: (context, index) => InkWell( onTap: () { Get.find<NavigationController>() .updatePanelView(dashboardPanelsList[index].panelView); }, child: FeatureInfoCard( info: dashboardPanelsList[index], ), ), ); } }
<template> <ModalDeleteCount ref="modale" /> <section class="border-bottom pb-3 mb-3 gradient-custom"> <div class="container py-5 h-10"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-8"> <div class="card bg-dark text-white" style="border-radius: 1rem;" > <div class="card-body p-4 text-center"> <div class="flex-shrink-0"> <img :src="editConsumer.profile_picture_path_consumer" alt="Generic placeholder image" class="img-fluid" style="width: 180px; border-radius: 10px;" > </div> <h3>{{ consumer.first_name }}</h3> <h3>{{ consumer.last_name }}</h3> </div> <h4>Changer mes informations</h4> <div class="card-body p-4 text-center"> <form> <div class="mb-3"> <label for="email" class="form-label" >Nouvel Email</label> <input id="email" v-model="editConsumer.email" type="email" class="form-control" > </div> <div class="mb-3"> <label for="password" class="form-label" >Nouveau mot de passe</label> <input id="password" v-model="editConsumer.password" type="password" class="form-control" > </div> <div class="mb-3"> <label for="confirmPassword" class="form-label" >Confirmer le nouveau mot de passe</label> <input id="confirmPassword" v-model="editConsumer.passwordConfirm" type="password" class="form-control" > </div> <div class="mb-3"> <label for="file" class="form-label" >Selectioner une nouvelle photo de profil</label> <input id="formFile" class="form-control" type="file" @change="handleFile" > </div> <button type="submit" class="btn btn-primary" @click="editProfile" > Modifier mes informations </button> </form> </div> <p class="text-success m-3"> {{ successMessage }} </p> <p class="text-danger m-3"> {{ errorMessage }} </p> <p class="text-warning m-3"> {{ waitingMessage }} </p> <!-- Bouton supprimer --> <div class="card-body p-4 text-center"> <button type="button" class="btn btn-danger" @click="deleteProfile" > Supprimer mon compte </button> </div> </div> </div> </div> <!--Message de contact --> <div class="card-body p-4 text-center text-white"> <p> Pour signaler tout problèmes de comportement, images inappropriées ou bug technique, merci de nous contacter à : [email protected] </p> </div> </div> </section> </template> <script> import ModalDeleteCount from '../components/ModalDeleteCount.vue'; export default { name: 'CompteParticulier', components:{ ModalDeleteCount}, data() { return { mail: null, picture: false, editConsumer: { }, consumer: {}, successMessage: null, errorMessage: null, waitingMessage: null, } }, mounted() { this.axios .get(`${process.env.VUE_APP_ENV_ENDPOINT_BACK}api/consumer/${this.$store.state.user.id}`) .then((response) => { this.consumer = response.data; this.editConsumer.email = response.data.email; // this.editConsumer.password=response.data.password; // this.editConsumer.passwordConfirm=this.editPro.password; this.editConsumer.profile_picture_path_consumer = response.data.profile_picture_path_consumer; this.editConsumer.email = response.data.email; this.mail = response.data.email; }) .catch((err) => { console.log(err); return }) document.querySelector('.ok-delete').addEventListener("click",()=>{ this.axios .delete(`${process.env.VUE_APP_ENV_ENDPOINT_BACK}api/consumer/${this.$store.state.user.id}`, ) .then((response) => { console.log(response.data); this.errorMessage = null; this.waitingMessage=null; this.successMessage = "Votre compte a bien été supprimé, vous allez être redirigé vers la page d'accueil"; setTimeout(() => { this.$store.dispatch('logout'); this.$router.push('/'); }, 2000); }) .catch((err) => { console.log(err); this.successMessage=null; this.waitingMessage=null; this.errorMessage = err.response.data.message; }) }) }, methods: { handleFile: function (e) { this.$store.dispatch('createRequestObjForCloudinary', e); this.picture = true; this.errorMessage=null; }, async editProfile(e) { e.preventDefault(); this.successMessage=null; this.waitingMessage = null; this.errorMessage=null; if (this.editConsumer.password === '') delete this.editConsumer.password; if (this.editConsumer.passwordConfirm === '') delete this.editConsumer.passwordConfirm; if (this.editConsumer.password !== undefined && this.editConsumer.passwordConfirm === undefined) { this.errorMessage = " Vous devez confirmer votre mot de passe" } else { this.waitingMessage="Veuillez patientez SVP ..."; if (this.picture) { let img; try { img = await this.$store.dispatch('handleUploadToCloudinary') await this.$store.dispatch('transformImg',img); this.editConsumer.profile_picture_path_consumer = this.$store.state.url; } catch (error) { console.log(error) } } // si le mail n'a pas été modifié il faut supprimer la donnée car sinon on aura une erreur d'utilisateur déjà existant côté back if (this.editConsumer.email === this.mail) delete this.editConsumer.email; else this.mail=this.editConsumer.email; this.axios .patch(`${process.env.VUE_APP_ENV_ENDPOINT_BACK}api/consumer/${this.$store.state.user.id}`, this.editConsumer) .then((response) => { console.log(response.data); this.errorMessage = null; this.waitingMessage = null; this.successMessage = "Vos informations ont bien été modifiées."; if(this.picture) this.successMessage+="Mise à jour de votre page..."; this.picture = false; this.editConsumer.email = this.mail; setTimeout(() => { this.successMessage = null; }, 2000); this.editConsumer.email = this.mail; }) .catch((err) => { console.log(err); this.editConsumer.email = this.mail; this.successMessage=null; this.waitingMessage = null; this.errorMessage = err.response.data.message; return }) } }, async deleteProfile(e) { e.preventDefault(); this.$refs.modale.toggleModal(); }, } } </script>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <meta name="categories" content="docking "> <meta name="profile" content="!Elements"> <meta name="product" content="Glide"> <title>Glide Overview</title> <link rel="stylesheet" type="text/css" href="../support/help.css"> </head> <script type="text/javascript"> function setTitle() { top.document.title = document.title + " - " + parent.parent.WINDOW_TITLE; } </script> <body onload="setTitle();"> <table border=0 cellspacing=0 bgcolor=#dcdcdc width=100%> <tr><td> <p><img src="../support/schrodinger_logo.gif" border=0 alt="" align="left" vspace=5 hspace=5 /></p> </td></tr> <tr><td> <h1 class=title><span class="glide">Glide Overview</span></h1> </td></tr> </table> <ul> <li><a href="#summary">Summary</a></li> <li><a href="#using">Using <span class="GUI">Glide</span></a></li> <li><a href="#links">Related Topics</a></li> </ul> <a name="summary"></a> <h2>Summary</h2> <br /> <p>Glide (Grid-based LIgand Docking with Energetics) searches for favorable interactions between one or more typically small ligand molecules and a typically larger receptor molecule, usually a protein. Each ligand must be a single molecule, while the receptor may include more than one molecule, e.g., a protein and a cofactor. Glide can be run in rigid or flexible docking modes; the latter automatically generates conformations for each input ligand. The combination of a ligand conformation (for rigid docking, the input conformation; for flexible docking, a generated conformation) with its position and orientation is referred to as a <i>ligand pose</i>.</p> <p>The ligand poses that Glide generates pass through a series of hierarchical filters that evaluate the ligand's interaction with the receptor. The initial filters test the spatial fit of the ligand to the defined active site, and examine the complementarity of ligand-receptor interactions using a grid-based method patterned after the empirical ChemScore function (Eldridge et al., <i>J.Comput. Aided Mol. Des.</i> <b>1997</b>, <i>11</i>, 425-445).</p> <p>Poses that pass these initial screens enter the final stage of the algorithm, which involves evaluation and minimization of a grid approximation to the OPLS-AA nonbonded ligand-receptor interaction energy.</p> <p>Final scoring, which by default uses Schr&ouml;dinger's proprietary GlideScore multi-ligand scoring function, is then carried out on the energy-minimized poses. Finally, if GlideScore was selected as the scoring function, a composite <i>Emodel</i> score is used to rank the ligand poses and to select which pose (or poses, if so specified) for a given ligand will be reported to the user. Emodel combines GlideScore, the nonbonded interaction energy, and, for flexible docking, the excess internal energy of the generated ligand conformation.</p> <a name="using"></a> <h2>Using Glide</h2> <p>The Glide task most frequently performed is ligand docking. The grid files produced by a single receptor grid generation task can be used for any number of jobs docking ligands to that receptor. Before generating receptor grids, it is strongly recommended that you prepare the protein. Therefore, the first steps of a typical project beginning with an unprepared protein-ligand complex structure (e.g., from PDB) might proceed using the Glide panels as follows:</p> <ol> <li><p>Prepare the protein using the <a href="../workflows/protein_preparation.html">Protein Preparation Wizard</a> In this process, you should check the correctness of formal charges and bond orders in the ligand, cofactors, and nonstandard residues.</p></li> <li><p>With the prepared receptor-ligand complex in the Workspace, use the <a href="receptor_grid_generation.html">Receptor Grid Generation Panel</a> to specify settings, optionally define Glide constraints, and start the receptor grid generation job.</p></li> <li><p>Prepare the ligands using <a href="../ligprep/ligprep.html">LigPrep</a>, to ensure that the structures are all-atom, minimized 3D structures. </p></li> <li><p>Specify the base name for the receptor grid files you want to use in the <a href="ligand_docking.html">Ligand Docking Panel</a>, and use the other settings and options in the panel to set up and start a ligand docking job. As many docking jobs as you want can be set up in this panel, using the current receptor grids or specifying a different set of grids to use.</p></li> </ol> <a name="links"></a> <h2>Related Topics</h2> <ul> <li><a href="receptor_grid_generation.html">Glide &mdash; Receptor Grid Generation Panel</a></li> <li><a href="ligand_docking.html">Glide &mdash; Ligand Docking Panel</a></li> <li><a href="../workflows/protein_preparation.html">Protein Preparation Wizard</a></li> <li><a href="../ligprep/ligprep.html">LigPrep Panel</a></li> </ul> <hr /> <table width="100%"> <td><p class="small"><a href="../support/legal_notice.html" target="LegalNoticeWindow">Legal Notice</a></p></td> <td> <table align="right"> <td><p class="small"> File: glide/glide.html<br /> Last updated: 10 Jan 2012 </p></td> </table> </td> </table> </body> </html>
import React from 'react' import { render } from '@testing-library/react' import '@testing-library/jest-dom'; import { Logo } from './index' jest.mock('../../assets/Logo/logo.png', () => 'logo-image'); describe('Logo', () => { it('renders the logo image and alt text', () => { const { getByAltText } = render(<Logo/>) const logo = getByAltText('Logo') expect(logo).toHaveAttribute('src', 'logo-image') expect(logo).toHaveAttribute('alt', 'Logo') }) it('renders the correct heading text', () => { const { getByText } = render(<Logo />) const heading = getByText('Hotel Finder') expect(heading).toBeInTheDocument() }) })
import networkx as nx def get_distances(num_nodes): distances = {} for i in range(1, num_nodes+1): for j in range(i+1, num_nodes+1): distance = float( input(f"enter the distance between nodes{i} and node{j}:")) distances[(i, j)] = distance distances[(j, i)] = distance return distances def tsp_optimal_drilling(distances): G = nx.Graph() G.add_weighted_edges_from((i, j, distances) for (i, j), distances in distances.items()) optimal_length, optimal_order = nx.approximation.traveling_salesman_problem( G, cycle=True) return optimal_order def calculate_optimal_cost(drill_order, distances): total_cost = sum(distances[(drill_order[i], drill_order[i+1])] for i in range(len(drill_order)-1)) return total_cost if __name__ == "__main__": while True: num_nodes = int(input("enter the number of dril holes(nodes):")) distances = get_distances(num_nodes) optimal_order = tsp_optimal_drilling(distances) optimal_cost = calculate_optimal_cost(optimal_order, distances) print("optimal drilling order:", optimal_order) print(" Total optimal cost:", optimal_cost) try_again = input( "do you want to try again with different number of nodes?(yes/no):").lower() if try_again != "yes": break ''' Output: enter the number of dril holes(nodes):4 enter the distance between nodes1 and node2:2 enter the distance between nodes1 and node3:9 enter the distance between nodes1 and node4:10 enter the distance between nodes2 and node3:6 enter the distance between nodes2 and node4:4 enter the distance between nodes3 and node4:8 optimal drilling order: [1, 2, 3, 4, 2, 1] Total optimal cost: 22.0 do you want to try again with different number of nodes?(yes/no):no '''
const ErrorResponse = require('../utils/errorResponse'); const errorHandler = (err, _req, res, _next) => { let error = { ...err }; error.message = err.message; console.log(err); // mongoose CastError for the bad ObjectID if (err.name === 'CastError') { const message = `Resource not found `; error = new ErrorResponse(message, 404); } //mongoose ServerError for the duplicate resource if (err.code === 11000) { const message = `The user has already added in our database! Duplicate resource detected!`; error = new ErrorResponse(message, 400); } // mongoose Validation Error for required fields if (err.name === 'ValidationError') { const message = Object.values(err.errors).map(({ message }) => message); error = new ErrorResponse(message, 400); } res.status(error.statusCode || 500).json({ success: false, error: error.message || 'Resource not found!', }); }; module.exports = errorHandler;
from typing import List, Union from .. import Parameters, CRStrategy, Checkpoint, WorkloadState, FixedStrategy import random import numpy as np import copy DEFAULT_MAX_CAPACITY = 14 DEFAULT_P = 0.40 DEFAULT_GAMMA = 0.10 DEFAULT_PERFORMANCE_FN = lambda arr: np.mean(np.array(arr)) # DEFAULT_PERFORMANCE_FN = lambda arr: np.median(np.array(arr)) DEFAULT_EPSILON = 0.5 MIN_WEIGHT_EPSILON = 1 # microseconds (median latency) class RequestCentricStrategy(CRStrategy): def __init__( self, workload: Parameters, pool: List[Checkpoint], max_capacity: int = DEFAULT_MAX_CAPACITY, p: float = DEFAULT_P, gamma: float = DEFAULT_GAMMA, performance_fn=DEFAULT_PERFORMANCE_FN, eps=DEFAULT_EPSILON, ) -> None: super().__init__(workload, pool) self.max_capacity = max_capacity self.p = p self.gamma = gamma self.performance_fn = performance_fn self.weights = np.array([0] * workload.max_requests) self.eps = eps @property def name(self) -> str: return f"RequestCentric{self.max_capacity}_P{self.p}_Gamma{self.gamma}" @property def strategy(self) -> str: return "RequestCentric" def _weights_for(self, req_num, scalar=False): cur_slice = self.weights[ req_num : min(req_num + self.workload.eviction, self.workload.max_requests) ] output = 1000000.0 / (cur_slice + MIN_WEIGHT_EPSILON) if scalar: output = self.performance_fn(output) return output def _prune_pool(self): output = [] by_performance = sorted( self.pool, key=lambda c: self._weights_for(c.state.request_number, scalar=True), reverse=True, ) keeping_p = round(self.p * len(by_performance)) output += by_performance[:keeping_p] by_performance = by_performance[keeping_p:] keeping_gamma = round(self.gamma * len(by_performance)) output += random.choices( by_performance, k=min(keeping_gamma, len(by_performance)) ) output_chkpts = {chkpt for chkpt in output} removed = [chkpt for chkpt in self.pool if chkpt not in output_chkpts] for chkpt in removed: chkpt.delete() self.pool[:] = output print( f"Evicted all but top {keeping_p} by performance and {keeping_gamma} by random" ) assert len(self.pool) <= self.max_capacity def checkpoint_to_use(self) -> Checkpoint: if len(self.pool) > self.max_capacity: self._prune_pool() print(f"Exploiting") expanded_pool = self.pool + [None] weights = [ self._weights_for( chkpt.state.request_number if chkpt is not None else 0, scalar=True ) for chkpt in expanded_pool ] weights = np.array(weights) weights_max = np.amax(weights, keepdims=True) weights_shifted = np.exp(weights - weights_max) weights = weights_shifted / np.sum(weights_shifted, keepdims=True) weights = weights.tolist() print(list(zip(weights, expanded_pool))) ret_val = random.choices(expanded_pool, weights=weights, k=1)[0] print("Choosing", ret_val) return ret_val def when_to_checkpoint(self, state: WorkloadState) -> int: # weights = [] # if self.temperature >= random.uniform(0, 1): # explore # print("Checkpoint exploring") # weights = cur_slice # else: # exploit # print("Checkpoint exploiting") weights = self._weights_for(state.request_number + 1) print( self.weights, weights, "Num Weights: ", len(weights), "Req Num: ", state.request_number, "Workload Dict: ", self.workload.__dict__, ) interval = list( range(state.request_number + 1, state.request_number + len(weights) + 1) ) if not interval: return 50000 # do not use a checkpoint weights = [self._weights_for(i, scalar=True) for i in interval] desired_request = random.choices( interval, # weights=weights.tolist(), weights=weights, k=1, )[0] print(f"Checkpointing at {desired_request}", list(zip(interval, weights))) fixed_strat = FixedStrategy(self.workload, self.pool, desired_request) return fixed_strat.when_to_checkpoint(state) def on_request(self, state: WorkloadState): request_num = state.request_number - 1 cur_weight = self.weights[request_num] if cur_weight == 0: self.weights[request_num] = state.latencies[-1] else: self.weights[request_num] = ( self.eps * state.latencies[-1] + (1 - self.eps) * cur_weight ) self.weights[-1] = self.weights[-2] def reset(self) -> None: for chkpt in self.pool: chkpt.delete() self.pool[:] = [] self.weights = np.array([0] * self.workload.max_requests) @property def extra_state(self) -> dict: return { "max_capacity": self.max_capacity, # = max_capacity "p": self.p, # = p "gamma": self.gamma, # = gamma "weights": self.weights.tolist(), # = np.array([0] * workload.max_requests) "eps": self.eps, # = eps }
<template> <view class="container"> <view class="status_bar"><!-- 这里是状态栏 --></view> <view class="navbar-placeholder"></view> <view class="page-title"> <view>南京机房智能运维</view> <view>支撑平台</view> </view> <uni-forms ref="loginForm" err-show-type="toast" :model="formData" :rules="rules" > <uni-forms-item name="phonenumber"> <uni-easyinput type="number" v-model="formData.phonenumber" placeholder="请输入手机号" /> </uni-forms-item> <uni-forms-item name="password"> <uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" /> </uni-forms-item> <uni-forms-item name="code"> <view class="code-row"> <uni-easyinput v-model="formData.code" placeholder="请输入验证码" /> <image :src="codeUrl" @click="getCodeUrl"></image> </view> </uni-forms-item> <view class="settings-row"> <checkbox-group @change="changeRemember"> <label> <checkbox value="1" :checked="isRememberPwd" style="transform: scale(0.75)" /> <text>记住密码</text> </label> </checkbox-group> <navigator url="./forgot-pwd">忘记密码</navigator> </view> <view class="btn-row"> <button type="primary" @click="submitLogin('loginForm')"> 登录 </button> </view> <view class="register-row"> <text>还没有账号?</text> <navigator url="./register">点击注册</navigator> </view> </uni-forms> </view> </template> <script> import { mapMutations, mapActions } from 'vuex' import { phonenumber, password, verify } from '@/utils/validate.js' import { captchaImage, appLogin } from '@/api/index.js' import { encrypt, decrypt } from '@/utils/rsa.js' export default { data() { return { formData: { phonenumber: '', password: '', // phonenumber: '15888888888', // 管理员 // phonenumber: '17611111111', // 经理/申请人 // phonenumber: '17711111111', // 项目经理1 // phonenumber: '17811111111', // 网格员1 // phonenumber: '17911111111', // 代维 // password: 'admin123', code: '', uuid: '' }, rules: { phonenumber, password, code: verify('验证码', 'input') }, codeUrl: '', isRememberPwd: true } }, onLoad() { const phonenumber = uni.getStorageSync('phonenumber') const password = uni.getStorageSync('password') if (phonenumber && password) { this.formData.phonenumber = phonenumber this.formData.password = password this.isRememberPwd = true } this.getCodeUrl() }, methods: { ...mapMutations(['SET_TOKEN']), ...mapActions(['GetInfo']), async getCodeUrl() { const { code, img, uuid } = await captchaImage() if (code === 200) { this.codeUrl = 'data:image/gif;base64,' + img this.formData.uuid = uuid } }, changeRemember(e) { this.isRememberPwd = e.detail.value.length > 0 }, submitLogin(ref) { this.$refs[ref].validate().then(async data => { const params = { ...this.formData, password: encrypt(this.formData.password) } const res = await appLogin(params) if (res.code === 200) { if (this.isRememberPwd) { const { phonenumber, password } = this.formData uni.setStorageSync('phonenumber', phonenumber) uni.setStorageSync('password', password) } else { uni.removeStorageSync('phonenumber') uni.removeStorageSync('password') } this.SET_TOKEN(res.token) this.GetInfo() } else { this.getCodeUrl() } }) } } } </script> <style lang="scss"> $input-height: 88rpx; .container { // padding: 40rpx; background-image: linear-gradient( to right bottom, rgba(250, 255, 217, 0.3), rgba(207, 255, 212, 0.4) 30%, rgba(208, 241, 255, 0.5) 70% ); } .uni-forms { padding: 40rpx; } /deep/ { .is-required { display: none; } .uni-forms-item__label { padding: 0 !important; } image, .uni-easyinput__content-input { height: $input-height !important; } } .code-row { display: flex; image { width: 240rpx; margin-left: 40rpx; } } .settings-row { display: flex; justify-content: space-between; color: #858597; /deep/ { .uni-checkbox-input { background-color: transparent; } } } navigator { color: #3d7fff; } .btn-row { margin: $input-height 0 0; } .register-row { margin-top: 40rpx; display: flex; justify-content: center; text { color: #858597; } } </style>
<?php namespace Tests\Feature\PromoCodeController; use App\Models\User\User; use Laravel\Passport\Passport; use Tests\TestCase; class PromoCodeControllerTest extends TestCase { protected function setUp(): void { parent::setUp(); $user = User::factory()->create(); Passport::actingAs($user); } public function test_create_promo_code() { $data = [ 'code' => 'zinger12345', 'discountAmount' => '1000', 'discountPercent' => '15', 'maxUses' => '23', 'expiredAt' => '2023-11-11 01:02:03', 'productVariantId' => [1, 2] ]; $response = $this->post('/api/promo-codes', $data); $response->assertOk(); $this->assertDatabaseHas('promo_codes', [ 'code' => $data['code'], 'discount_amount' => $data['discountAmount'], 'discount_percent' => $data['discountPercent'], 'max_uses' => $data['maxUses'], 'expired_at' => $data['expiredAt'], ]); } }
// city = name of the city // data_label = label that goes with the data // xaxis_data = number of days // chart_data = the actual values to plot (temperature, precipitation, snow) function draw_chart(city, data_label, xaxis_data, chart_data) { outputImg = document.getElementById("outputImg"); newElem = document.createElement("canvas"); elemId = city + "-" + data_label; newElem.setAttribute("id",elemId); new Chart(newElem, { type: 'line', data: { labels: xaxis_data, datasets: [{ label: data_label, fill: false, data: chart_data, borderWidth: 1 }] }, options: { responsive: true, scales: { y: { display: true, title: { display: true, text: data_label, }, beginAtZero: true }, x: { display: true, title: { display: true, text: "Day" } } } } }); outputImg.appendChild(newElem); } function get_city_status(city) { var xhttp; xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { fieldData = JSON.parse(this.responseText); console.log(fieldData); console.log("-------"); output_string = ""; statusString = document.getElementById("status_string"); statusString.innerHTML = "Output of " + city.id; // Clear the previous canvas elements; outputImg = document.getElementById("outputImg"); outputImg.innerHTML = ""; fieldTable = document.createElement("table"); fieldTable.setAttribute("class","table"); if ('name' in fieldData) { nameTD = document.createElement("td"); nameTD.innerHTML = "name"; nameValTD = document.createElement("td"); nameValTD.innerHTML = fieldData['name']; nameRow = document.createElement("tr"); nameRow.appendChild(nameTD) nameRow.appendChild(nameValTD); fieldTable.appendChild(nameRow); } if ('month' in fieldData) { nameTD = document.createElement("td"); nameTD.innerHTML = "month"; nameValTD = document.createElement("td"); nameValTD.innerHTML = fieldData['month']; nameRow = document.createElement("tr"); nameRow.appendChild(nameTD) nameRow.appendChild(nameValTD); fieldTable.appendChild(nameRow); } if ('year' in fieldData) { nameTD = document.createElement("td"); nameTD.innerHTML = "year"; nameValTD = document.createElement("td"); nameValTD.innerHTML = fieldData['year']; nameRow = document.createElement("tr"); nameRow.appendChild(nameTD) nameRow.appendChild(nameValTD); fieldTable.appendChild(nameRow); } if ('params' in fieldData) { nameTD = document.createElement("td"); nameTD.innerHTML = "params"; nameValTD = document.createElement("td"); nameValTD.innerHTML = fieldData['params']; nameRow = document.createElement("tr"); nameRow.appendChild(nameTD) nameRow.appendChild(nameValTD); fieldTable.appendChild(nameRow); } outputImg.appendChild(fieldTable); // Show the image document.getElementById("status").setAttribute("style","display:block;"); //Hide the form document.getElementById("newRunFormDiv").setAttribute("style","display:none;"); document.getElementById("addCityFormDiv").setAttribute("style","display:none;"); } }; url = "/status?city=" + city.id; xhttp.open("GET", url, true); xhttp.send(); } // TODO: Assignment 4 show the graph function get_city_weather_graphs(city) { var xhttp; xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { fieldData = JSON.parse(this.responseText); console.log(fieldData); console.log("-------"); output_string = ""; statusString = document.getElementById("status_string"); statusString.innerHTML = "Output of " + city.id; // Clear the previous canvas elements; outputImg = document.getElementById("outputImg"); outputImg.innerHTML = ''; // Example fieldData: // {'2023-08-TMAX': '411,406,400,406,411,406,411,411,422,417,422,411,411,411,389,400,433,411,400,417,-9999,-9999,-9999', '2023-08-TMIN': '256,261,256,261,256,256,256,256,250,256,261,267,261,250,267,228,250,250,239,256,-9999,-9999,-9999', '2023-08-PRCP': '-9999,-9999,-9999'} // Iterate through the <key, value> pairs and call draw_chart for each for (const [key, value] of Object.entries(fieldData)) { console.log(`${key}: ${value}`); vals = value.split(","); values = []; xaxis_vals = []; count = 1; for(const elem of vals) { if (elem != "-9999") { // Convert the number to decimal parts = elem.split(""); elem1 = parts.slice(0, parts.length-1); elem1.push("."); elem1.push(parts[parts.length-1]); elem2 = elem1.join(""); values.push(elem2); // Xaxis Day counter. xaxis_vals.push(count); count = count + 1; } } key1 = key; if (key.includes("TMAX") || key.includes("TMIN")) { key1 = key1 + " (Celcius)" } console.log(city.id + " " + key1 + " " + values); draw_chart(city.id, key1, xaxis_vals, values); } // Show the image document.getElementById("status").setAttribute("style","display:block;"); //Hide the form document.getElementById("newRunFormDiv").setAttribute("style","display:none;"); } }; url = "/weather_params?city=" + city.id; xhttp.open("GET", url, true); xhttp.send(); } function show_settings() { alert("To be done") } function logout() { var xhttp; xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { //Reference: https://stackoverflow.com/questions/33914245/how-to-replace-the-entire-html-webpage-with-ajax-response $("html").html(xhttp.responseText); window.history.pushState("object or string", "Title", "/"); } }; url = "/logout" xhttp.open("GET", url, true); xhttp.send(); } function display_new_run_form() { newRunFormDiv = document.getElementById("newRunFormDiv"); newRunFormDiv.setAttribute("style", "display:block;"); statusDiv = document.getElementById("status"); statusDiv.setAttribute("style", "display:none;"); document.getElementById("addCityFormDiv").setAttribute("style","display:none;"); } function display_add_city_form() { addCityFormDiv = document.getElementById("addCityFormDiv"); addCityFormDiv.setAttribute("style", "display:block;"); statusDiv = document.getElementById("status"); statusDiv.setAttribute("style", "display:none;"); document.getElementById("newRunForm").setAttribute("style","display:none;"); }
#ifndef PHYSICS_RT_PHYSICSOBJECT_H #define PHYSICS_RT_PHYSICSOBJECT_H #include "CK3dEntity.h" #include "ivp_physics.hxx" #include "ivp_real_object.hxx" class PhysicsContactData; class IPhysicsObject { public: virtual const char *GetName() const = 0; virtual CK3dEntity *GetEntity() const = 0; virtual void SetGameData(void *data) = 0; virtual void *GetGameData() const = 0; virtual void SetGameFlags(unsigned int flags) = 0; virtual unsigned int GetGameFlags() const = 0; virtual void Wake() = 0; virtual void Sleep() = 0; virtual bool IsStatic() const = 0; virtual bool IsMovable() const = 0; virtual bool IsCollisionEnabled() const = 0; virtual bool IsGravityEnabled() const = 0; virtual bool IsMotionEnabled() const = 0; virtual void EnableCollisions(bool enable) = 0; virtual void EnableGravity(bool enable) = 0; virtual void EnableMotion(bool enable) = 0; virtual void RecheckCollisionFilter() = 0; virtual float GetMass() const = 0; virtual float GetInvMass() const = 0; virtual void SetMass(float mass) = 0; virtual void GetInertia(VxVector &inertia) const = 0; virtual void GetInvInertia(VxVector &inertia) const = 0; virtual void SetInertia(const VxVector &inertia) = 0; virtual void GetDamping(float *speed, float *rot) = 0; virtual void SetDamping(const float *speed, const float *rot) = 0; virtual void ApplyForceCenter(const VxVector &forceVector) = 0; virtual void ApplyForceOffset(const VxVector &forceVector, const VxVector &worldPosition) = 0; virtual void ApplyTorqueCenter(const VxVector &torqueImpulse) = 0; virtual void CalculateForceOffset(const VxVector &forceVector, const VxVector &worldPosition, VxVector &centerForce, VxVector &centerTorque) = 0; virtual void CalculateVelocityOffset(const VxVector &forceVector, const VxVector &worldPosition, VxVector &centerVelocity, VxVector &centerAngularVelocity) = 0; virtual void GetPosition(VxVector *worldPosition, VxVector *angles) = 0; virtual void GetPositionMatrix(VxMatrix &positionMatrix) = 0; virtual void SetPosition(const VxVector &worldPosition, const VxVector &angles, bool isTeleport) = 0; virtual void SetPositionMatrix(const VxMatrix &matrix, bool isTeleport) = 0; virtual void GetVelocity(VxVector *velocity, VxVector *angularVelocity) = 0; virtual void GetVelocityAtPoint(const VxVector &worldPosition, VxVector &velocity) = 0; virtual void SetVelocity(const VxVector *velocity, const VxVector *angularVelocity) = 0; virtual void AddVelocity(const VxVector *velocity, const VxVector *angularVelocity) = 0; virtual float GetEnergy() = 0; }; class PhysicsObject : public IPhysicsObject { public: PhysicsObject(); ~PhysicsObject(); void Init(IVP_Real_Object *obj, CK3dEntity *entity); virtual const char *GetName() const; virtual CK3dEntity *GetEntity() const; IVP_Real_Object *GetObject() const; virtual void *GetGameData() const; virtual void SetGameData(void *data); virtual unsigned int GetGameFlags() const; virtual void SetGameFlags(unsigned int flags); virtual void Wake(); virtual void Sleep(); virtual bool IsStatic() const; virtual bool IsMovable() const; virtual bool IsCollisionEnabled() const; virtual bool IsGravityEnabled() const; virtual bool IsMotionEnabled() const; bool IsControlling(IVP_Controller *controller) const; virtual void EnableCollisions(bool enable); virtual void EnableGravity(bool enable); virtual void EnableMotion(bool enable); virtual void RecheckCollisionFilter(); virtual float GetMass() const; virtual float GetInvMass() const; virtual void SetMass(float mass); virtual void GetInertia(VxVector &inertia) const; virtual void GetInvInertia(VxVector &inertia) const; virtual void SetInertia(const VxVector &inertia); virtual void GetDamping(float *speed, float *rot); virtual void SetDamping(const float *speed, const float *rot); virtual void ApplyForceCenter(const VxVector &forceVector); virtual void ApplyForceOffset(const VxVector &forceVector, const VxVector &worldPosition); virtual void ApplyTorqueCenter(const VxVector &torqueImpulse); virtual void CalculateForceOffset(const VxVector &forceVector, const VxVector &worldPosition, VxVector &centerForce, VxVector &centerTorque); virtual void CalculateVelocityOffset(const VxVector &forceVector, const VxVector &worldPosition, VxVector &centerVelocity, VxVector &centerAngularVelocity); virtual void GetPosition(VxVector *worldPosition, VxVector *angles); virtual void GetPositionMatrix(VxMatrix &positionMatrix); virtual void SetPosition(const VxVector &worldPosition, const VxVector &angles, bool isTeleport); virtual void SetPositionMatrix(const VxMatrix &matrix, bool isTeleport); virtual void GetVelocity(VxVector *velocity, VxVector *angularVelocity); virtual void GetVelocityAtPoint(const VxVector &worldPosition, VxVector &velocity); virtual void SetVelocity(const VxVector *velocity, const VxVector *angularVelocity); virtual void AddVelocity(const VxVector *velocity, const VxVector *angularVelocity); virtual float GetEnergy(); CKBehavior *m_Behavior; IVP_Real_Object *m_RealObject; PhysicsContactData *m_ContactData; void *m_GameData; unsigned int m_GameFlags; }; #endif // PHYSICS_RT_PHYSICSOBJECT_H
Serialization in Java: ---------------------- Serialization in java is a mechanism of writing the state of an object into a byte stream. It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies. The reverse operation of serialization is called deserialization. The String class and all the wrapper classes implements java.io.Serializable interface by default. Advantage of Java Serialization: --------------------------------- It is mainly used to travel object's state on the network (known as "marshaling"). java.io.Serializable interface: -------------------------------- Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability. It must be implemented by the class whose object you want to persist. ex: Student.java ObjectOutputStream class: ------------------------- The ObjectOutputStream class is used to write primitive data types and Java objects to an OutputStream. Only objects that support the java.io.Serializable interface can be written to streams. Constructor: ------------ 1) public ObjectOutputStream(OutputStream out) throws IOException {} creates an ObjectOutputStream that writes to the specified OutputStream. Important Methods: ------------------ ------------------------------------------------------------------------------------------------------------------------------- Method | Description ------------------------------------------------------------------------------------------------------------------------------- 1) public final void writeObject(Object obj) throws IOException {} | writes the specified object to the ObjectOutputStream. ------------------------------------------------------------------------------------------------------------------------------- 2) public void flush() throws IOException {} | flushes the current output stream. ------------------------------------------------------------------------------------------------------------------------------- 3) public void close() throws IOException {} | closes the current output stream. ------------------------------------------------------------------------------------------------------------------------------- Example of Java Serialization : Persist.java Deserialization in java: ------------------------ Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. ObjectInputStream class: ------------------------ An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream. Constructor: ------------ 1) public ObjectInputStream(InputStream in) throws IOException {} creates an ObjectInputStream that reads from the specified InputStream. Important Methods: ------------------ ------------------------------------------------------------------------------------------------------------------------ Method | Description: ------------------------------------------------------------------------------------------------------------------------ 1) public final Object readObject() throws IOException, ClassNotFoundException{} | reads an object from the input stream. ------------------------------------------------------------------------------------------------------------------------ 2) public void close() throws IOException {} | closes ObjectInputStream. ------------------------------------------------------------------------------------------------------------------------ Example of Java Deserialization: Depersist.java Java Serialization with Inheritance (IS-A Relationship): -------------------------------------------------------- If a class implements serializable then all its sub classes will also be serializable. Let's see the example given below: import java.io.Serializable; class Person implements Serializable{ int id; String name; Person(int id, String name) { this.id = id; this.name = name; } } class Student extends Person{ String course; int fee; public Student(int id, String name, String course, int fee) { super(id,name); this.course=course; this.fee=fee; } } Now you can serialize the Student class object that extends the Person class which is Serializable. Parent class properties are inherited to subclasses so if parent class is Serializable, subclass would also be. Java Serialization with Aggregation (HAS-A Relationship): -------------------------------------------------------- If a class has a reference of another class, all the references must be Serializable otherwise serialization process will not be performed. In such case, "NotSerializableException" is thrown at runtime. class Address{ String addressLine,city,state; public Address(String addressLine, String city, String state) { this.addressLine=addressLine; this.city=city; this.state=state; } } import java.io.Serializable; public class Student implements Serializable{ int id; String name; Address address;//HAS-A public Student(int id, String name) { this.id = id; this.name = name; } } Since Address is not Serializable, you can not serialize the instance of Student class. Note: ----- "All the objects within an object must be Serializable." Java Serialization with static data member: ------------------------------------------- If there is any static data member in a class, it will not be serialized because static is the part of class not object. class Employee implements Serializable{ int id; String name; static String company="SSS IT Pvt Ltd";//it won't be serialized public Student(int id, String name) { this.id = id; this.name = name; } } Java Serialization with array or collection: -------------------------------------------- Rule: In case of array or collection, all the objects of array or collection must be serializable. If any object is not serialiizable, serialization will be failed. Externalizable in java: ----------------------- The Externalizable interface provides the facility of writing the state of an object into a byte stream in compress format. It is not a marker interface. The Externalizable interface provides two methods: -------------------------------------------------- public void writeExternal(ObjectOutput out) throws IOException public void readExternal(ObjectInput in) throws IOException Java Transient Keyword: ----------------------- If you don't want to serialize any data member of a class, you can mark it as transient. Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized. Let's take an example, I have declared a class as Student, it has three data members id, name and age. If you serialize the object, all the values will be serialized but I don't want to serialize one value, e.g. age then we can declare the age data member as transient. Example of Java Transient Keyword: ---------------------------------- In this example, we have created the two classes Employee and PersistExample. The age data member of the Employee class is declared as transient, its value will not be serialized. "If you deserialize the object, you will get the default value for transient variable." ex: Employee.java and PersistTransient.java
import { MigrationInterface, QueryRunner, Table } from "typeorm" export class CreateProducts1664676624045 implements MigrationInterface { public async up(queryRunner: QueryRunner): Promise<void> { await queryRunner.createTable(new Table({ name: "products", columns: [ { name: "id", type: "uuid", isPrimary: true, isUnique: true, isGenerated: false }, { name: "catalog_id", type: "uuid" }, { name: "product_id", type: "varchar" } ], foreignKeys:[ { name: "FKCatalog_id", columnNames: ["catalog_id"], referencedTableName: "catalogs", referencedColumnNames: ["id"], onDelete: "CASCADE", onUpdate: "CASCADE" } ] })) } public async down(queryRunner: QueryRunner): Promise<void> { await queryRunner.dropTable("products"); } }
#pragma once #include <iostream> #include <memory> #include <map> namespace Render { class ShaderProgram; class Texture2D; class Sprite; } class ResurceManager { public: ResurceManager(const std::string& executablePath); ~ResurceManager() = default; ResurceManager(const ResurceManager&) = delete; ResurceManager& operator=(const ResurceManager&) = delete; ResurceManager& operator=(ResurceManager&&) = delete; ResurceManager(ResurceManager&&) = delete; std::shared_ptr<Render::ShaderProgram>loadShaderProgram(const std::string& shaderName, const std::string& vertexPath, const std::string& fragmentPath); std::shared_ptr<Render::ShaderProgram>getShaderProgram(const std::string& shaderName); std::shared_ptr<Render::Texture2D>loadTexture(const std::string& textureName, const std::string& texturepath); std::shared_ptr<Render::Texture2D>getTexture(const std::string& textureName); std::shared_ptr<Render::Sprite>loadSprite(const std::string& spriteName, const std::string& textureName, const std::string& shaderName, const unsigned int spritesWidth, const unsigned int spritesHeight); std::shared_ptr<Render::Sprite>getSprite(const std::string& spriteName); private: std::string getFilestring(const std::string& reletivFilePath) const; typedef std::map<const std::string, std::shared_ptr<Render::ShaderProgram>> ShaderProgramsMap; ShaderProgramsMap m_shaderProgram; typedef std::map<const std::string, std::shared_ptr<Render::Texture2D>> TexturesMap; TexturesMap m_textures; typedef std::map<const std::string, std::shared_ptr<Render::Sprite>> SpritesMap; SpritesMap m_Sprites; std::string m_path; };
import tkinter as tk from tkinter.ttk import * from tkcalendar import DateEntry import csv from tkinter.constants import * class Table: def __init__(self,root, total_rows, total_columns, lst): # code for creating table for i in range(total_rows): for j in range(total_columns): self.e = Entry(root, width=15) self.e.config(state = "normal") self.e.grid(row=i, column=j) self.e.insert(tk.END, lst[i][j]) class VerticalScrolledFrame(Frame): """A pure Tkinter scrollable frame that actually works! * Use the 'interior' attribute to place widgets inside the scrollable frame. * Construct and pack/place/grid normally. * This frame only allows vertical scrolling. """ def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) # Create a canvas object and a vertical scrollbar for scrolling it. vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = tk.Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) # Reset the view canvas.xview_moveto(0) canvas.yview_moveto(0) # Create a frame inside the canvas which will be scrolled with it. self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) # Track changes to the canvas and frame width and sync them, # also updating the scrollbar. def _configure_interior(event): # Update the scrollbars to match the size of the inner frame. size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): # Update the canvas's width to fit the inner frame. canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != canvas.winfo_width(): # Update the inner frame's width to fill the canvas. canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas) def storeData(data): with open('data.csv','r')as file: filecontent=csv.reader(file) n = True for row in filecontent: if(n): pass else: data.append(row) n = False data = [] storeData(data) win = tk.Tk() win.tk.call("source", "azure.tcl") win.tk.call("set_theme", "dark") style = Style() #win.geometry("800x600+0+0") w, h = win.winfo_screenwidth(), win.winfo_screenheight() win.geometry("%dx%d+0+0" % (w, h)) shouldFilterDates = True selectDateLabel = Label(win, text= "Select Date") selectDateLabel.place(x = 10, y = 15) cal = DateEntry(win, day=1, month=4, year=2018) cal.place(x=110, y=10) style.configure("Toggle.TButton", font = (None, 6)) def shouldFilterDates(): global shouldFilterDates shouldFilterDates = not shouldFilterDates enableAllDates = Checkbutton(win, text = "Toggle Date filtering", style= 'Toggle.TButton', command = shouldFilterDates) enableAllDates.place(x = 250, y = 10) daysVar = tk.StringVar(win) selectDayLabel = Label(win, text= "Select Day") selectDayLabel.place(x = 10, y = 60) daysOption = OptionMenu(win, daysVar, *["All", "All", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] ) daysOption.place(x = 110, y = 55) pressureBox = Label(win , text="Pressure(at sea) Min:-:Max") pressureBox.place(x= 10,y=100) pressureInputMinBox = Entry(win, width = 5) pressureInputMinBox.place(x=200,y=95) pressureInputMaxBox = Entry(win, width = 5) pressureInputMaxBox.place(x=260 ,y=95) tempratureBox = Label(win , text="Temperature (Min:-:Max)") tempratureBox.place(x=10,y=150) tempratureInputMinBox = Entry(win, width = 5) tempratureInputMinBox.place(x=200,y=145) tempratureInputMaxBox = Entry(win, width = 5) tempratureInputMaxBox.place(x=260,y=145) humidityBox = Label(win , text="Rel Humidity (Min:-:Max)") humidityBox.place(x=10,y=200) humidityInputMinBox = Entry(win, width = 5) humidityInputMinBox.place(x=200,y=195) humidityInputMaxBox = Entry(win, width = 5) humidityInputMaxBox.place(x=260,y=195) visibilityBox = Label(win , text="Visibilty (Min:-:Max)") visibilityBox.place(x=10,y=250) visibilityInputMinBox = Entry(win, width = 5) visibilityInputMinBox.place(x=200,y=245) visibilityInputMaxBox = Entry(win, width = 5) visibilityInputMaxBox.place(x=260,y=245) windSpeedBox = Label(win , text="Wind Speed (Min:-:Max)") windSpeedBox.place(x=10,y=300) windSpeedInputMinBox = Entry(win, width = 5) windSpeedInputMinBox.place(x=200,y=295) windSpeedInputMaxBox = Entry(win, width = 5) windSpeedInputMaxBox.place(x=260,y=295) PMBox = Label(win , text="PM 2.5 (Min:-:Max)") PMBox.place(x=10,y=350) PMInputMinBox = Entry(win, width = 5) PMInputMinBox.place(x=200,y=345) PMInputMaxBox = Entry(win, width = 5) PMInputMaxBox.place(x=260,y=345) lst = [] def updateData(): date = cal.get_date().strftime("%d/%m/%Y") day = daysVar.get() print(day) lst.clear() lst.append(("Date",'Day','Avg. Temp',"Max Temp", "Min Temp", "ATM", "rel. humidity", "Avg. visibilty", "Max wind Speed", "AQI")) n = 0 for entry in data: filteredDate = False if(shouldFilterDates): if(date in entry[0]): filteredDate = True else: filteredDate = True if(filteredDate): if(day.lower() == entry[1].lower() or day == "All"): if(pressureInputMaxBox.get() == "" or pressureInputMinBox == ""): if(n < 20): lst.append(entry) n += 1 elif float(entry[5]) > float(pressureInputMinBox.get()) and float(entry[5]) < float(pressureInputMaxBox.get()): if(n < 20): lst.append(entry) n += 1 # n += 1 # if n < 20: lst.append(entry) frame = VerticalScrolledFrame(win) frame.place(x = 0, y = 400) t = Table(frame.interior, len(lst), len(lst[0]), lst) submitButton = Button(win, text="Get Filtered Data", command= updateData) submitButton.place(x = 700, y = 200) win.mainloop()
import 'package:conditional_builder_null_safety/conditional_builder_null_safety.dart'; import 'package:e_store/modules/shop_layout/layout_screen.dart'; import 'package:e_store/modules/shop_register_screen/cubit/cubit.dart'; import 'package:e_store/modules/shop_register_screen/cubit/states.dart'; import 'package:e_store/shared/components/components.dart'; import 'package:e_store/shared/components/constants.dart'; import 'package:e_store/shared/network/local/cache_helper.dart'; import 'package:e_store/shared/styles/colors.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; // ignore: must_be_immutable class ShopRegisterScreen extends StatelessWidget { var formKey = GlobalKey<FormState>(); var emailController = TextEditingController(); var passwordController = TextEditingController(); var nameController = TextEditingController(); var phoneController = TextEditingController(); ShopRegisterScreen({super.key}); @override Widget build(BuildContext context) { return BlocProvider( create: (context) => ShopRegisterCubit(), child: BlocConsumer<ShopRegisterCubit, ShopRegisterStates>( listener: (context, state) { if (state is ShopRegisterSuccessState) { if (state.loginModel.status!) { CacheHelper.saveData( key: 'token', value: state.loginModel.data?.token) .then((value) { token = state.loginModel.data!.token!; navigateAndFinish(context, const LayoutScreen()); }); } else { showToast( state.loginModel.message, ToastStates.error, ); } } }, builder: (context, state) { return Scaffold( appBar: AppBar(), body: Center( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(20.0), child: Form( key: formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: Icon( Icons.shopping_cart, color: defaultTeal, size: 80, ), ), const SizedBox( height: 30.0, ), Text( 'REGISTER', style: Theme.of(context) .textTheme .headlineMedium! .copyWith( color: Colors.black, ), ), Text( 'Register now to browse our hot offers', style: Theme.of(context) .textTheme .bodyLarge! .copyWith(color: Colors.grey), ), const SizedBox( height: 30.0, ), defaultFormField( controller: nameController, type: TextInputType.name, validate: (String value) { if (value.isEmpty) { return 'Please, enter your username'; } }, label: 'Username', prefix: Icons.person, hasSuffix: false, )!, const SizedBox( height: 15.0, ), defaultFormField( controller: emailController, type: TextInputType.emailAddress, validate: (String value) { if (value.isEmpty) { return 'Please, enter your email address'; } }, label: 'Email address', prefix: Icons.email_outlined, hasSuffix: false, )!, const SizedBox( height: 15.0, ), defaultFormField( controller: passwordController, type: TextInputType.visiblePassword, validate: (String value) { if (value.isEmpty) { return 'Password is too short'; } }, label: 'Password', prefix: Icons.lock_outline, hasSuffix: true, isPassword: ShopRegisterCubit.get(context).isPasswordShown, suffix: ShopRegisterCubit.get(context).suffix, suffixPressed: () { ShopRegisterCubit.get(context).changeVisibility(); }, )!, const SizedBox( height: 15.0, ), defaultFormField( controller: phoneController, type: TextInputType.phone, validate: (String value) { if (value.isEmpty) { return 'Please, enter your phone number'; } }, label: 'Phone', prefix: Icons.phone, hasSuffix: false, )!, const SizedBox( height: 30.0, ), ConditionalBuilder( condition: state is! ShopRegisterLoadingState, builder: (context) => defaultButton( function: () { if (formKey.currentState!.validate()) { ShopRegisterCubit.get(context).userRegister( email: emailController.text, password: passwordController.text, name: nameController.text, phone: phoneController.text, ); } FocusScope.of(context).unfocus(); }, text: 'Register', isUpperCase: true, ), fallback: (context) => const Center( child: CircularProgressIndicator(), ), ), const SizedBox( height: 50, ), ], ), ), ), ), ), ); }, ), ); } }
from .user_data import CLIX_DATA_DIR, CLIX_PREFERENCE_FILE import json from typing import Literal from dataclasses import dataclass, asdict @dataclass class Preference: area: Literal["side", "bottom", "top"] = "bottom" hide_title_bar: bool = False show_label: bool = False enter_completion: bool = True auto_focus: bool = True def as_repr(self) -> str: return "\n".join(f"{k} = {v!r}" for k, v in asdict(self).items()) def __eq__(self, other): return asdict(self) == asdict(other) def load_preference() -> Preference: if not CLIX_PREFERENCE_FILE.exists(): return Preference() with CLIX_PREFERENCE_FILE.open("r") as f: js = json.load(f) kwargs = {} for key, value in js.items(): if key in Preference.__annotations__: kwargs[key] = value return Preference(**kwargs) def save_preference(**kwargs): if not CLIX_DATA_DIR.exists(): CLIX_DATA_DIR.mkdir(parents=True) pref = load_preference() for k, v in kwargs.items(): if v is not None: setattr(pref, k, v) with CLIX_PREFERENCE_FILE.open("w") as f: json.dump(asdict(pref), f) return pref
# The Hugging Face Hub [[The Hugging Face Hub]] <CourseFloatingBanner chapter={4} classNames="absolute z-10 right-0 top-0" /> 我们的主网站——— [Hugging Face中心](https://huggingface.co/) 是一个集发现、使用及贡献最新先进模型与数据集为一体的中心平台。这里汇聚了超过 10,000 个公开可用的各种领域的模型。我们将在本章节专注探讨这些模型,并在第五章节深入讨论数据集。 Hub 中的模型不仅限于🤗 Transformers 或者是自然语言处理。这里有许多模型,比如用于自然语言处理的 [Flair](https://github.com/flairNLP/flair) 和 [AllenNLP](https://github.com/allenai/allennlp) 模型,用于音频检测的 [Asteroid](https://github.com/asteroid-team/asteroid) 和 [pyannote](https://github.com/pyannote/pyannote-audio) 模型,以及用于视觉的 [timm](https://github.com/rwightman/pytorch-image-models) 模型等,这些例子只是 Hub 中模型的冰山一角,更多的模型可以由你去探索。 这些模型中的每一个都以 Git 仓库的形式托管,方便进行版本控制和复现。在 Hub 上共享模型意味着向社区开放,让任何希望使用模型的人都可以轻松访问,从而使他们免于训练模型之苦,并且简化了模型分享和使用。 此外,在 Hub 上分享一个模型会自动为该模型部署一个推理 API。社区中的任何人都可以直接在模型页面上使用各自的输入和相应的小工具来进行测试。 最妙的是,在 Hub 上分享和使用任何公共模型都是完全免费的!如果你希望只把模型分享给特定的人,我们也有 [付费计划](https://huggingface.co/pricing) 。 下面的视频展示了如何使用 Hub。 <Youtube id="XvSGPZFEjDY"/> 如果你想跟进实现这一部分内容,你需要有一个 Huggingface.co 帐户,因为这一节我们将在 Hugging Face Hub 上创建和管理存储库: [创建一个账户](https://huggingface.co/join)
import supertest from 'supertest'; import dotenv from 'dotenv'; import app from '../../server'; dotenv.config(); const request = supertest(app); let REQ_TOKEN: string; describe('Products handlers routes work properly', (): void => { beforeAll(async () => { const req = request.post('/users').send({ first_name: 'maged', last_name: 'hady', password: '1234' }); REQ_TOKEN = (await req).text.replace(/['"]+/g, ''); }); it('should GET /products to show all products', async (): Promise<void> => { request .get('/products') .set({ token: REQ_TOKEN }) .expect('Content-Type', /json/) .expect(200) .then((response) => { expect(response.body).toEqual( jasmine.arrayContaining([ jasmine.objectContaining({ id: jasmine.any(Number), name: jasmine.any(String), price: jasmine.any(Number) }) ]) ); }); }); it('should GET /products/:id to show a specific product', async (): Promise<void> => { request .get('/products/1') .set({ token: REQ_TOKEN }) .expect('Content-Type', /json/) .expect(200); }); it('should GET /products/:id to show a 404 if a specific product does not exist', () => { request .get('/products/99999999999999999999') .set({ token: REQ_TOKEN }) .expect(404); request.get('/products/hfjdshf8').set({ token: REQ_TOKEN }).expect(404); }); it('should POST /products to create a new product', () => { request .post('/products') .set({ token: REQ_TOKEN }) .send({ name: 'back pack', price: 25 }) .expect('Content-Type', /json/) .expect(200) .then((response) => expect(response.body).toEqual( jasmine.objectContaining({ id: jasmine.any(Number), name: jasmine.any(String), price: jasmine.any(Number) }) ) ); }); it('Should validate request body', () => { request .post('/products') .set({ token: REQ_TOKEN }) .send({ name: 123213 }) .expect(422); }); });
<!DOCTYPE HTML> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head th:replace="base :: head"> </head> <body> <header th:replace="base :: header"></header> <div class="container py-4"> <div class="card bg-light"> <div class="card-header" th:text="#{text.layout.customers}"></div> <div class="card-body"> <div class="card-title"> <a th:href="@{/form}" class="btn btn-primary btn-xs my-2">Dodaj klienta </a> </div> <div> <form th:action="@{/search}" method="get" enctype="multipart/form-data" th:align="right"> <h5 class="card-title"> <input th:type="text" name="search" th:align="right" th:placeholder="Szukaj"/> <button th:type="submit" name="submit" class="btn btn-info btn-xs"><i class="material-icons">search</i> </button> </h5> </form> </div> <table class="table table-bordered table-striped"> <thead class="thead-inverse"> <tr> <th>Id</th> <th th:text="#{text.client.name}"></th> <th th:text="#{text.client.address}"></th> <th th:text="#{text.client.createdAt}"></th> <th th:text="#{text.list.invoice}">Faktury</th> <th th:text="#{text.list.edit}">Edytuj</th> <th th:text="#{text.list.delete}">Usuń</th> </tr> </thead> <tbody> <tr th:each="customer : ${customerList}"> <td><a th:href="@{/customer/} + ${customer.id}" th:text="${customer.id}" class="btn btn-primary btn-xs"></a></td> <td th:text="${customer.name}"></td> <td th:text="${customer.address}"></td> <td th:text="${customer.createdAt}"></td> <td><a th:href="@{/invoice/form/} + ${customer.id}" class="btn btn-success btn-xs"><i class="material-icons">message</i></a></td> <td><a th:href="@{/updateForm(customerId=${customer.id})}" class="btn btn-primary btn-xs"> <i class="material-icons">edit</i></a></td> <td><a th:href="@{/delete(customerId=${customer.id})}" class="btn btn-danger btn-xs" onclick="return confirm('Na pewno chcesz usunąć klienta?')"> <i class="material-icons">delete_forever</i></a></td> </tr> </tbody> </table> </div> </div> </div> <div class="row" th:fragment="pagination"> <div class="col-md-2"></div> <div class="col-md-8"> <nav aria-label="Pagination"> <ul class="pagination justify-content-center"> <li class="page-item" th:each="pageNumber : ${pageNumbers}"> <a class="page-link" th:href="@{|/customers/${pageNumber}|}" th:text=${pageNumber}>1</a> </li> </ul> </nav> </div> <div class="col-md-2"></div> </div> <footer th:replace="base :: footer"></footer> </body> </html>
<!--process_form_2.php Xử lý form với các input phức tạp --> <?php // XỬ LÝ FORM: // + B1: Debug echo '<pre>'; print_r($_GET); echo '</pre>'; // + B2: KHai báo biến $error = ''; $result = ''; // + B3: Chỉ xử lý form khi đã submit form if (isset($_GET['submit'])) { // + B4: Lấy giá trị từ form: $age = $_GET['age']; // PHP sẽ ko bắt dữ liệu từ radio và checkbox nếu như ko tích //vào cái nào, nên ko đc lấy giá trị trước // $gender = $_GET['gender']; // $jobs = $_GET['jobs']; $country = $_GET['country']; $note = $_GET['note']; // + B5: Validate form: // - Tuổi phải là số: is_numeric // - Bắt buộc phải chọn Giới tính và Nghề nghiệp: ktra //tồn tại của phần tử mảng theo key -> isset if (!is_numeric($age)) { $error = 'Tuổi phải là số'; } elseif (!isset($_GET['gender'])) { $error = 'Phải chọn giới tính'; } elseif (!isset($_GET['jobs'])) { $error = 'Phải chọn ít nhất 1 nghề nghiệp'; } // + B6: Xử lý logic chính chỉ khi ko có lỗi if (empty($error)) { $result .= "Tuổi: $age <br>"; // Xử lý radio: $gender = $_GET['gender'];// 1 2 3 $gender_text = ''; switch ($gender) { case 1: $gender_text = 'Nam';break; case 2: $gender_text = 'Nữ';break; case 3: $gender_text = 'Khác'; } $result .= "Giới tính: $gender_text <br>"; // Xử lý checkbox: $jobs = $_GET['jobs']; $job_text = ''; foreach ($jobs AS $job) { switch ($job) { case 1: $job_text .= " Tester";break; case 2: $job_text .= " Dev";break; case 3: $job_text .= " BrSE"; } } $result .= "Nghề nghiệp: $job_text <br>"; // Xử lý select: giống hệt radio $country_text = ''; switch ($country) { case 1: $country_text = 'VN';break; case 2: $country_text = 'JP';break; case 3: $country_text = 'KR'; } $result .= "Quốc gia: $country_text <br>"; // Xử lý textarea $result .= "Ghi chú: $note"; } } // + B7: Đổ error và result ra form // + B8: Đổ lại dữ liệu đã nhập ra form ?> <h3 style="color: red"><?php echo $error; ?></h3> <h3 style="color: green"><?php echo $result; ?></h3> <form action="" method="GET"> Nhập tuổi: <input type="text" name="age" value="<?php echo isset($_GET['age']) ? $_GET['age'] : '' ?>"> <br> Chọn giới tính: <!-- Với radio, PHP dựa vào value tương ứng để biết đc dữ liệu gửi lên là của radio nào--> <?php // - Đổ dữ liệu radio là can thiệp thuộc tính checked // + Có bao nhiêu radio thì tạo từng đó biến để lưu checked $checked_male = ''; $checked_female = ''; $checked_another = ''; // + Xử lý nếu submit form thì mới gán: if (isset($_GET['gender'])) { switch ($_GET['gender']) { case 1: $checked_male = 'checked';break; case 2: $checked_female = 'checked';break; case 3: $checked_another = 'checked'; } } // + Hiển thị vào tương ứng với radio ?> <input <?php echo $checked_male ?> type="radio" name="gender" value="1"> Nam <input <?php echo $checked_female ?> type="radio" name="gender" value="2"> Nữ <input <?php echo $checked_another ?> type="radio" name="gender" value="3"> Khác <br> Chọn nghề nghiệp: <!-- Với checkbox, nếu có từ 2 checkbox trở lên thì bắt buộc name phải ở dạng mảng --> <?php // - Đổ dữ liệu cho checkbox thì cũng can thiệp checked // + Có bao nhiêu checkbox thì có từng đó biến $checked_dev = ''; $checked_tester = ''; $checked_brse = ''; // + Ktra nếu submit form thì xử lý gán checked if (isset($_GET['jobs'])) { foreach ($_GET['jobs'] AS $job) { switch ($job) { case 1: $checked_dev = 'checked';break; case 2: $checked_tester = 'checked';break; case 3: $checked_brse = 'checked'; } } } // + Hiển thị biến ra input tương ứng ?> <input <?php echo $checked_dev ?> type="checkbox" name="jobs[]" value="1"> Dev <input <?php echo $checked_tester ?> type="checkbox" name="jobs[]" value="2"> Tester <input <?php echo $checked_brse ?> type="checkbox" name="jobs[]" value="3"> brSE <br> Chọn quốc gia: <?php // - Can thiệp selected vào option, xử lý giống hệt radio $selected_vn = ''; $selected_jp = ''; $selected_kr = ''; if (isset($_GET['country'])) { switch ($_GET['country']) { case 1: $selected_vn = 'selected';break; case 2: $selected_jp = 'selected';break; case 3: $selected_kr = 'selected'; } } ?> <select name="country"> <option <?php echo $selected_vn ?> value="1">VN</option> <option <?php echo $selected_jp ?> value="2">JP</option> <option <?php echo $selected_kr ?> value="3">KR</option> </select> <br> Ghi chú: <textarea name="note"><?php echo isset($_GET['note']) ? $_GET['note'] : ''?></textarea> <br> <input type="submit" name="submit" value="Hiển thị"> </form>
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import scipy.stats as stats """ Author Information: - Name: Victor Irekponor, Taylor Oshan - Email: [email protected] - Date Created: 2023-10-12 """ def shift_colormap(cmap, start=0, midpoint=0.5, stop=1.0, name='shiftedcmap'): """ Shift the colormap to make visualization easier and more intuitive. Parameters: - cmap: A matplotlib colormap instance or name. - start (float): Start point of the new colormap segment. Defaults to 0.0. - midpoint (float): Midpoint (anchor point) for the shifted colormap. Defaults to 0.5. - stop (float): End point for the new colormap segment. Defaults to 1.0. - name (str): The name of the new colormap. Defaults to 'shiftedcmap'. Returns: - new_cmap: A new colormap that is shifted as per the given parameters. """ cdict = {'red': [], 'green': [], 'blue': [], 'alpha': []} reg_index = np.linspace(start, stop, 257) shift_index = np.hstack([ np.linspace(0.0, midpoint, 128, endpoint=False), np.linspace(midpoint, 1.0, 129, endpoint=True) ]) for ri, si in zip(reg_index, shift_index): r, g, b, a = cmap(ri) cdict['red'].append((si, r, r)) cdict['green'].append((si, g, g)) cdict['blue'].append((si, b, b)) cdict['alpha'].append((si, a, a)) new_cmap = mpl.colors.LinearSegmentedColormap(name, cdict) return new_cmap def truncate_colormap(cmap, minval=0.0, maxval=1.0, n=100): """ Truncate a colormap by creating a new colormap from a subsection of an existing one. Parameters: - cmap: A matplotlib colormap instance. - minval (float): The minimum value for the new truncated colormap. Defaults to 0.0. - maxval (float): The maximum value for the new truncated colormap. Defaults to 1.0. - n (int): The number of divisions for the linspace function that generates new colors. Defaults to 100. Returns: - new_cmap: A new colormap that is truncated as per the given parameters. """ new_cmap = mpl.colors.LinearSegmentedColormap.from_list( 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=minval, b=maxval), cmap(np.linspace(minval, maxval, n))) return new_cmap def merge_index(left, right): """ Merge two pandas DataFrames based on their indices. Parameters: - left: The left pandas DataFrame. - right: The right pandas DataFrame. Returns: - A new pandas DataFrame resulting from merging the left and right DataFrames based on their indices. """ return left.merge(right, left_index=True, right_index=True) def mask_insignificant_t_values(df, alpha=0.05): """ Calculate t-values from a dataframe containing coefficients and their standard errors. Mask insignificant t-values with zero. Args: - df (pd.DataFrame): Dataframe containing columns with coefficients (prefixed with "b") and standard errors (prefixed with "se"). - alpha (float): Significance level. Default is 0.05 (95% confidence). Returns: - pd.DataFrame: A new dataframe with coefficients and t-values, where insignificant t-values are set to zero. """ coefficient_cols = [col for col in df.columns if col.startswith("beta")] se_cols = [col for col in df.columns if col.startswith("std")] # Check if the number of coefficient columns matches the number of standard error columns if len(coefficient_cols) != len(se_cols): raise ValueError("Mismatch in number of coefficient and standard error columns.") # Calculate t-values for coeff_col, se_col in zip(coefficient_cols, se_cols): t_value_col = f"t_{coeff_col}" df[t_value_col] = df[coeff_col] / df[se_col] # Calculate degrees of freedom (assuming we're in the context of linear regression) # df - number of predictors - 1 degrees_of_freedom = len(df) - len(coefficient_cols) - 1 # Calculate critical t-value from the t-distribution critical_t_value = stats.t.ppf(1 - alpha/2, degrees_of_freedom) # Mask where t-values are insignificant insignificant_mask = df.filter(like="t_").abs().le(critical_t_value) # Set t-values to zero where they are insignificant for t_value_col in df.filter(like="t_").columns: df.loc[insignificant_mask[t_value_col], t_value_col] = 0 return df
from io import StringIO from plum import dispatch from .et import ET from .empty import empty_svg_string class SVG: @dispatch def __init__(self, figurename: str, filename=None) -> None: if filename is not None: self.et = ET.parse(filename) else: self.et = ET.parse(StringIO(empty_svg_string)) for index in [ "docname", "sodipodi:docname", "{http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd}docname", "export-filename", "inkscape:export-filename", "{http://www.inkscape.org/namespaces/inkscape}export-filename", ]: self.et.getroot().attrib.pop(index, None) self.et.getroot().set("sodipodi:docname", f"{figurename}.svg") self.et.getroot().set("inkscape:export-filename", f"{figurename}.pdf") def __getitem__(self, id): try: return self.et.findall(f""".//*[@id="{id}"]""")[0] except: raise Exception(f'Element with id "{id}" not found in tree {self}') def add_grid(self, grid): self["namedview1"].append(grid) def add_layer(self, id, label): element = ET.Element( "svg:g", attrib={ "inkscape:label": label, "inkscape:groupmode": "layer", "id": id, }, ) self.et.getroot().append(element) def add_group(self, insert_id, group_id, group_label=None): attrib = { "id": group_id, } if group_label is not None: attrib["inkscape:label"] = group_label element = ET.Element("svg:g", attrib=attrib) self[insert_id].append(element) def element_remove(self, id): parent_map = {c: p for p in self.et.iter() for c in p} child = self[id] parent = parent_map[child] parent.remove(child) def element_vacate(self, id): parent = self[id] for child in list(parent): parent.remove(child) def write_to(self, filename): ET.indent(self.et, space=4 * " ", level=0) with open(filename, "wb") as f: self.et.write(f, encoding="utf-8", xml_declaration=True)
import 'package:flutter_widget/flutter_widget.dart'; class AppScaffold extends StatelessWidget { final String? path; final Widget? background; final String backButton; final String? package; final double? width; final double? height; final VoidCallback? onClick; const AppScaffold( {super.key, this.path, required this.backButton, this.background, this.width, this.height, this.onClick, this.package}); @override Widget build(BuildContext context) { return SizedBox( width: width, height: height, child: Stack( children: [ background ?? AppIcon( path: path ?? '', width: width, height: height, ), Positioned( top: 45, left: 16, child: GestureDetector( onTap: () { onClick?.call(); }, child: AppIcon( path: backButton, width: 32, height: 32, ), )), Positioned( bottom: 0, left: 12, right: 12, child: Container( height: 20, width: width, decoration: BoxDecoration( border: Border.all( color: context.color.lightGray, ), color: context.color.lightGray, borderRadius: const BorderRadius.only( topLeft: Radius.circular(30), topRight: Radius.circular(30))), ), ) ], ), ); } }
import asyncio import json import logging import os import platform import random import sys import requests import aiosqlite import discord from discord.ext import commands, tasks from discord.ext.commands import Bot, Context from discord import app_commands from json import JSONDecodeError from helpers import db_manager import exceptions if not os.path.isfile(f"{os.path.realpath(os.path.dirname(__file__))}/config.json"): sys.exit("'config.json' not found! Please add it and try again.") else: with open(f"{os.path.realpath(os.path.dirname(__file__))}/config.json") as file: config = json.load(file) intents = discord.Intents( messages=True, guilds=True, reactions=True, message_content=True ) bot = Bot( command_prefix=commands.when_mentioned_or(config["prefix"]), intents=intents, help_command=None, ) messageCounter = 0 # Setup both of the loggers class LoggingFormatter(logging.Formatter): # Colors black = "\x1b[30m" red = "\x1b[31m" green = "\x1b[32m" yellow = "\x1b[33m" blue = "\x1b[34m" gray = "\x1b[38m" # Styles reset = "\x1b[0m" bold = "\x1b[1m" COLORS = { logging.DEBUG: gray + bold, logging.INFO: blue + bold, logging.WARNING: yellow + bold, logging.ERROR: red, logging.CRITICAL: red + bold, } def format(self, record): log_color = self.COLORS[record.levelno] format = "(black){asctime}(reset) (levelcolor){levelname:<8}(reset) (green){name}(reset) {message}" format = format.replace("(black)", self.black + self.bold) format = format.replace("(reset)", self.reset) format = format.replace("(levelcolor)", log_color) format = format.replace("(green)", self.green + self.bold) formatter = logging.Formatter(format, "%Y-%m-%d %H:%M:%S", style="{") return formatter.format(record) logger = logging.getLogger("discord_bot") logger.setLevel(logging.INFO) # Console handler console_handler = logging.StreamHandler() console_handler.setFormatter(LoggingFormatter()) # File handler file_handler = logging.FileHandler(filename="discord.log", encoding="utf-8", mode="w") file_handler_formatter = logging.Formatter( "[{asctime}] [{levelname:<8}] {name}: {message}", "%Y-%m-%d %H:%M:%S", style="{" ) file_handler.setFormatter(file_handler_formatter) # Add the handlers logger.addHandler(console_handler) logger.addHandler(file_handler) bot.logger = logger async def init_db(): async with aiosqlite.connect( f"{os.path.realpath(os.path.dirname(__file__))}/database/database.db" ) as db: with open( f"{os.path.realpath(os.path.dirname(__file__))}/database/schema.sql" ) as file: await db.executescript(file.read()) await db.commit() """ Create a bot variable to access the config file in cogs so that you don't need to import it every time. The config is available using the following code: - bot.config # In this file - self.bot.config # In cogs """ bot.config = config async def initialize_counter() -> None: """ Initialize the message counter. """ return await db_manager.initialize_counter() async def initialize_message_counter() -> None: """ Initialize the message counter post bot reboot. """ return await db_manager.initialize_message_counter() @bot.event async def on_ready() -> None: """ The code in this event is executed when the bot is ready. """ bot.logger.info(f"Logged in as {bot.user.name}") bot.logger.info(f"discord.py API version: {discord.__version__}") bot.logger.info(f"Python version: {platform.python_version()}") bot.logger.info(f"Running on: {platform.system()} {platform.release()} ({os.name})") bot.logger.info("-------------------") status_task.start() if await initialize_counter() is False: bot.logger.info( "Counter already initialized, going at " + str(await db_manager.get_counter()) ) else: bot.logger.info( "Counter initialized successfully, going at " + str(await db_manager.get_counter()) ) if await initialize_message_counter() is False: bot.logger.info( "Message counter already initialized, reset to " + str(await db_manager.get_message_counter()) ) spam_task.start() else: bot.logger.info( "Message counter initialized successfully at " + str(await db_manager.get_message_counter()) ) spam_task.start() if config["sync_commands_globally"]: bot.logger.info("Syncing commands globally...") await bot.tree.sync() @tasks.loop(minutes=1.0) async def status_task() -> None: """ Setup the game status task of the bot. """ statusList = await db_manager.get_states() statuses = [] for status in statusList: statuses.append(status[0]) await bot.change_presence(activity=discord.Game(random.choice(statuses))) @tasks.loop(hours=6.0) async def spam_task() -> None: """ Send a random message from the memories database every hour """ messagesPastReboot = await db_manager.get_message_counter() if messagesPastReboot != 0: memoryList = await db_manager.get_memories() memory = random.choice(memoryList) await bot.get_channel(1081029031316692994).send(memory[0]) @bot.event async def on_message(message: discord.Message) -> None: """ The code in this event is executed every time someone sends a message, with or without the prefix :param message: The message that was sent. """ if message.author == bot.user or message.author.bot: return # randomize a number from 0 to 1 messageCounter = await db_manager.get_counter() randomnum = random.random() messageLog = ( str(message.author) + ": " + str(message.content) + " -> " + str(randomnum) ) print(messageLog) # check if the number is under 0.5% or over 99.5% if randomnum < 0.005 or randomnum > 0.995: # check if the message is not empty if message.content != "": # if it isn't, add message to the memories database reactions = ["✍️", "🤔", "👀", "👍"] await message.add_reaction(random.choice(reactions)) await db_manager.add_memory(message.content, message.author.id) # check if the message mentions the bot, # replies to the bot, # or if the number is under 2% if ( randomnum < 0.02 or bot.user in message.mentions or ( message.reference is not None and message.reference.resolved.author == bot.user ) ): # if it meets those conditions, reply a random message from the memories database memoryList = await db_manager.get_memories() memory = random.choice(memoryList) await message.reply(memory[0]) await db_manager.reset_counter() return else: await db_manager.increase_counter() # legacy e n faz absolutamente nada mas cba mudar await db_manager.increase_message_counter() await bot.process_commands(message) @bot.event async def on_command_completion(context: Context) -> None: """ The code in this event is executed every time a normal command has been *successfully* executed. :param context: The context of the command that has been executed. """ full_command_name = context.command.qualified_name split = full_command_name.split(" ") executed_command = str(split[0]) if context.guild is not None: bot.logger.info( f"Executed {executed_command} command in {context.guild.name} (ID: {context.guild.id}) by {context.author} (ID: {context.author.id})" ) else: bot.logger.info( f"Executed {executed_command} command by {context.author} (ID: {context.author.id}) in DMs" ) @bot.event async def on_command_error(context: Context, error) -> None: """ The code in this event is executed every time a normal valid command catches an error. :param context: The context of the normal command that failed executing. :param error: The error that has been faced. """ if isinstance(error, commands.CommandOnCooldown): await context.send("matate") elif isinstance(error, exceptions.UserBlacklisted): """ The code here will only execute if the error is an instance of 'UserBlacklisted', which can occur when using the @checks.not_blacklisted() check in your command, or you can raise the error by yourself. """ embed = discord.Embed(description="olha o burro", color=0xE02B2B) await context.send(embed=embed) if context.guild: bot.logger.warning( f"{context.author} (ID: {context.author.id}) tried to execute a command in the guild " f"{context.guild.name} (ID: {context.guild.id}), but the user is blacklisted from using the bot." ) else: bot.logger.warning( f"{context.author} (ID: {context.author.id}) tried to execute a command in the bot's DMs, but the " f"user is blacklisted from using the bot." ) elif isinstance(error, exceptions.UserNotOwner): """ Same as above, just for the @checks.is_owner() check. """ embed = discord.Embed(description="deve ser deve", color=0xE02B2B) await context.send(embed=embed) if context.guild: bot.logger.warning( f"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the guild " f"{context.guild.name} (ID: {context.guild.id}), but the user is not an owner of the bot." ) else: bot.logger.warning( f"{context.author} (ID: {context.author.id}) tried to execute an owner only command in the bot's DMs, " f"but the user is not an owner of the bot." ) elif isinstance(error, commands.MissingPermissions): embed = discord.Embed( description="nao porque falta-te`" + ", ".join(error.missing_permissions) + "` agora matate", color=0xE02B2B, ) await context.send(embed=embed) elif isinstance(error, commands.BotMissingPermissions): embed = discord.Embed( description="ganda burro da me`" + ", ".join(error.missing_permissions) + "`", color=0xE02B2B, ) await context.send(embed=embed) elif isinstance(error, commands.MissingRequiredArgument): embed = discord.Embed( title="olha foda se", # We need to capitalize because the command arguments have no capital letter in the code. description=str(error).capitalize(), color=0xE02B2B, ) await context.send(embed=embed) else: raise error @bot.tree.context_menu(name="Parar de dizer isto") async def remove_memory(interaction: discord.Interaction, message: discord.Message): """ Parar de dizer uma frase. :param interaction: The interaction that triggered the command. :param message: The message to remove. """ if "bruno aleixo" not in [role.name for role in interaction.user.roles]: message = "nao nao!!! nao tens o role do bruno aleixo!!! nao nao nao podes nao podes!!!" tauas = await interaction.response.send_message(message, ephemeral=True) return if message.content == "": message = "boa e a mensagem tá onde burro de merda" tauas = await interaction.response.send_message( message, file=discord.File("E_ca_burro.mp4"), ephemeral=True ) return if await db_manager.is_memory(message.content) is False: message = "eu nem digo essa merda seu burro" tauas = await interaction.response.send_message(message, ephemeral=True) return await db_manager.remove_memory(message.content) message = "isguici 🗿" await interaction.response.send_message(message, ephemeral=True) @bot.tree.context_menu(name="Tweetar") async def tweet(interaction: discord.Interaction, message: discord.Message): """ Tweetar a foto :param interaction: The interaction that triggered the command. :param message: The message that triggered the command. """ # Check if the person who sent the message has the "bruno aleixo" role if "bruno aleixo" not in [role.name for role in interaction.user.roles]: message = "nao nao!!! nao tens o role do bruno aleixo!!! nao nao nao podes nao podes!!!" tauas = await interaction.response.send_message(message) return image = "" # Check if the message has an attachment if not message.attachments: # Check if the message has a gif or if it comes from tenor if ".gif" in message.content: image = message.content.split(" ")[-1] # Check if the gif is from tenor if "tenor.com" in image: # Append the .gif to the end of the url image += ".gif" else: image = message.content.split("?")[0] else: message = "boa e a foto tá onde burro de merda" tauas = await interaction.response.send_message( message, file=discord.File("E_ca_burro.mp4") ) return else: image = message.attachments[0].url # Send a message to the channel saying that the bot is processing the image message = "1 sec <a:fomeca:1152686416048951447>" tauas = await interaction.response.send_message(message) # edit the message to say that the bot is uploading the image # Grab the image from the message # Create an object with the image url imagejson = {"url": image} # Send a post request to the api (port 5000) with the image response = requests.post( "http://localhost:5000/imagemquepodespostar", json=imagejson ) tauas = await interaction.original_response() # Check if the request went wrong if response.status_code >= 500 or response.status_code >= 400: # From the user side if response.status_code == 400: # If the error was "Invalid file format" if response.json()["error"] == "Invalid file format": await tauas.edit( content="só posso comer gifs, fotos (jpg, png, webp) ou vids (mp4) <:emomi:1107452473523834892>" ) return # If the error was "Invalid file size" elif response.json()["error"] == "File size too large": await tauas.edit( content="muito pesado <:emomi:1107452473523834892> só posso comer até 15 MB <:emomi:1107452473523834892>" ) return # If the error was "Rate limited" elif response.status_code == 429: await tauas.edit(content="estou rate limited <:emomi:1107452473523834892>") return # From the server side elif response.status_code >= 500: if response.status_code == 503: await tauas.edit( content="man imagina o twitter disse me que borrou se todo mas acho que ele tweetou na mesma, checka pff" ) return # If the error does not have a json response (it's a server error) try: test = response.json() except JSONDecodeError: await tauas.edit( content="algo deu merda no server <:emomi:1107452473523834892>" ) return # If the error was "Unable to upload media" if test["error"] == "Unable to upload media": await tauas.edit( content="n consegui dar upload <:emomi:1107452473523834892>" ) return # Get the response from the api response = response.json() # If everything went well, grab the tweet url tweeturl = response["post"] # Send the tweet url to the channel message = f"boa {tweeturl}" await tauas.edit(content=message) return async def load_cogs() -> None: """ The code in this function is executed whenever the bot will start. """ for file in os.listdir(f"{os.path.realpath(os.path.dirname(__file__))}/cogs"): if file.endswith(".py"): extension = file[:-3] try: await bot.load_extension(f"cogs.{extension}") bot.logger.info(f"Loaded extension '{extension}'") except Exception as e: exception = f"{type(e).__name__}: {e}" bot.logger.error(f"Failed to load extension {extension}\n{exception}") asyncio.run(init_db()) asyncio.run(load_cogs()) bot.run(config["token"])
import * as parsers from '../parsers'; describe('JSON Parsing', () => { it('pareses JSON object and remaps _message and _ts', () => { const lineObject = { lineNo: 12, offset: 25, line: JSON.stringify({ message: 'Hello world', timestamp: '2021-03-18T03:59:52.017Z', }), }; const parsed = parsers.parseJson(lineObject, { message: 'message', timestamp: 'timestamp', }); // console.log(parsed) expect(parsed._message).toBe('Hello world'); expect(parsed.lineNo).toBe(12); expect(parsed.timestamp).toBe('2021-03-18T03:59:52.017Z'); }); it('if unable to parse JSON renders JSON text', () => { const lineObject = { lineNo: 12, offset: 25, line: JSON.stringify({ message: 'Hello world', timestamp: '2021-03-18T03:59:52.017Z', }).substring(0, 25), }; const parsed = parsers.parseJson(lineObject, { message: 'message', timestamp: 'timestamp', }); // console.log(parsed) expect(parsed._message).toBe(lineObject.line); expect(parsed.lineNo).toBe(12); expect(parsed.timestamp).toBeUndefined(); }); it('if unable to find mapping for _message renders JSON text', () => { const lineObject = { lineNo: 12, offset: 25, line: JSON.stringify({ message: 'Hello world', timestamp: '2021-03-18T03:59:52.017Z', }), }; const parsed = parsers.parseJson(lineObject, { message: 'message_name', timestamp: 'timestamp', }); // console.log(parsed) expect(parsed._message).toBe(lineObject.line); expect(parsed.lineNo).toBe(12); expect(parsed.timestamp).toBe('2021-03-18T03:59:52.017Z'); }); }); describe('Text Parsing', () => { it('simplest case returns the same line', () => { const lineObject = { lineNo: 12, offset: 25, line: 'Hello world', }; const parsed = parsers.parsePlainText(lineObject, {}, 'ISO'); expect(parsed._message).toBe('Hello world'); }); it('extract key value pairs', () => { const lineObject = { lineNo: 12, offset: 25, line: 'Hello world time=12sec cpu=21', }; const parsed = parsers.parsePlainText( lineObject, { extractKeyValue: true, }, 'ISO' ); expect(parsed._message).toBe(lineObject.line); expect(parsed.time).toBe('12sec'); expect(parsed.cpu).toBe('21'); }); it('extract timestamp', () => { const lineObject = { lineNo: 12, offset: 25, line: '2021-03-18T03:59:52.017Z Hello world time=12sec cpu=21', }; const parsed = parsers.parsePlainText( lineObject, { timestampPattern: '^.{24}', extractKeyValue: true, }, 'ISO' ); expect(parsed._message).toBe('Hello world time=12sec cpu=21'); expect(parsed.time).toBe('12sec'); expect(parsed.cpu).toBe('21'); expect(parsed._ts).toBe('2021-03-18T03:59:52.017Z'); }); it('extract timestamp complex regexp', () => { const lineObject = { lineNo: 12, offset: 25, line: '2021-03-18T03:59:52.017Z - Hello world time=12sec cpu=21', }; const parsed = parsers.parsePlainText( lineObject, { timestampPattern: '^(.{24}) -', extractKeyValue: true, }, 'ISO' ); expect(parsed._message).toBe('Hello world time=12sec cpu=21'); expect(parsed.time).toBe('12sec'); expect(parsed.cpu).toBe('21'); expect(parsed._ts).toBe('2021-03-18T03:59:52.017Z'); }); it('extract timestamp ignores dates that cannot be parsed', () => { const lineObject = { lineNo: 12, offset: 25, line: 'this line does not have a date - Hello world time=12sec cpu=21', }; const parsed = parsers.parsePlainText( lineObject, { timestampPattern: '^(.{24}) -', extractKeyValue: true, }, 'ISO' ); expect(parsed._message).toBe( 'this line does not have a date - Hello world time=12sec cpu=21' ); expect(parsed.time).toBe('12sec'); expect(parsed.cpu).toBe('21'); expect(parsed._ts).toBeFalsy(); }); });
<template> <div> <section class="vh-100" style="background-color: #eee;"> <div class="container h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-lg-12 col-xl-11"> <div class="card text-black" style="border-radius: 25px;"> <div class="card-body p-md-5"> <div class="row justify-content-center"> <div class="col-md-10 col-lg-6 col-xl-5 order-2 order-lg-1"> <p class="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4 font1">Sign up</p> <form class="mx-1 mx-md-4"> <!-- <div class="row"> <div class="col-12"> <div class="mb-3 d-flex flex-column"> <img :src="`${previewImage}`" alt="" style="width: 100px; height: 100px;" class="rounded-circle mx-auto"> <div class="form-text" style="margin: 5px 0px 5px 5px; font-size: medium;">Your photo</div> <div class="input-group"> <input class="form-control rounded-4" type="file" ref="fileInput" @input="pickFile" > </div> </div> </div> </div> --> <div class="d-flex flex-row align-items-center mb-4"> <div class="form-outline flex-fill mb-0"> <input required type="text" id="form3Example1c" class="form-control" v-model="name" /> <label class="form-label" style="color: #94979c;" for="form3Example1c">Your Name</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <div class="form-outline flex-fill mb-0"> <input required type="email" id="form3Example3c" class="form-control" v-model="email" /> <label class="form-label" style="color: #94979c;" for="form3Example3c">Your Email</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <div class="form-outline flex-fill mb-0"> <input required type="text" id="form3Example5c" class="form-control" v-model="tel" /> <label class="form-label" style="color: #94979c;" for="form3Example3c">Your phone number</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <div class="form-outline flex-fill mb-0"> <input required type="password" id="form3Example6c" class="form-control" v-model="password" /> <label class="form-label" style="color: #94979c;" for="form3Example4c">Password</label> </div> </div> <div class="d-flex flex-row align-items-center mb-4"> <div class="form-outline flex-fill mb-0"> <input required type="password" id="form3Example4cd" class="form-control" v-model="Conpassword" /> <label class="form-label" style="color: #94979c;" for="form3Example4cd">Repeat your password</label> </div> </div> <div class="form-check d-flex justify-content-center mb-5"> <label class="form-check-label" for="form2Example3"> <input class="form-check-input me-2" type="checkbox" value="" id="form2Example3c" /> I agree all statements in <a href="#!">Terms of service</a> </label> </div> <div class="d-flex justify-content-center mx-4 mb-3 mb-lg-4"> <button type="button" class="btn btn-primary btn-lg" @click="register()">Register</button> </div> </form> </div> <div class="col-md-10 col-lg-6 col-xl-7 d-flex align-items-center justify-content-center order-1 order-lg-2"> <img src="~/static/logo.png" class="img-fluid" alt="Sample image"> </div> </div> </div> </div> </div> </div> </div> </section> </div> </template> <script> // CommonJS const Swal = require('sweetalert2') export default{ data() { return { name: "", email: "", password: "", Conpassword: "", // previewImage: "", tel: "", } }, methods: { register() { if (this.password === this.Conpassword) { // เปลี่ยน "==" เป็น "===" const axios = require('axios'); let data = JSON.stringify({ "Username": this.name, "Password": this.password, "Email": this.email, "tel": this.tel, // "img": this.previewImage }); let config = { method: 'post', url: 'https://twotsneaker.onrender.com/register', headers: { 'Content-Type': 'application/json' }, data: data }; axios.request(config) .then((response) => { console.log("register >>>>", JSON.stringify(response.data)); Swal.fire({ position: 'center', icon: 'success', title: 'Sign up successfully!', showConfirmButton: true, }).then((result) => { if (result.isConfirmed) { window.location = '/login'; } }); }) .catch((error) => { Swal.fire({ title: 'มีบางอย่างผิดปกติ', text: "ระบบขัดข้อง", icon: 'warning', confirmButtonColor: '#3085d6', }); console.log(error); }); } else { // เพิ่มโค้ดสำหรับกรณีที่รหัสผ่านไม่ตรงกัน Swal.fire({ title: 'รหัสผ่านไม่ตรงกัน', text: 'กรุณาตรวจสอบรหัสผ่านอีกครั้ง', icon: 'error', }); } }, pickFile () { let input = this.$refs.fileInput let file = input.files if (file && file[0]) { let reader = new FileReader reader.onload = e => { this.previewImage = e.target.result console.log(this.previewImage) } reader.readAsDataURL(file[0]) this.$emit('input', file[0]) } }, } } </script>
'use client'; import Line from './Line'; import Marker from './Marker'; import Points from './Points'; import { useRef, useContext, CSSProperties } from 'react'; import { useDimensions } from 'webrix/hooks'; import { Context } from '../Context'; type GraphProps = { data: WeatherData; }; const Graph = ({ data }: GraphProps) => { const { active, setActive, selectedDay, selectedCondition, graphColor } = useContext(Context) || { active: { path: 0, point: 0 }, setActive: () => {}, selectedDay: 0, selectedCondition: 'tempature', graphColor: '#f7d500', }; const graph = useRef<HTMLDivElement | null>(null); const { width, height } = useDimensions(graph); const maxLimit = Math.min(...data[selectedDay][selectedCondition]) < 0 ? Math.max(...data[selectedDay][selectedCondition]) + Math.abs(Math.min(...data[selectedDay][selectedCondition])) + 2 : Math.max(...data[selectedDay][selectedCondition]) + 2; const range = [0, maxLimit]; return ( <div className="px-6 sm:px-0"> <div className="graph mb-32" ref={graph}> <Marker colors={[graphColor]} data={[data[selectedDay][selectedCondition]]} active={active} width={width} height={height} range={range} /> <svg viewBox={`0 ${range[0]} 100 ${range[1]}`} preserveAspectRatio="none"> {/* {data && <Line path={[data[selectedDay][selectedCondition]][0]} color={graphColor} />} */} {data && <Line path={[data[selectedDay][selectedCondition]][0]} color={graphColor} />} </svg> <div className="labels"> {data[selectedDay].hours.map((label, i) => ( <div key={label} style={ { '--x': `${(i * width) / (data[selectedDay].hours.length - 1)}px`, '--y': `0px`, } as CSSProperties } className="text-white text-sm font-medium font-inter" > {String(label).length !== 2 ? '0' + label : label} <span className="hidden sm:inline">:00</span> </div> ))} </div> <Points data={[data[selectedDay][selectedCondition]]} width={width} height={height} setActive={setActive} range={range} /> </div> </div> ); }; export default Graph;
package com.schemafactor.rogueserver.entities.monsters; import java.util.List; import com.schemafactor.rogueserver.common.Constants; import com.schemafactor.rogueserver.common.Position; import com.schemafactor.rogueserver.dungeon.Dungeon; import com.schemafactor.rogueserver.entities.Entity; import com.schemafactor.rogueserver.entities.monsters.Monster.States; public class Zombie extends Monster { private static final long serialVersionUID = 1L; /** Creates a new instance of the Zombie */ public Zombie(String name, Position startposition) { super(name, startposition, entityTypes.MONSTER, Constants.CHAR_MONSTER_ZOMBIE, 1000f, 30f, 200); } @Override public void takeAction() { boolean moved = false; if (target != null) { if (target.isInvisible) { State = States.IDLE; } if (target.getRemoved()) // Target disconnected, or was removed/killed { target = null; State = States.IDLE; } } switch (State) { case IDLE: { // Is a Human entity nearby? List<Entity> nearby = Dungeon.getInstance().getEntitiesRange(this, 5); List<Entity> nearby_humans = Dungeon.getInstance().getEntitiesType(this, entityTypes.CLIENT, nearby); if (nearby_humans.size() == 0) // All clear, keep idling { State = States.IDLE; } else // Attack! { target = nearby_humans.get(0); State = States.CHASING; } break; } case WANDERING: // Never { State = States.IDLE; } case CHASING: { byte chase_direction = getPathDirectionTo(target, 10); if (chase_direction == Constants.DIRECTION_NONE) // Gone, or other level { State = States.IDLE; } moved = attemptMove(chase_direction); double target_distance = distanceTo(target); if (target_distance <= 1.5d) { State = States.ATTACKING; break; } if (distanceTo(target) > 10) // Too far (just off screen...) { State = States.IDLE; } break; } case ATTACKING: { byte attack_direction = getDirectionTo(target); if (attack_direction == Constants.DIRECTION_NONE) // Gone, or other level { State = States.IDLE; break; } moved = attemptAttack(attack_direction); if (distanceTo(target) > 1.5d) { State = States.CHASING; } break; } case RETREATING: { State = States.IDLE; // Never retreat! } } finishMove(moved); } }
import { Injectable } from '@angular/core'; import { ISanpham } from './isanpham'; @Injectable({ providedIn: 'root' }) export class SanPhamService { constructor() { } products:ISanpham[] = [ { id:1, tensp:'Leaf Rake', code: 'GDN-0011', giasp:19.95, mota:'Leaf rake with 48-inch wooden handle', urlImage:'http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png', ngay:'March 19, 2016', starRate:3.2 }, { id:2, tensp:'Garden Cart', code: 'GDN-0023', giasp:32.99, mota:'15 gallon capacity rolling garden cart', urlImage:'http://openclipart.org/image/300px/svg_to_png/58471/garden_cart.png', ngay:'March 18, 2016', starRate:4.2 }, { id:5, tensp:'Hammer', code: 'TBX-0048', giasp:8.9, mota:'Curved claw steel hammer', urlImage:'http://openclipart.org/image/300px/svg_to_png/73/rejon_Hammer.png', ngay:'May 21, 2016', starRate:3.8 }, { id:8, tensp:'Saw', code: 'TBX-0022', giasp:11.55, mota:'15-inch steel blade hand saw', urlImage:'http://openclipart.org/image/300px/svg_to_png/27070/egore911_saw.png', ngay:'May 15, 2016', starRate:3.7 }, { id:10, tensp:'Video Game Controller', code: 'GMG-0042', giasp:35.95, mota:'Standard two-button video game controller', urlImage:'http://openclipart.org/image/300px/svg_to_png/120337/xbox-controller_01.png', ngay:'October 15, 2015', starRate:4.6 }, ] getSanPham(){ return this.products; } getMotSanPham(id:number=0){ return this.products.find(sp => sp.id==id); } themSanPham(sp:ISanpham=<ISanpham>{}){ this.products.push(sp); } capnhatSanPham(sp:ISanpham=<ISanpham>{}){ let index = this.products.findIndex(p => p.id === sp.id); this.products[index]=sp; } xoaSanPham(id:number=0){ let index = this.products.findIndex(p => p.id == id); this.products.splice(index); } // xoaSanPham(index: number) { // this.products.splice(index, 1); // } }
import { RefreshCategoriesSingletonService } from './../../services/refresh-categories-singleton.service'; import { CategoryService } from './../../services/category.service'; import { lastValueFrom } from 'rxjs'; import { Component, Input } from '@angular/core'; @Component({ selector: 'app-create-category-modal', templateUrl: './create-category-modal.component.html', styleUrl: './create-category-modal.component.css', }) export class CreateCategoryModalComponent { @Input() visible: boolean = false; public catName: String; public errorMessage: String; constructor( private categoryService: CategoryService, private refreshCategoriesSingletonService: RefreshCategoriesSingletonService ) {} showDialog() { this.visible = true; } async addCategory() { try { await lastValueFrom(this.categoryService.createCategory(this.catName)); } catch (e: any) { this.errorMessage = e.error.message; } finally { this.visible = false; this.refreshCategoriesSingletonService.sendMessage({ refresh: true }); this.catName = ''; } } }
{% load static %} <!doctype html> <html lang="en"> <head> {% block meta %} <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% endblock %} {% block extra_meta %} {% endblock %} {% block corecss %} <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="{% static 'css/base.css' %}"> {% endblock %} {% block extra_css %} {% endblock %} {% block corejs %} <script src="https://kit.fontawesome.com/7216a39cef.js" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> {% endblock %} {% block extra_js %} {% endblock %} <title>PokeMerchMania {% block extra_title %}{% endblock %}</title> </head> <body> <header class="container-fluid fixed-top"> <div id="topnav" class="row bg-white pt-lg-2 d-none d-lg-flex"> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0 text-center text-lg-left"> <a href="{% url 'home' %}" class="nav-link main-logo-link main-color"> <h2 class="logo-font my-0 main-color"><strong>PokeMerchMania</strong></h2> </a> </div> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <form method="GET" action="{% url 'products' %}"> <div class="input-group w-100"> <input class="form-control border-color" type="text" name="q" placeholder="Search our website"> <div class="input-group-append"> <button class="form-control btn btn-red border-color" type="submit"> <span class="icon"> <i class="fas fa-search"></i> </span> </button> </div> </div> </form> </div> <div class="col-12 col-lg-4 my-auto py-1 py-lg-0"> <ul class="list-inline list-unstyled text-center text-lg-right my-0"> <li class="list-inline-item dropdown"> <a class="text-dark nav-link main-color" href="#" id="user-options" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <div class="text-center"> <div><i class="fas fa-user fa-lg main-color"></i></div> <p class="my-0 main-color">My Account</p> </div> </a> <div class="dropdown-menu border-0" aria-labelledby="user-options"> {% if request.user.is_authenticated %} {% if request.user.is_superuser %} <a href="" class="dropdown-item main-color">Manage Products</a> {% endif %} <a href="" class="dropdown-item main-color">My Profile</a> <a href="{% url 'account_logout' %}" class="dropdown-item main-color">Logout</a> {% else %} <a href="{% url 'account_signup' %}" class="dropdown-item main-color">Signup</a> <a href="{% url 'account_login' %}" class="dropdown-item main-color">Login</a> {% endif %} </div> </li> <li class="list-inline-item"> <a class="{% if grand_total %}text-info font-weight-bold{% else %}text-dark{% endif %} nav-link basket-icon" href="{% url 'view_bag' %}"> <div class="text-center"> <div><i class="fas fa-shopping-bag fa-lg basket-icon"></i></div> <p class="my-0 basket-icon"> {% if grand_total %} €{{ grand_total|floatformat:2 }} {% else %} €0.00 {% endif %} </p> </div> </a> </li> </ul> </div> </div> <div class="row bg-white"> <nav class="navbar navbar-expand-lg w-100"> <li class="list-inline-item"> <a href="{% url 'home' %}" class="nav-link main-logo-link d-lg-none main-color"> <h2 class="logo-font my-0 main-color"><strong>PokeMerchMania</strong></h2> </a> </li> <button class="navbar-toggler navbar-light main-color" type="button" data-toggle="collapse" data-target="#main-nav" aria-controls="main-nav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon main-color"></span> </button> {% include 'includes/mobile-top-header.html' %} {% include 'includes/main-nav.html' %} </nav> </div> <div id="delivery-banner" class="row text-center"> <h4 class="py-1 w-100 delivery-text text-uppercase">Free delivery on orders over €{{ free_delivery_threshold }}!</h4> </div> </header> {% if messages %} <div class="message-container"></div> {% endif %} {% block page_header %} {% endblock %} {% block content %} {% endblock %} {% block postloadjs %} {% endblock %} </body> </html>
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.neworin.layoutweightdemo.MainActivity"> <!--1,LinearLayout中的layout_weight属性,首先按照控件声明的尺寸进行分配, 然后再按照剩下的空间按weight进行分配--> <LinearLayout android:layout_width="match_parent" android:layout_height="100dp" android:baselineAligned="false" android:orientation="horizontal"> <TextView android:layout_width="0dp" android:layout_height="48dp" android:layout_weight="1" android:background="#44ff0000" android:gravity="center" android:text="11111111111111" android:textSize="16sp" /> <TextView android:layout_width="0dp" android:layout_height="48dp" android:layout_weight="2" android:background="#4400ff00" android:gravity="center" android:text="2" android:textSize="16sp" /> <TextView android:layout_width="0dp" android:layout_height="48dp" android:layout_weight="3" android:background="#440000ff" android:gravity="center" android:text="3" android:textSize="16sp" /> </LinearLayout> <!--2,layout_weight,首先减去控件所声明的尺寸,剩下的尺寸按比例分配--> <!--尺寸=控件宽度+父控件剩余尺寸*比例--> <LinearLayout android:layout_width="match_parent" android:layout_height="100dp" android:orientation="horizontal"> <TextView android:layout_width="match_parent" android:layout_height="48dp" android:layout_weight="1" android:background="#44ff0000" android:gravity="center" android:text="11111111111111" android:textSize="16sp" /> <TextView android:layout_width="match_parent" android:layout_height="48dp" android:layout_weight="2" android:background="#4400ff00" android:gravity="center" android:text="2" android:textSize="16sp" /> <TextView android:layout_width="match_parent" android:layout_height="48dp" android:layout_weight="2" android:background="#440000ff" android:gravity="center" android:text="3" android:textSize="16sp" /> </LinearLayout> </LinearLayout>
package Pod::WSDL2::Type; use strict; use warnings; our $VERSION = "0.08"; use Pod::WSDL2::Attr; # use Pod::WSDL2::Utils qw(:writexml :namespaces :types); use base("Class::Accessor::Fast"); __PACKAGE__->mk_ro_accessors(qw(attrs descr wsdlName name reftype)); __PACKAGE__->mk_accessors(qw(array)); sub new { my ($pkg, %data) = @_; die "A type needs a name, died" unless $data{name}; my $wsdlName = $data{name}; $wsdlName =~ s/(?:^|::)(.)/uc $1/eg; my $me = bless { name => $data{name}, wsdlName => ucfirst $wsdlName, array => $data{array} || 0, attrs => $data{attrs} || [], descr => $data{descr} || '', reftype => $data{reftype} || 'HASH', }, $pkg; $me->_initPod($data{pod}) if $data{pod}; return $me; } sub _initPod { my $me = shift; my $pod = shift; my @data = split "\n", $pod; # Preprocess wsdl pod: trim all lines and concatenate lines not # beginning with wsdl type tokens to previous line. # Ignore first element, if it does not begin with wsdl type token. for (my $i = $#data; $i >= 0; $i--) { if ($data[$i] !~ /^\s*(?:_ATTR|_REFTYPE)/i) { if ($i > 0) { $data[$i - 1] .= " $data[$i]"; $data[$i] = ''; } } } for (@data) { s/\s+/ /g; s/^ //; s/ $//; if (/^\s*_ATTR\s+/i) { push @{$me->{attrs}}, new Pod::WSDL2::Attr($_); } elsif (/^\s*_REFTYPE\s+(HASH|ARRAY)/i) { $me->reftype(uc $1); } } } 1; __END__ =head1 NAME Pod::WSDL2::Type - Represents a type in Pod::WSDL2 (internal use only) =head1 SYNOPSIS use Pod::WSDL2::Type; my $type = new Pod::WSDL2::Param(name => 'My::Foo', array => 0, descr => 'My foo bars'); =head1 DESCRIPTION This module is used internally by Pod::WSDL2. It is unlikely that you have to interact directly with it. If that is the case, take a look at the code, it is rather simple. =head1 METHODS =head2 new Instantiates a new Pod::WSDL2::Type. =head3 Parameters =over 4 =item name - name of the type, something like 'string', 'boolean', 'My::Foo' etc. =item array - if true, an array of the type is used (defaults to 0) =item descr - description of the type =item pod - the wsdl pod of the type. Please see the section "Pod Syntax" in the description of Pod::WSDL2. =back =head2 writeComplexType Write complex type element for XML output. Takes one parameter: ownTypes, reference to hash with own type information =head1 EXTERNAL DEPENDENCIES [none] =head1 EXAMPLES see Pod::WSDL2 =head1 BUGS see Pod::WSDL2 =head1 TODO see Pod::WSDL2 =head1 SEE ALSO Pod::WSDL2 :-) =head1 AUTHOR Tarek Ahmed, E<lt>bloerch -the character every email address contains- oelbsk.orgE<gt> =head1 COPYRIGHT AND LICENSE Copyright (C) 2006 by Tarek Ahmed This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.5 or, at your option, any later version of Perl 5 you may have available. =cut
import * as React from 'react'; import { Table, Thead, Tbody, Tfoot, Tr, Th, Td, TableCaption, TableContainer } from '@chakra-ui/react'; // TYPE type Props = { wins: number; losses: number; draws: number; }; export const StatusTable = ({ wins, losses, draws }: Props) => { return ( <TableContainer w="100%"> <Table variant="simple" fontSize="xl"> <Tbody> <Tr> <Td>Total Games</Td> <Td isNumeric>{wins + losses + draws}</Td> </Tr> <Tr> <Td>Wins</Td> <Td isNumeric color="primary"> {wins} </Td> </Tr> <Tr> <Td>Losses</Td> <Td isNumeric color="secondary"> {losses} </Td> </Tr> <Tr> <Td>Draws</Td> <Td isNumeric>{draws}</Td> </Tr> </Tbody> <Tfoot> <Tr> <Th>Win rate</Th> <Th isNumeric>{Math.round((wins / (wins + losses + draws)) * 100)}%</Th> </Tr> </Tfoot> </Table> </TableContainer> ); };
using Entities.Models; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using DataAccessLayer.Constants; namespace DataAccessLayer.Configuration; public class StaffConfiguration : IEntityTypeConfiguration<Staff> { public void Configure(EntityTypeBuilder<Staff> builder) { builder.ToTable(TableNames.Staff); builder.HasKey(c => c.Id); builder.Property(c => c.Name).IsRequired(); builder.Property(c => c.Email).IsRequired(); builder.Property(c => c.PhoneNumber).IsRequired(); builder.Property(c => c.Role).IsRequired(); builder .HasMany(c => c.AssessmentPapers) .WithOne(c => c.Staff) .HasForeignKey(c => c.StaffId) .OnDelete(DeleteBehavior.Restrict); builder .HasMany(c => c.RegisterForms) .WithOne(c => c.Staff) .HasForeignKey(c => c.StaffId) .OnDelete(DeleteBehavior.Restrict); builder .HasMany(c => c.DiamondDetails) .WithOne(c => c.Staff) .HasForeignKey(c => c.StaffId) .OnDelete(DeleteBehavior.Restrict); } }
import { createFormSaveDisabledTracker, FormGroupTabHandle, FormTabHandle } from '@admin-ui/common'; import { detailLoading } from '@admin-ui/common/utils/rxjs-loading-operators/detail-loading.operator'; import { EditorTabTrackerService, PermissionsService, RoleOperations } from '@admin-ui/core/providers'; import { RoleDataService } from '@admin-ui/shared'; import { BaseDetailComponent } from '@admin-ui/shared/components'; import { LanguageDataService } from '@admin-ui/shared/providers/language-data'; import { AppStateService } from '@admin-ui/state'; import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core'; import { UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { createNestedControlValidator } from '@gentics/cms-components'; import { AccessControlledType, AnyModelType, GcmsPermission, Index, Language, NormalizableEntityTypesMap, Normalized, PagePrivileges, Raw, Role, RoleBO, RolePermissions, RoleUpdateRequest, TypePermissions, } from '@gentics/cms-models'; import { cloneDeep, isEqual } from 'lodash-es'; import { NGXLogger } from 'ngx-logger'; import { Observable } from 'rxjs'; import { distinctUntilChanged, map, publishReplay, refCount, switchMap, takeUntil, tap, repeat, delay } from 'rxjs/operators'; import { RoleTableLoaderService } from '../../providers'; export enum RoleDetailTabs { PROPERTIES = 'properties', PAGE_PRIVILEGES = 'pagePrivileges', FILE_PRIVILEGES = 'filePrivileges', } // ************************************************************************************************* /** * # RoleDetailComponent * Display and edit entity role detail information */ // ************************************************************************************************* @Component({ selector: 'gtx-role-detail', templateUrl: './role-detail.component.html', styleUrls: [ 'role-detail.component.scss' ], changeDetection: ChangeDetectionStrategy.OnPush, }) export class RoleDetailComponent extends BaseDetailComponent<'role', RoleOperations> implements OnInit { public readonly RoleDetailTabs = RoleDetailTabs; entityIdentifier: keyof NormalizableEntityTypesMap<AnyModelType> = 'role'; /** current entity value */ currentEntity: RoleBO; /** current role permissions */ currentRolePermissions: RolePermissions; /** current languages */ public supportedLanguages$: Observable<Language[]>; private currentLanguagesSorted: Language[] = []; /** form of tab 'Properties' */ fgProperties: UntypedFormControl; fgPropertiesSaveDisabled$: Observable<boolean>; /** form of tab 'Pages' */ fgPagePrivileges: UntypedFormGroup; fgPagePrivilegesSaveDisabled$: Observable<boolean>; private pageLanguagesPrivilegesChildControlNames: string[] = []; pageLanguagesSortedAndRemainingChildControlNames: { id: string, name: string }[] = []; /** form of tab 'Images and Files' */ fgFilePrivileges: UntypedFormGroup; fgFilePrivilegesSaveDisabled$: Observable<boolean> get isLoading(): boolean { return this.currentEntity == null || !this.currentEntity.nameI18n || this.currentEntity.name === ''; } get activeFormTab(): FormTabHandle { return this.tabHandles[this.appState.now.ui.editorTab]; } /** TRUE if logged-in user is allowed to read entity `role` */ permissionRolesRead$: Observable<boolean>; activeTabId$: Observable<string>; private tabHandles: Index<RoleDetailTabs, FormTabHandle>; constructor( logger: NGXLogger, route: ActivatedRoute, router: Router, appState: AppStateService, roleData: RoleDataService, changeDetectorRef: ChangeDetectorRef, private roleOperations: RoleOperations, private languageData: LanguageDataService, private permissionsService: PermissionsService, private editorTabTracker: EditorTabTrackerService, private tableLoader: RoleTableLoaderService, ) { super( logger, route, router, appState, roleData, changeDetectorRef, ); } ngOnInit(): void { super.ngOnInit(); // init language data this.initLanguageData(); // init forms this.initForms(); // assign values and validation of current entity this.currentEntity$.pipe( takeUntil(this.stopper.stopper$), ).subscribe((currentEntity: RoleBO<Raw>) => { this.currentEntity = currentEntity; // fill form with entity property values this.fgPropertiesUpdate(currentEntity); this.changeDetectorRef.markForCheck(); }); this.currentEntity$.pipe( takeUntil(this.stopper.stopper$), tap(_ => { /** * On tab change, the form must be reset to the current state. * This is how discarded changes are typically removed when reentering the previously unselected tab. * * However, role permissions are not part of the entity state and thus refetched every time the entity * state is updated. In order to avoid excessive network requests, we only refetch when the role id * has changed. Nevertheless, this prevents the default procedure that ensures that discarded changes * are actually gone from the UI, when a user revisits the corresponding tab. * * Thus, we always update the form with the role permissions, in case they exist. And then refetch * and update again in case the role id changed. Without going into too much detail, this won't lead * to UI flickering due to the content shown before the update being either identical or invisible * when changed. */ // fill form with entity permission values, if they exist if (this.currentRolePermissions) { this.fgPagePrivilegesUpdate(this.currentRolePermissions); this.fgFilePrivilegesUpdate(this.currentRolePermissions); } }), map((currentEntity: RoleBO<Raw>) => currentEntity.id), distinctUntilChanged(isEqual), switchMap((id: string): Observable<RolePermissions> => { return this.roleOperations.getPermissions(id); }), ).subscribe((currentRolePermissions: RolePermissions) => { this.currentRolePermissions = currentRolePermissions; // fill form with entity permission values this.fgPagePrivilegesUpdate(currentRolePermissions); this.fgFilePrivilegesUpdate(currentRolePermissions); this.changeDetectorRef.markForCheck(); }); this.permissionRolesRead$ = this.permissionsService.getPermissions(AccessControlledType.ROLE).pipe( map((typePermissions: TypePermissions) => typePermissions.hasPermission(GcmsPermission.READ)), ); this.supportedLanguages$ = this.languageData.watchSupportedLanguages(); this.activeTabId$ = this.editorTabTracker.trackEditorTab(this.route).pipe( map((tabId: RoleDetailTabs) => !Object.values(RoleDetailTabs).includes(tabId) ? RoleDetailTabs.PROPERTIES : tabId), repeat(1), delay(10), ); } private initLanguageData(): void { this.languageData.watchAllEntities().pipe( takeUntil(this.stopper.stopper$), publishReplay(1), refCount(), ).subscribe((currentLanguages: Language[]) => { this.currentLanguagesSorted = currentLanguages.sort((languageA: Language, languageB: Language) => { return languageA.name.localeCompare(languageB.name); }); this.updatePageLanguagesSortedAndRemainingChildControlNames(); }); } /** * Requests changes of role by id to CMS */ private updateRole(): Promise<void> { // assemble payload with conditional properties const role: RoleUpdateRequest = { ...this.fgProperties.value, id: Number(this.currentEntity.id), }; return this.roleOperations.update(role.id, role).pipe( detailLoading(this.appState), tap((updatedRole: RoleBO<Raw>) => { this.currentEntity = updatedRole; // update the UI this.changeDetectorRef.markForCheck(); this.tableLoader.reload(); }), map(() => this.fgProperties.markAsPristine()), ).toPromise(); } /** * Requests changes of role by id to CMS */ private updateRolePermissions(type: 'page' | 'file'): Promise<void> { // assemble payload with conditional properties let rolePermissions: RolePermissions = null; if (type === 'page') { rolePermissions = Object.assign({}, this.currentRolePermissions, this.fgPagePrivileges.value) } if (type === 'file') { rolePermissions = Object.assign({}, this.currentRolePermissions, this.fgFilePrivileges.value) } if (rolePermissions !== null) { return this.roleOperations.updatePermissions(this.currentEntity.id, rolePermissions).pipe( detailLoading(this.appState), tap((updatedRolePermissions: RolePermissions) => this.currentRolePermissions = updatedRolePermissions), map(() => { if (type === 'page') { this.fgPagePrivileges.markAsPristine(); } if (type === 'file') { this.fgFilePrivileges.markAsPristine(); } }), ).toPromise(); } } btnSavePropertiesOnClick(): void { this.updateRole(); } btnSavePrivilegesOnClick(type: 'page' | 'file'): void { this.updateRolePermissions(type); } /** * Initialize form 'Properties' */ protected fgPropertiesInit(): void { this.fgProperties = new UntypedFormControl(cloneDeep(this.currentEntity), createNestedControlValidator()); this.fgPropertiesSaveDisabled$ = createFormSaveDisabledTracker(this.fgProperties); } /** * Initialize form 'Page Privileges' */ protected fgPagePrivilegesInit(): void { this.fgPagePrivileges = new UntypedFormGroup({ page: this.buildPagePrivilegesFormGroup(), pageLanguages: new UntypedFormGroup({}), }); this.fgPagePrivilegesSaveDisabled$ = createFormSaveDisabledTracker(this.fgPagePrivileges); } /** * Initialize form 'File Privileges' */ protected fgFilePrivilegesInit(): void { this.fgFilePrivileges = new UntypedFormGroup({ file: this.buildFilePrivilegesFormGroup(), }); this.fgFilePrivilegesSaveDisabled$ = createFormSaveDisabledTracker(this.fgFilePrivileges); } /** * Set new value of form 'Properties' */ protected fgPropertiesUpdate(role: RoleBO<Normalized | Raw>): void { this.fgProperties.setValue(cloneDeep(role)); this.fgProperties.markAsPristine(); } /** * Set new value of form 'Properties' */ protected fgPagePrivilegesUpdate(rolePermissions: RolePermissions): void { this.fgPagePrivileges.get('page').setValue({ viewpage: rolePermissions.page.viewpage, createpage: rolePermissions.page.createpage, updatepage: rolePermissions.page.updatepage, deletepage: rolePermissions.page.deletepage, publishpage: rolePermissions.page.publishpage, translatepage: rolePermissions.page.translatepage, }, { onlySelf: false, emitEvent: false }); const pageLanguagesPrivileges: Index<string, PagePrivileges> = rolePermissions.pageLanguages; const updatedPageLanguagesPrivileges: string[] = []; const pageLanguagesFormGroup: UntypedFormGroup = (this.fgPagePrivileges.get('pageLanguages') as UntypedFormGroup); for (const [id, formGroup] of Object.entries(pageLanguagesFormGroup.controls)) { if (pageLanguagesPrivileges[id]) { formGroup.setValue({ viewpage: pageLanguagesPrivileges[id].viewpage, createpage: pageLanguagesPrivileges[id].createpage, updatepage: pageLanguagesPrivileges[id].updatepage, deletepage: pageLanguagesPrivileges[id].deletepage, publishpage: pageLanguagesPrivileges[id].publishpage, translatepage: pageLanguagesPrivileges[id].translatepage, }, { onlySelf: false, emitEvent: false }); updatedPageLanguagesPrivileges.push(id); } else { pageLanguagesFormGroup.removeControl(id); } } for (const [id, pageLanguagePrivileges] of Object.entries(pageLanguagesPrivileges)) { if (!updatedPageLanguagesPrivileges.includes(id)) { pageLanguagesFormGroup.addControl(id, new UntypedFormGroup({ viewpage: new UntypedFormControl(pageLanguagePrivileges.viewpage), createpage: new UntypedFormControl(pageLanguagePrivileges.createpage), updatepage: new UntypedFormControl(pageLanguagePrivileges.updatepage), deletepage: new UntypedFormControl(pageLanguagePrivileges.deletepage), publishpage: new UntypedFormControl(pageLanguagePrivileges.publishpage), translatepage: new UntypedFormControl(pageLanguagePrivileges.translatepage), })); } } this.fgPagePrivileges.updateValueAndValidity(); this.pageLanguagesPrivilegesChildControlNames = Object.keys(pageLanguagesFormGroup.controls); this.updatePageLanguagesSortedAndRemainingChildControlNames(); this.fgPagePrivileges.markAsPristine(); } /** * Set new value of form 'Properties' */ protected fgFilePrivilegesUpdate(rolePermissions: RolePermissions): void { this.fgFilePrivileges.get('file').setValue({ viewfile: rolePermissions.file.viewfile, createfile: rolePermissions.file.createfile, updatefile: rolePermissions.file.updatefile, deletefile: rolePermissions.file.deletefile, }); this.fgFilePrivileges.markAsPristine(); } private initForms(): void { this.fgPropertiesInit(); this.fgPagePrivilegesInit(); this.fgFilePrivilegesInit(); this.tabHandles = { [RoleDetailTabs.PROPERTIES]: new FormGroupTabHandle(this.fgProperties, { save: () => this.updateRole(), }), [RoleDetailTabs.PAGE_PRIVILEGES]: new FormGroupTabHandle(this.fgPagePrivileges, { save: () => this.updateRolePermissions('page'), }), [RoleDetailTabs.FILE_PRIVILEGES]: new FormGroupTabHandle(this.fgFilePrivileges, { save: () => this.updateRolePermissions('file'), }), }; } private buildPagePrivilegesFormGroup(): UntypedFormGroup { return new UntypedFormGroup({ viewpage: new UntypedFormControl(false), createpage: new UntypedFormControl(false), updatepage: new UntypedFormControl(false), deletepage: new UntypedFormControl(false), publishpage: new UntypedFormControl(false), translatepage: new UntypedFormControl(false), }) } private buildFilePrivilegesFormGroup(): UntypedFormGroup { return new UntypedFormGroup({ viewfile: new UntypedFormControl(false), createfile: new UntypedFormControl(false), updatefile: new UntypedFormControl(false), deletefile: new UntypedFormControl(false), }) } private updatePageLanguagesSortedAndRemainingChildControlNames(): void { this.pageLanguagesSortedAndRemainingChildControlNames = []; const addedChildControlNames = []; for (const currentLanguage of this.currentLanguagesSorted) { const stringifiedId = `${currentLanguage.id}`; if (this.pageLanguagesPrivilegesChildControlNames.includes(stringifiedId)) { this.pageLanguagesSortedAndRemainingChildControlNames.push({ id: stringifiedId, name: currentLanguage.name, }); addedChildControlNames.push(stringifiedId); } } for (const childControlName of this.pageLanguagesPrivilegesChildControlNames) { if (!addedChildControlNames.includes(childControlName)) { this.pageLanguagesSortedAndRemainingChildControlNames.push({ id: childControlName, name: childControlName, }); } } this.changeDetectorRef.markForCheck(); } childControlInformationTrackBy(_: number, childControlInformation: { id: string, name: string }): string { return childControlInformation.id; } }
// // EventRepository.swift // main project // // Created by Алла alla2104 on 10.09.23. // import Foundation import CoreData final class EventRepository { func save(category: String, currency: String, descriptionEvent: String, title: String ) -> Event? { let context = CoreDataService.context var event: Event? context.performAndWait { let newEvent = Event(context: context) newEvent.category = category newEvent.currency = currency newEvent.descriptionEvent = descriptionEvent newEvent.title = title do { try context.save() } catch let error as NSError { print("\(error)") } event = newEvent } return event } func getAll() -> [Event] { let request = Event.fetchRequest() request.sortDescriptors = [ NSSortDescriptor(key: "\(#keyPath(Event.title))", ascending: true)] return (try? CoreDataService.context.fetch(request)) ?? [] } func delete(event: Event) { let context = CoreDataService.context context.delete(event) CoreDataService.saveContext() } func getEventWithTitle(_ title: String) -> Event? { let request = Event.fetchRequest() request.predicate = NSPredicate(format: "title == %@", title) request.fetchLimit = 1 let events = try? CoreDataService.context.fetch(request) return events?.first } }
import { Doughnut } from 'react-chartjs-2' import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js' import { RankingSiswa } from '@/libs/types/cbt-type' ChartJS.register(ArcElement, Tooltip, Legend) export function StatistikSekolahPieChart({ jsonData, }: { jsonData: RankingSiswa[] }) { // Membuat objek untuk menyimpan jumlah siswa dari setiap sekolah const sekolahData = {} // Mengelompokkan jumlah siswa berdasarkan nama sekolah jsonData?.forEach((item) => { const { sekolah } = item if (sekolahData[sekolah]) { sekolahData[sekolah] += 1 } else { sekolahData[sekolah] = 1 } }) // Membuat array untuk labels (nama sekolah) dan data (jumlah siswa) const labels = Object.keys(sekolahData) const data = Object.values(sekolahData) // Mengatur warna secara acak untuk setiap sekolah const backgroundColor = labels.map(() => { return `rgb(${Math.floor(Math.random() * 256)}, ${Math.floor( Math.random() * 256, )}, ${Math.floor(Math.random() * 256)})` }) // Konfigurasi data untuk grafik doughnut const doughnutData = { labels: labels, datasets: [ { data: data, backgroundColor: backgroundColor, hoverOffset: 4, }, ], } return ( <div className="flex w-6/12 flex-col gap-y-24 rounded-2xl bg-white p-32 phones:w-full"> <h2>Statistik Jumlah Siswa Per Sekolah</h2> <Doughnut data={doughnutData} /> </div> ) }
package org.example.taski.dryKissYagni; import java.util.List; public class D1 { public double calculateAverageValueForGivenList(List<Double> listOfNumbers) { double sumOfAllValues = 0; for (double currentValue : listOfNumbers) { sumOfAllValues += currentValue; } return sumOfAllValues / listOfNumbers.size(); } } class DataProcessor { /** * Вычисляет среднее значение для данного списка чисел. * * @param listOfNumbers Список чисел, для которых нужно вычислить среднее значение. * @return Среднее значение чисел в списке. * @throws IllegalArgumentException Если список пуст. */ public double calculateAverageValueForGivenList(List<Double> listOfNumbers) { double sumOfAllValues = 0; if (listOfNumbers.isEmpty()) {// проверка на пустой список, что бы не было деления на ноль throw new IllegalArgumentException("List cannot be empty"); } for (double currentValue : listOfNumbers) { sumOfAllValues += currentValue; } return sumOfAllValues / listOfNumbers.size(); } }
package com.library.base.dialog; import android.annotation.SuppressLint; import android.app.Dialog; import android.content.Context; import android.util.DisplayMetrics; import android.view.View; import android.widget.Toast; import com.library.base.R; import butterknife.ButterKnife; /** * 基本对话框 * @author : jerome */ public abstract class BaseDialog extends Dialog implements View.OnClickListener { private Context context; public CallBack callBack; private Toast mToast; public BaseDialog(Context context, int dialogLayout) { super(context, R.style.Dialog); this.context = context; this.setCanceledOnTouchOutside(true); setContentView(dialogLayout); ButterKnife.bind(this); initDialog(); setListener(); } /** * 初始化对话框 */ protected abstract void initDialog(); /** * 设置监听器 */ protected abstract void setListener(); /** * 显示一个Toast信息 * * @param resId */ @SuppressLint("ShowToast") public void showToast(int resId) { if (mToast == null) { mToast = Toast.makeText(context, resId, Toast.LENGTH_SHORT); } else { mToast.setText(resId); } mToast.show(); } /** * 显示一个Toast信息 * * @param content */ @SuppressLint("ShowToast") public void showToast(String content) { if (mToast == null) { mToast = Toast.makeText(context, content, Toast.LENGTH_SHORT); } else { mToast.setText(content); } mToast.show(); } public void setCallBack(CallBack callBack) { this.callBack = callBack; } /** * 用户选择回调 */ public interface CallBack { void callBack(Object returnData); void cancel(Object returnData); } }
import React, { useContext, useEffect, useState } from "react"; import { SidebarContext } from "../contexts/SidebarContext"; import { CartContext } from "../contexts/CartContext"; import { Link } from "react-router-dom"; import { BsBag } from "react-icons/bs"; const Header = () => { // header state const [isActive, setIsActive] = useState(false); const { isOpen, setIsOpen } = useContext(SidebarContext); const { itemAmount } = useContext(CartContext); // event listener useEffect(() => { window.addEventListener("scroll", () => { window.scrollY > 60 ? setIsActive(true) : setIsActive(false); }); }); const [isLoggedIn, setIsLoggedIn] = useState(false); useEffect(() => { setIsLoggedIn(!!localStorage.getItem('authToken')); }, []); return ( <header className={`${isActive ? "bg-white py-4 shadow-md" : "bg-none py-6" } fixed w-full z-10 lg:px-8 transition-all`} > <div className="container mx-auto flex items-center justify-between h-full"> <Link to={"/"}> <div className="w-[50px] font-bold text-5xl"> Kid's<span className="text-red-900">World</span> </div> </Link> {/* cart */} { !isLoggedIn ? <Link to='/auth'> <div className="bg-black text-white font-bold text-md hover:bg-gray-700 p-2 ">Sign in kid's world</div> </Link> : <div className="w-[40%] gap-[20px] flex items-center justify-end border-3 border-cyan-800"> <div onClick={() => setIsOpen(!isOpen)} className="cursor-pointer flex relative" > <BsBag className="text-2xl" /> <div className="bg-red-500 absolute -right-2 -bottom-2 text-[12px] w-[18px] h-[18px] text-white rounded-full flex justify-center items-center"> {itemAmount} </div> </div> <div onClick={() => { setIsLoggedIn(false); localStorage.removeItem('authToken'); }} className="bg-black cursor-pointer text-white font-bold text-sm hover:bg-gray-700 px-2 py-1 ">Log out</div> </div> } </div> </header> ); }; export default Header;
/* * Copyright (C) 2014 The Android Open Source Project * * 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 uk.co.sentinelweb.tvmod.playback; import android.app.Activity; import android.media.MediaMetadataRetriever; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.v17.leanback.widget.AbstractDetailsDescriptionPresenter; import android.support.v17.leanback.widget.Action; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.ClassPresenterSelector; import android.support.v17.leanback.widget.ControlButtonPresenterSelector; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ListRow; import android.support.v17.leanback.widget.ListRowPresenter; import android.support.v17.leanback.widget.OnActionClickedListener; import android.support.v17.leanback.widget.OnItemViewClickedListener; import android.support.v17.leanback.widget.OnItemViewSelectedListener; import android.support.v17.leanback.widget.PlaybackControlsRow; import android.support.v17.leanback.widget.PlaybackControlsRow.FastForwardAction; import android.support.v17.leanback.widget.PlaybackControlsRow.PlayPauseAction; import android.support.v17.leanback.widget.PlaybackControlsRow.RepeatAction; import android.support.v17.leanback.widget.PlaybackControlsRow.RewindAction; import android.support.v17.leanback.widget.PlaybackControlsRow.ShuffleAction; import android.support.v17.leanback.widget.PlaybackControlsRow.SkipNextAction; import android.support.v17.leanback.widget.PlaybackControlsRow.SkipPreviousAction; import android.support.v17.leanback.widget.PlaybackControlsRow.ThumbsDownAction; import android.support.v17.leanback.widget.PlaybackControlsRow.ThumbsUpAction; import android.support.v17.leanback.widget.PlaybackControlsRowPresenter; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.Row; import android.support.v17.leanback.widget.RowPresenter; import android.util.Log; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import rx.Observable; import rx.Observer; import rx.Subscription; import uk.co.sentinelweb.tvmod.R; import uk.co.sentinelweb.tvmod.browse.CardPresenter; import uk.co.sentinelweb.tvmod.details.DetailsActivity; import uk.co.sentinelweb.tvmod.model.Item; /* * Class for video playback with media control */ public class PlaybackOverlayFragment extends android.support.v17.leanback.app.PlaybackOverlayFragment { private static final String TAG = "PlaybackControlsFragmnt"; private static final boolean SHOW_DETAIL = true; private static final boolean HIDE_MORE_ACTIONS = false; private static final int PRIMARY_CONTROLS = 5; private static final boolean SHOW_IMAGE = PRIMARY_CONTROLS <= 5; private static final int BACKGROUND_TYPE = PlaybackOverlayFragment.BG_LIGHT; private static final int CARD_WIDTH = 200; private static final int CARD_HEIGHT = 240; private static final int DEFAULT_UPDATE_PERIOD = 1000; private static final int UPDATE_PERIOD = 16; private static final int SIMULATED_BUFFERED_TIME = 10000; private ArrayObjectAdapter mRowsAdapter; private ArrayObjectAdapter mPrimaryActionsAdapter; private ArrayObjectAdapter mSecondaryActionsAdapter; private PlayPauseAction mPlayPauseAction; private RepeatAction mRepeatAction; private ThumbsUpAction mThumbsUpAction; private ThumbsDownAction mThumbsDownAction; private ShuffleAction mShuffleAction; private FastForwardAction mFastForwardAction; private RewindAction mRewindAction; private SkipNextAction mSkipNextAction; private SkipPreviousAction mSkipPreviousAction; private PlaybackControlsRow mPlaybackControlsRow; private ArrayList<Item> mItems = new ArrayList<>(); private int mCurrentItem; private Handler mHandler; private Runnable mRunnable; private Item _mSelectedItem; private OnPlayPauseClickedListener mCallback; private Subscription _subscribe; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); mItems = new ArrayList<>(); _mSelectedItem = (Item) getActivity() .getIntent().getSerializableExtra(DetailsActivity.MOVIE); mItems.add(_mSelectedItem); _subscribe = Observable.<List<Item>>empty() // MovieList.setupMovies() // .subscribeOn(Schedulers.io()) .subscribe(new Observer<List<Item>>() { @Override public void onCompleted() { } @Override public void onError(final Throwable e) { } @Override public void onNext(final List<Item> movies) { for (int j = 0; j < movies.size(); j++) { mItems.add(movies.get(j)); if (_mSelectedItem.getTitle().contentEquals(movies.get(j).getTitle())) { mCurrentItem = j; } } } }); mHandler = new Handler(); setBackgroundType(BACKGROUND_TYPE); setFadingEnabled(false); setupRows(); setOnItemViewSelectedListener(new OnItemViewSelectedListener() { @Override public void onItemSelected(final Presenter.ViewHolder itemViewHolder, final Object item, final RowPresenter.ViewHolder rowViewHolder, final Row row) { Log.i(TAG, "onItemSelected: " + item + " row " + row); } }); setOnItemViewClickedListener(new OnItemViewClickedListener() { @Override public void onItemClicked(final Presenter.ViewHolder itemViewHolder, final Object item, final RowPresenter.ViewHolder rowViewHolder, final Row row) { Log.i(TAG, "onItemClicked: " + item + " row " + row); } }); } @Override public void onAttach(final Activity context) { super.onAttach(context); if (context instanceof OnPlayPauseClickedListener) { mCallback = (OnPlayPauseClickedListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnPlayPauseClickedListener"); } } private void setupRows() { final ClassPresenterSelector ps = new ClassPresenterSelector(); final PlaybackControlsRowPresenter playbackControlsRowPresenter; if (SHOW_DETAIL) { playbackControlsRowPresenter = new PlaybackControlsRowPresenter( new DescriptionPresenter()); } else { playbackControlsRowPresenter = new PlaybackControlsRowPresenter(); } playbackControlsRowPresenter.setOnActionClickedListener(new OnActionClickedListener() { public void onActionClicked(final Action action) { if (action.getId() == mPlayPauseAction.getId()) { togglePlayback(mPlayPauseAction.getIndex() == PlayPauseAction.PLAY); } else if (action.getId() == mSkipNextAction.getId()) { next(); } else if (action.getId() == mSkipPreviousAction.getId()) { prev(); } else if (action.getId() == mFastForwardAction.getId()) { Toast.makeText(getActivity(), "TODO: Fast Forward", Toast.LENGTH_SHORT).show(); } else if (action.getId() == mRewindAction.getId()) { Toast.makeText(getActivity(), "TODO: Rewind", Toast.LENGTH_SHORT).show(); } if (action instanceof PlaybackControlsRow.MultiAction) { ((PlaybackControlsRow.MultiAction) action).nextIndex(); notifyChanged(action); } } }); playbackControlsRowPresenter.setSecondaryActionsHidden(HIDE_MORE_ACTIONS); ps.addClassPresenter(PlaybackControlsRow.class, playbackControlsRowPresenter); ps.addClassPresenter(ListRow.class, new ListRowPresenter()); mRowsAdapter = new ArrayObjectAdapter(ps); addPlaybackControlsRow(); addOtherRows(); setAdapter(mRowsAdapter); } public void togglePlayback(final boolean playPause) { if (playPause) { startProgressAutomation(); setFadingEnabled(true); mCallback.onFragmentPlayPause(mItems.get(mCurrentItem), mPlaybackControlsRow.getCurrentTime(), true); mPlayPauseAction.setIcon(mPlayPauseAction.getDrawable(PlayPauseAction.PAUSE)); } else { stopProgressAutomation(); setFadingEnabled(false); mCallback.onFragmentPlayPause(mItems.get(mCurrentItem), mPlaybackControlsRow.getCurrentTime(), false); mPlayPauseAction.setIcon(mPlayPauseAction.getDrawable(PlayPauseAction.PLAY)); } notifyChanged(mPlayPauseAction); } private int getDuration() { final Item item = mItems.get(mCurrentItem); final MediaMetadataRetriever mmr = new MediaMetadataRetriever(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mmr.setDataSource(item.getVideoUrl(), new HashMap<>()); } else { mmr.setDataSource(item.getVideoUrl()); } final String time = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); final long duration = Long.parseLong(time); return (int) duration; } private void addPlaybackControlsRow() { if (SHOW_DETAIL) { mPlaybackControlsRow = new PlaybackControlsRow(_mSelectedItem); } else { mPlaybackControlsRow = new PlaybackControlsRow(); } mRowsAdapter.add(mPlaybackControlsRow); updatePlaybackRow(mCurrentItem); final ControlButtonPresenterSelector presenterSelector = new ControlButtonPresenterSelector(); mPrimaryActionsAdapter = new ArrayObjectAdapter(presenterSelector); mSecondaryActionsAdapter = new ArrayObjectAdapter(presenterSelector); mPlaybackControlsRow.setPrimaryActionsAdapter(mPrimaryActionsAdapter); mPlaybackControlsRow.setSecondaryActionsAdapter(mSecondaryActionsAdapter); mPlayPauseAction = new PlayPauseAction(getActivity()); mRepeatAction = new RepeatAction(getActivity()); mThumbsUpAction = new ThumbsUpAction(getActivity()); mThumbsDownAction = new ThumbsDownAction(getActivity()); mShuffleAction = new ShuffleAction(getActivity()); mSkipNextAction = new PlaybackControlsRow.SkipNextAction(getActivity()); mSkipPreviousAction = new PlaybackControlsRow.SkipPreviousAction(getActivity()); mFastForwardAction = new PlaybackControlsRow.FastForwardAction(getActivity()); mRewindAction = new PlaybackControlsRow.RewindAction(getActivity()); if (PRIMARY_CONTROLS > 5) { mPrimaryActionsAdapter.add(mThumbsUpAction); } else { mSecondaryActionsAdapter.add(mThumbsUpAction); } mPrimaryActionsAdapter.add(mSkipPreviousAction); if (PRIMARY_CONTROLS > 3) { mPrimaryActionsAdapter.add(new PlaybackControlsRow.RewindAction(getActivity())); } mPrimaryActionsAdapter.add(mPlayPauseAction); if (PRIMARY_CONTROLS > 3) { mPrimaryActionsAdapter.add(new PlaybackControlsRow.FastForwardAction(getActivity())); } mPrimaryActionsAdapter.add(mSkipNextAction); mSecondaryActionsAdapter.add(mRepeatAction); mSecondaryActionsAdapter.add(mShuffleAction); if (PRIMARY_CONTROLS > 5) { mPrimaryActionsAdapter.add(mThumbsDownAction); } else { mSecondaryActionsAdapter.add(mThumbsDownAction); } mSecondaryActionsAdapter.add(new PlaybackControlsRow.HighQualityAction(getActivity())); mSecondaryActionsAdapter.add(new PlaybackControlsRow.ClosedCaptioningAction(getActivity())); } private void notifyChanged(final Action action) { ArrayObjectAdapter adapter = mPrimaryActionsAdapter; if (adapter.indexOf(action) >= 0) { adapter.notifyArrayItemRangeChanged(adapter.indexOf(action), 1); return; } adapter = mSecondaryActionsAdapter; if (adapter.indexOf(action) >= 0) { adapter.notifyArrayItemRangeChanged(adapter.indexOf(action), 1); return; } } private void updatePlaybackRow(final int index) { if (mPlaybackControlsRow.getItem() != null) { final Item item = (Item) mPlaybackControlsRow.getItem(); if (mItems.size()<mCurrentItem) { item.setTitle(mItems.get(mCurrentItem).getTitle()); item.setExtension(mItems.get(mCurrentItem).getExtension()); } } if (SHOW_IMAGE) { if (mItems.size()<mCurrentItem) { updateVideoImage(mItems.get(mCurrentItem).getCardImageURI().toString()); } } mRowsAdapter.notifyArrayItemRangeChanged(0, 1); mPlaybackControlsRow.setTotalTime(getDuration()); mPlaybackControlsRow.setCurrentTime(0); mPlaybackControlsRow.setBufferedProgress(0); } private void addOtherRows() { final ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(new CardPresenter()); for (final Item item : mItems) { listRowAdapter.add(item); } final HeaderItem header = new HeaderItem(0, getString(R.string.related_movies)); mRowsAdapter.add(new ListRow(header, listRowAdapter)); } private int getUpdatePeriod() { if (getView() == null || mPlaybackControlsRow.getTotalTime() <= 0) { return DEFAULT_UPDATE_PERIOD; } return Math.max(UPDATE_PERIOD, mPlaybackControlsRow.getTotalTime() / getView().getWidth()); } private void startProgressAutomation() { mRunnable = new Runnable() { @Override public void run() { final int updatePeriod = getUpdatePeriod(); final int currentTime = mPlaybackControlsRow.getCurrentTime() + updatePeriod; final int totalTime = mPlaybackControlsRow.getTotalTime(); mPlaybackControlsRow.setCurrentTime(currentTime); mPlaybackControlsRow.setBufferedProgress(currentTime + SIMULATED_BUFFERED_TIME); if (totalTime > 0 && totalTime <= currentTime) { next(); } mHandler.postDelayed(this, updatePeriod); } }; mHandler.postDelayed(mRunnable, getUpdatePeriod()); } private void next() { if (++mCurrentItem >= mItems.size()) { mCurrentItem = 0; } if (mPlayPauseAction.getIndex() == PlayPauseAction.PLAY) { mCallback.onFragmentPlayPause(mItems.get(mCurrentItem), 0, false); } else { mCallback.onFragmentPlayPause(mItems.get(mCurrentItem), 0, true); } updatePlaybackRow(mCurrentItem); } private void prev() { if (--mCurrentItem < 0) { mCurrentItem = mItems.size() - 1; } if (mPlayPauseAction.getIndex() == PlayPauseAction.PLAY) { mCallback.onFragmentPlayPause(mItems.get(mCurrentItem), 0, false); } else { mCallback.onFragmentPlayPause(mItems.get(mCurrentItem), 0, true); } updatePlaybackRow(mCurrentItem); } private void stopProgressAutomation() { if (mHandler != null && mRunnable != null) { mHandler.removeCallbacks(mRunnable); } } @Override public void onStop() { stopProgressAutomation(); if (_subscribe != null) { _subscribe.unsubscribe(); _subscribe = null; } super.onStop(); } protected void updateVideoImage(final String uri) { Glide.with(getActivity()) .load(uri) .centerCrop() .into(new SimpleTarget<GlideDrawable>(CARD_WIDTH, CARD_HEIGHT) { @Override public void onResourceReady(final GlideDrawable resource, final GlideAnimation<? super GlideDrawable> glideAnimation) { mPlaybackControlsRow.setImageDrawable(resource); mRowsAdapter.notifyArrayItemRangeChanged(0, mRowsAdapter.size()); } }); } // Container Activity must implement this interface public interface OnPlayPauseClickedListener { void onFragmentPlayPause(Item item, int position, Boolean playPause); } static class DescriptionPresenter extends AbstractDetailsDescriptionPresenter { @Override protected void onBindDescription(final ViewHolder viewHolder, final Object item) { viewHolder.getTitle().setText(((Item) item).getTitle()); viewHolder.getSubtitle().setText(((Item) item).getExtension().toString()); } } }
import styled from "styled-components/native"; import { colors, fontFamilies, GeneralText } from "../../styles/styles"; import React, { useEffect, useState } from "react"; import { useQuery } from "react-query"; import { getMyRooms } from "../../lib/api/getMyRooms"; import { GetMyRooms, IRoom } from "../../lib/api/types.d"; import ChatListFlatList from "../../components/chat/ChatListFlatList"; import { useNavigation } from "@react-navigation/native"; import messaging from "@react-native-firebase/messaging"; import storage, { StorageKey } from "../../lib/helpers/myAsyncStorage"; interface Props {} export default function ChatList(props: Props) { const navigation = useNavigation(); const [showSubText, setShowSubText] = useState(false); const { data: chatRoomData, isLoading, refetch, } = useQuery<GetMyRooms | undefined>(["room"], () => getMyRooms(), { retry: 1, refetchOnWindowFocus: true, refetchOnMount: true, refetchOnReconnect: true, }); useEffect(() => { async function setUp() { refetch(); await storage.setItem(StorageKey.message, false); } messaging().onMessage(async (remoteMessage) => { if (remoteMessage.data?.type === "message") { if (navigation.isFocused) refetch(); } }); navigation.addListener("focus", async (e) => { await setUp(); }); }, []); useEffect(() => { if (chatRoomData?.myRooms.length === 0) { setShowSubText(true); } if (chatRoomData?.myRooms.length !== 0) { setShowSubText(false); } }, [chatRoomData]); return ( <Container showsVerticalScrollIndicator={false} data={chatRoomData?.myRooms} ListHeaderComponent={ <HeaderContainer> <HeaderMainText>프렌즈들과 소통해요</HeaderMainText> {showSubText && ( <HeaderSubText> 도착한 메세지가 없습니다. 먼저 프렌즈들에게 메세지를 보내보세요 </HeaderSubText> )} </HeaderContainer> } keyExtractor={(item: IRoom) => item.id + ""} renderItem={({ item }) => ( <ChatListFlatList roomId={item.id} lastMessage={item.lastMessage} receiver={item.receiver} latestMessageAt={item.latestMessageAt} /> )} /> ); } const HeaderContainer = styled.View` padding-left: 30px; padding-right: 30px; margin-bottom: 14px; `; const HeaderMainText = styled(GeneralText)` font-size: 30px; font-family: ${fontFamilies.bold}; `; const HeaderSubText = styled(GeneralText)` margin-top: 10px; font-size: 18px; color: ${colors.midGrey}; `; const Container = styled.FlatList` width: 100%; height: 100%; background-color: ${colors.white}; `;
/*[meta] mimetype = text/x-pool author = Marc Woerlein <[email protected]> version = 0.1.0 */ namespace pool::command; use command::AbstractCommand; use pool::compiler::parser::Parser; use sys::core::String; use sys::core::Task; use sys::core::anycollection::AnyIterator; use sys::stream::IStream; use sys::stream::OStream; use sys::stream::SeekableIOStream; use sys::runtime::ClassDescriptor; use sys::runtime::ClassDescriptorLoader; use sys::runtime::DynamicClassStorage; use sys::runtime::Class; use sys::runtime::Runtime; class PoolRuntime extends linux::Command { Parser parser; [] __init() { this._initCommand(); parser = this.createOwn(Parser:CLASSNAME); } [] configure() { this.setName("poolb") .setVersion("0.1.0") .setUsage(<" Pool Bootstrap Runtime. Usage: poolb [options] (-c <dir> | -s <file>) [(-c <dir> | -s <file>)]... <fqn> [-- <classArg>...] Options: -h --help Show this screen. --version Show version. -c <dir> --classpath <dir> Search for classes in all of these directories. -s <file> --store <file> Search for classes in the given store. ">); // TODO: poolb [options] (-c <dir> | -s <file>) [(-c <dir> | -s <file>)]... --class <fqn> [<arg>]... // or: poolb [options] (-c <dir> | -s <file>) [(-c <dir> | -s <file>)]... <fqn> [--] [<arg>]... this.registerOptionAlias('h', "help") .registerOptionAlias('c', "classpath").registerOptionList("classpath") .registerOptionAlias('s', "store").registerOptionList("store") ; } [int] run() { OStream out = this.rt().out(); if (this.hasOption("help")) { out.printCString(usage).printNewline(); return 0; } if (this.hasOption("version")) { out.printCString(name).printChar(' ').printCString(version).printNewline(); return 0; } if (this.getArgumentsSize() != 1 || !(this.hasOption("classpath") || this.hasOption("store"))) { out.printCString(usage).printNewline(); return -1; } // TODO: setup dynamic runtime /*/ Runtime rt = this.rt(); DynamicClassStorage dcs = rt.cast(DynamicClassStorage:CLASSNAME, rt.getClassStorage()); { AnyIterator it = this.getListOption("classpath"); while (it.hasNext()) { dcs.addLoader(this.openDirectory(it.next()).classDescriptorLoader()); } it.destroy(); } { AnyIterator it = this.getListOption("store"); while (it.hasNext()) { dcs.addLoader(this.openStoreFile(it.next()).classDescriptorLoader()); } it.destroy(); } /*/ Runtime parent = this.rt(); Runtime rt = parent.createInstance(Runtime:CLASSNAME); rt.setAllocator(parent.getAllocator()); rt.setOut(parent.out()); rt.setErr(parent.err()); DynamicClassStorage dcs = parent.createInstance(DynamicClassStorage:CLASSNAME); { AnyIterator it = this.getListOption("classpath"); while (it.hasNext()) { dcs.addLoader(this.openDirectory(it.next()).classDescriptorLoader()); } it.destroy(); } { AnyIterator it = this.getListOption("store"); while (it.hasNext()) { dcs.addLoader(this.openStoreFile(it.next()).classDescriptorLoader()); } it.destroy(); } rt.setClassStorage(dcs.classStorage()); Class classClass = rt._createClassClass(); rt.refreshInstance(rt); rt.refreshInstance(rt.out()); rt.refreshInstance(rt.err()); rt.refreshInstance(rt.getAllocator()); rt.refreshInstance(rt.getClassStorage()); if (parent.hasClock()) { sys::time::Clock c := parent.getClock(); rt.refreshInstance(c); rt.setClock(c); } //*/ AnyIterator argIt = this.getArguments(); String classname = argIt.next(); argIt.destroy(); Task t = rt.createInstanceAs(classname.toCString(), Task:CLASSNAME); if (!t) { return -1; } AbstractCommand c = rt.cast(AbstractCommand:CLASSNAME, t); if (c) { return c.executeCommand(_unparsedArguments); } return t.run(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Project Starter</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="index,follow"> <meta name="description" content="TODO: A starter project for ..."> <title>Bootstrap 5 Landing Page Template</title> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Bitter:wght@400;500;600&family=Montserrat:wght@400;500;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="./stylesheets/main.scss"> </head> <body> <!-- THE NAVBAR SECTION --> <nav class="navbar navbar-expand-lg navbar-dark menu shadow fixed-top"> <div class="container"> <a class="navbar-brand" href="#"> <img src="images/developer.png" alt="logo image" style="height: auto; width: auto; max-height: 72px; max-width: 250px;"> </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-end" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"><a class="nav-link active" aria-current="page" href="#">Home</a></li> <li class="nav-item"><a class="nav-link" href="#">Services</a></li> <li class="nav-item"><a class="nav-link" href="#">Testimonials</a></li> <li class="nav-item"><a class="nav-link" href="#">Faq</a></li> <li class="nav-item"><a class="nav-link" href="#">Portfolio</a></li> <li class="nav-item"><a class="nav-link" href="#">Contact</a> </li> </ul> <button type="button" class="rounded-pill btn-rounded"> 801-626-1234 <span> <i class="bi bi-telephone-fill"></i> </span> </button> </div> </div> </nav> <!-- THE INTRO SECTION --> <section id="home" class="intro-section"> <div class="container"> <div class="row align-items-center text-white"> <div class="col-md-6 intros text-start"> <h1 class="display-2"> <span class="display-2--intro">Welcome!</span> <span class="display-2--description lh-base"> Welcome to my digital space, where creativity meets expertise, showcasing a diverse range of projects that reflect my passion and skills. </span> </h1> <button type="button" class="rounded-pill btn-rounded">Get in Touch <span><i class="bi bi-arrow-right"></i></span> </button> </div> <div class="col-md-6 intros text-end"> <div class="video-box"> <img src="images/arts/smiley-face-monochromatic.png" alt="video illutration" class="img-fluid"> <a href="#" class="glightbox position-absolute top-50 start-50 translate-middle"> <span> <i class="bi bi-play-circle"></i> </span> <span class="border-animation border-animation--border-1"></span> <span class="border-animation border-animation--border-2"></span> </a> </div> </div> </div> </div> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"> <path fill="#ffffff" fill-opacity="1" d="M0,160L48,176C96,192,192,224,288,208C384,192,480,128,576,133.3C672,139,768,213,864,202.7C960,192,1056,96,1152,74.7C1248,53,1344,107,1392,133.3L1440,160L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"> </path> </svg> </section> <!--Education Section--> <div class="container"> <div class="row text-center"> <h1 class="display-3 fw-bold">Education</h1> <div class="heading-line mb-1"></div> </div> <div class="row pt-2 pb-2 mt-0 mb-3"> </div> </div> <div class="container py-4"> <div class="row align-items-md-stretch"> <div class="col-md-6"> <div class="h-100 p-5 text-bg-dark rounded-3" style="background-color: #4d3d6f; color: white;" > <h2>Weber State University</h2> <p>I am currently pursing a Bachelor's degree in Web and User Experience. I am dedicated to mastering the latest technologies and design principles to bring innovative solutions to the digital landscape.</p> <button class="btn btn-outline-secondary" type="button">Read More</button> </div> </div> <div class="col-md-6"> <div class="h-100 p-5 bg-body-tertiary border rounded-3" style="background-color: #7caef3; color: white;"> <h2>Brigham Young University - Idaho</h2> <p>With a passion for global affairs and a keen interest in understanding diverse cultures, I successfully earned a Bachelor's degree in International Studies. I have a comprehensive understanding of international relations and I am equipped to navigate the complexities of our interconnected world and contribute meaningfully to the field.</p> <button class="btn btn-outline-primary" type="button">Read More</button> </div> </div> </div> </div> <!-- THE SERVICES SECTION --> <section id="services" class="services"> <div class="container"> <div class="row text-center"> <h1 class="display-3 fw-bold">Skills</h1> <div class="heading-line mb-1"></div> </div> <div class="row pt-2 pb-2 mt-0 mb-3"> <!--<div class="col-md-6 border-right">--> <div class="bg-white p-3"> <h2 class="fw-bold text-capitalize text-center"> Explore my skills </h2> </div> <!--</div>--> <!--<div class="col-md-6"> <div class="bg-white p-4 text-start"> <p class="fw-light"> Hello </p> </div> </div>--> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 services mt-4"> <div class="services__content"> <div class="icon d-block bi bi-send-fill"></div> <h3 class="display-3--title mt-1">HTML/CSS</h3> <p class="lh-lg"> Welcome to my portfolio! Discover the world of web development with HTML and CSS, the building blocks of engaging websites. HTML defines the structure, while CSS adds style and layout, creating visually appealing web pages. Mastering these languages lets you craft impressive portfolios that showcase your skills and creativity online. </p> <button type="button" class="rounded-pill btn-rounded border-primary">Learn more <span><i class="bi bi-arrow-right"></i></span> </button> </div> </div> <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 services mt-4 text-end"> <div class="services__pic"> <img src="images/services/landing-page-outline.png" alt="HTML Landing Page illustration" class="img-fluid"> </div> </div> </div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 services mt-4 text-start"> <div class="services__pic"> <img src="images/services/code-development-flatline.png" alt="JavaScript illustration" class="img-fluid"> </div> </div> <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 services mt-4"> <div class="services__content"> <div class="icon d-block bi bi-code-slash"></div> <h3 class="display-3--title mt-1">JavaScript</h3> <p class="lh-lg"> I'm a dedicated developer proficient in JavaScript, specializing in creating dynamic and interactive web applications. From front-end magic with React to server-side scripting using Node.js, I blend creativity and technical expertise to craft seamless digital experiences. Explore my work and see how I use JavaScript in modern web development. </p> <button type="button" class="rounded-pill btn-rounded border-primary">Learn more <span><i class="bi bi-arrow-right"></i></span> </button> </div> </div> </div> <div class="row"> <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 services mt-4"> <div class="services__content"> <div class="icon d-block bi bi-cloud-arrow-up"></div> <h3 class="display-3--title mt-1">C++</h3> <p class="lh-lg"> I specialize in C++, a powerful and versatile programming language. Explore my projects to see how I use C++ to create high-performance applications and tackle complex programming challenges. </p> <button type="button" class="rounded-pill btn-rounded border-primary">Learn more <span><i class="bi bi-arrow-right"></i></span> </button> </div> </div> <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 services mt-4 text-end"> <div class="services__pic"> <img src="images/services/coding-monochromatic-4c818.png" alt="C++ illustration" class="img-fluid"> </div> </div> </div> </div> </section> <!-- THE CAMPANIES SECTION --> <section id="companies" class="companies"> <div class="container"> <div class="row text-center"> <h1 class="display-3 fw-bold">Trusted by</h1> <div class="heading-line mb-5"></div> </div> </div> <div class="container"> <div class="row"> <div class="col-md-4 col-lg-2"> <div class="companies__logo-box shadow-sm"> <img src="images/companies/company-1.png" alt="Company 1 logo" title="Company 1 Logo" class="img-fluid"> </div> </div> <div class="col-md-4 col-lg-2"> <div class="companies__logo-box shadow-sm"> <img src="images/companies/company-2.png" alt="Company 2 logo" title="Company 2 Logo" class="img-fluid"> </div> </div> <div class="col-md-4 col-lg-2"> <div class="companies__logo-box shadow-sm"> <img src="images/companies/company-3.png" alt="Company 3 logo" title="Company 3 Logo" class="img-fluid"> </div> </div> <div class="col-md-4 col-lg-2"> <div class="companies__logo-box shadow-sm"> <img src="images/companies/company-4.png" alt="Company 4 logo" title="Company 4 Logo" class="img-fluid"> </div> </div> <div class="col-md-4 col-lg-2"> <div class="companies__logo-box shadow-sm"> <img src="images/companies/company-5.png" alt="Company 5 logo" title="Company 5 Logo" class="img-fluid"> </div> </div> <div class="col-md-4 col-lg-2"> <div class="companies__logo-box shadow-sm"> <img src="images/companies/company-6.png" alt="Company 6 logo" title="Company 6 Logo" class="img-fluid"> </div> </div> </div> </div> </section> <!--Work Experience--> <div class="container px-4 py-5 work_experience" style="color: white;"> <h1 class="pb-2 border-bottom fw-bold">Work Experience</h1> <div class="row row-cols-1 row-cols-md-2 align-items-md-center g-5 py-5"> <div class="col d-flex flex-column align-items-start gap-2"> <h2 class="fw-bold text-body-emphasis">My journey in the professional landscape</h2> <p class="text-body-secondary">Learn more about my work experience and how I have grown in professional settings over the years.</p> <a href="#" class="btn btn-secondary btn-lg">Learn more</a> </div> <div class="col"> <div class="row row-cols-1 row-cols-sm-2 g-4"> <div class="col d-flex flex-column gap-2"> <div class="feature-icon-small d-inline-flex align-items-center justify-content-center text-bg-primary bg-gradient fs-4 rounded-3"> <svg class="bi" width="1em" height="1em"> <use xlink:href="#collection"></use> </svg> </div> <h4 class="fw-semibold mb-0 text-body-emphasis">ILP Recruiter</h4> <p class="text-body-secondary">2017-2019</p> </div> <div class="col d-flex flex-column gap-2"> <div class="feature-icon-small d-inline-flex align-items-center justify-content-center text-bg-primary bg-gradient fs-4 rounded-3"> <svg class="bi" width="1em" height="1em"> <use xlink:href="#gear-fill"></use> </svg> </div> <h4 class="fw-semibold mb-0 text-body-emphasis">SLC Community and Neighborhoods</h4> <p class="text-body-secondary">2019-2020</p> </div> <div class="col d-flex flex-column gap-2"> <div class="feature-icon-small d-inline-flex align-items-center justify-content-center text-bg-primary bg-gradient fs-4 rounded-3"> <svg class="bi" width="1em" height="1em"> <use xlink:href="#speedometer"></use> </svg> </div> <h4 class="fw-semibold mb-0 text-body-emphasis">IRS</h4> <p class="text-body-secondary">2019-2022</p> </div> <div class="col d-flex flex-column gap-2"> <div class="feature-icon-small d-inline-flex align-items-center justify-content-center text-bg-primary bg-gradient fs-4 rounded-3"> <svg class="bi" width="1em" height="1em"> <use xlink:href="#table"></use> </svg> </div> <h4 class="fw-semibold mb-0 text-body-emphasis">Revel Media Group</h4> <p class="text-body-secondary">2022 - Present</p> </div> </div> </div> </div> </div> <!-- THE TESTIMONIALS SECTION --> <section id="testimonials" class="testimonials"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"> <path fill="#fff" fill-opacity="1" d="M0,96L48,128C96,160,192,224,288,213.3C384,203,480,117,576,117.3C672,117,768,203,864,202.7C960,203,1056,117,1152,117.3C1248,117,1344,203,1392,245.3L1440,288L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"> </path> </svg> <div class="container"> <div class="row text-center text-white"> <h1 class="display-3 fw-bold">Testimonials</h1> <hr style="width: 100px; height: 3px; " class="mx-auto"> <p class="lead pt-1">What our clients are saying</p> </div> <div class="row align-items-center"> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <div class="testimonials__card"> <p class="lh-lg"> <i class="bi bi-blockquote-left"></i> Incredible talent and professionalism! Jasmine took the time to understand my vision and turned it into a beautiful, responsive website. Their coding skills are top-notch, and they were always quick to respond to my questions and requests. A pleasure to work with! <i class="bi bi-blockquote-right"></i> <div class="ratings p-1"> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> </div> </p> </div> <div class="testimonials__picture"> <img src="images/testimonials/client-1.jpg" alt="client-1 picture" class="rounded-circle img-fluid"> </div> <div class="testimonials__name"> <h3>Patrick Miller</h3> <p class="fw-light">CEO & founder</p> </div> </div> <div class="carousel-item"> <div class="testimonials__card"> <p class="lh-lg"> <i class="bi bi-blockquote-left"></i> An absolute wizard at web development! Jasmine transformed our outdated site into a modern masterpiece. They were communicative throughout the entire process, explaining technical details in a way that was easy to understand. The result? A sleek, user-friendly website that perfectly represents our brand. <i class="bi bi-blockquote-right"></i> <div class="ratings p-1"> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> </div> </p> </div> <div class="testimonials__picture"> <img src="images/testimonials/client-2.jpg" alt="client-2 picture" class="rounded-circle img-fluid"> </div> <div class="testimonials__name"> <h3>Olivia Garcia</h3> <p class="fw-light">Finance Manager</p> </div> </div> <div class="carousel-item"> <div class="testimonials__card"> <p class="lh-lg"> <i class="bi bi-blockquote-left"></i> Exceptional web development skills! I hired Jasmine to revamp our e-commerce site, and the results were beyond my expectations. The new site is not only aesthetically pleasing but also optimized for seamless navigation. Sales have skyrocketed since the upgrade. Highly recommend their services! <i class="bi bi-blockquote-right"></i> <div class="ratings p-1"> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> </div> </p> </div> <div class="testimonials__picture"> <img src="images/testimonials/client-3.jpg" alt="client-3 picture" class="rounded-circle img-fluid"> </div> <div class="testimonials__name"> <h3>Carol Lopez</h3> <p class="fw-light">Global brand manager</p> </div> </div> <div class="carousel-item"> <div class="testimonials__card"> <p class="lh-lg"> <i class="bi bi-blockquote-left"></i> I couldn't be happier with the website Jasmine created for my startup. They have a keen eye for design and a deep understanding of user experience. The site is not only visually appealing but also optimized for performance. If you're in need of a skilled and reliable web developer, look no further! <i class="bi bi-blockquote-right"></i> <div class="ratings p-1"> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> <i class="bi bi-star"></i> </div> </p> </div> <div class="testimonials__picture"> <img src="images/testimonials/client-4.jpg" alt="client-4 picture" class="rounded-circle img-fluid"> </div> <div class="testimonials__name"> <h3>James Smith</h3> <p class="fw-light">C.E.O & Founder</p> </div> </div> </div> <div class="text-center"> <button class="btn btn-outline-light bi bi-arrow-left" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> </button> <button class="btn btn-outline-light bi bi-arrow-right" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> </button> </div> </div> </div> </div> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"> <path fill="#fff" fill-opacity="1" d="M0,96L48,128C96,160,192,224,288,213.3C384,203,480,117,576,117.3C672,117,768,203,864,202.7C960,203,1056,117,1152,117.3C1248,117,1344,203,1392,245.3L1440,288L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"> </path> </svg> </section> <!-- THE FAQ SECTION --> <section id="faq" class="faq"> <div class="container"> <div class="row text-center"> <h1 class="display-3 fw-bold text-uppercase">faq</h1> <div class="heading-line"></div> <p class="lead">Frequently asked questions</p> </div> <div class="row mt-5"> <div class="col-md-12"> <div class="accordion" id="accordionExample"> <div class="accordion-item shadow mb-3"> <h2 class="accordion-header" id="headingOne"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> What is your expertise in web development? </button> </h2> <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionExample"> <div class="accordion-body"> While I do have basic knowledge in languages such as C++ and SQL, I have been growing my skills with HTML/CSS and JavaScript recently. </div> </div> </div> <div class="accordion-item shadow mb-3"> <h2 class="accordion-header" id="headingTwo"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> What challenges have you overcome in your projects? </button> </h2> <div id="collapseTwo" class="accordion-collapse collapse" aria-labelledby="headingTwo" data-bs-parent="#accordionExample"> <div class="accordion-body"> There are many things I have learned throughout my degree. Some of the main challenges I have overcome are learning how to debug my code and improving my technical skills. I had no prior knowledge of code or computers when I chose Web Development like some of my peers have. Because of this, I felt like I had to put extra effort and practice a lot to really grasp concepts that I was learning in my classes. </div> </div> </div> <div class="accordion-item shadow mb-3"> <h2 class="accordion-header" id="headingThree"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Are you available for freelance or full-time work? </button> </h2> <div id="collapseThree" class="accordion-collapse collapse" aria-labelledby="headingThree" data-bs-parent="#accordionExample"> <div class="accordion-body"> I currently have a full-time job however, I am open to freelancing throughout the year. </div> </div> </div> <div class="accordion-item shadow mb-3"> <h2 class="accordion-header" id="headingFour"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour"> How do you stay updated with the latest technologies? </button> </h2> <div id="collapseFour" class="accordion-collapse collapse" aria-labelledby="headingFour" data-bs-parent="#accordionExample"> <div class="accordion-body"> Sometimes in my free time, I read blogs or news feeds. Even in work, some of my co-workers send interesting articles in our group chat or we discuss trending topics in weekly meetings. </div> </div> </div> </div> </div> </div> </div> </section> <!-- THE PORTFOLIO --> <section id="portfolio" class="portfolio"> <div class="container"> <div class="row text-center mt-5"> <h1 class="display-3 fw-bold text-capitalize">Latest Projects</h1> <div class="heading-line"></div> <p class="lead"> Explore my recent Projects </p> </div> <div class="row mt-5 mb-4 g-3 text-center"> <div class="col-md-12"> <button class="btn btn-outline-primary" type="button">All</button> <button class="btn btn-outline-primary" type="button">websites</button> <button class="btn btn-outline-primary" type="button">design</button> <button class="btn btn-outline-primary" type="button">Miscellaneous</button> </div> </div> <div class="row"> <div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/joony-VleAEtGmQH0-unsplash.jpg" alt="portfolio 1 image" title="portfolio 1 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>Sunny Crochet</h4> <p>Websites, Design</p> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/shahadat-rahman-O2MdroNurVw-unsplash.jpg" alt="portfolio 2 image" title="portfolio 2 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>Rock, Paper, Scissors</h4> <p>JavaScript</p> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/portfolio-3.jpg" alt="portfolio 3 image" title="portfolio 3 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>Dinosaur Park</h4> <p>Miscellaneous</p> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/pankaj-patel-bYiw48KLbmw-unsplash.jpg" alt="portfolio 4 image" title="portfolio 4 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>Practicing Bootstrap</h4> <p>Websites</p> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/money-knack-ZsJRSHWOi1I-unsplash.jpg" alt="portfolio 5 image" title="portfolio 5 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>The PayRoll Record Class</h4> <p>Miscellaneous</p> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/portfolio-6.jpg" alt="portfolio 6 image" title="portfolio 6 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>3D Game Library</h4> <p>C++</p> </div> </div> </div> </div> <!--<div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/portfolio-7.jpg" alt="portfolio 7 image" title="portfolio 7 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>project name goes here 7</h4> <p>category project</p> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/portfolio-8.jpg" alt="portfolio 8 image" title="portfolio 8 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>project name goes here 8</h4> <p>category project</p> </div> </div> </div> </div> <div class="col-lg-4 col-md-6"> <div class="portfolio-box shadow"> <img src="images/portfolio/portfolio-9.jpg" alt="portfolio 9 image" title="portfolio 9 picture" class="img-fluid"> <div class="portfolio-info"> <div class="caption"> <h4>project name goes here 9</h4> <p>category project</p> </div> </div> </div> </div>--> </div> </div> </section> <!-- THE GET STARTED SECTION --> <section id="contact" class="get-started"> <div class="container"> <div class="row text-center"> <h1 class="display-3 fw-bold text-capitalize">Contact Me!</h1> <div class="heading-line"></div> <p class="lh-lg"> </p> </div> <div class="row text-white"> <div class="col-12 col-lg-6 gradient shadow p-3"> <div class="cta-info w-100"> <h4 class="display-4 fw-bold">Get In Touch!</h4> <p class="lh-lg"> Whether you have a project in mind, want to collaborate, or just want to say hello, I'd love to hear from you. Please use the form below or reach out through the contact details provided. </p> <h3 class="display-3--brief"></h3> <!-- <ul class="cta-info__list"> <li></li> <li></li> <li></li> </ul>--> </div> </div> <div class="col-12 col-lg-6 bg-white shadow p-3"> <div class="form w-100 pb-2"> <h4 class="display-3--title mb-5">start your project</h4> <form action="#" class="row"> <div class="col-lg-6 col-md mb-3"> <input type="text" placeholder="First Name" id="inputFirstName" class="shadow form-control form-control-lg"> </div> <div class="col-lg-6 col-md mb-3"> <input type="text" placeholder="Last Name" id="inputLastName" class="shadow form-control form-control-lg"> </div> <div class="col-lg-12 mb-3"> <input type="email" placeholder="Email address" id="inputEmail" class="shadow form-control form-control-lg"> </div> <div class="col-lg-12 mb-3"> <textarea name="message" placeholder="Message" id="message" rows="8" class="shadow form-control form-control-lg"></textarea> </div> <div class="text-center d-grid mt-1"> <button type="button" class="btn btn-primary rounded-pill pt-3 pb-3"> submit <i class="bi bi-send"></i> </button> </div> </form> </div> </div> </div> </div> </section> <!-- THE FOOTER SECTION --> <footer class="footer"> <div class="container"> <div class="row"> <div class="col-md-4 col-lg-4 contact-box pt-1 d-md-block d-lg-flex d-flex"> <div class="contact-box__icon"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-phone-call" viewBox="0 0 24 24" stroke-width="1" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <path d="M5 4h4l2 5l-2.5 1.5a11 11 0 0 0 5 5l1.5 -2.5l5 2v4a2 2 0 0 1 -2 2a16 16 0 0 1 -15 -15a2 2 0 0 1 2 -2" /> <path d="M15 7a2 2 0 0 1 2 2" /> <path d="M15 3a6 6 0 0 1 6 6" /> </svg> </div> <div class="contact-box__info"> <a href="#" class="contact-box__info--title">801-626-1234</a> <p class="contact-box__info--subtitle"> Mon-Fri 9am-5pm</p> </div> </div> <div class="col-md-4 col-lg-4 contact-box pt-1 d-md-block d-lg-flex d-flex"> <div class="contact-box__icon"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-mail-opened" viewBox="0 0 24 24" stroke-width="1" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <polyline points="3 9 12 15 21 9 12 3 3 9" /> <path d="M21 9v10a2 2 0 0 1 -2 2h-14a2 2 0 0 1 -2 -2v-10" /> <line x1="3" y1="19" x2="9" y2="13" /> <line x1="15" y1="13" x2="21" y2="19" /> </svg> </div> <div class="contact-box__info"> <a href="#" class="contact-box__info--title">[email protected]</a> <p class="contact-box__info--subtitle">Online support</p> </div> </div> <div class="col-md-4 col-lg-4 contact-box pt-1 d-md-block d-lg-flex d-flex"> <div class="contact-box__icon"> <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-map-2" viewBox="0 0 24 24" stroke-width="1" fill="none" stroke-linecap="round" stroke-linejoin="round"> <path stroke="none" d="M0 0h24v24H0z" fill="none" /> <line x1="18" y1="6" x2="18" y2="6.01" /> <path d="M18 13l-3.5 -5a4 4 0 1 1 7 0l-3.5 5" /> <polyline points="10.5 4.75 9 4 3 7 3 20 9 17 15 20 21 17 21 15" /> <line x1="9" y1="4" x2="9" y2="17" /> <line x1="15" y1="15" x2="15" y2="20" /> </svg> </div> <div class="contact-box__info"> <a href="#" class="contact-box__info--title">Layton, USA</a> <p class="contact-box__info--subtitle">UT 84041, US</p> </div> </div> </div> </div> <div class="footer-sm" style="background-color: #4d3d6f;"> <div class="container"> <div class="row py-4 text-center text-white"> <div class="col-lg-12 col-md-6"> <a href="#"><i class="bi bi-facebook"></i></a> <a href="#"><i class="bi bi-twitter"></i></a> <a href="#"><i class="bi bi-github"></i></a> <a href="#"><i class="bi bi-linkedin"></i></a> <a href="#"><i class="bi bi-instagram"></i></a> </div> </div> </div> </div> <div class="container mt-5"> <div class="row text-white justify-content-center mt-3 pb-3"> <div class="col-12 col-sm-6 col-lg-6 mx-auto"> <h5 class="text-capitalize fw-bold">Jasmine Reyna</h5> <hr class="bg-secondary d-inline-block mb-4" style="width: 100%; height: 2px;"> <p class="lh-lg"> Thank you for viewing my Portfolio </p> </div> <div class="col-12 col-sm-6 col-lg-2 mb-4 mx-auto"> <h5 class="text-capitalize fw-bold">Projects</h5> <hr class="bg-secondary d-inline-block mb-4" style="width: 100%; height: 2px;"> <ul class="list-inline company-list"> <li><a href="#">Sunny Crochet</a></li> <li><a href="#">Rock Paper Scissors</a></li> <li><a href="#">Dinosaur Park</a></li> </ul> </div> <div class="col-12 col-sm-6 col-lg-2 mb-4 mx-auto"> <h5 class="text-capitalize fw-bold">useful links</h5> <hr class="bg-secondary d-inline-block mb-4" style="width: 100%; height: 2px;"> <ul class="list-inline company-list"> <li><a href="#">Services</a></li> <li><a href="#">Testimonials</a></li> <li><a href="#">FAQ</a></li> <li><a href="#">Portfolio</a></li> </ul> </div> <div class="col-12 col-sm-6 col-lg-2 mb-4 mx-auto"> <h5 class="text-capitalize fw-bold">contact</h5> <hr class="bg-secondary d-inline-block mb-4" style="width: 100%; height: 2px;"> <ul class="list-inline company-list"> <li><a href="#">Jasmine Reyna</a></li> <li><a href="#">[email protected]</a></li> <li><a href="#">801-626-1234</a></li> </ul> </div> </div> </div> <div class="footer-bottom pt-5 pb-5"> <div class="container"> <div class="row text-center text-white"> <div class="col-12"> <div class="footer-bottom__copyright"> &COPY; Copyright 2024 <a href="#">J Reyna</a> | Created by <a href="http://codewithpatrick.com" target="_blank">Jasmine Reyna</a> </div> </div> </div> </div> </div> </footer> <a href="#" class="shadow btn-primary rounded-circle back-to-top"> <i class="bi bi-chevron-up"></i> </a> <script type="module" src="./javascripts/main.js"></script> </body> </html>
<html> <head> <title> Customs IT Inventory</title> <style> table, th, td, tr { border-collapse: collapse; text-align: center; } </style> </head> <body class="hold-transition skin-blue sidebar-mini"> <div class="wrapper"> <%= render 'layouts/header' %> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Inventory <small>Items</small> </h1> <ol class="breadcrumb"> <li> <a href="#"> <i class="fa fa-home"></i> Home Page</a> </li> <li class="active">Check Inventory</li> </ol> </section> <section class="content"> <div class="row"> <div class="col-xs-12"> <!-- Main data table --> <div class="box"> <!-- /.box-header --> <div class="box-body"> <div class="table-responsive fix-table-height"> <table id="example1" class="table-bordered table-striped"> <thead> <tr> <th>ID</th> <th>Category</th> <th>Consumable?</th> <th>Quantity</th> <th>Availability</th> <th>S/T</th> <th>Model</th> <th>Price</th> <th>Description</th> <% if current_user.admin? %> <th>Edit</th> <th>Delete</th> <% end %> <th>Deploy Item</th> </tr> </thead> <tbody> <% @items.each do |item| %> <% if item.remaining_quantity < 3 %> <tr> <td><%= item.id %></td> <td><%= item.category %></td> <td><%= item.consumable %></td> <td><%= item.quantity %></td> <td><%=item.remaining_quantity%></td> <td><%= item.serial %></td> <td><%= item.name %></td> <td><%= item.price %></td> <td><%= item.description %></td> <% if current_user.admin? %> <td><%= link_to 'Edit', edit_item_path(item) %></td> <td><%= link_to 'Delete', item, method: :delete, data: { confirm: 'Are you sure you want to delete this item?' } %></td> <% end %> <td><%= link_to 'Deploy', new_order_path(item: item.id) %></td> </tr> <% end %> <% end %> </tbody> </table> </div> </div> <!-- /.box-body --> </div> </div> </div> </section> </div> <%= render 'layouts/footer' %> </div> <script> $(function () { $("#example1").DataTable(); $('#example2').DataTable({ "paging": true, "lengthChange": false, "searching": false, "ordering": true, "info": true, "autoWidth": false }); }); </script> </body> </html>
package com.example.notes.important; import com.alibaba.fastjson.JSONObject; import com.example.notes.junit.PrivateMethodClass; import com.example.notes.model.base.request.UpdateMemberRequest; import com.example.notes.model.base.response.UpdateMemberResponse; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; import java.lang.reflect.Method; /** * @Description: * @Author HeSuiJin * @Date 2022/4/23 */ @Slf4j @SpringBootTest @RunWith(SpringRunner.class) public class PrivateMethodClassJunit { @Autowired private PrivateMethodClass privateMethodClass; /** * 测试共有方法 */ @Test public void publicMethodTest() { UpdateMemberRequest updateMemberRequest = new UpdateMemberRequest(); updateMemberRequest.setId(0L); updateMemberRequest.setName("HSJ"); updateMemberRequest.setAge(100); UpdateMemberResponse updateMemberResponse = privateMethodClass.publicMethodUpdateMember(updateMemberRequest); log.info("publicMethodTest返回:{}", JSONObject.toJSONString(updateMemberResponse)); } /** * 测试私有方法 使用反射机制获取 */ @Test public void privateMethodReflectTest() throws Exception { //1:获取目标类 //2:获取目标类的实例对象 Class<PrivateMethodClass> clazz = PrivateMethodClass.class; Object privateMethodClassObject = clazz.newInstance(); UpdateMemberRequest updateMemberRequest = new UpdateMemberRequest(); updateMemberRequest.setId(0L); updateMemberRequest.setName("HSJ"); updateMemberRequest.setAge(100); //3:获取方法 Method publicMethodUpdateMember = clazz.getMethod("publicMethodUpdateMember", UpdateMemberRequest.class); //最后:调用方法 (UpdateMemberResponse)privateMethodVoid.invoke(privateMethodClassObject, updateMemberRequest); // 1:privateMethodVoid方法使用invoke() // 2:privateMethodClassObject 目标类的对象 // 3:updateMemberRequest 方法参数 // 4:返回结果为Object需要转移 UpdateMemberResponse updateMemberResponse = (UpdateMemberResponse) publicMethodUpdateMember.invoke(privateMethodClassObject, updateMemberRequest); log.info("updateMemberResponse返回:{}", JSONObject.toJSONString(updateMemberResponse)); //注意1:getMethod仅能获取公共方法 getDeclaredMethod才能获取所有方法 否则会出现异常java.lang.NoSuchMethodException // Method privateMethodVoid = clazz.getMethod("privateMethodVoid"); //注意2:私有方法需要使用 setAccessible(true)(暴力破解 忽略权限修饰符) 才能被invoke调用 否则会出现异常PrivateMethodClass with modifiers "private" // privateMethodVoid.setAccessible(); Method privateMethodVoid = clazz.getDeclaredMethod("privateMethodVoid"); privateMethodVoid.setAccessible(true); privateMethodVoid.invoke(privateMethodClassObject); } /** * 测试私有方法 使用工具类Junit自带的功能类ReflectionTestUtils */ @Test public void privateMethodReflectUtilsTest() { //调用无参私有方法 privateMethodVoid ReflectionTestUtils.invokeMethod(privateMethodClass, "privateMethodVoid"); //调用有参私有方法 privateMethodString String privateMethodStringReturn = ReflectionTestUtils.invokeMethod(privateMethodClass, "privateMethodString", "string"); log.info("privateMethodStringReturn返回:{}", privateMethodStringReturn); //调用有参私有方法 privateMethodInteger 入参Integer类型 Integer privateMethodIntegerReturn = ReflectionTestUtils.invokeMethod(privateMethodClass, "privateMethodInteger", 1); log.info("privateMethodIntegerReturn返回:{}", privateMethodIntegerReturn); //调用有参私有方法 privateMethod 入参String类型 String privateMethod = ReflectionTestUtils.invokeMethod(privateMethodClass, "privateMethod", "HeSuiJin", 1); log.info("privateMethod返回:{}", JSONObject.toJSONString(privateMethod)); //调用私有方法 privateMethodUpdateMember 入参UpdateMemberRequest类型 UpdateMemberRequest updateMemberRequest = new UpdateMemberRequest(); updateMemberRequest.setId(0L); updateMemberRequest.setName("HSJ"); updateMemberRequest.setAge(100); UpdateMemberResponse updateMemberResponse = ReflectionTestUtils.invokeMethod(privateMethodClass, "privateMethodUpdateMember", updateMemberRequest); log.info("updateMemberResponse返回:{}", JSONObject.toJSONString(updateMemberResponse)); } }
--- sidebar: sidebar permalink: healthcare/ehr-meditech-deploy_deployment_and_configuration_overview.html keywords: ontap, cisco, blade, ucs, rack, mount, server, cabling, diagram summary: このセクションでは、 ONTAP または Cisco UCS ブレードサーバとラックマウントサーバを使用する環境での FlexPod の導入に関するストレージガイダンスについて説明します。 --- = 概要 :hardbreaks: :allow-uri-read: :nofooter: :icons: font :linkattrs: :imagesdir: ./../media/ [role="lead"] 本ドキュメントでは、 FlexPod 導入に関するネットアップストレージのガイダンスに以下の内容を記載します。 * ONTAP を使用する環境 * Cisco UCS ブレードサーバとラックマウントサーバを使用する環境 本ドキュメントの内容は以下のとおりです。 * FlexPod データセンター環境の詳細な導入 + 詳細については、を参照してください https://www.cisco.com/c/en/us/td/docs/unified_computing/ucs/UCS_CVDs/flexpod_esxi65u1_n9fc.html["FlexPod データセンターと FC の Cisco Validated Design の 2 つの機能があります"^] ( CVD )。 * MEDITECH ソフトウェア環境、リファレンス・アーキテクチャ、統合に関するベスト・プラクティス・ガイダンスの概要 + 詳細については、を参照してください https://fieldportal.netapp.com/content/310932["TR-4300i :『 NetApp FAS and All-Flash Storage Systems for MEDITECH Environments Best Practices Guide 』"^] (ネットアップログインが必要です)。 * パフォーマンス要件とサイジングガイダンスを定量化 + 詳細については、を参照してください https://fieldportal.netapp.com/content/198446["TR-4190 :『 NetApp Sizing Guidelines for MEDITECH Environments 』"^]。 * バックアップとディザスタリカバリの要件を満たすためにネットアップの SnapMirror テクノロジを使用する。 * ネットアップストレージの一般的な導入ガイダンス ここでは、インフラ導入のベストプラクティスを含む構成例を示し、インフラのハードウェア / ソフトウェアのさまざまなコンポーネントと使用可能なバージョンを示します。 == ケーブル配線図 次の図は、 MEDITECH 環境の 32Gb FC / 40GbE トポロジを示しています。 image:ehr-meditech-deploy_image5.png["エラー:グラフィックイメージがありません"] 必ずを使用してください http://mysupport.netapp.com/matrix/["Interoperability Matrix Tool ( IMT )"^] ソフトウェアとファームウェアのすべてのバージョンがサポートされていることを検証します。セクションの表 link:ehr-meditech-deploy_meditech_modules_and_components.html["MEDITECH のモジュールとコンポーネント"] に、解決策テストで使用したインフラのハードウェアコンポーネントとソフトウェアコンポーネントを示します。 link:ehr-meditech-deploy_base_infrastructure_configuration.html["次のステップ:基本インフラの構成。"]
import React, { useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import TextField from '@mui/material/TextField'; import Box from '@mui/material/Box'; import Stack from '@mui/material/Stack'; import { Typography } from '@mui/material'; import Button from '@mui/material/Button'; function RegisterForm() { const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [accountType, setAccountType] = useState(''); const errors = useSelector((store) => store.errors); const dispatch = useDispatch(); const registerUser = (event) => { event.preventDefault(); dispatch({ type: 'REGISTER', payload: { username: username, password: password, accountType: accountType, }, }); }; // end registerUser return ( <Box component="form" className="formPanel" onSubmit={registerUser} sx={{ '& > :not(style)': { m: 10, width: '25ch' } }}> <Typography variant="h2">Register User</Typography> {errors.registrationMessage && ( <h3 className="alert" role="alert"> {errors.registrationMessage} </h3> )} <Stack direction="column" spacing={2}> <div> <label htmlFor="username"> Username: <TextField sx={{backgroundColor: 'white', }} type="text" name="username" value={username} required onChange={(event) => setUsername(event.target.value)} /> </label> </div> <div> <label htmlFor="password"> Password: <TextField sx={{backgroundColor: 'white', }} type="password" name="password" value={password} required onChange={(event) => setPassword(event.target.value)} /> </label> </div> <div> <label htmlFor="accountType"> Account Type: <select style={{ width: '200px' }} name="accountType" value={accountType} required onChange={(event) => setAccountType(event.target.value)}> <option value="" disabled selected> -- select an option -- </option> <option value="customer">Customer</option> <option value="vendor">Vendor</option> </select> </label> </div> <div> <Button sx={{backgroundColor: 'white', }} variant="outlined" className="btn" type="submit" name="submit" value="Register">Register</Button> {/* <input className="btn" type="submit" name="submit" value="Register" /> */} </div> </Stack> </Box> ); } export default RegisterForm;
import React, { useContext, useEffect, useState } from "react"; import Modal from 'react-modal'; import { CartContext, RemoveCartContext,EmptyCartContext } from "../common/context"; import { useFormik } from "formik"; import axios from "axios"; import './cart.css'; import { useNavigate } from 'react-router-dom'; const Cart = () => { const navigate = useNavigate(); const items = useContext(CartContext); const removeItem = useContext(RemoveCartContext); const emptyCart = useContext(EmptyCartContext); const [cartTotal, setCartTotal] = useState(0); const [modelOpen , setModelOpen] = useState(false); const [ isUploading , setIsUploading] = useState(false); const formik = useFormik({ initialValues:{ name : window.localStorage.getItem('islogged')=== 'true' ? window.localStorage.getItem('name') : '', address: window.localStorage.getItem('islogged')=== 'true' ? window.localStorage.getItem('address') : '', contact: '', items:[] }, onSubmit : values=>{ if(!isUploading){ setIsUploading(true) let dataBody = { name:values.name, address:values.address, contact:values.contact, items } console.log(dataBody) axios.post('http://localhost:5000/addOrder', { name:values.name, address:values.address, contact:values.contact, items } ).then((res,err)=>{ console.log(res); setIsUploading(false); if(res.data === 'order added.'){ emptyCart() navigate('/completedOrder'); } }) }else{ console.log('error') } } }); const checkOutClicked = () =>{ setModelOpen(!modelOpen); } const total = () => { setCartTotal(items.reduce((acc, item) => acc + item.price, 0)); }; useEffect(() => { localStorage.setItem("cart", JSON.stringify(items)); total(); }, [items]); const modalStyles = { content: { top: '50%', left: '50%', right: 'auto', bottom: 'auto', marginRight: '-50%', transform: 'translate(-50%, -50%)', }, }; const cartItems = items.map((item) => ( <div class="item"> <div class="buttons"> <span class="delete-btn"></span> <span class="like-btn"></span> </div> <div > <img src={item.url} alt={item.name} class="cart-image"/> </div> <div class="description"> <span>{item.name}</span> </div> <div class="quantity"> <span>1</span> </div> <div class="total-price">{item.price}.00 LKR</div> <input type="button" className="cart-rmv-btn" value="remove item" onClick={e => removeItem(item)} /> </div> )); const checkoutItems = items.map((item) => ( <div class="item"> <div class="buttons"> <span class="delete-btn"></span> <span class="like-btn"></span> </div> <div > <img src={item.url} alt={item.name} class="cart-image"/> </div> <div class="description"> <span>{item.name}</span> </div> <div class="quantity"> <span>1</span> </div> <div class="total-price">{item.price}.00 LKR</div> </div> )); return ( <div> <div class="shopping-cart"> <div class="title"> Shopping Cart </div> { items.length > 0 ? <> {cartItems} <div className="cart-total">Total : {cartTotal}.00 LKR</div> <div className="cart-checkout" onClick={checkOutClicked}>Checkout</div> </>: <div className="cart-empty"> Cart Empty</div> } </div> <Modal isOpen={modelOpen} onRequestClose={()=> setModelOpen(false)} style={modalStyles} contentLabel='Checkout' > <div className='item-model-content'> <div> <div className="checkout-modal-title">Items List</div> {checkoutItems} <div className='item-checkout-modal-price'> Cart Total : {cartTotal}.00 LKR</div> <br /> <div className="checkout-modal-title">Delivery Details</div> <div className="note"><span className="star">*</span>We are currently only accepting cash on delivery</div> <form onSubmit={formik.handleSubmit}> <div className="formInput"> <label className="checkout-label">Customer Name</label> <input className="checkout-input" type='text' name='name' onChange={formik.handleChange} value={formik.values.name} /> </div> <div className="formInput"> <label className="checkout-label">Delivery Address</label> <input className="checkout-input" type='text' name='address' onChange={formik.handleChange} value={formik.values.address} /> </div> <div className="formInput"> <label className="checkout-label">Contact No</label> <input className="checkout-input" type='text' name='contact' onChange={formik.handleChange} value={formik.values.contact} /> </div> <button disabled={isUploading} className='checkout-confirm-btn'>Confirm</button> </form> <button onClick={()=> setModelOpen(false)} className='item-model-content-close-btn'>Close</button> </div> </div> </Modal> </div> ); }; export default Cart;
<template> <div> <div v-if="sortedRequests.length"> <h2 class="text-2xl font-bold mb-4 text-center">All created requests</h2> <div class="flex flex-col justify-end mb-4"> <label class="mr-2">Sort by:</label> <el-select v-model="sortKey" placeholder="Sort by" class="w-40 mr-4"> <el-option label="Date of Creation" value="dateOfCreation" ></el-option> <el-option label="Date of Dispatch" value="dispatchDate"></el-option> </el-select> </div> <TransitionGroup name="list" tag="ul"> <li v-for="request in sortedRequests" :key="request.id" class="fade"> <div class="bg-gray-100 rounded-lg shadow-md p-4 mb-4"> <div class="text-lg font-semibold text-gray-600 mb-2"> Request Details </div> <div class="text-gray-600"> <strong>From City:</strong> {{ request.fromCity }} </div> <div class="text-gray-600"> <strong>To City:</strong> {{ request.toCity }} </div> <div v-if=" request.selectedRequestType === ERequestType.ORDER && request.parcelType " class="text-gray-600" > <strong>Parcel Type:</strong> {{ request.parcelType }} </div> <div v-if="request.dispatchDate" class="text-gray-600"> <strong>Dispatch Date:</strong> {{ request.dispatchDate }} </div> <div v-if=" request.selectedRequestType === ERequestType.ORDER && request.parcelDescription " class="text-gray-600" > <strong>Description:</strong> {{ request.parcelDescription }} </div> <div class="text-gray-600"> <strong>Order Type:</strong> {{ request.selectedRequestType }} </div> </div> </li> </TransitionGroup> </div> <h2 v-else class="text-2xl font-bold mb-4 text-center">No requests yet</h2> </div> </template> <script setup lang="ts"> import { useRequestsStore } from "@/stores/requests"; import { ref, computed } from "vue"; import { ERequestType } from "@/types/request.enums"; import type { IDeliverTypeForm, IOrderTypeForm } from "@/types/request.types"; const requestsStore = useRequestsStore(); const sortKey = ref<string>("dateOfCreation"); enum ESortType { sortByCreationDate = "dateOfCreation", sortByDispatchDate = "dispatchDate", } const sortedRequests = computed<(IOrderTypeForm & IDeliverTypeForm)[]>(() => { return [...requestsStore.requests].sort((a, b) => { if (sortKey.value === ESortType.sortByCreationDate) { return ( (b.dateOfCreation ? new Date(b.dateOfCreation).getTime() : 0) - (a.dateOfCreation ? new Date(a.dateOfCreation).getTime() : 0) ); } else if (sortKey.value === ESortType.sortByDispatchDate) { return ( (b.dispatchDate ? new Date(b.dispatchDate).getTime() : 0) - (a.dispatchDate ? new Date(a.dispatchDate).getTime() : 0) ); } return 0; }); }); </script> <style lang="css"> .list-move, /* apply transition to moving elements */ .list-enter-active, .list-leave-active { transition: all 0.5s ease; } .list-enter-from, .list-leave-to { opacity: 0; transform: translateX(30px); } /* ensure leaving items are taken out of layout flow so that moving animations can be calculated correctly. */ .list-leave-active { position: absolute; } </style>