text stringlengths 184 4.48M |
|---|
package uk.gov.companieshouse.registeredemailaddressapi.integration;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.web.servlet.MockMvc;
import uk.gov.companieshouse.api.model.company.RegisteredEmailAddressJson;
import uk.gov.companieshouse.api.model.transaction.Transaction;
import uk.gov.companieshouse.registeredemailaddressapi.exception.ServiceException;
import uk.gov.companieshouse.registeredemailaddressapi.integration.utils.Helper;
import uk.gov.companieshouse.registeredemailaddressapi.interceptor.UserAuthenticationInterceptor;
import uk.gov.companieshouse.registeredemailaddressapi.model.dao.RegisteredEmailAddressDAO;
import uk.gov.companieshouse.registeredemailaddressapi.model.dto.RegisteredEmailAddressDTO;
import uk.gov.companieshouse.registeredemailaddressapi.repository.RegisteredEmailAddressRepository;
import uk.gov.companieshouse.registeredemailaddressapi.service.PrivateDataRetrievalService;
import uk.gov.companieshouse.registeredemailaddressapi.service.TransactionService;
import static java.lang.String.format;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static uk.gov.companieshouse.api.model.transaction.TransactionStatus.CLOSED;
import static uk.gov.companieshouse.api.model.transaction.TransactionStatus.OPEN;
@SpringBootTest
@AutoConfigureMockMvc
class RegisteredEmailAddressControllerIntegrationTest {
Helper helper = new Helper();
@Autowired
private MockMvc mvc;
@MockBean
protected RegisteredEmailAddressRepository registeredEmailAddressRepository;
@MockBean
protected TransactionService transactionService;
@MockBean
protected PrivateDataRetrievalService privateDataRetrievalService;
@MockBean
protected UserAuthenticationInterceptor userAuthenticationInterceptor;
@Test
void testCreateRegisteredEmailAddressSuccessTest() throws Exception {
String email = "Test@Test.com";
Transaction transaction = helper.generateTransaction();
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO(email);
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transaction.getId());
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.insert(any(RegisteredEmailAddressDAO.class)))
.thenReturn(registeredEmailAddressDAO);
RegisteredEmailAddressJson emailResponse = helper.generateRegisteredEmailAddressJson(email);
when(privateDataRetrievalService.getRegisteredEmailAddress(any())).thenReturn(emailResponse);
mvc.perform(post("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456").content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isCreated()).andExpect(jsonPath("$.id").isNotEmpty())
.andExpect(jsonPath("$.data.registered_email_address").value("Test@Test.com"))
.andExpect(jsonPath("$.data.accept_appropriate_email_address_statement").value(true));
}
@Test
void testCreateRegisteredEmailAddressEmptyEmailFailureTest() throws Exception {
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO(null);
Transaction transaction = helper.generateTransaction();
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
this.mvc.perform(post("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456")
.content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0]")
.value("registered_email_address must not be blank"));
}
@Test
void testCreateRegisteredEmailAddressRegexFailureTest() throws Exception {
Transaction transaction = helper.generateTransaction();
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO("223j&kg");
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
this.mvc.perform(post("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456")
.content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors[0]")
.value("registered_email_address must have a valid email format"));
}
@Test
void testCreateRegisteredEmailFailureNoExistingEmailAddress() throws Exception {
String email = "Test@Test.com";
Transaction transaction = helper.generateTransaction();
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO(email);
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transaction.getId());
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.insert(any(RegisteredEmailAddressDAO.class)))
.thenReturn(registeredEmailAddressDAO);
RegisteredEmailAddressJson emailResponse = helper.generateRegisteredEmailAddressJson(null);
when(privateDataRetrievalService.getRegisteredEmailAddress(any())).thenReturn(emailResponse);
this.mvc.perform(post("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456")
.content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isForbidden())
.andExpect(content().string(containsString("Transaction id: ")))
.andExpect(content().string(containsString("; company number: ")))
.andExpect(content().string(containsString(" has no existing Registered Email Address")));
}
@Test
void testCreateRegisteredEmailFailureSubmissionAlreadyExistsAddress() throws Exception {
String email = "Test@Test.com";
Transaction transaction = helper.generateTransaction();
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO(email);
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transaction.getId());
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.insert(any(RegisteredEmailAddressDAO.class)))
.thenReturn(registeredEmailAddressDAO);
RegisteredEmailAddressJson emailResponse = helper.generateRegisteredEmailAddressJson(email);
when(privateDataRetrievalService.getRegisteredEmailAddress(any())).thenReturn(emailResponse);
// Create an existing submission
mvc.perform(post("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456").content(helper.writeToJson(registeredEmailAddressDTO)));
// Test the failure case
this.mvc.perform(post("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456")
.content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isConflict())
.andExpect(content().string(containsString("Transaction id: ")))
.andExpect(content().string(containsString(" has an existing Registered Email Address submission")));
}
//Test Update End points
@Test
void testUpdateRegisteredEmailAddressSuccessfulTest() throws Exception {
String email = "UpdateTest@Test.com";
Transaction transaction = helper.generateTransaction();
transaction.setStatus(OPEN);
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO(email);
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transaction.getId());
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.findByTransactionId(transaction.getId()))
.thenReturn(registeredEmailAddressDAO);
when(registeredEmailAddressRepository.save(any(RegisteredEmailAddressDAO.class)))
.thenReturn(registeredEmailAddressDAO);
RegisteredEmailAddressJson emailResponse = helper.generateRegisteredEmailAddressJson(email);
when(privateDataRetrievalService.getRegisteredEmailAddress(any())).thenReturn(emailResponse);
mvc.perform(put("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456").content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isOk()).andExpect(jsonPath("$.id").isNotEmpty())
.andExpect(jsonPath("$.data.registered_email_address").value("UpdateTest@Test.com"))
.andExpect(jsonPath("$.data.accept_appropriate_email_address_statement").value(true));
}
@Test
void testUpdateRegisteredEmailAddressIncorrectStatusTest() throws Exception {
String email = "UpdateTest@Test.com";
Transaction transaction = helper.generateTransaction();
transaction.setStatus(CLOSED);
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO(email);
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transaction.getId());
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.findByTransactionId(transaction.getId()))
.thenReturn(registeredEmailAddressDAO);
when(registeredEmailAddressRepository.save(any(RegisteredEmailAddressDAO.class)))
.thenReturn(registeredEmailAddressDAO);
mvc.perform(put("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456").content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isForbidden())
.andExpect(jsonPath("$")
.value(format("Transaction %s can only be edited when status is OPEN",
transaction.getId())));
}
@Test
void testUpdateRegisteredEmailAddressTransactionNotFound() throws Exception {
String email = "UpdateTest@Test.com";
String transactionId = "xxxxx-xxxxx-xxxxx";
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO(email);
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transactionId);
when(transactionService.getTransaction(any(), any(), any())).thenThrow(new ServiceException("Error Retrieving Transaction " + transactionId));
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.save(any(RegisteredEmailAddressDAO.class)))
.thenReturn(registeredEmailAddressDAO);
mvc.perform(put("/transactions/" + transactionId + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456").content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$")
.value("Error Retrieving Transaction " + transactionId));
}
@Test
void testUpdateRegisteredEmailFailureNoExistingEmailAddress() throws Exception {
String email = "UpdateTest@Test.com";
Transaction transaction = helper.generateTransaction();
transaction.setStatus(OPEN);
RegisteredEmailAddressDTO registeredEmailAddressDTO = helper.generateRegisteredEmailAddressDTO(email);
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transaction.getId());
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.findByTransactionId(transaction.getId()))
.thenReturn(registeredEmailAddressDAO);
when(registeredEmailAddressRepository.save(any(RegisteredEmailAddressDAO.class)))
.thenReturn(registeredEmailAddressDAO);
RegisteredEmailAddressJson emailResponse = helper.generateRegisteredEmailAddressJson(null);
when(privateDataRetrievalService.getRegisteredEmailAddress(any())).thenReturn(emailResponse);
mvc.perform(put("/transactions/" + transaction.getId() + "/registered-email-address")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456").content(helper.writeToJson(registeredEmailAddressDTO)))
.andExpect(status().isForbidden())
.andExpect(content().string(containsString("Transaction id: ")))
.andExpect(content().string(containsString("; company number: ")))
.andExpect(content().string(containsString(" has no existing Registered Email Address")));
}
// Test ValidationStatus Endpoints
@Test
void testGetValidationStatusTest() throws Exception {
Transaction transaction = helper.generateTransaction();
String email = "Test@Test.com";
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transaction.getId());
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.findByTransactionId(transaction.getId()))
.thenReturn(registeredEmailAddressDAO);
this.mvc.perform(get("/transactions/" + transaction.getId() + "/registered-email-address/validation-status")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.is_valid").value(true));
}
@Test
void testGetValidationStatusTest_invalid() throws Exception {
Transaction transaction = helper.generateTransaction();
String email = "TestTest.com";
RegisteredEmailAddressDAO registeredEmailAddressDAO = helper
.generateRegisteredEmailAddressDAO(email, transaction.getId());
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
when(registeredEmailAddressRepository.findByTransactionId(transaction.getId()))
.thenReturn(registeredEmailAddressDAO);
this.mvc.perform(get("/transactions/" + transaction.getId() + "/registered-email-address/validation-status")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.errors").isNotEmpty())
.andExpect(jsonPath("$.is_valid").value(false));
}
@Test
void testGetValidationStatusFailureTest() throws Exception {
Transaction transaction = helper.generateTransaction();
when(transactionService.getTransaction(any(), any(), any())).thenReturn(transaction);
when(userAuthenticationInterceptor.preHandle(any(), any(), any())).thenReturn(true);
this.mvc.perform(get("/transactions/" + transaction.getId() + "/registered-email-address/validation-status")
.contentType("application/json").header("ERIC-Identity", "123")
.header("X-Request-Id", "123456"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$")
.value(String.format("Registered Email Address for TransactionId : %s Not Found", transaction.getId())));
}
} |
import axios from "axios";
import React, { useEffect, useState } from "react";
export default function Transfer({ customers, customer }) {
const [loading, setLoading] = useState(false);
const [disabled, setDisabled] = useState(true);
const [receiverData, setreceiverData] = useState(null);
const [senderData, setSenderData] = useState(null);
const [selectedCustomer, setSelectedCustomer] = useState("");
const [amount, setAmount] = useState(0);
const [senderUpdated, setSenderUpdated] = useState({
email: "",
currentBalance: 0,
});
const [receiver, setReceiver] = useState({
email: "",
currentBalance: 0,
});
function refreshPage() {
window.location.reload(false);
}
function handleSelectChange(e) {
setSelectedCustomer(e.target.value);
}
function handleAmountChange(e) {
let money = e.target.value;
if (money <= 0) {
console.log("first");
setDisabled(true);
} else {
if (money > customer.currentBalance) {
console.log("second");
setDisabled(true);
} else {
setAmount(e.target.value);
setDisabled(false);
}
}
}
function getReceiverInfo() {
let mySender = { ...senderUpdated };
mySender.email = customer.email;
mySender.currentBalance = customer.currentBalance - amount;
let myReciever = { ...receiver };
let valArr = selectedCustomer?.split(" ");
myReciever.email = valArr[0];
myReciever.currentBalance = Number(valArr[1]) + Number(amount);
setSenderUpdated(mySender);
setReceiver(myReciever);
}
useEffect(() => {
getReceiverInfo();
//eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedCustomer, amount]);
async function updateCustomer(customer, cb) {
let { data } = await axios.patch(
`https://basicbankingapi.herokuapp.com/customers`,
customer
);
cb({ data }.data);
}
function submit() {
updateCustomer(receiver, setreceiverData);
updateCustomer(senderUpdated, setSenderData);
setLoading(true);
console.log(senderData);
if (receiverData === null) {
setLoading(false);
} else {
setLoading(false);
refreshPage();
}
}
return (
<section
className="modal fade"
id="exampleModal"
tabIndex={-1}
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div className="modal-dialog .modal-dialog-scrollable modal-dialog-centered">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalLabel">
Send Money
</h5>
<button
type="button"
className="bg-transparent btn-x border-0 text-white"
data-bs-dismiss="modal"
aria-label="Close"
>
<i className="fa fa-close fs-5" aria-hidden="true"></i>
</button>
</div>
<div className="modal-body mt-4">
<h4 className="text-center mt-3">
The Current Balance of {customer?.name} is $
{customer?.currentBalance}
</h4>
<form>
<div className="receiver my-4 d-flex justify-content-between">
<div>
<h6>Transfer To</h6>
<select
className="form-select"
id="receivers"
aria-label="select"
value={selectedCustomer}
onChange={handleSelectChange}
>
<option value={" "}> </option>
{customers
.filter((ele) => ele.email !== customer.email)
.map(({ name, email, currentBalance }, index) => {
return (
<option
key={index}
value={email + " " + currentBalance}
name="email"
>
{name} (${currentBalance})
</option>
);
})}
</select>
</div>
<div className="ms-5 w-50">
<h6>Amount:</h6>
<input
className="form-control w-75"
type="Number"
onChange={handleAmountChange}
title="please enter number only"
name="amount"
value={amount}
/>
<p className="fs-10 text-danger">
{amount <= 0 ? "the amount should be more than 0 and not more than sender's current balance" : ""}
</p>
</div>
</div>
<div className="modal-footer px-0">
<div className="d-flex flex-column">
<button
type="button"
onClick={submit}
className="btn"
disabled={disabled}
>
{loading ? (
<i
className="fas fa-spinner fa-spin"
aria-hidden="true"
></i>
) : (
"Confirm & Transfer"
)}
</button>
<p className="fs-10">Click twice to Confirm</p>
</div>
</div>
</form>
</div>
</div>
</div>
</section>
);
} |
import "./App.css";
import Home from "./Pages/Home";
import LoginPage from "./Pages/LoginPage";
import SignUpPage from "./Pages/SignUpPage";
import MainLayout from "./components/MainLayout";
import { Routes, Route } from "react-router-dom"
import { UserContextProvider } from "./context/UserContext";
import CreatePost from "./Pages/CreatePost";
import PostPage from "./Pages/PostPage";
import EditPostPage from "./Pages/EditPostPage";
export const server_url = 'https://weblog-9c7k.onrender.com'
function App() {
return (
<>
<UserContextProvider>
<Routes>
<Route path="/" element={<MainLayout />}>
<Route index element={<Home />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/signup" element={<SignUpPage />} />
<Route path="/create" element={<CreatePost />} />
<Route path="/post/:id" element={<PostPage />} />
<Route path="/edit/:id" element={<EditPostPage />} />
</Route>
</Routes>
</UserContextProvider>
</>
);
}
export default App; |
<header class="flex justify-content-between align-items-center px-6 py-3">
<div class="flex gap-5 align-items-center">
<a id="logo" routerLink="/">
<h1>IFAdvert</h1>
</a>
<ul class="list-none flex gap-6">
<li>
<a routerLink="/app">App</a>
</li>
<li>
<a routerLink="/" fragment="services">Services</a>
</li>
<li>
<a routerLink="/" fragment="aboutUs">About us</a>
</li>
</ul>
</div>
<div class="flex gap-5">
<button pButton pRipple label="Sign in" routerLink="/login" class="p-button-text p-button-round"></button>
<button pButton pRipple label="Register" routerLink="/register" class="p-button-rounded"></button>
</div>
</header>
<section id="hero" class="flex justify-content-between gap-4">
<div>
<h1 class="text-6xl font-bold text-gray-900 line-height-2">
<span class="font-light block">Advertisement company</span>
<span class="text-primary">IFAdvert</span>
</h1>
<p class="font-normal text-2xl line-height-3 md:mt-3 text-gray-700">Your one-step solution for all your advertising
needs.</p>
<button pButton pRipple type="button" label="Get Started" routerLink="/app"
class="p-button-rounded bg-primary text-xl mt-3 px-3"></button>
</div>
<div class="align-self-center max-h-20rem" style="max-width: 43rem">
<img ngSrc="assets/landing/advertisement-scheme.jpeg" alt="bus ad" fill="true" priority="true"
class="relative bg-contain border-round-2xl"/>
</div>
</section>
<section id="services" class="grid px-2 mt-8 pt-5">
<h1 class="col-12 text-center text-primary mb-3">Ways to advertise your product</h1>
<div class="col-12 md:col-6 lg:col-4">
<p-card header="Billboards" subheader="Huge choice of billboard">
<img ngSrc="assets/landing/billboard-advertising.jpg" alt="billboard" fill="true" class="relative bg-contain"/>
<p>Billboard advertising is a powerful tool for reaching a large audience and creating brand awareness. It is a
cost-effective way to reach a wide range of people, and it can be very effective in driving traffic to your
website or business.<br><br><b>Here are some of the benefits of billboard advertising:</b></p>
<ul>
<li><b>High exposure:</b> Billboards are seen by millions of people every day.</li>
<li><b>Visual impact:</b> Billboards are large and eye-catching, so they can make a big impact.</li>
<li><b>Targeted advertising:</b> Billboards can be placed in specific locations to reach a particular audience.
</li>
<li><b>Cost-effective:</b> Billboards are a relatively inexpensive way to reach a large audience.</li>
</ul>
<ng-template pTemplate="footer">
<div class="flex justify-content-between">
<h4 class="my-2">Price range:</h4>
<h4 class="text-primary my-2">800$ – 10000$</h4>
</div>
</ng-template>
</p-card>
</div>
<div class="col-12 md:col-6 lg:col-4">
<p-card header="Transport" subheader="Buses, trucks, trams, metro">
<img ngSrc="assets/landing/metro-advertising.jpg" alt="transport" fill="true" class="relative bg-contain"/>
<p>
Transport advertising, also known as transit advertising, is a form of out-of-home (OOH) advertising that
utilizes
various modes of public transportation to display advertisements to passengers and commuters. This includes
buses,
trains, subways, taxis, and even airports.<br><br><b>Benefits of Transport Advertising:</b></p>
<ul>
<li><b>High frequency:</b> Passengers are exposed to transport advertisements multiple times throughout their
journeys, increasing brand recall and familiarity.
</li>
<li><b>Targeted audience:</b> Advertisers can strategically select transport routes and vehicles to reach
specific
demographics and geographic locations.
</li>
<li><b>Visual impact:</b> Creative and eye-catching advertisements can stand out amidst the captive audience,
making a lasting impression.
</li>
<li><b>Measurable results:</b> Transport advertising campaigns can be tracked and measured using various
metrics,
such as passenger traffic, ad visibility, and brand recall, allowing advertisers to assess campaign
effectiveness.
</li>
</ul>
<ng-template pTemplate="footer">
<div class="flex justify-content-between">
<h4 class="my-2">Bus:</h4>
<h4 class="text-primary my-2">50$ – 4000$</h4>
</div>
<div class="flex justify-content-between">
<h4 class="my-2">Truck:</h4>
<h4 class="text-primary my-2">800$ – 3600$</h4>
</div>
<div class="flex justify-content-between">
<h4 class="my-2">Metro:</h4>
<h4 class="text-primary my-2">400$ – 2500$</h4>
</div>
</ng-template>
</p-card>
</div>
<div class="col-12 md:col-6 lg:col-4">
<p-card header="TV & Radio" subheader="TV channels and radio stations">
<img ngSrc="assets/landing/tv-advertising.jpg" alt="tv and radio" fill="true" class="relative bg-contain"/>
<p>Television advertising is a form of advertising that utilizes television programs to deliver messages to
viewers.
It is a mass medium that can reach a large audience very quickly. Television ads can be very creative and
engaging, and they can be a powerful way to build brand awareness and promote products or services.
<br><br><b>Benefits of tv and radio advertising:</b></p>
<ul>
<li><b>Targeted audience:</b> tv and radio advertising can be very effective in reaching a specific audience.
</li>
<li><b>Creative potential:</b> tv and radio ads can be very creative and engaging, which can help them to
capture the attention of listeners and watchers.
</li>
<li><b>Brand building:</b> tv and radio ads can be very effective in building brand awareness and promoting
products or services.
</li>
</ul>
<ng-template pTemplate="footer">
<div class="flex justify-content-between">
<h4 class="my-2">Television:</h4>
<h4 class="text-primary my-2">10$ – 90$ per 1000 views</h4>
</div>
<div class="flex justify-content-between">
<h4 class="my-2">Radio:</h4>
<h4 class="text-primary my-2">10$ – 650$ per 60-second spot</h4>
</div>
</ng-template>
</p-card>
</div>
</section>
<section id="aboutUs" class="mt-8">
<h1 class="text-center text-primary">About us</h1>
<p class="text-lg"> At IFAdvert, we are passionate about the power of advertising to connect
brands with their
audiences and drive business results. We are a team of experienced professionals who are dedicated to helping our
clients achieve their marketing goals through innovative and effective advertising campaigns.
<br> We believe that advertising is not just about selling products and services; it's about
building relationships
and creating meaningful connections with consumers. We take a strategic approach to advertising, carefully
considering our clients' target audiences, brand messaging, and overall marketing objectives.</p>
<h3 class="text-primary mt-6">Our Mission</h3>
<p class="text-lg">Our mission is to help our clients achieve their marketing goals through innovative and effective
advertising campaigns.</p>
<h3 class="text-primary mt-6">Our Values</h3>
<p class="text-lg">We are committed to the following values:</p>
<ul class="text-lg">
<li><b>Creativity:</b> We believe in the power of creativity to break through the clutter and capture the attention
of our clients' target audiences.<br><br>
</li>
<li><b>Effectiveness:</b> We are focused on delivering results for our clients. We measure the success of our
campaigns against clear and measurable objectives.<br><br>
</li>
<li><b>Integrity:</b> We are committed to building relationships with our clients based on trust and respect.<br><br></li>
<li><b>Innovation:</b> We are constantly looking for new and innovative ways to help our clients succeed.<br><br></li>
</ul>
</section> |
/***************************************************************************
* Copyright (C) 2008 by Roberto Barreda <rbarreda@ac.upc.edu> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef NMGSTATISTICREMOTEWIDGET_H
#define NMGSTATISTICREMOTEWIDGET_H
#include "nmgstatisticfileloader.h"
#include <nmgmodulemanager.h>
#include <QString>
/*! \brief NMGStatisticRemoteContainer is a container class that stores the parsed information from the remote request
*
* Parses received information (request) to load the list of items requested, as well as statistical values required to generate
* after the output file from these options. */
class NMGStatisticRemoteContainer
{
public:
/*! \brief Parses part of the XML Request to list the requested items and statistic values
*
* This function is for "packets" tests
* \param items should be like a list of flowIds separated by semicolons like 1;2;3;...;N or ranges like 1..N or ALL.
* \param statistics should be a list of tags separated by semicolons.*/
NMGStatisticRemoteContainer( QString & items, QString & statistics );
/*! \brief Parses part of the XML Request to list the statistic requested values
*
* This function is for "throughtput" tests
* \param statistics should be a list of tags separated by semicolons.*/
NMGStatisticRemoteContainer( QString & statistics );
/*! \brief Returns if there is an error on the parsing.
* \return TRUE if there is an error on the parsing, FALSE if there is no error.*/
inline bool hasError() { return error; };
QStringList itemList; /*!< List of items that want to parse. */
QStringList basicStatistisList; /*!< List of basic statistics. */
QStringList delayStatistisList; /*!< List of delay statistics. */
QStringList ipdvStatistisList; /*!< List of ipdv statistics. */
int innerCounter; /*!< Number of requested items counter. */
private:
bool error; /*!< Error on parsing. */
};
/*! \brief NMGStatisticRemoteWidget is the class is responsible for receiving the petition, parsing the XML, upload the data structures
* and eventually generate the output from the configuration options requested. */
class NMGStatisticRemoteWidget : public QWidget
{
Q_OBJECT
public:
/*! \brief Contructor of the class. Loads the statistic file loader and cache
* \param modmanager Pointer to the Module manager.
* \param currentTestId Identifier of the current module id.
* \sa NMGStatisticFileLoader */
NMGStatisticRemoteWidget( NMGModuleManager * modmanager, QString currentTestId );
/*! \brief Default destructor of the class. */
~NMGStatisticRemoteWidget();
/*! \brief Parses the XML request and loads requested tests
* \param data QString with the request in XML format. */
bool loadData( QString data );
private slots:
/*! \brief Slot executed when a test parsing is finished that builds the XML reply
* \param filePathId QString with path of the file test.
* \param fileMD5Id QString with the MD5 ID of the file test. */
void updateWidgetBecauseOfTestEnd( const QString & filePathId, const QString & fileMD5Id );
private:
bool loadPacketData ( QXmlStreamReader * xml );
bool loadThroughtputData ( QXmlStreamReader * xml );
void generateFlow ( QXmlStreamWriter * xmlw, NMGStatisticPacketData * flow, const QString & filePathId );
QString testId;
QMap<QString, NMGStatisticRemoteContainer *> exportListMap;
NMGStatisticFileLoader * fileLoader;
NMGModuleManager * moduleManager;
};
#endif |
import tensorflow as tf
class ModifiedAdam(tf.keras.optimizers.Adam):
def __init__(self, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, use_locking=False, amsgrad=False, name="ModifiedAdam", **kwargs):
super(ModifiedAdam, self).__init__(learning_rate=learning_rate, beta_1=beta_1, beta_2=beta_2, epsilon=epsilon, amsgrad=amsgrad, name=name, **kwargs)
def _resource_apply_dense(self, grad, var, apply_state=None):
# get current states
# m = self.get_slot(var, 'm')
# v = self.get_slot(var, 'v')
# # here are the original update equations in Adam
# m.assign(m * self._get_hyper('beta_1') + grad * (1. - self._get_hyper('beta_1')))
# v.assign(v * self._get_hyper('beta_2') + (grad ** 2) * (1. - self._get_hyper('beta_2')))
# # make your modifications here
# # for example, let's square the m term before using it in the update
# m_mod = m ** 2
# var.assign_sub(self._get_hyper('learning_rate') * m_mod / (tf.sqrt(v) + self._get_hyper('epsilon')))
var_dtype = var.dtype.base_dtype
lr_t = tf.cast(self.learning_rate, var_dtype)
beta1_t = tf.cast(self.beta1, var_dtype)
beta2_t = tf.cast(self.beta2, var_dtype)
epsilon_t = tf.cast(self.epsilon, var_dtype)
m = self.get_slot(var, 'm')
v = self.get_slot(var, 'v')
d = self.get_slot(var, 'd')
g = self.get_slot(var, 'g')
m_t = m.assign(beta1_t * m + (1. - beta1_t) * grad)
v_t = v.assign(beta2_t * v + (1. - beta2_t) * tf.square(grad))
alpha_t = tf.sqrt(1 - beta2_t) / (1 - beta1_t)
g_t = (m_t*alpha_t) / (tf.sqrt(v_t) + epsilon_t)
m_t = tf.where((tf.sign(g) * tf.sign(grad)) < 0, tf.sign(g_t) * (beta1_t * tf.abs(g_t) - (1-beta1_t) * tf.abs(d)), tf.sign(g_t) * (beta1_t * tf.abs(g_t) + (1-beta1_t) * tf.abs(d)))
d_t = d.assign(m_t)
g_t = g.assign(grad)
var_update = var.assign_sub(lr_t * d_t)
updates = [var_update, m_t, v_t, d_t, g_t]
return tf.group(*updates)
def _create_slots(self, var_list):
for var in var_list:
self.add_slot(var, 'm')
self.add_slot(var, 'v')
self.add_slot(var, 'd')
self.add_slot(var, 'g')
def _resource_apply_sparse(self, grad, var, indices):
raise NotImplementedError("Sparse gradient updates are not supported.")
def get_config(self):
base_config = super().get_config()
return {
**base_config,
"learning_rate": self.learning_rate.numpy(),
"beta1": self.beta1.numpy(),
"beta2": self.beta2.numpy(),
"epsilon": self.epsilon,
} |
import { useEffect } from "react";
import { useActions } from "../hooks/use-actions";
import { Cell } from "../state";
import CodeEditor from "./code-editor";
import Preview from "./preview";
import { Resizable } from "./resizable";
import { useTypedSelector } from "../hooks/use-typed-selector";
import { useCumulativeCode } from "../hooks/use-cumulative-code";
import styled from "styled-components";
interface CodeCellProps {
cell: Cell;
focused: boolean;
}
const CodeCell: React.FC<CodeCellProps> = ({ cell, focused }) => {
const { updateCell, createBundle } = useActions();
const bundle = useTypedSelector((state) => state.bundles[cell.id]);
const cumulativeCode = useCumulativeCode(cell.id);
useEffect(() => {
if (!bundle) {
createBundle(cell.id, cumulativeCode);
return;
}
const timer = setTimeout(async () => {
createBundle(cell.id, cumulativeCode);
}, 750);
return () => {
clearTimeout(timer);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [cumulativeCode, cell.id, createBundle]);
return (
<StyledCodeCell className={focused ? "focused" : ""}>
<Resizable direction="vertical">
<div
style={{
height: "calc(100% - 10px)",
display: "flex",
flexDirection: "row",
}}
>
<Resizable direction="horizontal">
<CodeEditor
initialValue={cell.content}
onChange={(value) => updateCell(cell.id, value)}
/>
</Resizable>
<PreviewWrapper>
{!bundle || bundle.loading ? (
<ProgressWrapper>
<progress max="100">Loading</progress>
</ProgressWrapper>
) : (
<Preview code={bundle.code} error={bundle.err} />
)}
</PreviewWrapper>
</div>
</Resizable>
</StyledCodeCell>
);
};
const StyledCodeCell = styled.div`
&.focused {
-webkit-box-shadow: 0 2px 7px -2px #000000;
-moz-box-shadow: 0 2px 7px -2px #000000;
box-shadow: 0 2px 7px -2px #000000;
}
`;
const PreviewWrapper = styled.div`
height: 100%;
flex-grow: 1;
background-color: white;
`;
const ProgressWrapper = styled.div`
height: 100%;
width: 100%;
flex-grow: 1;
background-color: white;
display: flex;
align-items: center;
padding-left: 10%;
padding-right: 10%;
animation: fadeIn 0.5s;
@keyframes fadeIn {
0% {
opacity: 0;
}
50% {
opacity: 0.5;
}
100% {
opacity: 1;
}
}
`;
export default CodeCell; |
<template>
<Head :title="$t('category_module')" />
<ps-layout>
<!-- breadcrumb start -->
<ps-breadcrumb-2 :items="breadcrumb" class="mb-5 sm:mb-6 lg:mb-8" />
<!-- breadcrumb end -->
<!-- alert banner start -->
<ps-banner-icon v-if="visible" :visible="visible"
:theme="(status.flag)=='danger'?'bg-red-500':(status.flag)=='warning'?'bg-yellow-500':'bg-green-500'"
:iconName="(status.flag)=='danger'?'close-circle':(status.flag)=='warning'?'alert-triangle':'rightalert'"
class="text-white mb-5 sm:mb-6 lg:mb-8"
iconColor="white">{{status.msg}}</ps-banner-icon>
<!-- alert banner end -->
{{ sort_field }}
<!-- data table start -->
<!-- <div class="overflow-x-auto" > -->
<ps-table2 :row="row" :search="search" :object="this.categories" :colFilterOptions="colFilterOptions" :columns="columns" :sort_field="sort_field" :sort_order="sort_order" @FilterOptionshandle="FilterOptionshandle"
@handleSort="handleSorting" @handleSearch="handleSearching" @handleRow="handleRow"
:globalSearchPlaceholder="$t('core__be_search_category')">
<!-- for csv file import start -->
<template #searchLeft>
<ps-button v-if="can.createCategory" @click="csvUploadClicked" rounded="rounded" class="flex flex-wrap items-center ms-3 ">
<ps-icon name="plus" class="me-2 font-semibold" />
<ps-label textColor="text-white dark:text-secondary-800">{{ $t('core__be_import_file') }}</ps-label>
</ps-button>
<ps-csv-modal ref="ps_csv_modal" url="https://drive.google.com/file/d/1XRhURzcCkMb1UzUQMkFCBvTcOOrYFWRq/view?usp=sharing"/>
</template>
<!-- for csv file import end -->
<!-- add new field start -->
<template #button>
<ps-button v-if="can.createCategory" @click="handleCreate()" rounded="rounded-lg" type="button" class="flex flex-wrap items-center"> <ps-icon name="plus" class="me-2 font-semibold" />{{$t('core__add_category')}}</ps-button>
</template>
<template #responsive_button>
<ps-button v-if="can.createCategory" @click="handleCreate()" rounded="rounded-lg" type="button" class="flex flex-wrap items-center"> <ps-icon name="plus" class="me-2 font-semibold" />{{$t('core__add_category')}}</ps-button>
</template>
<!-- add new field end -->
<template #tableActionRow="rowProps">
<!-- For action (edit/delete) start -->
<div class="flex flex-row " v-if="rowProps.field == 'action'">
<ps-button :disabled="rowProps.row.authorization.update ? false : true" @click="handleEdit(rowProps.row.id)" class="me-2" colors="bg-green-400 text-white" padding="p-1.5"
hover="hover:outline-none hover:ring hover:ring-green-100"
focus="focus:outline-none focus:ring focus:ring-green-200">
<ps-icon theme="text-white dark:text-primary-900" name="editPencil" w="16" h="16" />
</ps-button>
<ps-button :disabled="rowProps.row.authorization.delete ? false : true" @click="confirmDeleteClicked(rowProps.row.id)" colors="bg-red-400 text-white" padding="p-1.5"
hover="hover:outline-none hover:ring hover:ring-red-100"
focus="focus:outline-none focus:ring focus:ring-red-200">
<ps-icon theme="text-white dark:text-primary-900" name="trash" w="16" h="16" />
</ps-button>
<ps-danger-dialog ref="ps_danger_dialog" />
</div>
<!-- For action (edit/delete) end -->
</template>
<template #tableRow="rowProps">
<div v-if="rowProps.field == 'status' && reRenderToogle">
<ps-toggle :disabled="rowProps.row.authorization.update ? false : true" v-if="rowProps.field == 'status'" :selectedValue="rowProps.row.status == 1 ? true : false"
@click="handlePublish(rowProps.row.id,rowProps.row.authorization.update)"></ps-toggle>
</div>
</template>
</ps-table2>
<!-- </div> -->
<!-- data table end -->
</ps-layout>
</template>
<script>
import { defineComponent, ref } from 'vue'
import { Link, Head, useForm } from '@inertiajs/inertia-vue3';
import PsLayout from "@/Components/PsLayout.vue";
import PsLabel from "@/Components/Core/Label/PsLabel.vue";
import PsButton from "@/Components/Core/Buttons/PsButton.vue";
import PsTable2 from "@/Components/Core/Table/PsTable2.vue";
import PsAlert from "@/Components/Core/Alert/PsAlert.vue";
import PsBreadcrumb2 from "@/Components/Core/Breadcrumbs/PsBreadcrumb2.vue";
import PsDangerDialog from "@/Components/Core/Dialog/PsDangerDialog.vue";
import PsToggle from '@/Components/Core/Toggle/PsToggle.vue';
import PsIcon from "@/Components/Core/Icons/PsIcon.vue";
import PsCsvModal from '@/Components/Core/Modals/PsCsvModal.vue';
import PsBannerIcon from "@/Components/Core/Banners/PsBannerIcon.vue";
import Dropdown from "@/Components/Core/DropdownModal/Dropdown.vue";
import PsIconButton from "@/Components/Core/Buttons/PsIconButton.vue";
import { trans } from 'laravel-vue-i18n';
import { Inertia } from "@inertiajs/inertia";
export default defineComponent({
name: "Index",
components: {
Link,
Head,
PsLabel,
PsButton,
PsTable2,
PsAlert,
PsBreadcrumb2,
PsDangerDialog,
PsToggle,
PsIcon,
PsCsvModal,
PsBannerIcon,
Dropdown,
PsIconButton
},
layout : PsLayout,
// props: ['categories', 'status', 'can','hideShowFieldForFilterArr', "showCoreAndCustomFieldArr",],
props:{
can:Object,
status:Object,
categories:Object,
hideShowFieldForFilterArr:Object,
showCoreAndCustomFieldArr:Object,
sort_field:{
type:String,
default:"",
},
sort_order:{
type:String,
default:'desc',
},
search:String,
},
data() {
return {
form: useForm(
{
csvFile : ""
}
)
}
},
setup(props) {
// For data table
let search = props.search ? ref(props.search) : ref('');
let sort_field = props.sort_field ? ref(props.sort_field) : ref('');
let sort_order = props.sort_order ? ref(props.sort_order) : ref('desc');
const ps_danger_dialog = ref();
const ps_csv_modal = ref();
let visible = ref(false)
const colFilterOptions = ref();
const columns = ref();
const reRenderToogle = ref(true);
function confirmDeleteClicked(id) {
ps_danger_dialog.value.openModal(
trans('core__delete'),
trans('delete_category_msg'),
trans('core__be_btn_confirm'),
trans('core__be_btn_cancel'),
() => {
this.$inertia.delete(route("category.destroy", id),{
onSuccess: () => {
visible.value = true;
setTimeout(() => {
visible.value = false;
}, 3000);
},
onError: () => {
visible.value = true;
setTimeout(() => {
visible.value = false;
}, 3000);
},
})
},
() => { }
);
}
function csvUploadClicked(){
ps_csv_modal.value.openModal(
(selectedFile) => {
let form = useForm({
csvFile: selectedFile,
"_method": "put"
})
Inertia.post(route('category.import.csv'), form)
}
);
}
function handleSorting(value){
sort_field.value = value.field
sort_order.value = value.sort_order
handleSearchingSorting()
}
function handleSearching(value){
search.value = value;
let page=1;
handleSearchingSorting(page);
}
function handleRow(value){
handleSearchingSorting(1,value);
}
function handleSearchingSorting(page = null,row=null){
Inertia.get(route('category.index'),
{
sort_field : sort_field.value,
sort_order: sort_order.value,
page:page ?? props.categories.meta.current_page,
row:row ?? props.categories.meta.per_page,
search:search.value,
},
{
preserveScroll: true,
preserveState:true,
})
}
function handlePublish(id,hasPermission){
if(hasPermission){
this.$inertia.put(route('category.statusChange',id));
setTimeout(() => {
reRenderToogle.value= false;
setTimeout(() => {
reRenderToogle.value = true;
}, 200);
}, 2000);
}
}
return {
handleRow,
handleSearchingSorting,
handleSearching,
handleSorting,
visible,
ps_csv_modal,
// globalSearchPlaceholder,
columns, ps_danger_dialog,
confirmDeleteClicked,
colFilterOptions ,
csvUploadClicked,
reRenderToogle,
handlePublish
}
},
computed: {
breadcrumb() {
return [
{
label: trans('core__be_dashboard_label'),
url: route('admin.index')
},
{
label: trans('category_module'),
color: "text-primary-500"
}
]
}
},
created() {
this.columns = this.showCoreAndCustomFieldArr.map(column => {
return {
action: column.action,
field: column.field,
label: trans(column.label),
sort: column.sort,
type: column.type
};
});
this.colFilterOptions = this.hideShowFieldForFilterArr.map(columnFilterOption => {
return {
hidden: columnFilterOption.hidden,
id: columnFilterOption.id,
key: trans(columnFilterOption.key),
key_id: columnFilterOption.key_id,
label: trans(columnFilterOption.label),
module_name: columnFilterOption.module_name
};
});
},
methods: {
handleCreate() {
this.$inertia.get(route("category.create"));
},
handleEdit(id){
this.$inertia.get(route('category.edit',id));
},
// handlePublish(id){
// this.$inertia.put(route('category.statusChange',id));
// },
FilterOptionshandle(value) {
Inertia.put(route('category.screenDisplayUiSetting.store'),
{
value,
sort_field :this.sort_field ,
sort_order:this.sort_order,
row:this.categories.per_page,
search:this.search.value,
current_page:this.categories.current_page
},
{
preserveScroll: true,
preserveState:true,
});
},
},
})
</script> |
package com.example.e_finity.teams
import android.R
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.e_finity.GroupRead
import com.example.e_finity.MainActivity
import com.example.e_finity.UserRead
import com.example.e_finity.adapter.MemberAdapter
import com.example.e_finity.databinding.ActivityJointeamBinding
import io.github.jan.supabase.SupabaseClient
import io.github.jan.supabase.createSupabaseClient
import io.github.jan.supabase.gotrue.GoTrue
import io.github.jan.supabase.postgrest.Postgrest
import io.github.jan.supabase.postgrest.postgrest
import io.github.jan.supabase.postgrest.query.Order
import io.github.jan.supabase.storage.Storage
import io.github.jan.supabase.storage.storage
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
class JoinTeamActivity: AppCompatActivity() {
private lateinit var binding: ActivityJointeamBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityJointeamBinding.inflate(layoutInflater)
setContentView(binding.root)
val client = getclient()
val bucket = client.storage["avatar"]
val sharePreference = getSharedPreferences("MY_PRE", Context.MODE_PRIVATE)
val name = intent.getStringExtra("name")
val color = intent.getStringExtra("color")
val timemodi = intent.getStringExtra("timemodi")
val url = bucket.publicUrl(name + ".png") + "?timestamp=" + timemodi
Glide.with(this).load(url).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL).error(
com.example.e_finity.R.drawable.baseline_person).into(binding.jgroupAva)
binding.jgroupName.text = name
binding.jgroupAvaBorder.setStrokeColor(Color.parseColor("#"+color))
binding.groupStroke.setStrokeColor(Color.parseColor("#"+color))
if (sharePreference.getString("GROUP", "").toString() == name) {
binding.teamjoinButton.text = "Leave"
}
else if (sharePreference.getString("GROUP", "").toString() != "None") {
binding.teamjoinButton.visibility = View.GONE
}
lifecycleScope.launch {
val memberDataResponse = client.postgrest["user"].select {
if (name != null) {
eq("group", name)
}
order("id", Order.ASCENDING)
}
val memberData = memberDataResponse.decodeList<UserRead>()
val adapter = MemberAdapter(memberData, name)
binding.groupMemberRecycler.adapter = adapter
binding.groupMemberRecycler.layoutManager = LinearLayoutManager(this@JoinTeamActivity)
}
binding.teamjoinButton.setOnClickListener {
if (binding.teamjoinButton.text.toString() == "Leave") {
runBlocking {
client.postgrest["user"].update ({
set("group", "None")
}) {
eq("uniqueID", sharePreference.getString("SESSION", "").toString())
}
}
val editor = sharePreference.edit()
editor.putString("GROUP", "None")
editor.apply()
Toast.makeText(this, "You've left the group", Toast.LENGTH_LONG).show()
binding.teamjoinButton.text = "Join"
}
else {
runBlocking {
client.postgrest["user"].update ({
set("group", name)
}) {
eq("uniqueID", sharePreference.getString("SESSION", "").toString())
}
}
val editor = sharePreference.edit()
editor.putString("GROUP", name)
editor.apply()
Toast.makeText(this, "You've joined the group", Toast.LENGTH_LONG).show()
binding.teamjoinButton.text = "Leave"
}
lifecycleScope.launch {
val memberDataResponse = client.postgrest["user"].select {
if (name != null) {
eq("group", name)
}
order("id", Order.ASCENDING)
}
val memberData = memberDataResponse.decodeList<UserRead>()
val adapter = MemberAdapter(memberData, name)
binding.groupMemberRecycler.adapter = adapter
binding.groupMemberRecycler.layoutManager = LinearLayoutManager(this@JoinTeamActivity)
}
}
}
override fun onResume() {
super.onResume()
val client = getclient()
val name = intent.getStringExtra("name")
lifecycleScope.launch {
val memberDataResponse = client.postgrest["user"].select {
if (name != null) {
eq("group", name)
}
order("id", Order.ASCENDING)
}
val memberData = memberDataResponse.decodeList<UserRead>()
val adapter = MemberAdapter(memberData, name)
binding.groupMemberRecycler.adapter = adapter
binding.groupMemberRecycler.layoutManager = LinearLayoutManager(this@JoinTeamActivity)
}
}
private fun getclient(): SupabaseClient {
return createSupabaseClient(
supabaseUrl = "https://nabbsmcfsskdwjncycnk.supabase.co",
supabaseKey = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im5hYmJzbWNmc3NrZHdqbmN5Y25rIiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTM5MDM3ODksImV4cCI6MjAwOTQ3OTc4OX0.dRVk2u91mLhSMaA1s0FSyIFwnxe2Y3TPdZZ4Shc9mAY"
) {
install(Postgrest)
install(GoTrue)
install(Storage)
}
}
} |
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::get('staff', 'StaffController@index');
Route::get('staff/{staff}', 'StaffController@show');
Route::post('staff', 'StaffController@store');
Route::put('staff/{staff}', 'StaffController@update');
Route::delete('staff/{staff}', 'StaffController@delete'); |
package pl.szymen.rxsample.api;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.logging.HttpLoggingInterceptor;
import java.util.List;
import pl.szymen.rxsample.Constants;
import pl.szymen.rxsample.data.model.Repo;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by szymen on 2015-11-25.
*/
public class ApiManager {
private GithubService mGithubService;
public ApiManager() {
mGithubService = getRetrofit().create(GithubService.class);
}
private Retrofit getRetrofit() {
OkHttpClient okhttp = new OkHttpClient();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okhttp.interceptors().add(interceptor);
return new Retrofit.Builder()
.baseUrl(Constants.API_BASE_URL)
.client(okhttp)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
}
public Observable<List<Repo>> getUserReposWithObservable(String username) {
return mGithubService.getUserReposWithObservable(username)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
} |
package christmas.domain;
import static org.assertj.core.api.Assertions.assertThat;
import christmas.domain.event.GiftEvent;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Test;
public class GiftEventTest {
@Test
void 증정_메뉴_증정하는_경우_테스트() {
// given
List<Order> orderList = new ArrayList<>() {{
add(new Order(Menu.BARBECUE_LIP, 2)); // 108000원
add(new Order(Menu.ZERO_COKE, 4)); // 12000원
}};
Orders orders = new Orders(orderList);
GiftEvent giftEvent = new GiftEvent(orders);
// when
Gift gift = giftEvent.requestGift();
// then
assertThat(gift).isEqualTo(Gift.CHAMPAGNE);
}
@Test
void 증정_메뉴_증정하지_않는_경우_테스트() {
// given
List<Order> orderList = new ArrayList<>() {{
add(new Order(Menu.BARBECUE_LIP, 2)); // 108000원
add(new Order(Menu.ZERO_COKE, 3)); // 9000원
}};
Orders orders = new Orders(orderList);
GiftEvent giftEvent = new GiftEvent(orders);
// when
Gift gift = giftEvent.requestGift();
// then
assertThat(gift).isEqualTo(Gift.NOTHING);
}
@Test
void 증정_메뉴_가격_계산_테스트() {
// given
List<Order> orderList = new ArrayList<>() {{
add(new Order(Menu.BARBECUE_LIP, 2)); // 108000원
add(new Order(Menu.ZERO_COKE, 4)); // 12000원
}};
Orders orders = new Orders(orderList);
GiftEvent giftEvent = new GiftEvent(orders);
// when
int actual = giftEvent.calculateDiscountResult()
.getAmount();
// then
assertThat(actual).isEqualTo(Gift.CHAMPAGNE.getPrice());
}
} |
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authorize, only: [:edit, :update]
helper_method :current_user
private
# See if @current_user is nil or not. If it has some value, leave it alone.
# Else, get the current user from the session using the user id.
# It first sees if the id is in the session, and then gets the User.
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def authorize
redirect_to login_url, alert: "Not authorized" if current_user.nil?
end
end |
import clsx from "clsx";
import { motion, type AnimationProps } from "framer-motion";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { TooltipWrapper } from "~/components/common/Tooltip";
const Eyeball = ({ isEnabled }: { isEnabled: boolean }) => {
const eyelidStyles =
"absolute left-1/2 w-24 h-24 bg-stone-300 border-4 border-stone-800 rounded-full";
const defaultStyles = {
translateX: "-50%",
scaleX: 3,
};
const isEnabledAnimation = (lid: "top" | "bottom"): AnimationProps => {
const translateYKeyframes = [
["-75%", "-100%", "-100%"],
["-75%", "-100%", "-100%"],
["-75%", "-100%", "-100%"],
["-75%", "-100%", "-100%"],
"-75%",
].flat();
return {
animate: {
scaleX: [[3, 1, 1], [3, 1, 1], [3, 1, 1], [3, 1, 1], 3].flat(),
translateY:
lid === "top"
? translateYKeyframes
: translateYKeyframes.map((item) => item.substring(1)),
},
transition: {
duration: 20,
ease: "easeOut",
repeat: Infinity,
repeatDelay: 0.1,
repeatType: "mirror",
times: [
[0, 0.01, 0.2],
[0.21, 0.22, 0.4],
[0.41, 0.42, 0.8],
[0.81, 0.82, 0.99],
1,
].flat(),
},
};
};
return (
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-12 h-12 bg-stone-200 border-4 border-stone-800 rounded-full overflow-hidden pointer-events-none">
<motion.div
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-6 h-6 bg-stone-800 rounded-full"
style={{ translateY: "-50%", translateX: "-50%", scale: 1 }}
{...(isEnabled && {
animate: {
translateY: [
["-50%", "-75%", "-50%"],
["-50%", "-66%", "-50%"],
["-50%", "-75%", "-50%"],
["-50%", "-50%", "-50%"],
].flat(),
translateX: [
["-50%", "-75%", "-50%"],
["-50%", "-50%", "-50%"],
["-50%", "-75%", "-50%"],
["-50%", "-75%", "-50%"],
].flat(),
scale: [
[1, 0.9, 1],
[1, 0.95, 1],
[1, 0.9, 1],
[1, 0.9, 1],
].flat(),
},
transition: {
duration: 30,
ease: "anticipate",
repeat: Infinity,
repeatDelay: 1,
times: [
[0, 0.05, 0.1],
[0.3, 0.35, 0.4],
[0.55, 0.6, 0.65],
[0.9, 0.95, 1],
].flat(),
},
})}
/>
<div className="absolute top-1.5 left-1.5 w-3 h-3 blur-[1px] bg-white/10 -skew-x-12 -skew-y-12 rounded-full" />
<div className="absolute top-2 left-2 w-2.5 h-2.5 bg-white/10 -skew-x-12 -skew-y-12 rounded-full" />
<motion.div
className={eyelidStyles}
style={{ bottom: 0, translateY: "75%", ...defaultStyles }}
{...(isEnabled && isEnabledAnimation("bottom"))}
/>
<motion.div
className={eyelidStyles}
style={{ translateY: "-75%", ...defaultStyles }}
{...(isEnabled && isEnabledAnimation("top"))}
/>
</div>
);
};
export const ScreenWakeLock = () => {
const [isSupported, setIsSupported] = useState<boolean>(false);
const [isEnabled, setIsEnabled] = useState<boolean>(false);
const [wakeLock, setWakeLock] = useState<WakeLockSentinel | null>(null);
const { t } = useTranslation();
useEffect(() => {
if (typeof document !== "undefined") {
if ("wakeLock" in navigator) {
setIsSupported(true);
}
}
}, []);
useEffect(() => {
if (isSupported) {
if (wakeLock) {
const release = () => setIsEnabled(false);
wakeLock.addEventListener("release", release);
return () => wakeLock.removeEventListener("release", release);
}
}
}, [isSupported, wakeLock]);
const handleEnable = async () => {
if (isSupported) {
if ("wakeLock" in navigator) {
try {
setWakeLock(await navigator.wakeLock.request("screen"));
setIsEnabled(true);
} catch (err) {
console.error("ScreenWakeLockAPI", err);
}
}
}
};
const handleDisable = async () => {
if (isSupported) {
if ("wakeLock" in navigator) {
await wakeLock?.release().then(() => {
setIsEnabled(false);
});
}
}
};
const handleClick = async () => {
if (isSupported) {
if (isEnabled) {
await handleDisable();
} else {
await handleEnable();
}
}
};
return (
isSupported && (
<motion.button
animate={{ opacity: 1, translateY: 0 }}
className={clsx(
"fixed bottom-8 right-8 aspect-square w-12 rounded-full shadow-lg"
)}
exit={{ opacity: 0, translateY: 8 }}
initial={{ opacity: 0, translateY: 8 }}
onClick={async () => await handleClick()}
>
<TooltipWrapper
className="w-12 aspect-square rounded-full"
content={t("common.cookingMode")}
>
<Eyeball isEnabled={isEnabled} />
</TooltipWrapper>
</motion.button>
)
);
}; |
import React from 'react';
import Card from './Card';
import { connect } from 'react-redux' //Conecta o componente ao estado da aplicação
const Media = (props) => {
const {minimo, maximo} = props
function media (min, max) {
return (min + max)/2
}
return (
<Card title="Média" green>
<span>
<strong>Resultado: </strong>
<strong>{media(minimo , maximo)}</strong>
</span>
</Card>
);
}
function mapToStateToProps (state) {
return {
minimo: state.numeros.min,
maximo: state.numeros.max
}
}
/* O connect vai devolver o componente que tem ligação
com o estado global da minha aplicação. Connect recebe
como parametro uma função que fará o mapeamento */
export default connect (mapToStateToProps) (Media) ; |
import NoticeCard from '@/components/common/NoticeCard';
import { useBoolean } from '@/hooks/useBoolean';
import LoadForm from '@/pages/admin-microentrepreneurship/pages/load/components/LoadForm';
import { MicroEntrepreneurshipService } from '@/services/micro-entrepreneurship.service';
import { Box, Container, Grid, Typography, CircularProgress } from '@mui/material';
import { useState } from 'react';
export default function LoadMicroentrepreneurship() {
const jwt = localStorage.getItem('token');
const { value, setFalse, toggle } = useBoolean(false);
const [success, setSuccess] = useState(true);
const [message, setMessage] = useState('');
const [loading, setLoading] = useState(false);
async function handleSubmit(values, { setSubmitting }) {
const {
images,
state: province,
name,
category,
subcategory,
country,
city,
description,
moreInfo,
} = values;
const formData = new FormData();
formData.append('name', name);
formData.append('country', country); // Se debe enviar el valor obtenido desde la base de datos ✅
formData.append('province', province); // Se debe enviar el valor obtenido desde la base de datos ✅
formData.append('category', category); // Se debe enviar el id del microemprendimiento, no el número. ✅
formData.append('subcategory', subcategory);
formData.append('description', description);
formData.append('moreInfo', moreInfo);
formData.append('city', city);
images.forEach((file) => {
formData.append('multipartImages', file, file.name);
});
setLoading(true);
try {
const service = new MicroEntrepreneurshipService();
await service.create({ payload: {}, abortController: new AbortController(), formData, jwt });
setSuccess(true);
setMessage('Microemprendimiento cargado con éxito');
} catch (error) {
setSuccess(false);
setMessage('Lo sentimos, el Microemprendimiento no pudo ser cargado.');
console.log(error);
} finally {
setSubmitting(false);
toggle((preValue) => !preValue);
setLoading(false);
}
}
return (
<Container sx={{ py: '2.5rem' }}>
<Grid container>
<Grid item xs={12}>
<Typography variant='h1' align='center'>
Carga de Microemprendimiento
</Typography>
<Box>
<Typography
variant='h2'
sx={{ fontSize: '1.25rem', fontWeight: '400' }}
align='center'
mt={'2rem'}
>
Completá el formulario para cargar un Microemprendimiento
</Typography>
{loading && (
<Box
sx={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
color: '#093c59',
paddingTop: '15px',
}}
>
<CircularProgress color='inherit' />
</Box>
)}
<LoadForm onSubmit={handleSubmit} />
</Box>
</Grid>
</Grid>
<NoticeCard
isOpen={value}
success={success}
handleClose={setFalse}
mainMessage={message}
cancelFunction={setFalse}
goBack
/>
</Container>
);
} |
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
import { Provider } from "react-redux";
import store from "./ducks/store";
import MuiThemeProvider from "@material-ui/core/styles/MuiThemeProvider";
import theme from "./theme";
import { BreakpointProvider } from "react-socks";
// import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<BreakpointProvider>
<MuiThemeProvider theme={theme}>
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
</MuiThemeProvider>
</BreakpointProvider>,
document.getElementById("root")
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
// serviceWorker.unregister(); |
const express = require("express")
const path = require("path")
const app = express()
const hbs = require("hbs")
const axios = require("axios")
const LogInCollection= require("./mongodb").LogInCollection;
const { MongoClient } = require("mongodb");
const session = require("express-session");
const SaveBuyDb = 'mongodb://127.0.0.1:27017/SaveBuy';
const templatePath = path.join(__dirname, '../templates')
app.use(express.json())
app.set('view engine', 'hbs')
app.set('views', templatePath)
app.use(express.urlencoded({ extended: false }))
const publicPath = path.join(__dirname, '../public')
console.log(publicPath);
app.use(express.static(publicPath))
app.use(session({
secret: 'my-secret-key-7558747250', // Replace with a random secret key
resave: false,
saveUninitialized: true,
}));
app.get('/', (req, res) => {
res.render('login')
})
app.get('/signup', (req, res) => {
res.render('signup')
})
app.get('/arbitragedata', async (req, res) => {
const dbURIArbitrageData = 'mongodb://127.0.0.1:27017/ArbitrageData';
try {
const client = await MongoClient.connect(dbURIArbitrageData, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db();
const ArbitrageDataCollection = db.collection("arbitragecollection");
const data = await ArbitrageDataCollection.find({}).toArray();
res.json(data);
} catch (error) {
console.error('Error fetching data from arbitragedata database:', error);
res.status(500).send('An error occurred while fetching data from arbitragedata database.');
}
});
app.post('/signup', async (req, res) => {
console.log("inside signup");
const data = {
name: req.body.name,
password: req.body.password
}
const checking = await LogInCollection.findOne({ name: req.body.name })
console.log(checking);
try{
if (checking!=null) {
res.status(409).json({ message: "User already exists" });
}
else{
await LogInCollection.insertMany([data])
return res.status(200).json({
message: "User registered successfully",
redirectTo: "/"
});
}
}
catch(error){
res.status(409).json({ message: "wrong-inputs" });
console.log(error);
}
})
app.post('/login', async (req, res) => {
try {
const abc=req.body.name;
console.log(abc);
const check = await LogInCollection.findOne({ name: req.body.name })
console.log("login"+check);
if (check.password === req.body.password) {
req.session.user = {
name: req.body.name,
// Add other user information as needed
};
return res.status(200).json({
message: "User logged in successfully",
redirectTo: "/home.html"
});
}
else {
res.status(409).json({ message: "incorrect password" });
}
}
catch (e) {
res.status(409).json({ message: "wrong details" });
}
})
app.get('/checkLoggedIn', (req, res) => {
if (req.session && req.session.user) {
res.json({ loggedIn: true });
} else {
res.json({ loggedIn: false });
}
});
app.get('/getLoggedInUser', (req, res) => {
console.log("before"+req.session.user);
if (req.session && req.session.user) {
res.json(req.session.user);
} else {
res.json({});
}
});
app.post('/saveEntry', async (req, res) => {
if (req.session && req.session.user) {
const user = req.session.user.name;
const savedate= new Date();
const { symbol, nseprice, bseprice, difference, buyat } = req.body;
const entry = {
user,
symbol,
nseprice,
bseprice,
difference,
buyat,
savedate
};
try {
const client = await MongoClient.connect(SaveBuyDb, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db();
const saveBuyCollection = db.collection("saved");
await saveBuyCollection.insertOne(entry);
res.sendStatus(200); // Respond with success status code
} catch (error) {
console.error('Error saving entry to savebuy database:', error);
res.sendStatus(500); // Respond with error status code
}
} else {
res.sendStatus(403); // Respond with forbidden status code if user is not logged in
}
});
app.get('/saveddata', async (req, res) => {
if (req.session && req.session.user) {
const user = req.session.user.name;
try {
const client = await MongoClient.connect(SaveBuyDb, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db();
const savedcollection = db.collection("saved");
const data = await savedcollection.find({user}).toArray();
console.log(data);
res.json(data);
} catch (error) {
console.error('Error fetching data from save database:', error);
res.status(500).send('An error occurred while fetching data from save database.');
}
}
else {
res.sendStatus(403); // Respond with forbidden status code if user is not logged in
}
});
app.post('/updateBuyStatus', async (req, res) => {
if (req.session && req.session.user) {
const user = req.session.user.name;
const { symbol, quantity, nseprice } = req.body;
try {
const client = await MongoClient.connect(SaveBuyDb, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db();
const saveBuyCollection = db.collection("saved");
// Find the document with the matching user and symbol
const query = { user, symbol, nseprice };
const existingDocument = await saveBuyCollection.findOne(query);
if (existingDocument) {
// Update the buy status to true
const buyDate = new Date(); // Get the current date and time
await saveBuyCollection.updateOne(query, { $set: { buy: true, quantity, buyDate } });
res.sendStatus(200); // Respond with success status code
} else {
res.sendStatus(404); // Respond with not found status code if document not found
}
} catch (error) {
console.error('Error updating buy status in savebuy database:', error);
res.sendStatus(500); // Respond with error status code
}
} else {
res.sendStatus(403); // Respond with forbidden status code if user is not logged in
}
});
app.post('/unsaveStock', async (req, res) =>{
if (req.session && req.session.user) {
const user = req.session.user.name;
const {symbol} = req.body;
try {
const client = await MongoClient.connect(SaveBuyDb, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db();
const saveBuyCollection = db.collection("saved");
// Find the document with the matching user and symbol
const query = { user, symbol };
console.log("query"+query);
const existingDocument = await saveBuyCollection.findOne(query);
console.log(existingDocument);
if (existingDocument) {
await saveBuyCollection.deleteOne(query);
res.sendStatus(200); // Respond with success status code
} else {
res.sendStatus(404); // Respond with not found status code if document not found
}
} catch (error) {
console.error('Error unsaving in savebuy database:', error);
res.sendStatus(500); // Respond with error status code
}
}
else{
res.sendStatus(403);
}
});
app.post('/sellStock', async (req, res) =>{
if (req.session && req.session.user) {
const user = req.session.user.name;
const {symbol} = req.body;
try {
const client = await MongoClient.connect(SaveBuyDb, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = client.db();
const saveBuyCollection = db.collection("saved");
// Find the document with the matching user and symbol
const query = { user, symbol };
console.log("query"+query);
const existingDocument = await saveBuyCollection.findOne(query);
console.log(existingDocument);
if (existingDocument) {
await saveBuyCollection.deleteOne(query);
res.sendStatus(200); // Respond with success status code
} else {
res.sendStatus(404); // Respond with not found status code if document not found
}
} catch (error) {
console.error('Error selling in savebuy database:', error);
res.sendStatus(500); // Respond with error status code
}
}
else{
res.sendStatus(403);
}
});
app.listen(3000,()=>{
console.log("port connected");
}) |
import React, { useEffect, useState } from "react";
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom'
import { DoctorHeader } from '../../reducer/HeaderReducer';
import { DoctorFooter } from '../../reducer/FooterReducer';
import { Tabs } from 'antd';
import { Container } from 'react-bootstrap';
import { DataStore } from 'aws-amplify';
import { CheckSkin, CheckSkinType, CheckSkinStatus } from '../../models';
import Mole from '../../component/common/Mole';
import Rash from '../../component/common/Rash';
const { TabPane } = Tabs;
const Inquiry = () => {
const dispatch = useDispatch();
const navigate = useNavigate();
const [mole, setMole] = useState([]);
const [rash, setRash] = useState([]);
useEffect(() => {
const auth = window.localStorage.getItem("user");
if (auth) {
window.localStorage.setItem("header", "doctor");
window.localStorage.setItem("footer", "doctor");
if (window.localStorage.getItem("header") === "doctor") {
dispatch(DoctorHeader());
}
if (window.localStorage.getItem("footer") === "doctor") {
dispatch(DoctorFooter());
}
getMoleData(auth);
getRashData(auth);
} else {
navigate('/doctor/login')
}
}, []);
const getMoleData = async (auth) => {
let moleData = await DataStore.query(CheckSkin, (c) => c.type('eq', CheckSkinType.MOLE).checkskinstatus('eq', CheckSkinStatus.ANSWERED).doctorID('eq', auth));
let table_data = moleData.map((item, key) => (
{
...item,
key: key
}
))
setMole(table_data);
}
const getRashData = async (auth) => {
let rashData = await DataStore.query(CheckSkin, (c) => c.type('eq', CheckSkinType.RASH).checkskinstatus('eq', CheckSkinStatus.ANSWERED).doctorID('eq', auth));
let table_data = rashData.map((item, key) => (
{
...item,
key: key
}
))
setRash(table_data);
}
return (
<React.Fragment>
<Container className='mt-4'>
<h1 className='request-header'>Answered Inquiries</h1>
<p className='request-description mt-1'>All requests that has been answered</p>
<Tabs defaultActiveKey="1">
<TabPane tab="Mole" key="1">
<Mole mole={mole} status="inquiry" />
</TabPane>
<TabPane tab="Rash" key="2">
<Rash rash={rash} status="inquiry" />
</TabPane>
</Tabs>
</Container>
</React.Fragment>
)
}
export default Inquiry; |
<?php
namespace Razzi\Addons\Modules\Mega_Menu;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class menu walker
*
* @package Razzi
*/
class Mobile_Walker extends \Walker_Nav_Menu {
/**
* Store state of top level item
*
* @since 1.0.0
* @var boolean
*/
protected $in_mega = false;
/**
* Background Item
*
* @since 1.0.0
* @var string
*/
protected $style = '';
/**
* Mega menu column
*
* @since 1.0.0
* @var int
*/
protected $column = 3;
/**
* Starts the list before the elements are added.
*
* @see Walker::start_lvl()
*
* @since 1.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*
* @return string
*/
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "\n$indent<ul class=\"sub-menu check\">\n";
}
/**
* Ends the list of after the elements are added.
*
* @see Walker::end_lvl()
*
* @since 1.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
*
* @return string
*/
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$indent = str_repeat( "\t", $depth );
$output .= "\n$indent</ul>\n";
}
/**
* Start the element output.
* Display item description text and classes
*
* @see Walker::start_el()
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of arguments. @see wp_nav_menu()
* @param int $id Current item ID.
*
* @return string
*/
public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
$item_icon_type = get_post_meta( $item->ID, 'tamm_menu_item_icon_type', true );
$item_icon_svg = get_post_meta( $item->ID, 'tamm_menu_item_icon_svg', true );
$item_icon_image = get_post_meta( $item->ID, 'tamm_menu_item_icon_image', true );
$item_icon_color = get_post_meta( $item->ID, 'tamm_menu_item_icon_color', true );
$item_badges_text = get_post_meta( $item->ID, 'tamm_menu_item_badges_text', true );
$item_badges_bg_color = get_post_meta( $item->ID, 'tamm_menu_item_badges_bg_color', true );
$item_badges_color = get_post_meta( $item->ID, 'tamm_menu_item_badges_color', true );
$item_hide_text = get_post_meta( $item->ID, 'tamm_menu_item_hide_text', true );
$classes = empty( $item->classes ) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
$this->style = '';
$this->class = '';
// Container
$class = array( 'mega-menu-content row-flex' );
$attrs = ' class="' . esc_attr( join( ' ', $class ) ) . '"';
$this->class = $attrs;
// Svg
$item_icon_html = '';
if ( $item_icon_type === 'svg' ) {
$item_icon_color = $item_icon_color ? 'style="color:' . $item_icon_color . '"' : '';
$item_icon_html = ! empty( $item_icon_svg ) ? '<span ' . $item_icon_color . ' class="razzi-svg-icon">' . \Razzi\Icon::sanitize_svg( $item_icon_svg ) . '</span> ' : '';
} elseif ( ! empty( $item_icon_image ) ) {
$item_icon_html = '<img src="' . esc_attr( $item_icon_image ) . '">';
}
// Badges
$item_badges_html = '';
if ( $item_badges_text ) {
$item_badges_bg_color = $item_badges_bg_color ? '--rz-badges-bg-color:' . $item_badges_bg_color . '' : '';
$item_badges_color = $item_badges_color ? 'color:' . $item_badges_color . '' : '';
$item_badges_style = $item_badges_bg_color || $item_badges_color ? 'style="' . $item_badges_bg_color . ';' . $item_badges_color . '"' : '';
$item_badges_html = '<span ' . $item_badges_style . ' class="razzi-menu-badges">' . $item_badges_text . '</span>';
}
/**
* Filter the arguments for a single nav menu item.
*
* @since 4.4.0
*
* @param array $args An array of arguments.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
*/
$args = apply_filters( 'nav_menu_item_args', $args, $item, $depth );
/**
* Add active class for current menu item
*/
$active_classes = array(
'current-menu-item',
'current-menu-parent',
'current-menu-ancestor',
);
$is_active = array_intersect( $classes, $active_classes );
if ( ! empty( $is_active ) ) {
$classes[] = 'active';
}
if ( $item_hide_text ) {
$classes[] = ' hide-text';
}
/**
* Filter the CSS class(es) applied to a menu item's list item element.
*
* @since 3.0.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $classes The CSS classes that are applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args, $depth ) );
$class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : '';
/**
* Filter the ID applied to a menu item's list item element.
*
* @since 3.0.1
* @since 4.1.0 The `$depth` parameter was added.
*
* @param string $menu_id The ID that is applied to the menu item's `<li>` element.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$output .= $indent . '<li' . $class_names . '>';
$atts = array();
$atts['title'] = ! empty( $item->attr_title ) ? $item->attr_title : '';
$atts['target'] = ! empty( $item->target ) ? $item->target : '';
$atts['rel'] = ! empty( $item->xfn ) ? $item->xfn : '';
$atts['href'] = ! empty( $item->url ) ? $item->url : '';
$atts['class'] = '';
/**
* Add attributes for menu item link when this is not mega menu item
*/
if ( in_array( 'menu-item-has-children', $classes ) ) {
$atts['class'] = 'dropdown-toggle';
$atts['role'] = 'button';
$atts['data-toggle'] = 'dropdown';
$atts['aria-haspopup'] = 'true';
$atts['aria-expanded'] = 'false';
}
if ( $item_icon_svg ) {
$atts['class'] .= ' has-icon';
}
/**
* Filter the HTML attributes applied to a menu item's anchor element.
*
* @since 3.6.0
* @since 4.1.0 The `$depth` parameter was added.
*
* @param array $atts {
* The HTML attributes applied to the menu item's `<a>` element, empty strings are ignored.
*
* @type string $title Title attribute.
* @type string $target Target attribute.
* @type string $rel The rel attribute.
* @type string $href The href attribute.
* }
*
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );
$attributes = '';
foreach ( $atts as $attr => $value ) {
if ( ! empty( $value ) ) {
$value = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
$attributes .= ' ' . $attr . '="' . $value . '"';
}
}
/** This filter is documented in wp-includes/post-template.php */
$title = apply_filters( 'the_title', $item->title, $item->ID );
/**
* Filter a menu item's title.
*
* @since 4.4.0
*
* @param string $title The menu item's title.
* @param object $item The current menu item.
* @param array $args An array of {@see wp_nav_menu()} arguments.
* @param int $depth Depth of menu item. Used for padding.
*/
$title = apply_filters( 'nav_menu_item_title', $title, $item, $args, $depth );
$item_output = ! empty( $args->before ) ? $args->before : '';
$item_output .= '<a' . $attributes . '>';
$item_output .= $item_icon_html;
$item_output .= ( ! empty( $args->link_before ) ? $args->link_before : '' ) . $title . ( ! empty( $args->link_after ) ? $args->link_after : '' );
$item_output .= $item_badges_html;
$item_output .= '</a>';
$item_output .= ! empty( $args->after ) ? $args->after : '';
/**
* Filter a menu item's starting output.
*
* The menu item's starting output only includes `$args->before`, the opening `<a>`,
* the menu item's title, the closing `</a>`, and `$args->after`. Currently, there is
* no filter for modifying the opening and closing `<li>` for a menu item.
*
* @since 3.0.0
*
* @param string $item_output The menu item's starting HTML output.
* @param object $item Menu item data object.
* @param int $depth Depth of menu item. Used for padding.
* @param array $args An array of {@see wp_nav_menu()} arguments.
*/
$output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
}
/**
* Ends the element output, if needed.
*
* @see Walker::end_el()
*
* @since 1.0.0
*
* @param string $output Passed by reference. Used to append additional content.
* @param object $item Page data object. Not used.
* @param int $depth Depth of page. Not Used.
* @param array $args An array of arguments. @see wp_nav_menu()
*
* @return string
*/
public function end_el( &$output, $item, $depth = 0, $args = array() ) {
$output .= "</li>\n";
}
} |
class Student:
all_students = {}
@classmethod
def list_students(cls) -> None:
counter = 0
for school_id in cls.all_students:
counter += 1
print(f"{counter}. {cls.all_students[school_id]._name} {school_id}")
@classmethod
def find_student_by_id(cls, student_id_str):
if student_id_str in cls.all_students:
return cls.all_students[student_id_str]
else:
print(f"Student ID {student_id_str} does not exist.")
@classmethod
def add_student(cls, dict) -> None:
instance = cls(**dict)
cls.all_students[instance._school_id] = instance
def __init__(self, name=None, age=None, role=None, school_id=None, password=None) -> None:
self._name = name
self._age = age
self._password = password
self._role = role
self._school_id = school_id
def __str__(self) -> str:
return f"{self._name.capitalize()}\n------------------\nAge: {self._age}\nID: {self._school_id}"
# def __repr__(self) -> str:
# return str(self)
@property
def get_id(self) -> int:
return int(self._school_id) |
# My Flix API
## Project description
This project is a REST API for a movie platform application that interacts with a database and displays data about different movies, directors, and genres.
The database can store movies and users to the users be able to sign up, login and create a list of their favorite movies.
This API is hosted using Vercel and the database using Atlas MongoDB.
# Hosting
The API is hosted in Vercel Paas service at [https://movie-api-afonsord.vercel.app/](https://movie-api-afonsord.vercel.app/).<br>
The DataBase is hosted in MongoDB.
**Key Features**
- Return a list of ALL movies to the user
- Return data (description, genre, director, image URL, whether it’s featured or not) about a single movie by title to the user
- Return data about a genre (description) by name/title
- Return data about a director (bio, birth year, death year) by name
- Allow new users to register
- Allow users to update their user info (username, password, email, date of birth)
- Allow users to add a movie to their list of favorites
- Allow users to remove a movie from their list of favorites
- Allow existing users to deregister
#### Technical Dependencies
- Node.js
- Express
- Morgan
- MongoDB
- Mongoose
- Passport
#### Testing Tools
Postman
## Endpoints
### Get a list of all movies
**Endpoint:** /movies
**HTTP Method:** GET
**Request body data format:** None
**Response body data format:** JSON Object holding data about all movies
### Get data about a single movie by title
**Endpoint:** /movies/[Title]
**Query Parameters:** [Title] of movie
**HTTP Method:** GET
**Request body data format:** None
**Response body data format:** JSON object holding data about a single movie, containing title, description, genre, director, imageURL, featured or not.
**Response Example:**
```
{
"Genre": {
"Name": "Mystery",
"Description": "A mystery film is a genre of film that revolves around the solution of a problem or a crime."
},
"Director": {
"Name": "Richard Kelly",
"Bio": "James Richard Kelly is an American filmmaker and screenwriter, who initially gained recognition for writing and directing the cult classic Donnie Darko in 2001.",
"Birthday": "1975-03-28"
},
"Actors": [],
"_id": "63b5b9fd5f0d693ad8d4e31f",
"Title": "Donnie Darko",
"Description": "A mystery film is a genre of film that revolves around the solution of a problem or a crime.",
"ImageURL": "https://upload.wikimedia.org/wikipedia/en/d/db/Donnie_Darko_poster.jpg",
"Featured": true,
"Year": "2001"
}
```
### Get data about a genre by name
**Endpoint:** /movies/genre/[Name]
**Query Parameters:** [Name] of genre
**HTTP Method:** GET
**Request body data format:** None
**Response body data format:** A JSON object holding data about a movie genre containing name and description.
**Response Example:**
```
{
"Name": "Drama",
"Description": "The drama genre features stories with high stakes and many conflicts. They're plot-driven and demand that every character and scene move the story forward. Dramas follow a clearly defined narrative plot structure, portraying real-life scenarios or extreme situations with emotionally-driven characters."
}
```
### Get data about a director by name
**Endpoint:** /movies/director/[Name]
**Query Parameters:** [Name] of director
**HTTP Method:** GET
**Request body data format:** None
**Response body data format:** JSON object holding data about a director, containing name, bio, date of birth and death if existing.
**Response Example:**
```
{
"Name": "Christopher Nolan",
"Bio": "Christopher Edward Nolan CBE is a British-American filmmaker. Known for his lucrative Hollywood blockbusters with complex storytelling, Nolan is considered a leading filmmaker of the 21st century. His films have grossed $4.9 billion worldwide.",
"Birthday": "1970"
}
```
### Get a list of all users
**Endpoint:** /users
**HTTP Method:** GET
**Request body data format:** None
**Response body data format:** JSON object holding data about all users.
### Get a user by username
**Endpoint:** /users/[Username]
**Query Parameters:** [Username] of user
**HTTP Method:** GET
**Request body data format:** None
**Response body data format:** JSON object holding data about a single user.
**Response Example:**
```
{
"_id": "647624ca29e0f06602c0fb29",
"Username": "ruitest123",
"Password": "$2b$10$0cTY.9ldpbtCXQTB9.QlkOSHU0kwSnLWbjcOwHb/mtdGN6MChKVa6",
"Email": "test1@email.com",
"Birthday": "1991-11-11T00:00:00.000Z",
"FavoriteMovies": [],
"__v": 0
}
```
### Add a new User
**Endpoint:** /users
**HTTP Method:** POST
**Request body data format:** JSON object holding data about a user, structured like:
**Request Example:**
```
{
"Username": "ruitest123",
"Password": "Password123!",
"Email": "test1@email.com",
"Birthday": "1991/11/11"
}
```
**Response body data format:** JSON object holding data about the user that was added, including an ID and a "Favorites" key.
**Response Example:**
```
{
"Username": "ruitest123",
"Password": "$2b$10$0cTY.9ldpbtCXQTB9.QlkOSHU0kwSnLWbjcOwHb/mtdGN6MChKVa6",
"Email": "test1@email.com",
"Birthday": "1991-11-11T00:00:00.000Z",
"FavoriteMovies": [],
"_id": "647624ca29e0f06602c0fb29",
"__v": 0
}
```
### Update user info by username
**Endpoint:** /users/[Username]
**Query Parameter:** [Username] of user
**HTTP Method:** PUT
**Request body data format:** JSON object holding data to be updated, structured like:
**Request Example:**
```
{
"Username": "ruitest123",
"Password": "Newpassword!",
"Email": "test1@email.com",
"Birthday": "1991/11/11"
}
```
**Response body data format:** JSON data holding updated user info.
**Response Example:**
```
{
"_id": "647624ca29e0f06602c0fb29",
"Username": "ruitest123",
"Password": "$2b$10$IC.OAhlShLQZWtdorx.F3Ose7ZktiEkSguGIPONWP7jQ91zriZnUy",
"Email": "test1@test.com",
"FavoriteMovies": [],
"__v": 0,
"Birthday": "1991-01-01T00:00:00.000Z"
}
```
### Add a movie to list of favorites by movie ID
**Endpoint:** /users/[Username]/movies/[MovieID]
**Query Parameter:** [Username] of user and [MovieID]
**HTTP Method:** POST
**Request body data format:** None
**Response body data format:** A text message indicating the movie was added to the list of favorites and the updated list of favorites.
**Response Example:**
```
The movie with ID 63f8dd377f048e406baf4a34 was successfully added to list of favorites. Favorites of ruitest123:
63f8dd377f048e406baf4a34,63b5b9fd5f0d693ad8d4e325,63b5b9fd5f0d693ad8d4e325
```
### Delete a movie from list of favorites by movie ID
**Endpoint:** /users/[Username]/movies/[MovieID]
**Query Parameter:** [Username] of user and [MovieID]
**HTTP Method:** DELETE
**Request body data format:** None
**Response body data format:** A text message indicating whether the movie was successfully removed and the updated list of favorites.
**Response Example:**
```
The movie with ID 63f8dd377f048e406baf4a34 was successfully deleted to list of favorites. Favorites of ruitest123:
63b5b9fd5f0d693ad8d4e325,63b5b9fd5f0d693ad8d4e325
```
### Delete user by username
**Endpoint:** /users/[Username]
**Query Parameter:** [Username] of user
**HTTP Method:** DELETE
**Request body data format:** None
**Response body data format:** A text message indicating whether the user account was successfully deleted.
**Response Example:**
```
ruitest123 was deleted
```
###### [My Flix app](https://movie-api-afonsord.vercel.app/) |
import { MinLength, MaxLength, Matches } from 'class-validator';
import { applyDecorators } from '@nestjs/common';
import { constants } from '@monorepo-ts/common';
export const ValidatePassword = () =>
applyDecorators(
MinLength(8),
MaxLength(30),
Matches(/(?=.*[a-z])/, {
message: constants.PASSWORD_LOWERCASE_ERROR_MESSAGE
}),
Matches(/(?=.*[A-Z])/, {
message: constants.PASSWORD_UPPERCASE_ERROR_MESSAGE
}),
Matches(/(?=.*\W)/, {
message: constants.PASSWORD_SYMBOL_ERROR_MESSAGE
}),
Matches(/(?=.*\d)/, {
message: constants.PASSWORD_NUMBER_ERROR_MESSAGE
})
); |
import Foundation
// MARK: - TodosResponse
struct TodosResponse: Codable {
let data: [Todo]?
let meta: Meta?
let message: String?
}
struct BaseListResponse<T: Codable>: Codable {
let data: [T]?
let meta: Meta?
let message: String?
}
struct BaseResponse<T: Codable>: Codable {
let data: T?
let message: String?
}
// MARK: - Datum
struct Todo: Codable {
let id: Int?
let title: String?
let isDone: Bool?
let createdAt, updatedAt: String?
enum CodingKeys: String, CodingKey {
case id, title
case isDone = "is_done"
case createdAt = "created_at"
case updatedAt = "updated_at"
}
}
// MARK: - Meta
struct Meta: Codable {
let currentPage, from, lastPage, perPage: Int?
let to, total: Int?
enum CodingKeys: String, CodingKey {
case currentPage = "current_page"
case from
case lastPage = "last_page"
case perPage = "per_page"
case to, total
}
} |
<?php
$executionStartTime = microtime(true);
include("config.php");
header('Content-Type: application/json; charset=UTF-8');
$conn = new mysqli($cd_host, $cd_user, $cd_password, $cd_dbname, $cd_port, $cd_socket);
if (mysqli_connect_errno()) {
echo json_encode([
'status' => [
'code' => "300",
'name' => "failure",
'description' => "database unavailable",
'returnedIn' => (microtime(true) - $executionStartTime) / 1000 . " ms"
],
'data' => []
]);
mysqli_close($conn);
exit;
}
$locationId = $_POST['locationId'];
// Check departments
$query = $conn->prepare('SELECT COUNT(id) as cnt FROM department WHERE locationID = ?');
if (false === $query) {
echo json_encode(['status' => 'error', 'message' => 'Failed to prepare department query.']);
mysqli_close($conn);
exit;
}
$query->bind_param("i", $locationId);
$query->execute();
$result = $query->get_result();
$row = $result->fetch_assoc();
if ($row['cnt'] > 0) {
echo json_encode(['status' => 'error', 'message' => 'Location is linked to one or more departments.']);
mysqli_close($conn);
exit;
}
// Check personnel
$query = $conn->prepare('SELECT COUNT(p.id) as cnt FROM personnel p JOIN department d ON p.departmentID = d.id WHERE d.locationID = ?');
if (false === $query) {
echo json_encode(['status' => 'error', 'message' => 'Failed to prepare personnel query.']);
mysqli_close($conn);
exit;
}
$query->bind_param("i", $locationId);
$query->execute();
$result = $query->get_result();
$row = $result->fetch_assoc();
if ($row['cnt'] > 0) {
echo json_encode(['status' => 'error', 'message' => 'Location is linked to one or more personnel records.']);
mysqli_close($conn);
exit;
}
// If we've reached this point, it is safe to delete
$query = $conn->prepare('DELETE FROM location WHERE id = ?');
if (false === $query) {
echo json_encode(['status' => 'error', 'message' => 'Failed to prepare delete query.']);
mysqli_close($conn);
exit;
}
$query->bind_param("i", $locationId);
$query->execute();
// Check for successful deletion
if ($query->affected_rows > 0) {
echo json_encode(['status' => 'success', 'message' => 'Location deleted successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'Failed to delete location.']);
}
mysqli_close($conn);
?> |
import React, {useContext, useEffect} from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import FeedBackContext from '../context/FeedBackContext'
import FeedBackItem from './FeedBackItem'
import Spinner from './shared/Spinner'
function FeedBackList() {
const {feedback, loading} = useContext(FeedBackContext)
if (!loading && (!feedback || feedback.length === 0)) {
return <p> Feedbacks List is Empty</p>
}
return loading ? <Spinner/> : (
<div className='feedback-list'>
<AnimatePresence>
{feedback.map(item => (
<motion.div
key={item.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}>
<FeedBackItem key={item.id}
item={item} />
</motion.div>
)
)}
</AnimatePresence>
</div>
)
// return (
// <div className='feedback-list'>
// {feedback.map(item => (
// <FeedBackItem key={item.id} {...item} handleDelete={handleDelete} />)
// )}
// </div>
// )
}
export default FeedBackList |
import os
import logging
from llama_index import VectorStoreIndex, SimpleDirectoryReader, ServiceContext, OpenAIEmbedding, StorageContext, load_index_from_storage
from llama_index.llms import OpenAI
from llama_index.text_splitter import TokenTextSplitter
from llama_index.node_parser import SimpleNodeParser
# Setup logging
logging.basicConfig(level=logging.INFO)
os.environ['OPENAI_API_KEY'] = 'INSERT-API-KEY-HERE'
# Load OpenAI API key from environment variable
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
logging.error("OPENAI_API_KEY not found in environment variables.")
exit(1)
# Create a ServiceContext
service_context = ServiceContext.from_defaults(
llm= OpenAI(model='gpt-3.5-turbo'),
embed_model= OpenAIEmbedding(),
node_parser= SimpleNodeParser.from_defaults(
text_splitter=TokenTextSplitter(chunk_size=1024, chunk_overlap=20)),
chunk_size=1024
)
# Initialize VectorStoreIndex and load or create index
def construct_index(directory_path):
try:
storage_context = StorageContext.from_defaults(persist_dir="./storage")
index = load_index_from_storage(storage_context)
except:
documents = SimpleDirectoryReader(directory_path).load_data()
index = VectorStoreIndex.from_documents(documents, service_context=service_context)
index.storage_context.persist()
return index
index = construct_index("html_downloads")
# Define queries and get responses from the chatbot using the context information
queries = [
"When is the live broadcast for the general session?",
"Where is VMware Explore Barcelona located?",
"Who's playing music at The Party?"
# Add more queries as needed
]
for query in queries:
query_engine = index.as_query_engine()
response = query_engine.query(query)
logging.info(f"Query: {query}\nResponse: {response}") |
import { useQueries, useQuery } from '@tanstack/react-query';
import { Exchange } from './types/exchanges.ts';
const FINNHUB_KEY = 'cjg7469r01qohhhj96dgcjg7469r01qohhhj96e0';
class FinnHubError extends Error {
constructor(message: string) {
super(`queryFinnHubFn: ${message}`);
this.name = 'queryFinnHubFn';
}
}
const applyToken = (url: string) => {
const [start = '', hash] = url.split('#');
const end = hash ? '#' + hash : '';
if (start.includes('?')) {
return start + '&token=' + FINNHUB_KEY + end;
} else {
return start + '?token=' + FINNHUB_KEY + end;
}
};
export function queryFinnHubFn<T>(url: string): Promise<T> {
if (typeof url === 'undefined') throw new FinnHubError('Missing URL for fetch function');
return fetch('https://finnhub.io/api/v1' + applyToken(url), {
method: 'GET',
// use headers when in prod to remove KEY from url
// headers: {
// 'Content-Type': 'application/json',
// 'X-Finnhub-Token': FINNHUB_KEY,
// },
}).then((response) => {
if (response.ok) {
// 1xx: Informational
// 2xx: Success
// 3xx: Redirection
return response.json() as T;
} else {
// 4xx: Client errors
// 5xx: Server errors
return Promise.reject(new FinnHubError('Fetch Error ' + response.status));
}
});
}
export interface StockSymbol {
currency: string; // "USD",
description: string; // "INDIEPUB ENTERTAINMENT INC",
displaySymbol: string; // "IPUB",
figi: string; // "BBG000PHSCM3",
mic: string; // "OOTC",
shareClassFIGI: string; // "BBG001SR2K91",
symbol: string; // "IPUB",
symbol2: string; // "",
type: string; // "Common Stock"
}
export const useFinnHubSymbols = ({
exchange,
filter,
}: {
exchange: Exchange;
filter?: (_: StockSymbol[]) => StockSymbol[];
}) => {
if (typeof exchange === 'undefined') throw Error('useFinnHubSymbols: Missing "exchange" string');
// https://finnhub.io/api/v1/stock/symbol?exchange=US
const queryStockFn = () => queryFinnHubFn<StockSymbol[]>(`/stock/symbol?exchange=${exchange}`);
return useQuery({
queryKey: ['finhub', 'stock', exchange],
queryFn: queryStockFn,
select: filter,
});
};
export interface Candle {
c: number[];
h: number[];
l: number[];
o: number[];
t: number[]; // date in ms since epoch
v: number[];
s: 'ok';
}
export interface Candles {
c: number;
h: number;
l: number;
o: number;
t: number; // date in ms since epoch
v: number;
}
export const useFinnHubCandles = ({
symbols,
from,
to,
resolution = 'W',
}: {
symbols: string[];
from: number | null;
to: number | null;
resolution?: string;
}) => {
if (typeof symbols === 'undefined') throw Error("useFinnHubCandles: Missing 'symbols' array<string>");
if (typeof from === 'undefined') throw Error("useFinnHubCandles: Missing 'from' date ms");
if (typeof to === 'undefined') throw Error("useFinnHubCandles: Missing 'to' date ms");
// https://finnhub.io/api/v1/stock/candle?symbol=AAPL&resolution=1&from=1679476980&to=1679649780
const queryStockFn = (symbol: string) =>
queryFinnHubFn<Candle>(`/stock/candle?symbol=${symbol}&from=${from}&to=${to}&resolution=${resolution}`);
return useQueries({
queries: symbols.map((symbol) => {
return {
queryKey: ['finhub', 'candle', from, to, resolution, symbol],
queryFn: () => queryStockFn(symbol),
staleTime: Infinity,
enabled: !!(symbols && from && to),
select: (candles: Candle): Candles[] => {
return candles.c?.map((c, i) => ({
c,
h: candles.h[i],
l: candles.l[i],
o: candles.o[i],
t: candles.t[i],
v: candles.v[i],
}));
},
};
}),
});
}; |
//
// Coordinator.swift
// Radiow
//
// Created by YEONGJUNG KIM on 2022/11/17.
// Copyright © 2022 dwarfini. All rights reserved.
//
import UIKit
protocol Coordinating {
associatedtype Location
var location: Location? { get }
}
protocol Coordinator: AnyObject {
associatedtype Location
associatedtype Target
/// A target currently managed by coordinator
var target: Target? { get }
/// Instantiates a new target. this instance is not managed yet by this coordinator
/// You should call this method to create a new target instance in `start()` or outside of the coordinator.
/// - Returns: new target instance
func instantiateTarget() -> Target
/// Coordinates to target managed by this coordinator
/// - Returns: a target instance created
@discardableResult
func start() -> Target
/// Coordinates to location from target
/// - Parameter location: target to locate
func coordinate(_ location: Location)
}
extension Coordinator {
func coordinate(_ location: Location) {}
} |
import asyncio
import threading
from flask import Flask, request, jsonify
import asyncio.subprocess
app = Flask(__name__)
# Initialize global variables to store the GDB subprocess and program name
gdb_process = None
program_name = None
lock = threading.Lock()
output_queue = asyncio.Queue()
def start_gdb_session(program):
global gdb_process, program_name
with lock:
program_name = program
# Start the GDB subprocess
gdb_process = asyncio.create_subprocess_exec('gdb', '--interpreter=mi', program_name,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
asyncio.ensure_future(read_output())
async def read_output():
global gdb_process
while True:
line = await gdb_process.stdout.readline()
if line.strip() == b"(gdb)":
await output_queue.put(line)
else:
await output_queue.put(line)
async def execute_gdb_command(command):
global gdb_process
async with lock:
# Send command to the GDB subprocess
gdb_process.stdin.write(command + '\n')
await gdb_process.stdin.drain()
# Wait for the GDB prompt
while True:
output = await output_queue.get()
if output.strip() == b"(gdb)":
break
# Read the output from the GDB subprocess
output = b""
while True:
line = await output_queue.get()
if line.strip() == b"(gdb)":
break
output += line
return output.strip()
@app.route('/gdb_command', methods=['POST'])
async def gdb_command():
data = await request.get_json()
command = data.get('command')
# Start the GDB session if not already started
if gdb_process is None:
await start_gdb_session(data.get('program', 'program.exe'))
# Execute the GDB command
try:
result = await execute_gdb_command(command)
response = {
'success': True,
'result': result.decode('utf-8'),
'code': f"await execute_gdb_command('{command}')"
}
except Exception as e:
response = {
'success': False,
'error': str(e),
'code': f"await execute_gdb_command('{command}')"
}
return jsonify(response)
if __name__ == '__main__':
app.run(debug=True, port=8000) |
package edu.ncsu.csc316.dsa.sorter;
import java.util.Comparator;
/**
* This is super class of InsertSorter, BubbleSorter, and SelectionSorter
* It has functionality to add custom comparators
* @author Tilak
*
* @param <E> Java generic type
*/
public abstract class AbstractComparisonSorter<E extends Comparable<E>> implements Sorter<E> {
/** Instance of comparator of type E*/
private Comparator<E> comparator;
/**
* Constructor
* @param comparator comparator can be custom or null
*/
public AbstractComparisonSorter(Comparator<E> comparator) {
setComparator(comparator);
}
private void setComparator(Comparator<E> comparator) {
if(comparator == null) {
this.comparator = new NaturalOrder();
} else {
this.comparator = comparator;
}
}
private class NaturalOrder implements Comparator<E> {
public int compare(E first, E second) {
return ((Comparable<E>) first).compareTo(second);
}
}
/**
* Compares two object of type E
* @param data1 object of type E
* @param data2 object of type E
* @return 1 if data1 is greater than data2,
* -1, if data1 is less than data2,
* 0, if data1 is equal to data2,
*/
public int compare(E data1, E data2) {
return comparator.compare(data1, data2);
}
} |
import type {HydratedDocument, Types} from 'mongoose';
import type {Request} from './model';
import RequestModel from './model';
import UserCollection from '../user/collection';
import ItemCollection from '../item/collection';
import {isUserLoggedIn} from 'server/user/middleware';
class RequestCollection {
/**
* Add a Request to the collection
*
* @param {string} itemId - The id of the item to be borrowed
* @param {string} borrowerId - The id of the user making the borrow request
* @param {date} startDate - The proposed start date of the borrowing period
* @param {date} endDate - The proposed end date of the borrowing period
* @return {Promise<HydratedDocument<Request>>} - The newly created Request object
*/
static async addOne(itemId: Types.ObjectId | string, borrowerId: Types.ObjectId | string, startDate: Date, endDate: Date): Promise<HydratedDocument<Request>> {
const item = await ItemCollection.findOne(itemId);
const {ownerId} = item;
const Request = new RequestModel({
itemId,
ownerId,
borrowerId,
startDate,
endDate
});
await Request.save(); // Saves Request to MongoDB
return Request;
}
/**
* Find a Request by RequestId
*
* @param {string} RequestId - The id of the Request to find
* @return {Promise<HydratedDocument<Request>> | Promise<null> } - The Request with the given RequestId, if any
*/
static async findOne(RequestId: Types.ObjectId | string): Promise<HydratedDocument<Request>> {
return RequestModel.findOne({_id: RequestId});
}
/**
* Get all the Requests in the database
*
* @return {Promise<HydratedDocument<Request>[]>} - An array of all of the Requests
*/
static async findAll(): Promise<Array<HydratedDocument<Request>>> {
// Retrieves Requests and sorts them from most to least recent endDate
return RequestModel.find({}).sort({endDate: -1}).populate('ownerId borrowerId itemId');
}
/**
* Get all the Requests associated with an item
*
* @param {string} itemId - The ID of the item whose Requests are sought
* @return {Promise<HydratedDocument<Request>[]>} - An array of the Requests for this item
*/
static async findAllByItem(itemId: Types.ObjectId | string): Promise<Array<HydratedDocument<Request>>> {
return RequestModel.find({itemId});
}
/**
* Get all the Requests to/from the owner
*
* @param {string} userId - The ID of the user whose Requests are sought
* @return {Promise<HydratedDocument<Request>[]>} - An array of Requests
*/
static async findAllByUser(userId: Types.ObjectId | string): Promise<Array<HydratedDocument<Request>>> {
return RequestModel.find({$or: [{ownerId: userId}, {borrowerId: userId}]}).populate(['itemId', 'ownerId', 'borrowerId']);
}
/**
* Update a Request's accepted status
*
* @param {string} requestId - The id of the Request to be updated
* @param {boolean} accepted - Whether or not the Request has been accepted
* @return {Promise<HydratedDocument<Request>>} - The newly updated Request
*/
static async acceptOne(requestId: Types.ObjectId | string, accepted: boolean): Promise<HydratedDocument<Request>> {
const Request = await RequestModel.findOne({_id: requestId});
Request.accepted = accepted;
await Request.save();
return Request;
}
/**
* Delete a Request with given requestId.
*
* @param {string} requestId - The Id of Request to delete
* @return {Promise<Boolean>} - true if the Request has been deleted, false otherwise
*/
static async deleteOne(requestId: Types.ObjectId | string): Promise<boolean> {
const Request = await RequestModel.deleteOne({_id: requestId});
return Request !== null;
}
/**
* Delete all the Requests by the given user
*
* @param {string} userId - The id of owner of the Requests
*/
static async deleteMany(userId: Types.ObjectId | string): Promise<void> {
await RequestModel.deleteMany({$or: [{ownerId: userId}, {borrowerId: userId}]});
}
}
export default RequestCollection; |
# FoodieBot 🍟🤖
## Description
FoodieBot is a chatbot application that assists customers in placing orders for their preferred meals.
## How to use
This chatbot application is pretty intuitive to use, but here are some instructions on how to use it:
- To see the menu, enter `1`.
- To place your order, enter the number preceding the items you want to order in comma-separated values, e.g `2,3,4`.
- To checkout an order, enter `99`.
- To see order history, enter `98`.
- To see current order, enter `97`.
- To cancel current order, enter `0`.
>**Note**- If you enter any command other than the ones above, the bot will regard it as an invalid response. Also, when ordering multiple items, enter the number preceding the items on the menu in comma-separated values, e.g. `2,3,4` (no spaces).
Built as a project at [Altschool Africa School of Engineering - Node.js track](https://www.altschoolafrica.com/schools/engineering)
## Tech Stack
### 1. Main Dependencies
* **node.js** and **express** as the JavaScript runtime environment and server framework.
* **mongodb** as a database of choice.
* **mongoose** as an ODM library of choice.
* **socket.io** as a WebSocket library of choice.
* **express-session**- simple session middleware for Express.
## Main Files: Project Structure
```sh
├── README.md *** Instructions on how to set-up the project locally.
├── package.json *** The dependencies to be installed with "npm install"
├── server.js *** Entry point of the app
├── app.js
├── db.js
├── handlers.js
├── helpers.js
├── .env
├── example.env
├── models
│ ├── userModel.js
│ ├── chatModel.js
│ ├── menuModel.js
├── middlewares
│ ├── sessionMiddleware.js
│ ├── socketMiddleware.js
├── views
│ ├── index.pug
├── data
│ ├── import-data.js *** File to be run independently to populate the "menus" collection with menu data or to offload the "menus" collection.
│ ├── menu.json
│ ├── options.json
├── public
│ ├── Chat.js
│ ├── config.js
│ ├── script.js
└── └── style.css
```
## Getting Started Locally
### Prerequisites & Installation
To be able to get this application up and running, ensure to have [node](https://nodejs.org/en/download/) installed on your device.
### Development Setup
1. **Download the project locally by forking this repo and then clone or just clone directly via:**
```bash
git clone https://github.com/omobolajisonde/FoodieBot.git
```
2. **Create a .env file just like the example.env**
- Assign the `SESSION_SECRET` variable a very strong secret.
- Assign the `COOKIE_EXPIRES_IN` variable a very long time in milliseconds.
3. **Set up the Database**
- Create a MongoDB database on your local MongoDB server or in the cloud (Atlas).
- Copy the connection string and assign it to the `DATABASE_URI` environment variable.
- On connection to the database, four collections - `users`, `chats`, `menus` and `sessions` are created. Though the `sessions` collection is created by [connect-mongodb-session](https://www.npmjs.com/package/connect-mongodb-session), an external session store for the session.
- In your terminal `cd` to the data directory and type the command `node import-data.js --import` to populate the `menus` collection with menu data. If you want to offload the `menus` collection, still in the data directory, type the command `node import-data.js --offload`.
## Models
---
### User
| Field | Data type | Description |
|---|---|---|
| _id | ObjectId | auto-generated |
| userId | String | required, unique, same as the userId in the stored in the session |
| orders | Array | A list of all the orders a user has checkedout |
| createdAt | Date | Defaults to current timestamp |
### Chat
| Field | Data type | Description |
|---|---|---|
| _id | ObjectId | auto-generated |
| message | String | User or bot message |
| isBotMsg | Boolean | True or false depending on whether the message is from the user or the bot. |
| userId | ObjectId (ref: User) | Used to map every chat to a particular user or session |
### Menu
| Field | Data type | Description |
|---|---|---|
| _id | ObjectId | auto-generated |
| id | Number | The number which is used when customers want to order a particular item on the menu. |
| name | String | Dish or Item name |
| price | Number | Dish or Item price |
| course | String | Dish or Item course |
| cuisine | String | Dish or Item cuisine |
4. **Install the dependencies** from the root directory, in terminal run:
```
npm install
```
5. **Run the development server:**
```bash
npm run dev
```
6. **At this point, your server should be up and running** at [http://127.0.0.1:5000/](http://127.0.0.1:5000/) or [http://localhost:8080](http://localhost:8080)
---
## Viewing the application in a browser
Visit http://127.0.0.1:5000/ or http://localhost:8080/ on your browser. You should see on you screen a page like the one below.

---
## Deployment
[foodiebotaltschool.onrender.com/](https://foodiebotaltschool.onrender.com/)
## Authors
[Sonde Omobolaji](https://github.com/omobolajisonde)
## Acknowledgements
The awesome team at Altschool. |
// Copyright 2020 John Millikin and the rust-fuse contributors.
//
// 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.
//
// SPDX-License-Identifier: Apache-2.0
//! Implements the `FUSE_GETLK` operation.
use core::cmp;
use core::fmt;
use crate::internal::fuse_kernel;
use crate::lock;
use crate::node;
use crate::server;
use crate::server::decode;
use crate::server::encode;
// GetlkRequest {{{
/// Request type for `FUSE_GETLK`.
///
/// See the [module-level documentation](self) for an overview of the
/// `FUSE_GETLK` operation.
pub struct GetlkRequest<'a> {
header: &'a fuse_kernel::fuse_in_header,
body: &'a fuse_kernel::fuse_lk_in,
lock_mode: lock::Mode,
lock_range: lock::Range,
}
impl GetlkRequest<'_> {
#[inline]
#[must_use]
pub fn node_id(&self) -> node::Id {
unsafe { node::Id::new_unchecked(self.header.nodeid) }
}
#[inline]
#[must_use]
pub fn handle(&self) -> u64 {
self.body.fh
}
#[inline]
#[must_use]
pub fn owner(&self) -> lock::Owner {
lock::Owner::new(self.body.owner)
}
#[inline]
#[must_use]
pub fn lock_mode(&self) -> lock::Mode {
self.lock_mode
}
#[inline]
#[must_use]
pub fn lock_range(&self) -> lock::Range {
self.lock_range
}
}
impl server::sealed::Sealed for GetlkRequest<'_> {}
impl<'a> server::FuseRequest<'a> for GetlkRequest<'a> {
fn from_request(
request: server::Request<'a>,
_options: server::FuseRequestOptions,
) -> Result<Self, server::RequestError> {
let mut dec = request.decoder();
dec.expect_opcode(fuse_kernel::FUSE_GETLK)?;
let header = dec.header();
decode::node_id(header.nodeid)?;
let body: &fuse_kernel::fuse_lk_in = dec.next_sized()?;
let lock_mode = lock::decode_mode(&body.lk)?;
let lock_range = lock::decode_range(&body.lk)?;
Ok(Self { header, body, lock_mode, lock_range })
}
}
impl fmt::Debug for GetlkRequest<'_> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("GetlkRequest")
.field("node_id", &self.node_id())
.field("handle", &self.handle())
.field("owner", &self.owner())
.field("lock_mode", &self.lock_mode())
.field("lock_range", &self.lock_range())
.finish()
}
}
// }}}
// GetlkResponse {{{
/// Response type for `FUSE_GETLK`.
///
/// See the [module-level documentation](self) for an overview of the
/// `FUSE_GETLK` operation.
pub struct GetlkResponse {
lock: Option<lock::Lock>,
raw: fuse_kernel::fuse_lk_out,
}
impl GetlkResponse {
#[inline]
#[must_use]
pub fn new(lock: Option<lock::Lock>) -> GetlkResponse {
let fuse_lock = match &lock {
None => fuse_kernel::fuse_file_lock {
r#type: lock::F_UNLCK,
start: 0,
end: 0,
pid: 0,
},
Some(lock) => fuse_kernel::fuse_file_lock {
r#type: match lock.mode() {
lock::Mode::Exclusive => lock::F_WRLCK,
lock::Mode::Shared => lock::F_RDLCK,
},
start: cmp::min(
lock.range().start(),
lock::OFFSET_MAX,
),
end: cmp::min(
lock.range().end().unwrap_or(lock::OFFSET_MAX),
lock::OFFSET_MAX,
),
pid: lock.process_id().map(|x| x.get()).unwrap_or(0),
},
};
Self {
lock,
raw: fuse_kernel::fuse_lk_out { lk: fuse_lock },
}
}
#[inline]
#[must_use]
pub fn lock(&self) -> Option<lock::Lock> {
self.lock
}
}
impl fmt::Debug for GetlkResponse {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("GetlkResponse")
.field("lock", &self.lock())
.finish()
}
}
impl server::sealed::Sealed for GetlkResponse {}
impl server::FuseResponse for GetlkResponse {
fn to_response<'a>(
&'a self,
header: &'a mut crate::ResponseHeader,
_options: server::FuseResponseOptions,
) -> server::Response<'a> {
encode::sized(header, &self.raw)
}
}
// }}} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VRage.Game.GUI.TextPanel;
using VRageMath;
namespace RedVsBlueClassSystem
{
class Table
{
public List<Column> Columns = new List<Column>();
public List<Row> Rows = new List<Row>();
public void Clear()
{
Rows.Clear();
}
public void RenderToSprites(List<MySprite> sprites, Vector2 topLeft, float width, Vector2 cellGap, float scale = 1)
{
Vector2 ignored;
RenderToSprites(sprites, topLeft, width, cellGap, out ignored, scale);
}
public void RenderToSprites(List<MySprite> sprites, Vector2 topLeft, float width, Vector2 cellGap, out Vector2 positionAfter, float scale = 1)
{
//Calculate column widths & row heights
float[] columnContentWidths = new float[Columns.Count];
float[] columnWidths = new float[Columns.Count];
float[] rowHeights = new float[Rows.Count];
float totalFreeSpaceWeight = 0;
float minWidthRequired = 0;
for (int colNum = 0; colNum < Columns.Count; colNum++)
{
totalFreeSpaceWeight += Columns[colNum].FreeSpace;
for (int rowNum = 0; rowNum < Rows.Count; rowNum++)
{
var row = Rows[rowNum];
var cell = row[colNum];
if (!cell.IsEmpty)
{
columnContentWidths[colNum] = Math.Max(columnContentWidths[colNum], TextUtils.GetTextWidth(cell.Value, scale));
rowHeights[rowNum] = Math.Max(rowHeights[rowNum], TextUtils.GetTextHeight(cell.Value, scale));
}
}
minWidthRequired += columnContentWidths[colNum] + (colNum > 0 ? cellGap.X : 0);
columnWidths[colNum] = columnContentWidths[colNum];
}
//distribute free space
if (minWidthRequired < width && totalFreeSpaceWeight > 0)
{
float freeSpace = width - minWidthRequired;
for (int i = 0; i < Columns.Count; i++)
{
if (Columns[i].FreeSpace > 0)
{
columnWidths[i] += freeSpace * (Columns[i].FreeSpace / totalFreeSpaceWeight);
}
}
}
var rowTopLeft = topLeft;
var tableHeight = 0f;
//render rows
for (int rowNum = 0; rowNum < Rows.Count; rowNum++)
{
var row = Rows[rowNum];
float rowX = 0;
for (int colNum = 0; colNum < Columns.Count; colNum++)
{
var cell = row[colNum];
var column = Columns[colNum];
if (!cell.IsEmpty)
{
var sprite = MySprite.CreateText(cell.Value, "Monospace", cell.Color, scale, column.Alignment);
switch (column.Alignment)
{
case TextAlignment.LEFT:
sprite.Position = rowTopLeft + new Vector2(rowX, 0);
break;
case TextAlignment.RIGHT:
sprite.Position = rowTopLeft + new Vector2(rowX + columnWidths[colNum], 0);
break;
case TextAlignment.CENTER:
sprite.Position = rowTopLeft + new Vector2(rowX + (columnWidths[colNum] / 2), 0);
break;
}
sprites.Add(sprite);
}
rowX += columnWidths[colNum] + cellGap.X;
}
float rowTotalHeight = rowHeights[rowNum] + (rowNum > 0 ? cellGap.Y : 0);
rowTopLeft += new Vector2(0, rowTotalHeight);
tableHeight += rowTotalHeight;
}
positionAfter = topLeft + new Vector2(0, tableHeight);
}
}
class Column
{
public string Name;
public float FreeSpace = 0;
public TextAlignment Alignment = TextAlignment.LEFT;
}
class Row : List<Cell>
{
}
struct Cell
{
public string Value;
public Color Color;
public bool IsEmpty { get { return string.IsNullOrEmpty(Value); } }
public Cell(string value, Color color)
{
Value = value;
Color = color;
}
public Cell(string value)
{
Value = value;
Color = Color.White;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Cineflix.Data;
using Cineflix.Models;
using Cineflix.ViewModels;
namespace Cineflix.Controllers
{
public class MoviesController : Controller
{
private readonly ApplicationDbContext _context;
public MoviesController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
if (_context.Movie == null) {
return Problem("Entity set 'ApplicationDbContext.Movie' is null.");
} else {
var movies = await _context.Movie.ToListAsync();
var viewModelMovies = new List<MovieViewModel>();
movies.ForEach(movie => viewModelMovies.Add(new MovieViewModel(movie)));
var userEmail = User.Identity.Name;
if (_context.PurchasedMovie != null && userEmail != null)
{
var allPurchasedMovies = await _context.PurchasedMovie.ToListAsync();
var userMovies = allPurchasedMovies.Where(movie => movie.UserId == userEmail);
if(userMovies != null)
{
foreach(var userMovie in userMovies)
{
foreach(var viewModelMovie in viewModelMovies)
{
if(viewModelMovie.Movie.Id == userMovie.MovieId)
{
viewModelMovie.IsPurchased = true;
}
}
}
}
}
return View(viewModelMovies);
}
}
public async Task<IActionResult> Details(int? id)
{
if (id == null || _context.Movie == null)
{
return NotFound();
}
var movie = await _context.Movie.FirstOrDefaultAsync(m => m.Id == id);
if (movie == null)
{
return NotFound();
}
var movieViewModel = new MovieViewModel(movie);
var userEmail = User.Identity.Name;
if (_context.PurchasedMovie != null && userEmail != null)
{
var userMovie = await _context.PurchasedMovie
.FirstOrDefaultAsync(m => m.MovieId == movie.Id && m.UserId == userEmail);
if(userMovie != null)
{
movieViewModel.IsPurchased = true;
}
}
return View(movieViewModel);
}
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price,FileUpload")] MovieCreateViewModel movieCreateViewModel)
{
if (ModelState.IsValid)
{
Movie movie = new Movie();
movie.Title = movieCreateViewModel.Title;
movie.ReleaseDate = movieCreateViewModel.ReleaseDate;
movie.Genre = movieCreateViewModel.Genre;
movie.Price = movieCreateViewModel.Price;
using (var ms = new MemoryStream())
{
if (movieCreateViewModel.FileUpload != null)
{
movieCreateViewModel.FileUpload.CopyTo(ms);
var fileBytes = ms.ToArray();
string byte64 = Convert.ToBase64String(fileBytes);
movie.MovieThumbnail = byte64;
}
}
_context.Add(movie);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(movieCreateViewModel);
}
public async Task<IActionResult> Edit(int? id)
{
if (id == null || _context.Movie == null)
{
return NotFound();
}
var movie = await _context.Movie.FindAsync(id);
if (movie == null)
{
return NotFound();
}
return View(movie);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Title,ReleaseDate,Genre,Price,MovieThumbnail")] Movie movie)
{
if (id != movie.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(movie);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(movie.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(movie);
}
public async Task<IActionResult> Delete(int? id)
{
if (id == null || _context.Movie == null)
{
return NotFound();
}
var movie = await _context.Movie
.FirstOrDefaultAsync(m => m.Id == id);
if (movie == null)
{
return NotFound();
}
return View(movie);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
if (_context.Movie == null)
{
return Problem("Entity set 'ApplicationDbContext.Movie' is null.");
}
var movie = await _context.Movie.FindAsync(id);
if (movie != null)
{
_context.Movie.Remove(movie);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public IActionResult Privacy()
{
return View();
}
public IActionResult Play()
{
return View();
}
private bool MovieExists(int id)
{
return (_context.Movie?.Any(e => e.Id == id)).GetValueOrDefault();
}
}
} |
import { Resolver, Query, Mutation, Args, Int, ID } from '@nestjs/graphql';
import { OrdersService } from './orders.service';
import { Order } from './entities/order.entity';
import { CreateOrderInput, UpdateOrderInput } from './dto';
@Resolver(() => Order)
export class OrdersResolver {
constructor(private readonly ordersService: OrdersService) {}
@Mutation(() => Order)
createOrder(@Args('createOrderInput') createOrderInput: CreateOrderInput) {
return this.ordersService.create(createOrderInput);
}
@Query(() => [Order], { name: 'orders' })
findAll():Promise<Order[]> {
return this.ordersService.findAll();
}
@Query(() => Order, { name: 'order' })
findOne(@Args('id', { type: () => ID }) id: string):Promise<Order> {
return this.ordersService.findOne(id);
}
@Mutation(() => Order)
updateOrder(@Args('updateOrderInput') updateOrderInput: UpdateOrderInput):Promise<Order> {
return this.ordersService.update(updateOrderInput.id, updateOrderInput);
}
@Mutation(() => Order)
removeOrder(@Args('id', { type: () => ID }) id: string):Promise<Order> {
return this.ordersService.remove(id);
}
} |
import i18n from '@dhis2/d2-i18n'
import { SingleSelect, SingleSelectOption } from '@dhis2/ui'
import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import {
tSetUiStage,
tClearUiProgramStageDimensions,
} from '../../../actions/ui.js'
import { sGetUiProgramStageId } from '../../../reducers/ui.js'
import styles from './ProgramSelect.module.css'
const StageSelect = ({ stages }) => {
const dispatch = useDispatch()
const selectedStageId = useSelector(sGetUiProgramStageId)
const onChange = ({ selected: stageId }) => {
const stage = stages.find(({ id }) => id === stageId)
dispatch(tSetUiStage(stage))
if (selectedStageId) {
dispatch(tClearUiProgramStageDimensions(selectedStageId))
}
}
return (
<div className={cx(styles.rows, styles.stage)}>
<div className={styles.columns}>
<div className={styles.stretch}>
<SingleSelect
prefix={i18n.t('Stage')}
dense
selected={selectedStageId}
onChange={onChange}
dataTest={'stage-select'}
filterable
noMatchText={i18n.t('No stages found')}
>
{stages.map(({ id, name }) => (
<SingleSelectOption
label={name}
key={id}
value={id}
/>
))}
</SingleSelect>
</div>
</div>
</div>
)
}
StageSelect.propTypes = {
stages: PropTypes.arrayOf(PropTypes.object).isRequired,
}
export { StageSelect } |
import Price from '@/app/components/Price';
import { Cuisine, Location, PRICE } from '@prisma/client';
import Link from 'next/link';
const SearchSideBar = async ({
locations,
cuisines,
searchParams,
}: {
locations: Location[];
cuisines: Cuisine[];
searchParams: {
city?: string;
cuisine?: string;
price?: PRICE;
};
}) => {
const prices = [
{ price: PRICE.CHEAP, label: <Price price={PRICE.CHEAP} /> },
{ price: PRICE.REGULAR, label: <Price price={PRICE.REGULAR} /> },
{ price: PRICE.EXPENSIVE, label: <Price price={PRICE.EXPENSIVE} /> },
];
return (
<div className='w-1/5'>
<div className='border-b pb-4 flex flex-col'>
<h1 className='mb-2'>Region</h1>
{locations.length ? (
locations.map((location) => (
<Link
href={{
pathname: '/search',
query: {
...searchParams,
city: location.name,
},
}}
className='font-light text-reg capitalize'
key={location.id}
>
{location.name}
</Link>
))
) : (
<p className='font-light text-reg'>No locations found.</p>
)}
</div>
<div className='border-b pb-4 mt-3 flex flex-col'>
<h1 className='mb-2'>Cuisine</h1>
{cuisines.length ? (
cuisines.map((cuisine) => (
<Link
href={{
pathname: '/search',
query: {
...searchParams,
cuisine: cuisine.name,
},
}}
className='font-light text-reg capitalize'
key={cuisine.id}
>
{cuisine.name}
</Link>
))
) : (
<p className='font-light text-reg'>No cuisines found.</p>
)}
</div>
<div className='mt-3 pb-4'>
<h1 className='mb-2'>Price</h1>
<div className='flex'>
{prices?.map(({ price, label }, idx) => (
<Link
key={idx}
href={{
pathname: '/search',
query: {
...searchParams,
price,
},
}}
className='border w-full text-reg font-light rounded-l p-2 flex'
>
{label}
</Link>
))}
</div>
</div>
</div>
);
};
export default SearchSideBar; |
<h1 align="center"> ToDo App </h1>
    
Projeto desenvolvido no curso Lógica de Programação e Algoritmos III - [Programa START da Capgemini](https://startcapgemini.com.br/)
## Índice
* [Índice](#índice)
* [Descrição do Projeto](#descrição-do-projeto)
* [Funcionalidades e Demonstração da Aplicação](#funcionalidades-e-demonstração-da-aplicação)
* [Tecnologias Utilizadas](#tecnologias-utilizadas)
* [Acesso ao Projeto](#acesso-ao-projeto)
* [Etapas do Desenvolvimento](#etapas-do-desenvolvimento)
* [Próximos Passos](#próximos-passos)
## Descrição do Projeto
Aplicação para gerenciamento de projetos e as tarefas envolvidas nos mesmos.
**Requisitos:**
* permitir criar projetos;
* permitir alterar projetos (em desenvolvimento);
* permitir deletar projetos (em desenvolvimento);
* permitir criar tarefas;
* permitir alterar tarefas;
* permitir deletar tarefas;
**Regras de negócio:**
* o sistema não contará com um sistema de login;
* não haverá o conceito de usuário;
* toda tarefa deve pertencer a um projeto.
## Funcionalidades e Demonstração da Aplicação
* Tela principal (com e sem tarefas):
<img src="./images/general.gif">
* Tela/cadastro de projetos:
<img src="./images/create_projects.gif">
* Tela/cadastro de tarefas:
<img src="./images/create_tasks.gif">
* Atualização de tarefas (campos `Nome`, `Descrição` e `Prazo`):
<img src="./images/update_tasks.gif">
* Atualização de tarefas (campo `Tarefa concluída`):
<img src="./images/update_tasks_status.gif">
* Exclusão de tarefas:
<img src="./images/delete_tasks.gif">
## Tecnologias Utilizadas
* Ubuntu 22.04.3 LTS
* JDK 21.0.1
* Gradle 8.3-rc-1
* Apache NetBeans IDE 19
* MySQL (XAMPP para Linux 8.2.4-0)
## Acesso ao Projeto
**Repositório:**
1. Clonar o repositório
```
git clone https://github.com/ana-karine/capgemini_school.git
```
2. Utilizando o NetBeans, abrir o projeto `TodoApp` (localizado no diretório `/capgemini_school/todo_app`)
3. Siga todos os passos referentes ao Banco de Dados
4. No NetBeans, executar o arquivo `MainScreen.java` (localizado no diretório `/capgemini_school/todo_app/TodoApp/app/src/main/java/view`)
**Banco de Dados:**
1. Iniciar o painel de controle do XAMPP
- se você usa um sistema de 32 bits:
```
sudo /opt/lampp/manager-linux.run
```
- se você usa um sistema de 64 bits:
```
sudo /opt/lampp/manager-linux-x64.run
```
- na aba `Manage Servers` clicar em `Start All`
2. Acessar o aplicativo phpMyAdmin (para administração do MySQL)
```
https://localhost/phpmyadmin/
```
3. No phpMyAdmin, importar o database `todoApp.sql` (localizado no diretório `/capgemini_school/todo_app/database`)
## Etapas do Desenvolvimento
* criação do banco de dados
* criação das classes de modelo
* criação da conexão com o banco de dados
* criação das classes de controle (acesso aos dados do banco)
* criação da interface gráfica
- criação da tela principal
- criação do CellRenderer Prazo
- criação do CellRenderer Editar e Deletar
- criação da tela de cadastro de Projeto
- criação da tela de cadastro de Tarefa
* implementação dos eventos
- validações
* ajustes finais
* testes da aplicação
## Próximos Passos
* criação do conceito de `tags` para que possamos atribuí-las as tarefas;
* criação do conceito de `conta` e `usuário`;
* construção de uma `tela de login`;
* permitir a alteração dos dados da tarefa, abrindo a `tela de tarefas` com os dados carregados, ao clicar no botão de editar. |
package kr.hs.example.backpractice01.controller;
import kr.hs.example.backpractice01.domain.Department;
import kr.hs.example.backpractice01.dto.department.DepartmentRes;
import kr.hs.example.backpractice01.dto.department.InsertDepartmentDto;
import kr.hs.example.backpractice01.service.DepartmentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;
@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping("/departments")
@RequiredArgsConstructor
@RestController
public class DepartmentController {
private final DepartmentService departmentService;
@PostMapping("")
public ResponseEntity<?> insertDepartment(@RequestBody InsertDepartmentDto params) {
Department department = departmentService.insertDepartment(params.getName());
return ResponseEntity.ok(department);
}
@GetMapping("")
public ResponseEntity<?> getDepartment() {
List<DepartmentRes> department = departmentService.getDepartments()
.stream().map(DepartmentRes::new).collect(Collectors.toList());
return ResponseEntity.ok(department);
}
} |

## table of contents
- [features](#features)
- [visualization](#visualization)
- [customization](#customization)
### features
- **multi-threaded crawling**: the web crawler utilizes up to 10 threads to maximize crawling efficiency.
- **live url display**: each thread shows its own urls in real-time on labeled panels.
- **crawling modes**: users can choose between vertical or horizontal crawling using stack or queue.
- **customizable settings**: users can adjust crawling depth, number of urls to crawl, and delays between http requests.
- **built-in visualization**: the crawler includes an embedded pyvis python script to visualize the crawled urls in a natural tree shape.
- **database integration**: the crawler creates sql tables for each root url and stores data about the crawled urls, including parent id, depth, spider id, created url count, url address, founding date, crawling date, and is failed.
- **table management**: tables can be deleted as needed to manage crawled data efficiently.
- **web browser integration**: users can inspect each crawled url and navigate to it using a button click.
- **custom thread count**: users can choose the number of threads to use during crawling.
- **csv file**: users can download the crawled urls as a csv file.
### visualization
the crawled urls can be visualized using the built-in pyvis script, generating a natural tree-shaped graph that shows the relationships between the urls. example image uses vertical crawling as its crawling direction.

### customization
the web crawler offers several customization options:
- crawling depth: set the depth of the crawling process to control how far the crawler follows links from the initial urls.
- url limit: define the maximum number of urls the crawler should scrape during the crawling process.
- delays: adjust the delay between each http request to prevent overwhelming the target server.
- thread count: choose the number of threads to use for the crawling process. |
"use client";
import { useMediaQuery, useTheme } from "@mui/material";
import AppbarMobile from "./appbarMobile";
import AppbarDesktop from "./appbarDesktop";
import { useEffect, useState } from "react";
const Navbar = () => {
const theme = useTheme();
const matches = useMediaQuery(theme.breakpoints.down("md"));
const [backgroundColor, setBackgroundColor] = useState(false);
useEffect(() => {
//navbar scroll changeBackground function
const handleBackgroundColor = () => {
if (window.scrollY > 80) {
setBackgroundColor(true);
} else {
setBackgroundColor(false);
}
};
window.addEventListener("scroll", handleBackgroundColor);
return () => window.removeEventListener("scroll", handleBackgroundColor);
});
return (
<>
{matches ? (
<AppbarMobile matches={matches} navbarColor={backgroundColor} />
) : (
<AppbarDesktop navbarColor={backgroundColor} matches={matches} />
)}
</>
);
};
export default Navbar; |
import { FC, PropsWithChildren, useEffect, useReducer } from 'react';
import { AuthContext, authReducer } from './';
import { IUser } from '@/interfaces';
import Cookies from 'js-cookie';
import axios from 'axios';
import { useRouter } from 'next/router';
import { useSession, signOut } from 'next-auth/react';
import { adminObraApi } from '@/api';
export interface AuthState {
isLoggedIn: boolean;
user?: IUser | undefined
}
const AUTH_INITIAL_STATE: AuthState = {
isLoggedIn: false,
user: undefined,
}
export const AuthProvider:FC<PropsWithChildren> = ({ children }:any) => {
const [state, dispatch] = useReducer( authReducer, AUTH_INITIAL_STATE )
const router = useRouter()
const { data, status } = useSession();
useEffect(() => {
if ( status === 'authenticated' ) {
dispatch({ type: '[Auth] - Login', payload: data?.user as IUser})
}
}, [ status, data ])
// useEffect(() => {
// checkToken()
// }, [])
const checkToken = async() => {
if ( !Cookies.get('token') ) {
return;
}
try {
const { data } = await adminObraApi.get('/user/validate-token');
const { token, user } = data;
Cookies.set('token', token );
dispatch({ type: '[Auth] - Login', payload: user })
} catch (error) {
Cookies.remove('token')
}
}
const loginUser = async ( email:string, password:string ): Promise<boolean> => {
try {
const { data } = await adminObraApi.post('/user/login', { email, password });
const { token, user } = data;
Cookies.set('token', token );
dispatch({ type: '[Auth] - Login', payload: user })
return true
} catch (error) {
return false;
}
}
const registerUser = async ( name:string, lastName: string, email:string, password:string ): Promise<{hasError: boolean; message?: string}> => {
try {
const { data } = await adminObraApi.post('/user/register', { name, email, password });
const { token, user } = data;
Cookies.set('token', token );
dispatch({ type: '[Auth] - Login', payload: user })
return {
hasError: false,
}
} catch (error) {
if ( axios.isAxiosError(error) ) {
return {
hasError: true,
message: error.response?.data.message
}
}
return {
hasError: true,
message: 'No se pudo crear el usuario'
}
}
}
const logout = () => {
Cookies.set('CallbackUrl', 'asd')
signOut();
// Cookies.remove('token');
// router.reload();
}
return (
<AuthContext.Provider value={{
...state,
// Methods
loginUser,
registerUser,
logout,
}}>
{ children }
</AuthContext.Provider>
)
} |
package com.omersungur.composeintro
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.omersungur.composeintro.ui.theme.ComposeIntroTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeIntroTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
MainScreen()
}
//testFunction(5,::testLambda) lambda gösterimi değil. bu fonksiyonu referans sistemiyle kullandık
/*testFunction(6) {
testLambda()
}*/
}
}
}
/*fun testFunction (number : Int, myFunction : () -> Unit) {
myFunction.invoke()
}
fun testLambda() {
println("Test")
}*/
}
@Composable
fun MainScreen() {
//Row > Satırda sıralama(yatay)
//Column > Sütunda sıralama (dikey)
//Box > Z ekseninde sıralama
Column(
modifier = Modifier
.fillMaxSize()
.background(color = Color.LightGray),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
)
{
CustomText(text = "Hello Android")
Spacer(modifier = Modifier.padding(bottom = 5.dp))
CustomText(text = "Hello Kotlin")
Spacer(modifier = Modifier.padding(bottom = 5.dp))
CustomText(text = "Hello Java")
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
CustomText(text = "Test 1")
Spacer(modifier = Modifier.padding(5.dp))
CustomText(text = "Test 2")
Spacer(modifier = Modifier.padding(5.dp))
CustomText(text = "Test 3")
}
}
}
@Composable
fun CustomText(text: String) {
Text(modifier = Modifier
.clickable {
println("Texte tıklandı!")
}
.background(color = Color.Yellow)
.padding(top = 10.dp, bottom = 5.dp, start = 15.dp, end = 20.dp)
.width(150.dp),
text = text,
color = Color.Blue,
fontWeight = FontWeight.Bold,
fontSize = 22.sp
)
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
MainScreen()
} |
from django import forms
from profiles.models import Profile
from bb2.lists import (COUNTRY_CHOICES, AGE_CHOICES,
PUNCTUALITY_CHOICES, IELTS_SCORE_CHOICES,
TOEFL_SCORE_CHOICES, PURPOSE_CHOICES)
class DateInput(forms.DateInput):
input_type = 'date'
class SearchForm(forms.Form):
q = forms.CharField(
required=False,
label='free word',
max_length=300,
widget= forms.TextInput(attrs={'placeholder':'Search...'}))
kind = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices = (('profile', 'people'),))
date_from = forms.DateTimeField(
required=False,
widget=DateInput())
date_to = forms.DateTimeField(
required=False,
widget=DateInput())
country = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices = [])
sex = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices = (('female', 'female'), ('male', 'male')))
age = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices = [])
punctuality = forms.ChoiceField(
required=False,
initial='no',
widget=forms.RadioSelect(),
choices = PUNCTUALITY_CHOICES)
purpose = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices = PURPOSE_CHOICES)
follow = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices=(('on', 'people you follow'),))
invited = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices=(('on', 'rooms you are invited'),))
no_apply = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices=(('on', 'no need to apply'),))
active = forms.MultipleChoiceField(
required=False,
initial='on',
widget=forms.CheckboxSelectMultiple(),
choices=(('on', 'active user'),))
ielts = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices=IELTS_SCORE_CHOICES)
toefl = forms.MultipleChoiceField(
required=False,
widget=forms.CheckboxSelectMultiple(),
choices=TOEFL_SCORE_CHOICES)
def __init__(self, *args, purpose_initial=None, **kwargs):
# print(self)
# print(vaslvnaslkv)
super().__init__(*args, **kwargs)
available_country = set(map(lambda x: x.country,Profile.objects.all()))
AVA_COUNTRY_CHOICES = filter(lambda x: x[0] in available_country, COUNTRY_CHOICES)
available_age = set(map(lambda x: x.age,Profile.objects.all()))
AVA_AGE_CHOICES = filter(lambda x: x[0] in available_age, AGE_CHOICES)
#self.fields['purpose'].initial = purpose_initial
self.fields['country'].choices = AVA_COUNTRY_CHOICES
self.fields['age'].choices = AVA_AGE_CHOICES |
package asciiart.image.models.pixel
case class RGBPixel(red: Int, green: Int, blue: Int) extends Pixel {
require(red >= 0 && red <= 255, "Red value must be between 0 and 255")
require(green >= 0 && green <= 255, "Green value must be between 0 and 255")
require(blue >= 0 && blue <= 255, "Blue value must be between 0 and 255")
private var _grayScaleValue: Int = (red * 0.3 + green * 0.59 + blue * 0.11).toInt
def setGrayScaleValue(value: Int) = {
if (value < 0 || value > 255) {
throw new IllegalArgumentException("Grayscale value must be between 0 and 255")
}
_grayScaleValue = value
}
def grayScaleValue = _grayScaleValue
} |
//
// Utils.swift
// Pokemon
//
// Created by Chaitanya Pandit on 22/05/24.
//
import Foundation
extension URL {
static let baseURL: URL = URL(string: "https://pokeapi.co/api/v2")!
public var params: [String: String]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true),
let queryItems = components.queryItems else {
return nil
}
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}
}
extension Encodable {
func toDictionary() throws -> [String: Any] {
let data = try JSONEncoder().encode(self)
guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
throw APIError.badEncoding
}
return dictionary
}
}
extension URLRequest {
static func get(path: String, params: Encodable? = nil) throws -> URLRequest {
guard var urlcomps = URLComponents(string: URL.baseURL.appendingPathComponent(path).absoluteString) else {
throw APIError.badRequest
}
if let params = params {
let paramsDict = try params.toDictionary()
urlcomps.queryItems = paramsDict.map({ (key, val) in
URLQueryItem(name: key, value: String(describing: val))
})
}
guard let url = urlcomps.url else {
throw APIError.badRequest
}
return URLRequest(url: url)
}
} |
import React, {useState, useEffect} from 'react'
import axios from 'axios'
import CarouselCenter from '../../components/carousel/CarouselCenter'
import ShoesCard from '../../components/shoes-card/ShoesCard'
const Product = () => {
const [limit, setLimit] = useState(5)
const [products, setProducts] = useState([])
const API_URL = `https://fakestoreapi.com/products?limit=${limit}`
//function to get product from API
const fetchProduct = async() => {
try {
const response = await axios.get(API_URL)
const {data} = response
console.log(
data, "response from fetchProduct"
)
setProducts(data)
} catch (error) {
console.log(error, 'error from fetchProduct')
}
}
console.log(products)
useEffect(
() => {
fetchProduct()
}, [limit]
)
return (
<div>
<CarouselCenter>
{
products.map(
(item,index) => {
return(
<ShoesCard
imgSrc={item.image}
name ={item.title}
des ={item.description}
buttonText ={item.price}
className ="carousel-item"
/>
)
}
)
}
</CarouselCenter>
<button className='' onClick={
() => setLimit(prev => prev + 5)
}>
Load 5 more products
</button>
</div>
)
}
export default Product |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="bootstrap-5.2.3-dist/css/bootstrap.css">
<link rel="stylesheet" href="css/site.css">
<!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> -->
<!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> -->
<style>
</style>
</head>
<body>
<!-- display 유틸리티를 적용하여 flexbox 컨테이너를 만들고 직계 자식 요소 를 플렉스 항목으로 변환합니다.
flex컨테이너와 아이템은 추가적인 flex 속성을 사용하여 수정할 수 있습니다.
-->
<div class="d-flex p-2">I'm a flexbox container!</div>
<div class="d-inline-flex p-2">I'm an inline flexbox container!</div>
<hr>
<div class="d-flex flex-row mb-3">
<div class="p-2">Flex item 1</div>
<div class="p-2">Flex item 2</div>
<div class="p-2">Flex item 3</div>
</div>
<hr>
<div class="d-flex flex-row-reverse">
<div class="p-2">Flex item 1</div>
<div class="p-2">Flex item 2</div>
<div class="p-2">Flex item 3</div>
</div>
<hr>
<div class="d-flex flex-column mb-3">
<div class="p-2">Flex item 1</div>
<div class="p-2">Flex item 2</div>
<div class="p-2">Flex item 3</div>
</div>
<hr>
<div class="d-flex flex-column-reverse">
<div class="p-2">Flex item 1</div>
<div class="p-2">Flex item 2</div>
<div class="p-2">Flex item 3</div>
</div>
<hr>
<div class="d-flex justify-content-start">
<span>item</span>
<span>item</span>
<span>item</span>
</div>
<hr>
<div class="d-flex justify-content-end">
<span>item</span>
<span>item</span>
<span>item</span>
</div>
<hr>
<div class="d-flex justify-content-center">
<span>item</span>
<span>item</span>
<span>item</span>
</div>
<hr>
<div class="d-flex justify-content-between">
<span>item</span>
<span>item</span>
<span>item</span>
</div>
<hr>
<div class="d-flex justify-content-around">
<span>item</span>
<span>item</span>
<span>item</span>
</div>
<hr>
<div class="d-flex justify-content-evenly">
<span>item</span>
<span>item</span>
<span>item</span>
</div>
<hr>
<hr>
<div class="d-flex align-items-start mb-3" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex align-items-end mb-3" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex align-items-center mb-3" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex align-items-baseline mb-3" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex align-items-stretch" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<hr><hr>
<!-- 자체정렬 -->
<div class="bd-example bd-example-flex">
<div class="d-flex mb-3" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="align-self-start p-2 bg-warning">Aligned flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex mb-3" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="align-self-end p-2 bg-warning">Aligned flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex mb-3" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="align-self-center p-2 bg-warning">Aligned flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex mb-3" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="align-self-baseline p-2 bg-warning">Aligned flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex" style="height: 100px; border:1px solid red;">
<div class="p-2 bg-warning">Flex item</div>
<div class="align-self-stretch p-2 bg-warning">Aligned flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
</div>
<!-- 일련의 형제 요소에 .flex-fill 클래스를 사용하면 사용 가능한 모든 가로 공간을 차지하면서
콘텐츠와 동일한 너비 (또는 콘텐츠가 테두리 상자를 초과하지 않는 너비)로 강제 설정합니다.
-->
<hr>
<div class="d-flex">
<div class="p-2 bg-warning flex-fill">Flex item with a lot of content</div>
<div class="p-2 bg-success flex-fill">Flex item</div>
<div class="p-2 bg-warning flex-fill">Flex item</div>
</div>
<hr>
<hr>
<!-- 자동마진 -->
<div class="d-flex mb-3">
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex mb-3">
<div class="me-auto p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
</div>
<div class="d-flex mb-3">
<div class="p-2 bg-warning">Flex item</div>
<div class="p-2 bg-warning">Flex item</div>
<div class="ms-auto p-2 bg-warning">Flex item</div>
</div>
<hr><hr>
<!-- 순서 -->
<div class="d-flex flex-nowrap">
<div class="order-3 p-2 bg-warning">First flex item</div>
<div class="order-2 p-2 bg-warning">Second flex item</div>
<div class="order-1 p-2 bg-warning">Third flex item</div>
</div>
<br><br><br><br><br><br>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> -->
<!-- <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script> -->
<!-- <script src="https://code.jquery.com/jquery-3.6.3.js"
integrity="sha256-nQLuAZGRRcILA+6dMBOvcRh5Pe310sBpanc6+QBmyVM=" crossorigin="anonymous"></script> -->
<script type="text/javascript" src="bootstrap-5.2.3-dist/js/bootstrap.bundle.js"></script>
</body>
</html> |
Feature: Entity user actions with own proposals (with 'View All + Create Proposals' access)
Background:
Given I have created a budget
And I am logged into default_subdomain as an entity_admin
And I go to budgets from reports page
And I visit the new budget
And I visit budget settings
And I visit budget access panel
And I turn up access for default_subdomain entity_user as 'View All + Create Proposals'
And default_subdomain entity_user has 'View All + Create Proposals' access
And I logged out from budget_builder page
And I am logged into default_subdomain as an entity_user
And I go to budgets from reports page
And I visit the new budget
@bvt
Scenario: can create the proposal
Then I can create a proposal
@p1
Scenario: can delete the proposal
When I have created a proposal via UI
And I search for the proposal
And I delete this proposal
Then I don't see this proposal
@p1
Scenario: can edit the proposal title
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
And I edit proposal title
Then I see new proposal title
@p2
Scenario: can edit the proposal details
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
And I edit proposal details
Then I see new proposal details
@p2
Scenario: can add support documents
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
And I add 'CoA_Cerritos_v0.xlsx' as support document
Then I can see this document
@p2
Scenario: can delete support documents
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
And I add 'CoA_Cerritos_v0.xlsx' as support document
And I delete this support document
Then I don't see this document
@p2
Scenario: can create expense operations
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
Then I can create expense operation
@p2
Scenario: can create revenue operations
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
Then I can create revenue operation
@p2
Scenario: can adjust amounts and persist to the backend
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
And I create expense operation ''
And I view this operation
And I see default status values on 'new_proposal' page
And I make a bulk adjustment of -1
Then I should see updated status values on 'new_proposal' page
@p2
Scenario: can see activity feed
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
Then I see activity feed
@p2
Scenario: can share proposal
When I have created a proposal via UI
And I search for the proposal
And I view the proposal
Then I can share this proposal |
*Copyright(c) 2016 CyberLogitec
*@FileName : BkgArrNtcAntfyVO.java
*@FileTitle : BkgArrNtcAntfyVO
*Open Issues :
*Change history :
*@LastModifyDate : 2016.02.11
*@LastModifier :
*@LastVersion : 1.0
* 2016.02.11
* 1.0 Creation
package com.hanjin.apps.alps.esm.bkg.inbounddocumentation.inboundnoticemgt.inboundnotice.vo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import com.hanjin.framework.component.common.AbstractValueObject;
import com.hanjin.framework.component.util.JSPUtil;
/**
* Table Value Ojbect<br>
* 관련 Event 에서 생성, 서버실행요청시 Data 전달역할을 수행하는 Value Object
*
* @author
* @since J2EE 1.6
* @see AbstractValueObject
*/
public class BkgArrNtcAntfyVO extends AbstractValueObject {
private static final long serialVersionUID = 1L;
private Collection<BkgArrNtcAntfyVO> models = new ArrayList<BkgArrNtcAntfyVO>();
/* Column Info */
private String updDt = null;
/* Column Info */
private String a2CntcEml = null;
/* Column Info */
private String custCntcTpCd = null;
/* Column Info */
private String antfyCustCd = null;
/* Column Info */
private String creDt = null;
/* Column Info */
private String cntcEml = null;
/* Page Number */
private String pagerows = null;
/* Column Info */
private String podCd = null;
/* VO Data Value( C:Creation, U:Update, D:Delete ) */
private String ibflag = null;
/* Column Info */
private String creUsrId = null;
/* Column Info */
private String a2FaxNo = null;
/* Column Info */
private String scNo = null;
/* Column Info */
private String a1CntcEml = null;
/* Column Info */
private String faxNo = null;
/* Column Info */
private String a1FaxNo = null;
/* Column Info */
private String updUsrId = null;
/* 테이블 컬럼의 값을 저장하는 Hashtable */
private HashMap<String, String> hashColumns = new LinkedHashMap<String, String>();
/* 테이블 컬럼에 대응되는 멤버변수를 저장하는 Hashtable */
private HashMap<String, String> hashFields = new LinkedHashMap<String, String>();
public BkgArrNtcAntfyVO() {}
public BkgArrNtcAntfyVO(String ibflag, String pagerows, String scNo, String antfyCustCd, String podCd, String a1CntcEml, String a1FaxNo, String a2CntcEml, String a2FaxNo, String creUsrId, String creDt, String updUsrId, String updDt, String custCntcTpCd, String faxNo, String cntcEml) {
this.updDt = updDt;
this.a2CntcEml = a2CntcEml;
this.custCntcTpCd = custCntcTpCd;
this.antfyCustCd = antfyCustCd;
this.creDt = creDt;
this.cntcEml = cntcEml;
this.pagerows = pagerows;
this.podCd = podCd;
this.ibflag = ibflag;
this.creUsrId = creUsrId;
this.a2FaxNo = a2FaxNo;
this.scNo = scNo;
this.a1CntcEml = a1CntcEml;
this.faxNo = faxNo;
this.a1FaxNo = a1FaxNo;
this.updUsrId = updUsrId;
}
/**
* 테이블 컬럼에 저장할 값을 Hashtable<"column_name", "value"> 로 반환
* @return HashMap
*/
public HashMap<String, String> getColumnValues(){
this.hashColumns.put("upd_dt", getUpdDt());
this.hashColumns.put("a2_cntc_eml", getA2CntcEml());
this.hashColumns.put("cust_cntc_tp_cd", getCustCntcTpCd());
this.hashColumns.put("antfy_cust_cd", getAntfyCustCd());
this.hashColumns.put("cre_dt", getCreDt());
this.hashColumns.put("cntc_eml", getCntcEml());
this.hashColumns.put("pagerows", getPagerows());
this.hashColumns.put("pod_cd", getPodCd());
this.hashColumns.put("ibflag", getIbflag());
this.hashColumns.put("cre_usr_id", getCreUsrId());
this.hashColumns.put("a2_fax_no", getA2FaxNo());
this.hashColumns.put("sc_no", getScNo());
this.hashColumns.put("a1_cntc_eml", getA1CntcEml());
this.hashColumns.put("fax_no", getFaxNo());
this.hashColumns.put("a1_fax_no", getA1FaxNo());
this.hashColumns.put("upd_usr_id", getUpdUsrId());
return this.hashColumns;
}
/**
* 컬럼명에 대응되는 멤버변수명을 저장하여 Hashtable<"column_name", "variable"> 로 반환
* @return
*/
public HashMap<String, String> getFieldNames(){
this.hashFields.put("upd_dt", "updDt");
this.hashFields.put("a2_cntc_eml", "a2CntcEml");
this.hashFields.put("cust_cntc_tp_cd", "custCntcTpCd");
this.hashFields.put("antfy_cust_cd", "antfyCustCd");
this.hashFields.put("cre_dt", "creDt");
this.hashFields.put("cntc_eml", "cntcEml");
this.hashFields.put("pagerows", "pagerows");
this.hashFields.put("pod_cd", "podCd");
this.hashFields.put("ibflag", "ibflag");
this.hashFields.put("cre_usr_id", "creUsrId");
this.hashFields.put("a2_fax_no", "a2FaxNo");
this.hashFields.put("sc_no", "scNo");
this.hashFields.put("a1_cntc_eml", "a1CntcEml");
this.hashFields.put("fax_no", "faxNo");
this.hashFields.put("a1_fax_no", "a1FaxNo");
this.hashFields.put("upd_usr_id", "updUsrId");
return this.hashFields;
}
/**
* Column Info
* @return updDt
*/
public String getUpdDt() {
return this.updDt;
}
/**
* Column Info
* @return a2CntcEml
*/
public String getA2CntcEml() {
return this.a2CntcEml;
}
/**
* Column Info
* @return custCntcTpCd
*/
public String getCustCntcTpCd() {
return this.custCntcTpCd;
}
/**
* Column Info
* @return antfyCustCd
*/
public String getAntfyCustCd() {
return this.antfyCustCd;
}
/**
* Column Info
* @return creDt
*/
public String getCreDt() {
return this.creDt;
}
/**
* Column Info
* @return cntcEml
*/
public String getCntcEml() {
return this.cntcEml;
}
/**
* Page Number
* @return pagerows
*/
public String getPagerows() {
return this.pagerows;
}
/**
* Column Info
* @return podCd
*/
public String getPodCd() {
return this.podCd;
}
/**
* VO Data Value( C:Creation, U:Update, D:Delete )
* @return ibflag
*/
public String getIbflag() {
return this.ibflag;
}
/**
* Column Info
* @return creUsrId
*/
public String getCreUsrId() {
return this.creUsrId;
}
/**
* Column Info
* @return a2FaxNo
*/
public String getA2FaxNo() {
return this.a2FaxNo;
}
/**
* Column Info
* @return scNo
*/
public String getScNo() {
return this.scNo;
}
/**
* Column Info
* @return a1CntcEml
*/
public String getA1CntcEml() {
return this.a1CntcEml;
}
/**
* Column Info
* @return faxNo
*/
public String getFaxNo() {
return this.faxNo;
}
/**
* Column Info
* @return a1FaxNo
*/
public String getA1FaxNo() {
return this.a1FaxNo;
}
/**
* Column Info
* @return updUsrId
*/
public String getUpdUsrId() {
return this.updUsrId;
}
/**
* Column Info
* @param updDt
*/
public void setUpdDt(String updDt) {
this.updDt = updDt;
}
/**
* Column Info
* @param a2CntcEml
*/
public void setA2CntcEml(String a2CntcEml) {
this.a2CntcEml = a2CntcEml;
}
/**
* Column Info
* @param custCntcTpCd
*/
public void setCustCntcTpCd(String custCntcTpCd) {
this.custCntcTpCd = custCntcTpCd;
}
/**
* Column Info
* @param antfyCustCd
*/
public void setAntfyCustCd(String antfyCustCd) {
this.antfyCustCd = antfyCustCd;
}
/**
* Column Info
* @param creDt
*/
public void setCreDt(String creDt) {
this.creDt = creDt;
}
/**
* Column Info
* @param cntcEml
*/
public void setCntcEml(String cntcEml) {
this.cntcEml = cntcEml;
}
/**
* Page Number
* @param pagerows
*/
public void setPagerows(String pagerows) {
this.pagerows = pagerows;
}
/**
* Column Info
* @param podCd
*/
public void setPodCd(String podCd) {
this.podCd = podCd;
}
/**
* VO Data Value( C:Creation, U:Update, D:Delete )
* @param ibflag
*/
public void setIbflag(String ibflag) {
this.ibflag = ibflag;
}
/**
* Column Info
* @param creUsrId
*/
public void setCreUsrId(String creUsrId) {
this.creUsrId = creUsrId;
}
/**
* Column Info
* @param a2FaxNo
*/
public void setA2FaxNo(String a2FaxNo) {
this.a2FaxNo = a2FaxNo;
}
/**
* Column Info
* @param scNo
*/
public void setScNo(String scNo) {
this.scNo = scNo;
}
/**
* Column Info
* @param a1CntcEml
*/
public void setA1CntcEml(String a1CntcEml) {
this.a1CntcEml = a1CntcEml;
}
/**
* Column Info
* @param faxNo
*/
public void setFaxNo(String faxNo) {
this.faxNo = faxNo;
}
/**
* Column Info
* @param a1FaxNo
*/
public void setA1FaxNo(String a1FaxNo) {
this.a1FaxNo = a1FaxNo;
}
/**
* Column Info
* @param updUsrId
*/
public void setUpdUsrId(String updUsrId) {
this.updUsrId = updUsrId;
}
/**
* Request 의 데이터를 추출하여 VO 의 멤버변수에 설정.
* @param request
*/
public void fromRequest(HttpServletRequest request) {
fromRequest(request,"");
}
/**
* Request 의 데이터를 추출하여 VO 의 멤버변수에 설정.
* @param request
*/
public void fromRequest(HttpServletRequest request, String prefix) {
setUpdDt(JSPUtil.getParameter(request, prefix + "upd_dt", ""));
setA2CntcEml(JSPUtil.getParameter(request, prefix + "a2_cntc_eml", ""));
setCustCntcTpCd(JSPUtil.getParameter(request, prefix + "cust_cntc_tp_cd", ""));
setAntfyCustCd(JSPUtil.getParameter(request, prefix + "antfy_cust_cd", ""));
setCreDt(JSPUtil.getParameter(request, prefix + "cre_dt", ""));
setCntcEml(JSPUtil.getParameter(request, prefix + "cntc_eml", ""));
setPagerows(JSPUtil.getParameter(request, prefix + "pagerows", ""));
setPodCd(JSPUtil.getParameter(request, prefix + "pod_cd", ""));
setIbflag(JSPUtil.getParameter(request, prefix + "ibflag", ""));
setCreUsrId(JSPUtil.getParameter(request, prefix + "cre_usr_id", ""));
setA2FaxNo(JSPUtil.getParameter(request, prefix + "a2_fax_no", ""));
setScNo(JSPUtil.getParameter(request, prefix + "sc_no", ""));
setA1CntcEml(JSPUtil.getParameter(request, prefix + "a1_cntc_eml", ""));
setFaxNo(JSPUtil.getParameter(request, prefix + "fax_no", ""));
setA1FaxNo(JSPUtil.getParameter(request, prefix + "a1_fax_no", ""));
setUpdUsrId(JSPUtil.getParameter(request, prefix + "upd_usr_id", ""));
}
/**
* Request 의 데이터를 VO 배열로 변환하여 반환.
* @param request
* @return BkgArrNtcAntfyVO[]
*/
public BkgArrNtcAntfyVO[] fromRequestGrid(HttpServletRequest request) {
return fromRequestGrid(request, "");
}
/**
* Request 넘어온 여러 건 DATA를 VO Class 에 담는다.
* @param request
* @param prefix
* @return BkgArrNtcAntfyVO[]
*/
public BkgArrNtcAntfyVO[] fromRequestGrid(HttpServletRequest request, String prefix) {
BkgArrNtcAntfyVO model = null;
String[] tmp = request.getParameterValues(prefix + "ibflag");
if(tmp == null)
return null;
int length = request.getParameterValues(prefix + "ibflag").length;
try {
String[] updDt = (JSPUtil.getParameter(request, prefix + "upd_dt", length));
String[] a2CntcEml = (JSPUtil.getParameter(request, prefix + "a2_cntc_eml", length));
String[] custCntcTpCd = (JSPUtil.getParameter(request, prefix + "cust_cntc_tp_cd", length));
String[] antfyCustCd = (JSPUtil.getParameter(request, prefix + "antfy_cust_cd", length));
String[] creDt = (JSPUtil.getParameter(request, prefix + "cre_dt", length));
String[] cntcEml = (JSPUtil.getParameter(request, prefix + "cntc_eml", length));
String[] pagerows = (JSPUtil.getParameter(request, prefix + "pagerows", length));
String[] podCd = (JSPUtil.getParameter(request, prefix + "pod_cd", length));
String[] ibflag = (JSPUtil.getParameter(request, prefix + "ibflag", length));
String[] creUsrId = (JSPUtil.getParameter(request, prefix + "cre_usr_id", length));
String[] a2FaxNo = (JSPUtil.getParameter(request, prefix + "a2_fax_no", length));
String[] scNo = (JSPUtil.getParameter(request, prefix + "sc_no", length));
String[] a1CntcEml = (JSPUtil.getParameter(request, prefix + "a1_cntc_eml", length));
String[] faxNo = (JSPUtil.getParameter(request, prefix + "fax_no", length));
String[] a1FaxNo = (JSPUtil.getParameter(request, prefix + "a1_fax_no", length));
String[] updUsrId = (JSPUtil.getParameter(request, prefix + "upd_usr_id", length));
for (int i = 0; i < length; i++) {
model = new BkgArrNtcAntfyVO();
if (updDt[i] != null)
model.setUpdDt(updDt[i]);
if (a2CntcEml[i] != null)
model.setA2CntcEml(a2CntcEml[i]);
if (custCntcTpCd[i] != null)
model.setCustCntcTpCd(custCntcTpCd[i]);
if (antfyCustCd[i] != null)
model.setAntfyCustCd(antfyCustCd[i]);
if (creDt[i] != null)
model.setCreDt(creDt[i]);
if (cntcEml[i] != null)
model.setCntcEml(cntcEml[i]);
if (pagerows[i] != null)
model.setPagerows(pagerows[i]);
if (podCd[i] != null)
model.setPodCd(podCd[i]);
if (ibflag[i] != null)
model.setIbflag(ibflag[i]);
if (creUsrId[i] != null)
model.setCreUsrId(creUsrId[i]);
if (a2FaxNo[i] != null)
model.setA2FaxNo(a2FaxNo[i]);
if (scNo[i] != null)
model.setScNo(scNo[i]);
if (a1CntcEml[i] != null)
model.setA1CntcEml(a1CntcEml[i]);
if (faxNo[i] != null)
model.setFaxNo(faxNo[i]);
if (a1FaxNo[i] != null)
model.setA1FaxNo(a1FaxNo[i]);
if (updUsrId[i] != null)
model.setUpdUsrId(updUsrId[i]);
models.add(model);
}
} catch (Exception e) {
return null;
}
return getBkgArrNtcAntfyVOs();
}
/**
* VO 배열을 반환
* @return BkgArrNtcAntfyVO[]
*/
public BkgArrNtcAntfyVO[] getBkgArrNtcAntfyVOs(){
BkgArrNtcAntfyVO[] vos = (BkgArrNtcAntfyVO[])models.toArray(new BkgArrNtcAntfyVO[models.size()]);
return vos;
}
/**
* VO Class의 내용을 String으로 변환
*/
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE );
}
/**
* 포맷팅된 문자열에서 특수문자 제거("-","/",",",":")
*/
public void unDataFormat(){
this.updDt = this.updDt .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.a2CntcEml = this.a2CntcEml .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.custCntcTpCd = this.custCntcTpCd .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.antfyCustCd = this.antfyCustCd .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.creDt = this.creDt .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.cntcEml = this.cntcEml .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.pagerows = this.pagerows .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.podCd = this.podCd .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.ibflag = this.ibflag .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.creUsrId = this.creUsrId .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.a2FaxNo = this.a2FaxNo .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.scNo = this.scNo .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.a1CntcEml = this.a1CntcEml .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.faxNo = this.faxNo .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.a1FaxNo = this.a1FaxNo .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
this.updUsrId = this.updUsrId .replaceAll(",", "").replaceAll("-", "").replaceAll("/", "").replaceAll(":", "");
}
} |
#include <bits/stdc++.h>
using namespace std;
// Process for reversing an int
// 123 -> "123" -> [3,2,1] -> validate number is within 32bit limit -> 0 | "321" -> 321;
class Solution {
public:
int reverse(int x) {
// Convert number to str and reverse it
string reverse = to_string(x);
if (reverse[0] == '-') {
reverse.erase(0, 1);
}
std::reverse(reverse.begin(), reverse.end());
// Check if number is in the billions
if (reverse.size() > 9) {
// Check if reversed number is >= 3b
if (reverse[0] > '2') { return 0;}
// set to min or max of 32bit int depending on original numbers sign
int maxval = INT32_MAX;
if ((x < 0) - (x > 0)) {maxval =INT32_MIN;}
string maxvalue = to_string(maxval);
if (maxvalue[0] == '-') {maxvalue.erase(0, 1);}
// Check if any value exceeds max value
for (int i = 0; i < maxvalue.size(); i++) {
if (maxvalue[i] > reverse[i]) {
break;
} else if(reverse[i] > maxvalue[i]) {
return 0;
}
}
}
int finalnum = stoi(string(reverse.begin(), reverse.end()));
finalnum = x < 0 ? finalnum*-1 : finalnum;
return finalnum;
}
};
int main(int argc, char** argv) {
Solution s;
cout << s.reverse(-2147483412) << endl;
cout << s.reverse(1563847412) << endl;
cout << (s.reverse(-2147483412) == -2143847412) << endl;
return 0;
} |
import React, { useState, useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import GoogleLoginButton from "components/GoogleLoginButton";
import authService from "services/auth";
import swal from "sweetalert2";
import "./style.css";
import { useContext } from "react";
import { AccountContext } from "context/AccountContext";
import {
validateEmail,
validateMinLength,
validatePhone,
} from "utils/validator";
import { Button, Checkbox } from "antd";
import i18n from "lang/i18n";
import { useTranslation } from "react-i18next";
const SignupPage = () => {
const { t } = useTranslation();
useEffect(() => {
i18n.changeLanguage(localStorage.getItem("language"));
}, []);
const { login } = useContext(AccountContext);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [passwordConfirm, setPasswordConfirm] = useState("");
const [fullname, setFullname] = useState("");
const [phone, setPhone] = useState("");
const [error, setError] = useState("");
const [acceptTerms, setAcceptTerms] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const navigator = useNavigate();
const validateFields = (
password,
passwordConfirm,
email,
phone,
acceptTerms
) => {
if (password !== passwordConfirm) {
swal.fire({
title: "Error",
text: t("userInformation.notMatchingPass"),
icon: "error",
confirmButtonText: "OK",
});
return;
}
if (!validateEmail(email)) {
swal.fire({
title: "Error",
text: t("userInformation.enterValidEmail"),
icon: "error",
confirmButtonText: "OK",
});
return;
}
if (!validateMinLength(password, 6)) {
swal.fire({
title: "Error",
text: t("userInformation.moreThan6Letters"),
icon: "error",
confirmButtonText: "OK",
});
return;
}
if (!validatePhone(phone)) {
swal.fire({
title: "Error",
text: t("userInformation.pleaseEnterValidPhoneNumber"),
icon: "error",
confirmButtonText: "OK",
});
return;
}
console.log(acceptTerms);
if (!acceptTerms) {
swal.fire({
title: "Error",
text: t("userInformation.pleaseAcceptTerms"),
icon: "error",
confirmButtonText: "OK",
});
return;
}
return true;
};
const onSubmit = async (e) => {
try {
if (email && password && passwordConfirm && fullname && phone) {
if (
!validateFields(password, passwordConfirm, email, phone, acceptTerms)
) {
return;
}
const entity = {
email,
password,
fullname,
phone,
};
setIsLoading(true);
const response = await authService.signup(entity);
setIsLoading(false);
const { exitcode, message } = response.data;
if (exitcode === 0) {
swal.fire({
title: "Success",
text: t("signupPage.checkEmail"),
icon: "success",
confirmButtonText: "OK",
});
navigator("/login");
} else {
setError(message);
}
} else {
swal.fire({
text: t("userInformation.pleaseEnterAll"),
icon: "info",
confirmButtonText: "OK",
});
}
} catch (err) {
navigator("/error");
}
};
const handleGoogleSuccess = async (response) => {
const { credential } = response;
const result = await authService.googleLogin(credential);
const { exitcode, token } = result.data;
if (exitcode === 0) {
login(token);
} else {
setError(result.data);
}
};
const handleGoogleError = () => {
setError("Đăng nhập thất bại");
};
return (
<div className="d-flex container flex-column justify-content-center my-4">
{error && <p className="text-danger">{error}</p>}
<form className="d-flex flex-column justify-content-center align-items-center form_container col-xl-4 col-md-6 col-xs-12 row">
<h2 className="mb-4 color-key">{t("loginPage.signup")}</h2>
<div className="signup-input d-flex align-items-center input-group mb-3 p-2">
<i className="ml-2 fa fa-envelope"></i>
<input
name="email"
type="email"
placeholder="Email"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="signup-input d-flex align-items-center input-group mb-3 p-2">
<i className="ml-2 fa fa-lock"></i>
<input
name="password"
type="password"
autoComplete="on"
placeholder={t("userInformation.enterPass")}
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div className="signup-input d-flex align-items-center input-group mb-3 p-2">
<i className="ml-2 fa fa-lock"></i>
<input
name="passwordConfirm"
type="password"
autoComplete="on"
placeholder={t("userInformation.enterPass")}
value={passwordConfirm}
onChange={(e) => setPasswordConfirm(e.target.value)}
/>
</div>
<div className="signup-input d-flex align-items-center input-group mb-3 p-2">
<i className="ml-2 fa fa-user"></i>
<input
name="fullname"
placeholder={t("userInformation.fullname")}
value={fullname}
onChange={(e) => setFullname(e.target.value)}
/>
</div>
<div className="signup-input d-flex align-items-center input-group mb-3 p-2">
<i className="ml-2 fa fa-phone"></i>
<input
name="phone"
placeholder={t("userInformation.phoneNumber")}
value={phone}
onChange={(e) => setPhone(e.target.value)}
/>
</div>
<div className="align-items-left mb-3 p-2" style={{ width: "100%" }}>
<Checkbox
value={acceptTerms}
onChange={(event) => {
setAcceptTerms(event.target.checked);
}}
>
{t("signupPage.hasAgreed")}{" "}
<Link to="/policy/terms">{t("signupPage.termsPolicy")}</Link>{" "}
{t("signupPage.and")}{" "}
<Link to="/policy/privacy">{t("signupPage.privacyPolicy")}</Link>{" "}
{t("signupPage.ofHuimitu")}
</Checkbox>
</div>
<Button
className="primary-btn bg-key signup-btn col-6"
type="primary"
size="large"
onClick={onSubmit}
isLoading={isLoading}
disabled={isLoading}
>
{t("loginPage.signup")}
</Button>
</form>
<div className="my-2 d-flex flex-column justify-content-center align-items-center">
<p>{t("loginPage.or")}</p>
<GoogleLoginButton
onError={handleGoogleError}
onSuccess={handleGoogleSuccess}
/>
<p className="mt-3">
{t("loginPage.hadAccount")}
<Link to="/login" className="text-key pointer pl-1">
{t("loginPage.login")}
</Link>
</p>
</div>
</div>
);
};
export default SignupPage; |
import requests
from urllib.parse import unquote, quote
from lxml import etree
import json
import time
import xlwt
import pandas as pd
'''
爬下读书标签下的所有图书,按评分标准依次存储,存储到excel中, 可方便大家筛选搜罗,比如筛选评价人数大于1000的高分书籍;
可依据不同的主题存储到Excel不同的sheet,采用User-agent伪装成游览器进行爬取,并加入随机延时来更好的模仿用户行为;
避免爬虫被封。
本次只获取书籍名称和评分及评价人数相关数据
'''
#豆瓣读书爬虫
class doubanSpider():
def __init__(self):
self.base_url = 'https://book.douban.com/'
self.headers ={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
}
self.tag_titles = [] #获取所有书籍的分类名
self.tags_dict = {} #获取tag_titles对应的所有子标签
self.tags2_dict = {} #分类标签列表
self.tag_books = [] #获取该标签下所有的书籍信息
self.books = [] #所有书籍信息
#获取数据
def get_tag_title_data(self):
response = requests.get(self.base_url, headers=self.headers)
html_data = etree.HTML(response.content)
tag_title = html_data.xpath('//*[@id="content"]/div/div[2]/ul/li//li[@class="tag_title"]/text()')
for tag in tag_title:
tag = str(tag).replace(" ", "")
tag = str(tag).replace("\n", "")
self.tag_titles.append(tag)
for i in range(1,7):
index = '//*[@id="content"]/div/div[2]/ul/li[{}]/ul/li//a/text()'.format(i)
tags = html_data.xpath(index)
yield tags[0:-1] # 大标签的值,eg:['漫画', '推理', '绘本', '青春', '科幻', '言情', '奇幻', '武侠', '更多»']
def get_detail_page_data(self):
print(1)
values = self.get_tag_title_data()
for tags in values:
for tag in tags:
start = 0
keys = quote(str(tag))
title = '{}_books'.format(tag)
title = [] #重置
tags1_dict = {} #重置
for i in range(0, 6):
url = 'https://book.douban.com/tag/'+keys+'?start={}'.format(start)
time.sleep(0.2) #限制爬虫速度,避免被封IP
response = requests.get(url, headers=self.headers)
if response.status_code == 200:
print("success")
html_data = etree.HTML(response.content)
try:
li_list = html_data.xpath('//*[@id="subject_list"]/ul//li[@class="subject-item"]')
for li in li_list:
detail_book = {}
detail_book["title"] = str(li.xpath('.//div[2]/h2/a/text()')[0]).replace("\n", "").replace(" ","") #书籍书名
detail_book["score"] = str(li.xpath('.//div[2]/div[2]/span[2]/text()')[0]).replace("\n", "").replace(" ","") #书籍评分
detail_book["people_nums"] = str(li.xpath('./div[2]/div[2]/span[3]/text()')[0]).replace("\n", "").replace(" ","").replace("(", "").replace("人评价)","") #评价人数
title.append(detail_book)
except:
print("Error")
else:
print("请求错误")
start += 20
tags1_dict[tag] = title
tags1_dict = json.dumps(tags1_dict, ensure_ascii=False)
self.save_data(tags1_dict)
#创建excel表
def creat_excel(self):
# 创建excel 工作表
workbook = xlwt.Workbook(encoding="utf-8")
worksheet = workbook.add_sheet('sheet1', cell_overwrite_ok=True)
# 设置表头
worksheet.write(0, 0, label='title')
worksheet.write(0, 1, label='score')
worksheet.write(0, 2, label='people_nums')
# 变量用来循环时控制写入单元格,感觉有更好的表达方式
val1 = 1
val2 = 1
val3 = 1
return workbook, worksheet, val1, val2, val3
#对excel中的数据进行排序
def sort_data(self, name):
excel_name = 'D:\pycharm\豆瓣读书\{}.xlsx'.format(name)
stexcel = pd.read_excel(excel_name)
stexcel.sort_values(by=['people_nums'], inplace=True, ascending=[False])
pd.DataFrame(data=stexcel).to_excel(excel_name, index=False, header=True) #保存对excel数据的修改
#解析数据
def parse_data(self):
with open("douban.json", "r", encoding="utf-8") as f:
for jsonline in f.readlines():
jsonline = json.loads(jsonline.encode("utf-8"))
tag_names = []
for tag_name in jsonline.keys():
jsonline[tag_name].append(dict(tag_name=tag_name)) #将分类标签添加进入
workbook, worksheet, val1, val2, val3 = self.creat_excel() #每遍历一次创建一个excel
for book in range(len(jsonline[tag_name])):
for key, value in jsonline[tag_name][book].items():
if key == "title":
worksheet.write(val1, 0, value)
val1 += 1
elif key == 'score':
worksheet.write(val2, 1, value)
val2 += 1
elif key == "people_nums":
worksheet.write(val3, 2, value)
val3 += 1
else:
worksheet.write(val1, 0, value)
val1 += 1
workbook.save("{}.xlsx".format(value))
self.sort_data(value)
#存储数据
def save_data(self,data):
print(data)
with open('douban.json', "a", encoding="utf-8") as f:
f.write(data + '\n')
#运行程序
def start(self):
self.get_detail_page_data()
self.parse_data()
doubanSpider().start() |
---
sidebar_position: 1
---
# Introduction
## Hackathon!

----------------------------
From March 18 to April 8, 2024, participants will compete to showcase their best application of IF in measuring the environmental impacts of software.
Carbon Hack is a dynamic competition that combines healthy rivalry with collaborative innovation. Hackers will push the limits of the framework, uncover potential weaknesses, and create innovations to enhance the tool.
CarbonHack is open to all, including software practitioners and those with a passion for Green Software.
Find out more about CarbonHack 2024 on the [CarbonHack website](https://grnsft.org/hack/github)
**Registration opens 22nd January!**
----------------------------
<br />
## Impact Framework
Impact Framework (IF) aims to make the environmental impacts of software easier to calculate **and** share.
IF allows you to calculate the environmental impacts, such as carbon, of your software applications without writing any code. All you have to do is write a simple **manifest file**, known as an `impl` and IF handles the rest.
The project is entirely open source and composability is a core design principle - we want you to be able to create your own models and plug them in to our framework, or pick from a broad universe of open source models created by others.
## Motivation
If you can't measure, you can't improve. Software has many negative environmental **impacts** which we need to optimize, carbon, water, and energy, to name just a few.
Unfortunately, measuring software impact metrics like carbon, water, and energy is complex and nuanced.
Modern applications are composed of many smaller pieces of software (components) running on different environments, for example, private cloud, public cloud, bare-metal, virtualized, containerized, mobile, laptops, desktops, embedded, and IoT. Many components that make up a typical software application are run on something other than resources you own or control, which makes including the impact of managed services in your measurement especially hard.
The impacts of software components also vary over time, so as well as understanding **which** components contribute most to the overall impacts, there is also a question of **when** they contribute the most.
Only through a granular analysis of the impacts of your software system can investments in reducing its impact be prioritized and verified. Measurement is the first and most crucial step in greening a software system, and the first step in that process with the [Impact Framework](./06-specification/impact-framework.md) is to create a [Graph](./06-specification/graph.md).
## Background
This project has evolved over the two years of the GSF's existence.
During the development of the [SCI](https://github.com/Green-Software-Foundation/sci/blob/dev/SPEC.md), we acknowledged that the biggest blocker to adoption was data regarding the emissions of software components on different platforms and runtimes.
We then launched the sci-data project to help create the data sets required to calculate an SCI score.
After some investigation, the original sci-data team quickly realized that there were several existing data sources, and many more were in development, free open source or private commercial. The future challenge wouldn't be to source them, it would be knowing which data set to use for which use case, how data sets differed in their methodology and interface and when to use one over the other, the pros/cons, and trade-offs.
The project evolved into the [sci-guide](https://sci-guide.greensoftware.foundation/) to document existing data sets, providing guidance for when to use one over another and how to use it to create your own software measurement reports.
Finally, we had enough information, and [SCI case studies](https://sci-guide.greensoftware.foundation/CaseStudies) started to be written. This was a milestone moment.
But now we are in the next evolution, to have software measurement be a mainstream activity. For this to be an industry with thousands of professionals working to decarbonize software, for businesses to grow and thrive in a commercial software measurement ecosystem, we need to formalize software measurement into a discipline with standards and tooling. The SCI Specification is the standard, and the [Impact Framework](./06-specification/impact-framework.md) is the tooling.
## Project Structure
The **IF source code** can be found in the [IF Github repository](https://github.com/Green-Software-Foundation/if). The code there covers the framework, which includes all the infrastructure for reading and writing input and output yamls, invoking models, running the command line tool and associated helper functions. However, it does not include the actual models themselves. Part of the IF design philosophy is that all models should be plugins, so that the IF is as composable and configurable as possible. Therefore, to use IF, you have to either create your own models or find some prebuilt ones and install them yourself. This also implies that you take responsibility for the models you choose to install.
We do provide a **standard library of models** built and maintained by the IF core team. These can be found in the [`if-models` Github repository](https://github.com/Green-Software-Foundation/if-models). You can install these into `if` by running `npm install https://github.com/Green-Software-Foundation/if-models` from the `if` project directory.
There is also a second repository for **models we expect community members to maintain**. These can be found in the [`if-unofficial-models` Github repository](https://github.com/Green-Software-Foundation/if-unofficial-models). You can install these into `if` by running `npm install https://github.com/Green-Software-Foundation/if-unofficial-models` from the `if` project directory.
Finally, the **source code for this documentation** website is available at the [`if-docs` Github repository](https://github.com/Green-Software-Foundation/if-docs).
## Navigating these docs
The lefthand sidebar contains links to all the information you need to understand Impact Framework.
You can find specification pages for individual components of the framework in [`specification`](./specification/).
In [`tutorials`](./tutorials) you will find walkthrough guides and tutorials explaining how to achieve specific tasks, such as writing an `impl`, running the model and creating new plugins.
You will find documentation for the individual built-in model implementations in [`models`](./models/). |
// @ts-check
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/restrict-plus-operands */
/**
* Stringify an Error instance
* @param err - The error to stringify
*/
function stringifyErrorValue(err: Error): string {
return `${err.name.toUpperCase()}: ${err.message}
${err.stack || '(no stack trace information)'}`;
}
/**
* Stringify a thrown value
*
* @param errorDescription
* @param err
*
*/
export function stringifyError(
errorDescription: string,
err: any,
): string {
return `${errorDescription}\n${
err instanceof Error
? stringifyErrorValue(err)
: err
? '' + err
: '(missing error information)'
}`;
} |
/// Whether this dependency has a hash value which is different to the one
/// previously observed (if any).
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum DependencyState {
/// No local hash was present, or the latest hash was not equal to the
/// stored value.
Dirty,
/// This dependency was previously resolved and the hash is equivalent.
Clean,
}
#[cfg(test)]
mod tests {
use std::hash::{Hash, Hasher};
use super::*;
#[test]
fn test_dependency_state_derives() {
let state = DependencyState::Dirty;
assert_eq!(state.clone(), state);
assert_eq!("Dirty", format!("{:?}", state));
let hasher = &mut std::collections::hash_map::DefaultHasher::new();
state.hash(hasher);
assert_eq!(hasher.finish(), 13646096770106105413);
}
} |
package util
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/playwright-community/playwright-go"
"go.uber.org/zap"
)
type Util struct {
Logger *zap.SugaredLogger
result map[string]interface{}
}
// CheckCloudFlareRecaptcha returns recaptcha parameters and true if recaptcha is present. otherwise false. We consider SEC uses only Cloudflare.
func (u *Util) CheckCloudFlareRecaptcha(url string) (map[string]interface{}, error) {
pw, err := playwright.Run()
if err != nil {
u.Logger.Errorf("could not start playwright: %v", err)
return make(map[string]interface{}), err
}
if err != nil {
u.Logger.Errorf("Failed to get current directory: %v", err)
return make(map[string]interface{}), err
}
browser, err := pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
Headless: playwright.Bool(false),
IgnoreDefaultArgs: []string{"--enable-automation"},
Args: []string{"--start-maximized"},
})
if err != nil {
u.Logger.Errorf("could not launch browser: %v", err)
return make(map[string]interface{}), err
}
page, err := browser.NewPage()
if err != nil {
u.Logger.Errorf("could not create page: %v", err)
return make(map[string]interface{}), err
}
headers := map[string]string{
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36",
}
err = page.SetExtraHTTPHeaders(headers)
if err != nil {
u.Logger.Errorf("could not set user agent: %v", err)
return make(map[string]interface{}), err
}
currentDir, err := os.Getwd()
scriptPath := filepath.Join(currentDir, "..", "pkg", "util", "turnstile.js")
script := playwright.Script{Path: &scriptPath}
err = page.AddInitScript(script)
if err != nil {
u.Logger.Errorf("could not inject script: %v", err)
return make(map[string]interface{}), err
}
scriptContent := "Object.defineProperty(navigator, 'webdriver', {get: () => undefined})"
script = playwright.Script{Content: &scriptContent}
err = page.AddInitScript(script)
scriptContent = "const originalQuery = window.navigator.permissions.query; window.navigator.permissions.query = (parameters) => (parameters.name === 'notifications' ? Promise.resolve({ state: Notification.permission }) : originalQuery(parameters));"
script = playwright.Script{Content: &scriptContent}
err = page.AddInitScript(script)
scriptContent = "Object.defineProperty(navigator, 'plugins', { get: function () { return [2]; }, });"
script = playwright.Script{Content: &scriptContent}
err = page.AddInitScript(script)
scriptContent = "Object.defineProperty(navigator, 'languages', { get: function () { return ['en-US', 'en']; }, });"
script = playwright.Script{Content: &scriptContent}
err = page.AddInitScript(script)
var wg sync.WaitGroup
wg.Add(1)
page.OnConsole(func(msg playwright.ConsoleMessage) {
if strings.Contains(msg.Text(), "sitekey") {
var result map[string]interface{}
err := json.Unmarshal([]byte(msg.Text()), &result)
if err != nil {
u.Logger.Errorf("Error unmarshalling JSON: %v", err)
return
}
u.result = result
wg.Done()
}
})
_, err = page.Goto(url)
if err != nil {
u.Logger.Errorf("could not navigate to website: %v", err)
return make(map[string]interface{}), err
}
timeout := time.After(10 * time.Second)
done := make(chan bool)
go func() {
wg.Wait()
done <- true
}()
select {
case <-timeout:
u.Logger.Info("Timeout reached while waiting for console message")
return make(map[string]interface{}), err
case <-done:
}
if err = browser.Close(); err != nil {
u.Logger.Infof("could not close browser: %v", err)
return make(map[string]interface{}), err
}
pw.Stop()
return u.result, err
} |
#!/usr/bin/env fuchsia-vendored-python
# Copyright 2024 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from typing import Any, Dict, List
# Default cut-off for the percentage CPU. Any process that has CPU below this
# won't be listed in the results. User can pass in a cutoff.
DEFAULT_PERCENT_CUTOFF = 0.0
class AggCpuBreakdownMetricsProcessor:
"""
Aggregates a given breakdown over the cores for each available frequency,
and outputs in a free-form metrics format.
"""
def __init__(
self,
# The json output from the cpu_breakdown script.
breakdown: List[Dict[str, Any]],
# A map from cpu numbers to their frequency.
# e.g. { 0: 1.8, 1: 1.8, 2: 2.2, 3: 2.2, 4: : 2.2, 5: 2.2 }
cpu_to_freq: Dict[int, float],
total_time: float,
percent_cutoff: float = DEFAULT_PERCENT_CUTOFF,
) -> None:
# Output from the cpu_breakdown script.
self._breakdown = breakdown
# Transforms the frequency config to a map from cpu to frequency. Used
# to determine which frequency each record should contribute its duration to.
self._cpu_to_freq = cpu_to_freq
self._percent_cutoff = percent_cutoff
self._total_time = total_time
def aggregate_metrics(self) -> Dict[float, List[Dict[str, Any]]]:
"""
Given the breakdown of duration per thread, iterates through all the threads' durations for each
CPU and aggregates them over each CPU frequency.
"""
# Map from frequency to tid to aggregated duration.
freq_to_tid_durs: Dict[float, Dict[int, float]] = {}
# Tracks the final output. Contains a map from frequency to list of
# threads with their durations and percentages.
agg_breakdown: Dict[float, List[Dict[str, Any]]] = {}
tid_to_thread_name: Dict[int, str] = {}
tid_to_process_name: Dict[int, str] = {}
for t in self._breakdown:
# Save process and thread name for tid
tid = t["tid"]
tid_to_process_name[tid] = t["process_name"]
tid_to_thread_name[tid] = t["thread_name"]
# Get frequency for the cpu
freq = self._cpu_to_freq[t["cpu"]]
# Set the duration sum for the tid to 0 if nonexistent
freq_to_tid_durs.setdefault(freq, {})
freq_to_tid_durs[freq].setdefault(tid, 0)
# Add the duration to the tid
duration = t["duration"]
freq_to_tid_durs[freq][tid] += duration
for freq, tid_durs in freq_to_tid_durs.items():
dur_list: List[Dict[str, Any]] = []
for tid, dur in tid_durs.items():
percent = (dur / self._total_time) * 100
if percent >= self._percent_cutoff:
dur_list.append(
{
"process_name": tid_to_process_name[tid],
"thread_name": tid_to_thread_name[tid],
"duration": round(dur, 3),
"percent": round(percent, 3),
}
)
agg_breakdown[freq] = sorted(
dur_list,
key=lambda m: (m["duration"]),
reverse=True,
)
return agg_breakdown |
import React from 'react';
import {block} from '../../utils/cn';
import Image from 'next/image';
import Meta from '../Meta';
import i18n from '../../../i18n';
import Icon404 from '../../../ui/assets/images/404.svg';
import Icon500 from '../../../ui/assets/images/500.svg';
import './ErrorPage.scss';
const b = block('error-page');
interface ErrorPageProps {
code?: number;
}
const i18nK = i18n('error');
const getPublicCode = (code: number) => (code === 404 ? 404 : 500);
const ErrorPage: React.FC<ErrorPageProps> = ({code = 500}) => {
const publicCode = getPublicCode(code);
const title = i18nK(`label_meta-title-${publicCode}`);
const imgSrc = code === 404 ? Icon404 : Icon500;
return (
<div className={b({code: String(code)})}>
<Meta data={{title}} />
<Image src={imgSrc as unknown as string} alt="" width="220" height="220" />
<h1 className={b('code')}>{i18nK('label_title-code', {code: publicCode})}</h1>
<h2 className={b('title')}>{i18nK(`label_title-${publicCode}`)}</h2>
<p className={b('description')}>
{publicCode === 404 ? (
<a href="/">{i18nK('label_link-main')}</a>
) : (
<React.Fragment>
{i18nK('label_error-description-open')}
<a onClick={() => window.location.reload()}>
{i18nK('label_description-link')}
</a>
{i18nK('label_error-description-close')}
</React.Fragment>
)}
</p>
</div>
);
};
export default ErrorPage; |
import { Progress } from "@/components/ui/progress";
import { cn } from "@/lib/utils";
interface Props {
value: number;
variant?: "default" | "success";
size?: "default" | "sm";
}
const sizeByVariant = {
default: "text-sm",
sm: "text-xs",
};
const CourseProgress = ({ value, variant, size }: Props) => {
return (
<div className="flex flex-col items-center justify-center">
<Progress
className={cn("h-2 w-56", size === "sm" && "h-2 w-32 mt-1")}
value={value}
variant={variant}
/>
<p
className={cn(
"font-medium text-sm text-muted-foreground mt-1",
sizeByVariant[size || "default"]
)}
>
{size !== "sm" && (
<>
{Math.round(value)}% Complete{value === 100 && "!"}
</>
)}
</p>
</div>
);
};
export default CourseProgress; |
//
// SwiftUIView.swift
// TextEditor
//
// Created by Leonardo Lemos on 03/02/22.
//
import SwiftUI
struct ListView: View {
@State
private var activeNavigationAction: String = NavigationActions[0].title;
func onChange(action: NavigationAction) {
self.activeNavigationAction = action.title
}
var body: some View {
VStack (alignment: .leading) {
Text("My Stuff")
.font(.title3)
.padding()
ForEach(NavigationActions, id: \.self) { option in
let isActive: Bool = activeNavigationAction == option.title;
HStack {
Image(systemName: option.imageName)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 14)
.foregroundColor(isActive ? Color.accentColor : Color.white)
Text(option.title)
Spacer()
}
.onTapGesture {
onChange(action: option)
}
}
.padding()
Spacer()
}
.background(Color.secondary)
}
}
struct ListView_Previews: PreviewProvider {
static var previews: some View {
ListView()
}
} |
import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Query } from 'components/grid/query/Query'
import { executeSql } from 'data/sql/execute-sql-query'
import type { ResponseError } from 'types'
import { pgSodiumKeys } from './keys'
export type VaultSecretDeleteVariables = {
projectRef: string
connectionString?: string
id: string
}
export async function deleteVaultSecret({
projectRef,
connectionString,
id,
}: VaultSecretDeleteVariables) {
const sql = new Query().from('key', 'pgsodium').delete().match({ id }).toSql()
const { result } = await executeSql({
projectRef,
connectionString,
sql,
queryKey: ['projects', projectRef, 'pg-sodium-keys', 'delete', id],
})
return result
}
type VaultSecretDeleteData = Awaited<ReturnType<typeof deleteVaultSecret>>
export const usePgSodiumKeyDeleteMutation = ({
onError,
onSuccess,
...options
}: Omit<
UseMutationOptions<VaultSecretDeleteData, ResponseError, VaultSecretDeleteVariables>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
return useMutation<VaultSecretDeleteData, ResponseError, VaultSecretDeleteVariables>(
(vars) => deleteVaultSecret(vars),
{
async onSuccess(data, variables, context) {
const { projectRef } = variables
await queryClient.invalidateQueries(pgSodiumKeys.list(projectRef))
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(`Failed to delete key: ${data.message}`)
} else {
onError(data, variables, context)
}
},
...options,
}
)
} |
import React, { useState, useEffect } from "react";
import ProductNotFound from "./ProductNotFound";
import Products from "./Products";
import PageButton from "./buttons/PageButton";
import { AiOutlineSearch } from "react-icons/ai";
import {
HiOutlineArrowNarrowRight,
HiOutlineArrowNarrowLeft,
} from "react-icons/hi";
import { range } from "lodash";
import Loader from "./Loader";
import Alert from "./ContextProvider/Alert";
import { getProducts } from "./api";
import { withAlert } from "./ContextProvider/withProvider";
import { Link, useSearchParams } from "react-router-dom";
const FrontPage = ({ alert }) => {
const [loading, setLoading] = useState(true);
const [product, setProduct] = useState([]);
const [ paging, setPaging ] = useState({range: 1, pages: 1})
const [searchParams, setSearchParams] = useSearchParams();
const params = Object.fromEntries([...searchParams]);
let page = +searchParams.get("page");
const query = searchParams.get("query") || "";
const sortBy = searchParams.get("sort") || "default";
page = page || 1;
useEffect(() => {
let sortType;
let mySort;
if (sortBy == "title") {
mySort = "title";
} else if (sortBy == "LowToHigh") {
mySort = "price";
sortType;
} else if (sortBy == "HighToLow") {
mySort = "price";
sortType = "desc";
}
getProducts(query, mySort, page, sortType).then((response) => {
setProduct(response.data);
setLoading(false);
});
}, [query, sortBy, page]);
return (
<div className="px-[10%] sm:px-[20%] ">
<div className="bg-white shadow shadow-gray-50 px-12 py-20 lg:pt-0 lg:pb-11 w-full h-full space-y-8">
<div className="flex justify-end">
{alert ? <Alert /> : <div className="h-8"></div>}
</div>
<div className="flex justify-between w-full">
<div className="lg:flex lg:items-center border px-3 py-1 rounded-md border-gray-300 hover:border-gray-500 hidden ">
<input
value={query}
onChange={(event) =>
setSearchParams(
{ ...params, query: event.target.value },
{ replace: false }
)
}
className="border-transparent outline-none p-2"
placeholder="Find ?"
/>
<AiOutlineSearch size={25} color="gray" />
</div>
<select
value={sortBy}
onChange={(event) =>
setSearchParams(
{ ...params, sort: event.target.value },
{ replace: false }
)
}
className="font-mono text-gray-500 rounded-md sm:border-0 cursor-pointer text-center sm:text-left px-1 sm:px-3 ring-1 ring-gray-300 focus:ring-gray-500 py-2 sm:py-0"
>
<option value="default">Sort Default</option>
<option value="title">Sort By Title</option>
<option value="LowToHigh">PRICE: Low tO High</option>
<option value="HighToLow">PRICE: High tO Low</option>
</select>
</div>
{loading ? (
<Loader />
) : (
<div className="space-y-28">
<div className="h-full grid grid-cols-1 sm:grid-cols-3 grid-flow-rows gap-10">
{product.data.length ? (
product.data.map((e) => <Products {...e} key={e.id} />)
) : (
<ProductNotFound />
)}
</div>
<div className="flex gap-2 items-center">
{paging.range > 3 && (
<PageButton onClick={() => setPaging({ range: 1, pages: 1 })}>
<HiOutlineArrowNarrowLeft size={15} />
</PageButton>
)}
{range(paging.range, product.meta.last_page - paging.pages).map(
(pageNo) => (
<Link
to={`?${new URLSearchParams({ ...params, page: pageNo })}`}
className={
"font-poppins text-xs py-3 px-4 border border-primary hover:text-white hover:bg-primary flex items-center " +
(page === pageNo
? "bg-primary text-white"
: "bg-transparent text-primary")
}
>
{pageNo}
</Link>
)
)}
{paging.range <= 3 && (
<PageButton onClick={() => setPaging({ range: 4, pages: -1 })}>
<HiOutlineArrowNarrowRight size={15} />
</PageButton>
)}
</div>
</div>
)}
</div>
</div>
);
}
export default withAlert(FrontPage); |
/*
* Copyright 2021 EPAM Systems.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.digital.data.platform.bphistory.service.api.controller;
import static com.epam.digital.data.platform.bphistory.service.api.TestUtils.OFFICER_TOKEN;
import static com.epam.digital.data.platform.bphistory.service.api.util.Header.X_ACCESS_TOKEN;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import com.epam.digital.data.platform.bphistory.service.api.BaseIT;
import com.epam.digital.data.platform.bphistory.service.api.TestUtils;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
class ProcessHistoryControllerIT extends BaseIT {
@Test
void getHistoryProcessInstances() throws Exception {
createBpmHistoryProcessAndSaveToDatabase("id", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "COMPLETED", "testuser", null);
var expectedJson = TestUtils.readClassPathResource(
"/json/getHistoryProcessInstancesExpectedResponse.json");
mockMvc.perform(get("/api/history/process-instances")
.header(X_ACCESS_TOKEN.getHeaderName(), OFFICER_TOKEN))
.andExpect(status().is2xxSuccessful())
.andExpect(content().json(expectedJson));
}
@Test
void getOrderedHistoryProcessInstancesAsc() throws Exception {
createBpmHistoryProcessAndSaveToDatabase("id2", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "COMPLETED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("id4", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "SUSPENDED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("id1", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "EXTERNALLY_TERMINATED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("id5", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "ACTIVE", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("id3", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "PENDING", "testuser", null);
mockMvc.perform(get("/api/history/process-instances")
.header(X_ACCESS_TOKEN.getHeaderName(), OFFICER_TOKEN)
.queryParam("sort", "asc(statusTitle)"))
.andExpect(status().is2xxSuccessful())
.andExpect(jsonPath("$[0].status.code", is("EXTERNALLY_TERMINATED")))
.andExpect(jsonPath("$[1].status.code", is("COMPLETED")));
}
@Test
void getOrderedHistoryProcessInstancesDesc() throws Exception {
createBpmHistoryProcessAndSaveToDatabase("id2", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "COMPLETED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("id4", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "SUSPENDED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("id1", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "EXTERNALLY_TERMINATED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("id5", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "ACTIVE", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("id3", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "PENDING", "testuser", null);
mockMvc.perform(get("/api/history/process-instances")
.header(X_ACCESS_TOKEN.getHeaderName(), OFFICER_TOKEN)
.queryParam("sort", "desc(statusTitle)"))
.andExpect(status().is2xxSuccessful())
.andExpect(jsonPath("$[0].status.code", is("COMPLETED")))
.andExpect(jsonPath("$[1].status.code", is("EXTERNALLY_TERMINATED")));
}
@Test
void shouldReturnSortedByStatusAndStartTimeDesc() throws Exception {
createBpmHistoryProcessAndSaveToDatabase("Process1", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 37), "COMPLETED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process4", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 38), "EXTERNALLY_TERMINATED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process2", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 16), "COMPLETED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process5", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 15), "EXTERNALLY_TERMINATED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process3", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 44), "COMPLETED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process6", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 46), "EXTERNALLY_TERMINATED", "testuser", null);
mockMvc.perform(get("/api/history/process-instances")
.header(X_ACCESS_TOKEN.getHeaderName(), OFFICER_TOKEN)
.queryParam("sort", "desc(statusTitle)"))
.andExpect(status().is2xxSuccessful())
.andExpect(jsonPath("$[0].startTime", is("2022-01-11T12:44:00.000Z")))
.andExpect(jsonPath("$[0].status.code", is("COMPLETED")))
.andExpect(jsonPath("$[1].startTime", is("2022-01-11T12:37:00.000Z")))
.andExpect(jsonPath("$[1].status.code", is("COMPLETED")))
.andExpect(jsonPath("$[2].startTime", is("2022-01-11T12:16:00.000Z")))
.andExpect(jsonPath("$[2].status.code", is("COMPLETED")))
.andExpect(jsonPath("$[3].startTime", is("2022-01-11T12:46:00.000Z")))
.andExpect(jsonPath("$[3].status.code", is("EXTERNALLY_TERMINATED")))
.andExpect(jsonPath("$[4].startTime", is("2022-01-11T12:38:00.000Z")))
.andExpect(jsonPath("$[4].status.code", is("EXTERNALLY_TERMINATED")))
.andExpect(jsonPath("$[5].startTime", is("2022-01-11T12:15:00.000Z")))
.andExpect(jsonPath("$[5].status.code", is("EXTERNALLY_TERMINATED")));
}
@Test
void shouldReturnSortedByStatusAndStartTimeAsc() throws Exception {
createBpmHistoryProcessAndSaveToDatabase("Process1", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 37), "COMPLETED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process4", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 38), "EXTERNALLY_TERMINATED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process2", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 16), "COMPLETED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process5", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 15), "EXTERNALLY_TERMINATED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process3", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 44), "COMPLETED", "testuser", null);
createBpmHistoryProcessAndSaveToDatabase("Process6", "processDefinition",
LocalDateTime.of(2022, 1, 11, 12, 46), "EXTERNALLY_TERMINATED", "testuser", null);
mockMvc.perform(get("/api/history/process-instances")
.header(X_ACCESS_TOKEN.getHeaderName(), OFFICER_TOKEN)
.queryParam("sort", "asc(statusTitle)"))
.andExpect(status().is2xxSuccessful())
.andExpect(jsonPath("$[0].startTime", is("2022-01-11T12:46:00.000Z")))
.andExpect(jsonPath("$[0].status.code", is("EXTERNALLY_TERMINATED")))
.andExpect(jsonPath("$[1].startTime", is("2022-01-11T12:38:00.000Z")))
.andExpect(jsonPath("$[1].status.code", is("EXTERNALLY_TERMINATED")))
.andExpect(jsonPath("$[2].startTime", is("2022-01-11T12:15:00.000Z")))
.andExpect(jsonPath("$[2].status.code", is("EXTERNALLY_TERMINATED")))
.andExpect(jsonPath("$[3].startTime", is("2022-01-11T12:44:00.000Z")))
.andExpect(jsonPath("$[3].status.code", is("COMPLETED")))
.andExpect(jsonPath("$[4].startTime", is("2022-01-11T12:37:00.000Z")))
.andExpect(jsonPath("$[4].status.code", is("COMPLETED")))
.andExpect(jsonPath("$[5].startTime", is("2022-01-11T12:16:00.000Z")))
.andExpect(jsonPath("$[5].status.code", is("COMPLETED")));
}
@Test
void getTasks() throws Exception {
createBpmHistoryProcessAndSaveToDatabase("processInstanceId", "procDef",
LocalDateTime.of(2022, 1, 10, 11, 42), "COMPLETED", "testUser", "businessKey");
createBpmHistoryTaskAndSaveToDatabase("unCompletedTask", "processInstanceId",
LocalDateTime.of(2022, 1, 10, 11, 42), null, "testuser");
createBpmHistoryTaskAndSaveToDatabase("completedTask", "processInstanceId",
LocalDateTime.of(2022, 1, 10, 11, 42),
LocalDateTime.of(2022, 1, 10, 11, 43), "testuser");
var expectedJson = TestUtils.readClassPathResource(
"/json/getHistoryTasksExpectedResponse.json");
mockMvc.perform(get("/api/history/tasks")
.header(X_ACCESS_TOKEN.getHeaderName(), OFFICER_TOKEN))
.andExpect(status().is2xxSuccessful())
.andExpect(content().json(expectedJson));
}
} |
import { Inject, Injectable, forwardRef } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Message } from './entities/message.entity';
import { CreateMessageDto } from './dto/create-message.dto';
import { MessageType } from './entities/message-type.entity';
import { ChatService } from 'src/chat/chat.service';
import { UserService } from 'src/user/user.service';
@Injectable()
export class MessageService {
constructor(
private readonly userService: UserService,
@Inject(forwardRef(() => ChatService))
private readonly chatService: ChatService,
@InjectRepository(Message)
private messageRepository: Repository<Message>,
@InjectRepository(MessageType)
private messageTypeRepository: Repository<MessageType>,
) {}
async findByChatId(chatId: number): Promise<Message[]> {
return await this.messageRepository.find({
relations: ['chat', 'user', 'messageType'],
where: {
chat: {
id: chatId,
},
},
});
}
async findOneTypeByName(name: string): Promise<MessageType> {
return await this.messageTypeRepository.findOne({ where: { name: name } });
}
async create(createMessageDto: CreateMessageDto): Promise<Message> {
const message: Message =
await this.messageRepository.create(createMessageDto);
message.chat = await this.chatService.findOne(createMessageDto.chatId);
message.user = await this.userService.findOne(createMessageDto.userId);
message.messageType = await this.messageTypeRepository.findOne({
where: { id: createMessageDto.messageTypeId },
});
return await this.messageRepository.save(message);
}
} |
using FluentValidation;
using WebApplication_StudentAPI_115.Models;
using WebApplication_StudentAPI_115.Models.ViewModels;
namespace WebApplication_StudentAPI_115.Validator
{
public class UserValidator:AbstractValidator<UserVM2>
{
public UserValidator()
{
RuleFor(u => u.UserName)
.NotEmpty()
.WithMessage("{PropertyName} cannot be empty");
RuleFor(u => u.Password)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.WithMessage("{PropertyName} cannot be empty")
.Matches(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$")
.WithMessage("{PropertyName} must be 8-15 characters long and must contain a small and Capital letter along with a special character and a number");
RuleFor(u => u.ConfirmPassword)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty()
.WithMessage("{PropertyName} cannot be empty")
.Matches(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$")
.WithMessage("{PropertyName} must be 8-15 characters long and must contain a small and Capital letter along with a special character and a number")
.Equal(u => u.Password)
.WithMessage("{PropertyName} must be equals to Password");
RuleFor(u => u.Role)
.NotEmpty()
.WithMessage("{PropertyName} cannot be empty");
}
}
} |
package com.example.hotels_api.Dto;
import com.example.hotels_api.Model.Apartment;
import com.example.hotels_api.Model.Customer;
import com.example.hotels_api.Model.OrderStatus;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import java.time.LocalDate;
@Setter @Getter
@AllArgsConstructor
public class Order1Dto {
private Integer customer_id;
private Integer apartment_id;
@CreationTimestamp
private LocalDate createdAt;
@NotNull(message = "Number of days should not be empty")
@Positive(message = "Number of days should be a positive number")
@Column(nullable = false)
private Integer numberOfDays;
@Column(columnDefinition = "DATE")
private LocalDate endDate;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private OrderStatus status;
} |
#Konversi Video.mp4 ke frame dengan dimensi 255x255
import cv2
def convert_video_to_frames(video_path, output_dir, frame_width, frame_height):
"""Konversi video ke frame dengan dimensi yang ditentukan.
Args:
video_path: Path ke video yang akan dikonversi.
output_dir: Path ke direktori tempat frame akan disimpan.
frame_width: Lebar dimensi frame.
frame_height: Tinggi dimensi frame.
Returns:
None.
"""
# Buka video
video = cv2.VideoCapture(video_path)
# Cek apakah video dapat dibuka
if not video.isOpened():
raise FileNotFoundError("Video tidak dapat ditemukan.")
# Dapatkan frame rate video
frame_rate = video.get(cv2.CAP_PROP_FPS)
# Looping untuk membaca setiap frame
while True:
# Baca frame
ret, frame = video.read()
# Jika frame tidak dapat dibaca, keluar dari looping
if not ret:
break
# Ubah dimensi frame
frame = cv2.resize(frame, (frame_width, frame_height))
# Simpan frame
filename = f"{output_dir}/frame_{int(video.get(cv2.CAP_PROP_POS_FRAMES))}.jpg"
cv2.imwrite(filename, frame)
# Tutup video
video.release()
if __name__ == "__main__":
# Input
video_path = "D:\LAPORAN TA\Pemrograman/contoh.mp4"
output_dir = "D:\LAPORAN TA\Pemrograman/hasil cobaan 256"
frame_width = 256
frame_height = 256
# Konversi video
convert_video_to_frames(video_path, output_dir, frame_width, frame_height)
# Tampilkan pesan
print("Konversi video berhasil.") |
import React from "react";
import { Modal, Container, Row, Col, Card, Button } from "react-bootstrap";
import { useCart } from "../Context/CartContext";
const Cart = ({ show, onHide }) => {
const { cart } = useCart();
return (
<Modal show={show} onHide={onHide}>
<Modal.Header>
<Modal.Title> Cart</Modal.Title>
<Button onClick={onHide}>❌</Button>
</Modal.Header>
<Modal.Body>
<Container>
{cart.map((item, index) => (
<Row key={index} className="mb-3">
<Col md={4}>
<Card.Img src={item.imageUrl} alt={item.title} />
</Col>
<Col md={8}>
<Card.Title>{item.title}</Card.Title>
<Card.Text>${item.price}</Card.Text>
<Card.Text>Quantity: {item.quantity}</Card.Text>
<Button variant="danger">Remove</Button>
</Col>
</Row>
))}
</Container>
</Modal.Body>
</Modal>
);
};
export default Cart; |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html dir="ltr" xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN"><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="author" content="TeliuTe" />
<meta content="TeliuTe系列教程之Ubuntu安装教程" name="description" />
<meta content="TeliuTe,86团学校,基础教程网" name="Copyright" />
<meta content="基础教程网,TeliuTe系列教程,一步一步教你学会使用电脑" name="description" />
<meta content="Ubuntu,TeliuTe,安装,教程,基础,入门" name="keywords" />
<meta content="TeliuTe" name="author" />
<style type="text/css">
<!--
body {
background-color: #CCFFFF;
}
.title {
font-family: "文泉驿正黑","黑体",Arial,Helvetica,sans-serif;
color: #FF0000;
font-size: 24px;
text-align: center;
}
.brown {color: #800000}
.green {
color: #008000;
}
.tblue { color: #0000FF;
}
-->
</style><title>Ubuntu安装|安装Ubuntu10.10</title></head><body style="direction: ltr;"><p class="title">Ubuntu安装基础教程</p>
<p class="green">作者:TeliuTe 来源:基础教程网</p>
<span class="tblue">二十、安装Ubuntu10.10</span> <a href="../index.html">返回目录</a> <a href="../lesson21/lesson21.html">下一课</a>
<p> 10.10 版安装与前面版本类似,学习中遇到不清楚的地方,可以参考一下前面的内容,操作中注意细心,下面来看一个练习;</p>
<p> <span class="tblue">1、进入 live cd 桌面
</span></p>
<p> 1)设置好<span class="brown">启动</span>后,断开网络,然后重启动计算机,可以用硬盘启动,也可以刻成光盘启动,镜像的下载地址:</p>
<p> 进入后找蓝色链接点击下载,如 ubuntu-10.10-desktop-i386.iso:<a href="http://mirrors.sohu.com/ubuntu-releases/10.10/">http://mirrors.sohu.com/ubuntu-releases/10.10/</a></p>
<p> 硬盘安装请参阅:<a target="_blank" href="http://teliute.org/linux/Ubsetup/jichu0/jichu0.html">http://teliute.org/linux/Ubsetup/jichu0/jichu0.html</a><br />
</p>
<p> 2)启动后稍等,系统自动运行,在下边出来两个图标<img src="images/a2tb.png" alt="a2tb.png" />时,可以按ESC键呼出菜单项;</p>
<p> <img src="images/a1jt.png" alt="a1jt.png" /></p>
<p> </p>
<p> 3)等一会就进入一个桌面,这就是试用的 live cd 桌面,<span class="brown">桌面</span>左上边有有两个图标,右上角是“<span class="brown">关机</span>”按钮;</p>
<p> <img src="images/a3zm.jpg" alt="a3zm.jpg" /></p>
<p> </p>
<p> 4)对于<span class="brown">硬盘</span>安装,点左上角菜单:“ 应用程序-附件-终端” 进入终端窗口;</p>
<p> <img src="images/a4zd.png" alt="a4zd.png" /></p>
<p> </p>
<p> 5)输入命令 sudo umount -l /isodevice 然后按一下<span class="brown">回车键</span>,没什么提示就是成功了;</p>
<p> <img src="images/a5xz.png" alt="a5xz.png" /></p>
<p> </p>
<p> <span class="tblue">2、安装系统</span></p>
<p> 1)双击桌面“<span class="brown">安装Ubuntu10.10</span>”图标,稍等出来一个“欢迎”面板,左侧应该选中了“中文(简体)”,</p>
<p> 如果不是就在左边选中它,然后点右下角“<span class="brown">前进</span>”按钮继续;</p>
<p> <img src="images/b1hy.png" alt="b1hy.png" /></p>
<p> </p>
<p> 2)第2步是检查准备情况,要求磁盘空间足够,是否安装一些受限软件,一般不用勾选,网络也不要连接,<span class="brown">直接</span>点“前进”按钮继续;</p>
<p> <img src="images/b2zb.png" alt="b2zb.png" /></p>
<p> </p>
<p> 3)接下来<span class="brown">第3步</span>是询问安装到哪个分区,选择第三个“手动指定分区(高级)”,点“<span class="brown">前进</span>”按钮继续;</p>
<p> <img src="images/b3sd.png" alt="b3sd.png" /></p>
<p> </p>
<p> </p>
<p> 4)接下来出来磁盘分区情况,如果要新建分区和转换分区可以参考前面的第7、13、15、16、19课,这儿是<span class="brown">安装</span>到之前的8.10分区上;</p>
<p> <img src="images/b4fq.png" alt="b4fq.png" /></p>
<p> </p>
<p> 5)点击选中要安装的分区,可以根据分区类型和大小来确定,然后点下边的“<span class="brown">更改</span>”按钮;</p>
<p> </p>
<p> </p>
<p> 6)在出来的对话框中,设定<span class="brown">用于</span>分区的格式Ext4,打勾“格式化”,在“挂载点”右边点一下,选 “/”,点“确定”</p>
<p> <span class="brown">注意</span>,格式化会删除这个分区上的所有文件,请提前备份重要数据; </p>
<p> <img src="images/b6bjfq.png" alt="b6bjfq.png" /></p>
<p> </p>
<p> 7)回到分区面板,检查一下<span class="brown">分区</span>编辑好了,点“现在安装”,如果还有 /home 分区,按原来的设,一般不打勾“<span class="brown">格式化</span>”,只需提前清理里面的配置文件;</p>
<p> <img src="images/b7jc.png" alt="b7jc.png" /></p>
<p> </p>
<p> 8)检查以后,点“现在安装”开始复制文件,如果提示没有交换空间,点“继续”,这个是用于休眠的,大小跟内存相同的分区,一般不用它;</p>
<p> <img src="images/b8jhkj.png" alt="b8jhkj.png" /></p>
<p> </p>
<p> 9)点“继续”后出来询问地区的,点“前进”即可,同时下边已经开始安装了;</p>
<p> <img src="images/b9dq.png" alt="b9dq.png" /></p>
<p> </p>
<p> 10)接下来是键盘布局,一般是“USA”,直接点“前进”继续;</p>
<p> <img src="images/b10jp.png" alt="b10jp.png" /></p>
<p> </p>
<p> 11)接下来是设定自己的用户名和密码等,从上到下依次输入即可,然后点“前进”;</p>
<p> <img src="images/b11yhmm.png" alt="b11yhmm.png" /></p>
<p> </p>
<p> 12)然后接着继续安装过程,可以看一下系统的介绍;</p>
<p> <img src="images/b12az.png" alt="ba12az.png" /></p>
<p> </p>
<p> 13)耐心等待完成,然后出来一个对话框,点“<span class="brown">现在重启</span>”完成安装,按组合键 Ctr + Alt + Delete 也可以呼出关机对话框;</p>
<p> <img src="images/b13cq.png" alt="ba13cq.png" /></p>
<p> </p>
<p> 14)稍等提示取出光盘,然后按<span class="brown">回车键</span>,重新启动计算机,安装完成;</p>
<p> <img src="images/b14hc.png" alt="b14hc.png" /></p>
<p> </p>
<p> <span class="tblue">3、连网换源</span></p>
<p> 1)重新启动后,停在一个<span class="brown">登录</span>界面,点击自己的用户名,输入密码后按回车,或点“登录”按钮,进入系统;</p>
<p> <img src="images/c1dl.jpg" alt="c1dl.jpg" /> <img src="images/c1mm.png" alt="c1mm.png" /></p>
<p> </p>
<p> 2)进入桌面后会出来一个“<span class="brown">不完整</span>语言支持”的提示对话框,先不关闭拖到一边后面要用;</p>
<p> <img src="images/c2bwz.png" alt="c2bwz.png" /></p>
<p> </p>
<p> 3)先连网,找到屏幕<span class="brown">右上角</span>键盘旁边的一个网络图标,瞄准点<span class="brown">右键</span>,选“编辑连接”;</p>
<p> <img src="images/c3bjlj.png" alt="c3bjlj.png" /></p>
<p> </p>
<p> 4)对于ADSL拨号宽带连接上网,在出来的对话框右边,点 <span class="brown">DSL</span> 标签,然后点添加;</p>
<p> <img src="images/c4dsltj.png" alt="c4dsltj.png" /></p>
<p> </p>
<p> 5)在出来的对话框里,先<span class="brown">打勾</span>上边的 “自动连接”,然后在用户名里输入ADSL宽带<span class="brown">用户名</span>,</p>
<p> 下面的密码里,输入宽带<span class="brown">密码</span>,然后点右下角的“应用”按钮,在出来的密码框中输入密码;</p>
<p> <img src="images/c5dsl.png" alt="c5dsl.png" /></p>
<p> </p>
<p> 关闭对话框以后,稍等一下会提示连网成功,</p>
<p> <img src="images/c5dsl1.png" alt="c5dsl1.png" /></p>
<p> </p>
<p> 也可以<span class="brown">重新</span>启动计算机,命令行使用 sudo pppoeconf 命令也可以;</p>
<p> </p>
<p> (下面6-7是局域网的,宽带用户不要设置)</p>
<p> 6)如果是<span class="brown">局域网</span>上网,在出来的对话框里,选中里面的“Auto eth0”,点右边的“编辑”按钮;</p>
<p> <img src="images/c6bj.png" alt="c6bj.png" /></p>
<p> </p>
<p> 7)在出来的对话框里,选择 <span class="brown">IPV4 设置</span>标签,在下面的方法里选“手动”,再点下边的“添加”按钮,</p>
<p> 在出来的文本框里,<span class="brown">依次</span>输入 IP 地址、子网掩码、网关,然后按<span class="brown">回车键</span>确定,在下面的 DNS 里输入 DNS 服务器地址,</p>
<p> 检查一下,点右下角的“<span class="brown">应用</span>”按钮,在出来的认证中,输入自己的密码;</p>
<p> <img src="images/c7ipv4.png" alt="c7ipv4.png" /> <img src="images/c7rz.png" alt="c7rz.png" /></p>
<p> </p>
<p> 回到原来对话框点“关闭”,稍等一会就可以上网了,也可以重新启动计算机;</p>
<p> <img src="images/c7lw.png" alt="c7lw.png" /></p>
<p> </p>
<p> 8)连接好网络后先<span class="brown">换源</span>,在左上角“应用程序菜单”上点右键,在出来的菜单中选“编辑菜单”;</p>
<p> <img src="images/c8cd.png" alt="c8cd.png" /></p>
<p> </p>
<p> 9)在出来的面板左侧选中“系统管理”,在右侧面板中打勾“软件源”,然后点“关闭”;</p>
<p> <img src="images/c9mb.png" alt="c9mb.png" /></p>
<p> </p>
<p> 10)点菜单“系统 - 系统管理 - 软件源”,输入密码后进入窗口;</p>
<p> <img src="images/c10cd.png" alt="c10cd.png" /></p>
<p> </p>
<p> 11)在出来的窗口中,点“下载自”旁边的下拉列表,选“其他站点”;</p>
<p> <img src="images/c11mb.png" alt="c11mb.png" /></p>
<p> </p>
<p> 12)在出来的面板中,选择一个搜狐、163 或 cn99 的站点都可以;</p>
<p> <img src="images/c12xz.png" alt="c12xz.png" /></p>
<p> </p>
<p> 13)点下面的“选择服务器”,关闭窗口后,出来更新提示,点“重新载入”,等待完成就好了;</p>
<p> <img src="images/c13cx.png" alt="c13cx.png" /></p>
<p> </p>
<p> 更多设置源的相关介绍,请参阅:<a href="http://teliute.org/linux/Ubsetup/lesson9/lesson9.html" target="_blank">http://teliute.org/linux/Ubsetup/lesson9/lesson9.html</a></p>
<p> </p>
<p> <span class="tblue">4、更新系统</span></p>
<p> 1)回到最开头的“不完整语言言支持”对话框,点“现在执行此动作”;</p>
<p> <img src="images/d1run.png" alt="d1run.png" /></p>
<p> 2)在出来的“语言支持没有完全安装”对话框中,点“安装”,安装语言包;</p>
<p> <img src="images/d2install.png" alt="d2install.png" /></p>
<p> </p>
<p> 3)然后开始下载语言包,耐心<span class="brown">等待</span>下载完成,然后接着安装这些包;</p>
<p> <img src="images/d3az.png" alt="d3az.png" /></p>
<p> </p>
<p> 4)待语言包安装完成后,点<span class="brown">关闭</span>按钮关闭各个对话框;</p>
<p> 如果“不完整语言言支持”对话框没了,就点上边的菜单“系统-系统管理-语言支持”;</p>
<p> <img src="images/d1yyzc.png" alt="d1yyzc.png" /></p>
<p> </p>
<p> 在出来的面板中,点下边的“添加或删除语言”按钮,打勾选中“中文(简体)-应用变更”,等待安装完成;<br />
</p>
<p> <img src="images/d2tjsc.png" alt="d2tjsc.png" /><img src="images/d2yybg.png" alt="d2yybg.png" /></p>
<p> </p>
<p> 5)过一会还会出来更新管理器对话框,点<span class="brown">安装更新</span>按钮;</p>
<p> <img src="images/d5gx.png" alt="d5gx.png" /></p>
<p> </p>
<p> 6)然后在出来的密码框中,输入自己的密码,点<span class="brown">确定</span>;</p>
<p> <img src="images/d6mm.png" alt="d6mm.png" /></p>
<p> </p>
<p> 7)接下来就是下载和安装,这儿<span class="brown">耐心</span>等待即可;</p>
<p> <img src="images/d3dw.png" alt="d3dw.png" /></p>
<p> </p>
<p> 8)安装完成后,关闭对话框,点<span class="brown">右上角</span>的关机按钮,再点“重启动”重启动电脑;</p>
<p> <img src="images/d8cq.png" alt="d8cq.png" /></p>
<p> </p>
<p> 9)重新启动后,各个程序也都是中文的了;</p>
<p> <img src="images/d9zm.jpg" alt="d9zm.jpg" /></p>
<p> </p>
<p> 其他细节:如果发现 Windows 的启动菜单项没了,先不着急,更新完就有了,如果还没有则在终端执行 sudo update-grub,或者把原来备份的 grub.cfg 找出来,照着填加进去;</p>
<p> <span class="tblue">本节</span>学习了安装 ubuntu 10.10 的基本方法,如果你成功地完成了练习,请继续学习下一课内容;</p>
<p><a href="../index.html">返回目录</a> <a href="../lesson21/lesson21.html">下一课</a></p>
<p class="green">本教程由86团学校TeliuTe制作|著作权所有</p>
<p class="green">基础教程网:<a href="http://teliute.org/">http://teliute.org/</a></p>
<p class="green">美丽的校园……</p>
<p style="text-align: center;">转载和引用本站内容,请保留作者和本站链接。</p>
<script language="javascript" type="text/javascript" src="http://js.users.51.la/1132862.js">
</script>
<noscript><a href="http://www.51.la/?1132862" target="_blank"><img alt="我要啦免费统计" src="http://img.users.51.la/1132862.asp" style="border: medium none ;" height="20" width="20" /></a> </noscript>
<div>
<script type="text/javascript"><!--
google_ad_client = "pub-2989083345397211";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text";
//2007-09-15: new1
google_ad_channel = "9381269263";
google_ui_features = "rc:6";
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br />
<script type="text/javascript"><!--
google_ad_client = "pub-2989083345397211";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "image";
//2007-09-15: new1
google_ad_channel = "9381269263";
google_ui_features = "rc:6";
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br />
<script type="text/javascript"><!--
google_ad_client = "pub-2989083345397211";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_ad_type = "text";
//2007-09-15: new1
google_ad_channel = "9381269263";
google_ui_features = "rc:6";
//-->
</script>
<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
</body></html> |
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use VictorPrdh\RecaptchaBundle\Form\ReCaptchaType;
class ContactType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('name', null, [
'label' => false,
'attr' => [
'class' => 'input-message-contact',
'placeholder' => 'Nom et prénom',
'value'=> ''
]
])
->add('email', EmailType::class, [
'label' => false,
'attr' => [
'class' => 'input-message-contact',
'placeholder' => 'Email',
'value'=> ''
]
])
->add('subject', null, [
'label' => false,
'attr' => [
'class' => 'input-message-contact',
'placeholder' => 'Object',
'value'=> ''
]
])
->add('message', TextareaType::class, [
'label' => false,
'row_attr' => [
'placeholder' => 'Message',
'wrap' => true
],
'attr' => [
'class' => 'textarea-message-contact',
'value'=> '',
]
])
->add('captcha', ReCaptchaType::class)
->add('send', SubmitType::class, [
'label' => 'Envoyer',
'attr' => [
'class' => 'button-message-contact',
]
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
// Configure your form options here
]);
}
} |
import 'package:exemple2/widgets/Drawer.dart';
import 'package:exemple2/widgets/Methodes.dart';
import 'package:flutter/material.dart';
import 'HomeScreen.dart';
class AddNews extends StatefulWidget {
const AddNews({Key? key}) : super(key: key);
@override
_AddNewsState createState() => _AddNewsState();
}
class _AddNewsState extends State<AddNews> {
late String _object;
late String _message;
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
bool isLoading = false;
Widget _builObject() {
return TextFormField(
decoration: InputDecoration(
labelText: 'Objet',
prefixIcon: Icon(Icons.emoji_objects_outlined),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),),
validator: (String? value) {
if (value!.isEmpty) {
return 'Objet obligatoire';
}
return null;
},
onSaved: (String? value) {
_object = value!;
},
);
}
Widget _builMessage() {
return TextFormField(
maxLines: 11,
decoration: InputDecoration(
// labelText: 'Message',
hintText: "Message",
prefixIcon: Icon(Icons.message_outlined),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
),),
onSaved: (String? value) {
_message = value!;
},
);
}
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: Text("Ajouter News"),
centerTitle: true,
),
drawer: MainDrawer(),
body: isLoading? Center(
child: Container(
height: size.height/20,
width: size.width/10,
child: CircularProgressIndicator(),
),
)
:SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: size.height/30,
),
Container(
width: size.width/1.3,
child: Text(
"Ajouter News",
style: TextStyle(
color: Colors.grey,
fontSize: 25,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
),
Container(
margin: EdgeInsets.only(bottom: 24, right: 24, left: 24),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: size.height/20,
),
_builObject(),
SizedBox(
height: size.height/50,
),
_builMessage(),
SizedBox(
height: size.height/30,
),
GestureDetector(
child: Container(
height: size.height/14,
width: size.width/1.2,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.blue,
),
alignment: Alignment.center,
child: Text(
"Envoyer",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
onTap: () {
if (!_formKey.currentState!.validate()) {
return;
}
_formKey.currentState!.save();
var date=DateTime.now();
createNews(_object, _message,date.add(Duration(days: 5, hours: 5, minutes: 5)).toString());
setState(() {
isLoading= true;
});
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => HomeScreen()));
},
),
],
),
),
),
],
),
),
);
}
} |
from __future__ import annotations
from configparser import ConfigParser
from datetime import datetime, timedelta, timezone
from importlib.resources import as_file, files
import json
import logging
from typing import IO
import click
from click_loglevel import LogLevel
from flask import current_app
from flask.cli import FlaskGroup
from flask_migrate import stamp
from sqlalchemy import inspect
from . import __version__
from .app import create_app, emit_json_log
from .dbutil import dbcontext, purge_old_versions
from .models import EntryPointGroup, OrphanWheel, PyPISerial, Wheel, db
from .process import process_queue
from .pypi_api import PyPIAPI
from .scan import scan_changelog, scan_pypi
log = logging.getLogger(__name__)
# FlaskGroup causes all commands to be run inside an application context,
# thereby letting `db` do database operations. This does require that
# `ctx.obj` be left untouched, though.
@click.group(cls=FlaskGroup, create_app=create_app)
@click.version_option(
__version__,
"-V",
"--version",
message="%(prog)s %(version)s",
)
@click.option(
"-l",
"--log-level",
type=LogLevel(),
default="INFO",
help="Set logging level",
show_default=True,
)
def main(log_level: int) -> None:
"""Manage a Wheelodex instance"""
logging.basicConfig(
format="%(asctime)s [%(levelname)-8s] %(name)s: %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S%z",
level=log_level,
)
@main.command()
@click.option("-f", "--force", is_flag=True, help="Force initialization")
def initdb(force: bool) -> None:
"""
Initialize the database.
This command creates the database tables, initializes the PyPI serial to 0,
and sets the Alembic revision to the latest version. In an attempt at
ensuring idempotence, this command will do nothing if there are already one
or more tables in the database; use the ``--force`` option to override this
check.
"""
if force or not inspect(db.engine).get_table_names():
click.echo("Initializing database ...")
with dbcontext():
db.create_all()
PyPISerial.set(0)
stamp()
else:
click.echo("Database appears to already be initialized; doing nothing")
@main.command("scan-pypi")
def scan_pypi_cmd() -> None:
"""Scan all PyPI projects for wheels"""
with dbcontext():
scan_pypi()
@main.command("scan-changelog")
def scan_changelog_cmd() -> None:
"""Scan the PyPI changelog for new wheels"""
with dbcontext():
serial = PyPISerial.get()
if serial is None:
raise click.UsageError("No saved state to update")
scan_changelog(serial)
@main.command("process-queue")
@click.option(
"-S", "--max-wheel-size", type=int, help="Maximum size of wheels to process"
)
def process_queue_cmd(max_wheel_size: int | None) -> None:
"""
Analyze new wheels.
This command downloads & analyzes wheels that have been registered but not
analyzed yet and adds their data to the database. Only wheels for the
latest nonempty version of each project are analyzed.
"""
if max_wheel_size is None:
# Setting the option's default to the below expression or a
# lambdafication thereof doesn't work:
max_wheel_size = current_app.config.get("WHEELODEX_MAX_WHEEL_SIZE")
with dbcontext():
process_queue(max_wheel_size=max_wheel_size)
@main.command()
@click.option("-A", "--all", "dump_all", is_flag=True, help="Dump all wheels")
@click.option("-o", "--outfile", default="-", help="File to dump to")
def dump(dump_all: bool, outfile: str) -> None:
"""
Dump wheel data as line-delimited JSON.
This command outputs a JSONification of the wheels in the database to
standard output or the file specified with ``--outfile``. By default, only
wheels that have been analyzed are output; use the ``--all`` option to also
include registered wheels that have not yet been analyzed.
The output format is a stream of newline-delimited one-line JSON objects.
The order in which the wheels are output is undefined.
If the output filename contains the substring "%(serial)s", it is replaced
with the serial ID of the last seen PyPI event.
"""
with dbcontext():
outfile %= {"serial": PyPISerial.get()}
with click.open_file(outfile, "w", encoding="utf-8") as fp:
q = db.select(Wheel)
if not dump_all:
q = q.filter(Wheel.data.has())
# Dumping in pages gives a needed efficiency boost:
page = db.paginate(q, page=1, per_page=100)
while True:
for whl in page:
click.echo(json.dumps(whl.as_json()), file=fp)
if page.has_next:
page = page.next()
else:
break
@main.command()
@click.option("-S", "--serial", type=int, help="Also update PyPI serial to given value")
@click.argument("infile", type=click.File(encoding="utf-8"))
def load(infile: IO[str], serial: int | None) -> None:
"""
Load wheel data from line-delimited JSON.
This command reads a file of JSONified wheel data, such as produced by
the `dump` command, and adds the wheels to the database. Wheels in the
database that already have data are not modified.
"""
with dbcontext(), infile:
if serial is not None:
PyPISerial.set(serial)
for line in infile:
Wheel.add_from_json(json.loads(line))
@main.command("purge-old-versions")
def purge_old_versions_cmd() -> None:
"""Delete old versions from the database"""
with dbcontext():
purge_old_versions()
@main.command()
def process_orphan_wheels() -> None:
"""
Register or expire orphan wheels.
This command queries PyPI's JSON API to see if it can find the data for any
orphaned wheels. Those that are found are registered as "normal" wheels
and no longer orphaned. Those that aren't found despite being older than a
configured number of seconds are considered expired and deleted from the
database.
"""
log.info("BEGIN process_orphan_wheels")
start_time = datetime.now(timezone.utc)
unorphaned = 0
remaining = 0
pypi = PyPIAPI()
max_age = int(current_app.config["WHEELODEX_MAX_ORPHAN_AGE_SECONDS"])
with dbcontext():
for orphan in db.session.scalars(db.select(OrphanWheel)):
data = pypi.asset_data(
orphan.project.name,
orphan.version.display_name,
orphan.filename,
)
if data is not None:
log.info("Wheel %s: data found", orphan.filename)
orphan.version.ensure_wheel(
filename=data.filename,
url=data.url,
size=data.size,
md5=data.digests.md5,
sha256=data.digests.sha256,
uploaded=data.upload_time,
)
db.session.delete(orphan)
unorphaned += 1
else:
log.info("Wheel %s: data not found", orphan.filename)
remaining += 1
expired = db.session.execute(
db.delete(OrphanWheel).where(
OrphanWheel.uploaded
< datetime.now(timezone.utc) - timedelta(seconds=max_age)
)
)
log.info("%d orphan wheels expired", expired)
end_time = datetime.now(timezone.utc)
emit_json_log(
"process_orphan_wheels.log",
{
"op": "process_orphan_wheels",
"start": str(start_time),
"end": str(end_time),
"unorphaned": unorphaned,
"expired": expired,
"remain": remaining - expired,
},
)
log.info("END process_orphan_wheels")
@main.command()
@click.argument("infile", type=click.File(encoding="utf-8"), required=False)
def load_entry_points(infile: IO[str] | None) -> None:
"""
Load entry point group descriptions from a file.
This command reads descriptions & summaries for entry point groups from
either the given file or, if no file is specified, from a pre-made file
bundled with Wheelodex; the data read is then stored in the database for
display in the web interface when viewing entry point-related data.
The file must be an INI file as parsed by ``configparser``. Each section
describes the entry point group of the same name and may contain
``summary`` and ``description`` options whose values are Markdown strings
to render as the group's summary or description. Summaries are limited to
2048 characters and are expected to be a single line. Descriptions are
limited to 65535 characters and may span multiple lines.
"""
epgs = ConfigParser(interpolation=None)
if infile is None:
with as_file(files("wheelodex") / "data" / "entry_points.ini") as ep_path:
with ep_path.open(encoding="utf-8") as fp:
epgs.read_file(fp)
else:
epgs.read_file(infile)
with dbcontext():
for name in epgs.sections():
group = EntryPointGroup.ensure(name)
if epgs.has_option(name, "summary"):
group.summary = epgs.get(name, "summary")
if epgs.has_option(name, "description"):
group.description = epgs.get(name, "description")
if __name__ == "__main__":
main(prog_name=__package__) |
package core
import common.Common.*
object Syntax:
type CStage = Stage[Tm]
final case class Defs(defs: List[Def]):
override def toString: String = defs.mkString("\n")
def toList: List[Def] = defs
enum Def:
case DDef(module: String, name: Name, ty: Ty, stage: CStage, value: Tm)
override def toString: String = this match
case DDef(m, x, t, SMeta, v) => s"def $m/$x : $t = $v"
case DDef(m, x, t, STy(_), v) => s"def $m/$x : $t := $v"
export Def.*
enum ProjType:
case Fst
case Snd
case Named(name: Option[Name], ix: Int)
override def toString: String = this match
case Fst => ".1"
case Snd => ".2"
case Named(Some(x), _) => s".$x"
case Named(None, i) => s".$i"
export ProjType.*
type Ty = Tm
enum Tm:
case Var(ix: Ix)
case Global(module: String, name: Name)
case Prim(name: PrimName)
case Let(
usage: Usage,
name: Name,
ty: Ty,
stage: CStage,
bty: Ty,
value: Tm,
body: Tm
)
case U(stage: CStage)
case IntLit(value: Int)
case StringLit(value: String)
case Pi(usage: Usage, name: Bind, icit: PiIcit, ty: Ty, body: Ty)
case Fun(usage: Usage, pty: Ty, cv: Ty, rty: Ty)
case Lam(name: Bind, icit: Icit, fnty: Ty, body: Tm)
case App(fn: Tm, arg: Tm, icit: Icit)
case Fix(ty: Ty, rty: Ty, g: Bind, x: Bind, b: Tm, arg: Tm)
case Sigma(name: Bind, ty: Ty, body: Ty)
case Pair(fst: Tm, snd: Tm, ty: Ty)
case Proj(tm: Tm, proj: ProjType, ty: Ty, pty: Ty)
case Lift(cv: Ty, tm: Ty)
case Quote(tm: Tm)
case Splice(tm: Tm)
case Foreign(io: Boolean, rt: Ty, cmd: Tm, args: List[(Tm, Ty)])
case Data(x: Bind, cs: List[(Name, List[(Bind, Ty)])])
case Con(c: Name, t: Ty, as: List[Tm])
case Match(
dty: Ty,
rty: Ty,
scrut: Tm,
cs: List[(Name, Boolean, Int, Tm)],
other: Option[Tm]
)
case Wk(tm: Tm)
case Meta(id: MetaId)
case AppPruning(tm: Tm, spine: Pruning)
case Irrelevant
def appPruning(pr: Pruning): Tm =
def go(x: Ix, pr: Pruning): Tm = pr match
case Nil => this
case Some(i) :: pr => App(go(x + 1, pr), Var(x), i)
case None :: pr => go(x + 1, pr)
go(ix0, pr)
def quote: Tm = this match
case Splice(t) => t
case t => Quote(t)
def splice: Tm = this match
case Quote(t) => t
case t => Splice(t)
def metas: Set[MetaId] = this match
case Var(ix) => Set.empty
case Global(m, name) => Set.empty
case Prim(name) => Set.empty
case IntLit(_) => Set.empty
case StringLit(_) => Set.empty
case U(stage) => stage.fold(Set.empty, _.metas)
case Let(_, name, ty, stage, bty, value, body) =>
ty.metas ++ stage.fold(
Set.empty,
_.metas
) ++ bty.metas ++ value.metas ++ body.metas
case Pi(_, name, icit, ty, body) => ty.metas ++ body.metas
case Fun(_, a, b, c) => a.metas ++ b.metas ++ c.metas
case Lam(name, icit, fnty, body) => fnty.metas ++ body.metas
case App(fn, arg, icit) => fn.metas ++ arg.metas
case Fix(ty, rty, g, x, b, arg) =>
ty.metas ++ rty.metas ++ b.metas ++ arg.metas
case Sigma(name, ty, body) => ty.metas ++ body.metas
case Pair(fst, snd, ty) => fst.metas ++ snd.metas ++ ty.metas
case Proj(tm, proj, ty, pty) => tm.metas ++ ty.metas ++ pty.metas
case Lift(cv, tm) => cv.metas ++ tm.metas
case Quote(tm) => tm.metas
case Splice(tm) => tm.metas
case Data(_, cs) =>
cs.flatMap((_, as) => as.flatMap((_, t) => t.metas)).toSet
case Con(con, ty, args) => ty.metas ++ args.flatMap(_.metas)
case Match(dty, rty, scrut, cs, other) =>
dty.metas ++ rty.metas ++ scrut.metas ++ cs
.map((_, _, _, t) => t.metas)
.foldLeft(Set.empty[MetaId])(_ ++ _) ++ other
.map(_.metas)
.getOrElse(Set.empty[MetaId])
case Wk(tm) => tm.metas
case Meta(id) => Set(id)
case AppPruning(tm, spine) => tm.metas
case Irrelevant => Set.empty
case Foreign(_, rt, cmd, args) =>
rt.metas ++ cmd.metas ++ args
.map((a, b) => a.metas ++ b.metas)
.foldLeft(Set.empty[MetaId])(_ ++ _)
override def toString: String = this match
case Var(x) => s"'$x"
case Global(m, x) => s"$m/$x"
case Prim(x) => s"$x"
case Let(u, x, t, SMeta, _, v, b) => s"(let ${u.prefix}$x : $t = $v; $b)"
case Let(u, x, t, STy(_), _, v, b) =>
s"(let ${u.prefix}$x : $t := $v; $b)"
case U(s) => s"$s"
case IntLit(v) => s"$v"
case StringLit(v) => s"\"$v\""
case Pi(Many, DontBind, PiExpl, t, b) => s"($t -> $b)"
case Pi(u, x, i, t, b) => s"(${i.wrap(s"${u.prefix}$x : $t")} -> $b)"
case Fun(Many, a, _, b) => s"($a -> $b)"
case Fun(u, a, _, b) => s"($a ${u.prefix}-> $b)"
case Lam(x, Expl, _, b) => s"(\\$x. $b)"
case Lam(x, Impl, _, b) => s"(\\{$x}. $b)"
case App(f, a, Expl) => s"($f $a)"
case App(f, a, Impl) => s"($f {$a})"
case Fix(_, _, g, x, b, arg) => s"(fix ($g $x. $b) $arg)"
case Sigma(DontBind, t, b) => s"($t ** $b)"
case Sigma(x, t, b) => s"(($x : $t) ** $b)"
case Pair(a, b, _) => s"($a, $b)"
case Proj(t, p, _, _) => s"$t$p"
case Lift(_, t) => s"^$t"
case Quote(t) => s"`$t"
case Splice(t) => s"$$$t"
case Foreign(io, rt, cmd, Nil) =>
s"(foreign${if io then "IO" else ""} $rt $cmd)"
case Foreign(io, rt, cmd, as) =>
s"(foreign${if io then "IO" else ""} $rt $cmd ${as.map(_._1).mkString(" ")})"
case Data(x, Nil) => s"(data $x.)"
case Data(x, as) =>
s"(data $x. ${as.map((c, as) => s"$c ${as.map((x, t) => s"($x : $t)").mkString(" ")}").mkString(" | ")})"
case Con(c, t, Nil) => s"(con $c {$t})"
case Con(c, t, as) => s"(con $c {$t} ${as.mkString(" ")})"
case Match(_, _, scrut, cs, other) =>
s"(match $scrut ${cs
.map((c, _, _, b) => s"| $c $b")
.mkString(" ")} ${other.map(t => s"| $t").getOrElse("")})"
case Wk(t) => s"(Wk $t)"
case Irrelevant => "Ir"
case Meta(id) => s"?$id"
case AppPruning(t, sp) => s"($t [${sp.reverse.mkString(", ")}])"
export Tm.* |
/*
Pagination Component Props
- totalCount, total count of data from soruce
- currentPage, 0 based index
- pageSize, maximum data that's visible in single page
- onPageChange, callback invoked with updated page value
- siblingCount, min number of page buttons to be shown on each
side of current page button
usePagination hook, takes params totalCount,
currentPage, pageSize, siblingCount
- return range of numbers to display in our pagination
- re run when any of the input changes
- total number of items returned by hook should remain constant
*/
import { ChevronLeftIcon, ChevronRightIcon } from '@heroicons/react/solid';
import { useMemo } from 'react';
const DOTS = '...';
const usePagination = ({ totalCount, pageSize, siblingCount, currentPage }) => {
const paginationRange = useMemo(() => {
const range = (start, end) => {
let length = end - start + 1;
return Array.from({ length }, (_, i) => i + start);
};
const totalPageCount = Math.ceil(totalCount / pageSize);
const totalPageNumbers = Math.max(8, siblingCount + 4);
if (totalPageNumbers >= totalPageCount) {
return range(1, totalPageCount);
}
const leftSiblingIndex = Math.max(currentPage - siblingCount, 1);
const rightSiblingIndex = Math.min(currentPage + siblingCount, totalPageCount);
const showLeftDots = leftSiblingIndex > 2;
const showRightDots = rightSiblingIndex < totalPageCount - 2;
const firstPageIndex = 1;
const lastPageIndex = totalPageCount;
if (!showLeftDots && showRightDots) {
const leftItemCount = 3 + 2 * siblingCount;
const leftRange = range(1, leftItemCount);
return [...leftRange, DOTS, totalPageCount];
}
if (showLeftDots && !showRightDots) {
const rightItemCount = 3 + 2 * siblingCount;
const rightRange = range(totalPageCount - rightItemCount + 1, totalPageCount);
return [firstPageIndex, DOTS, ...rightRange];
}
if (showLeftDots && showRightDots) {
const middleRange = range(leftSiblingIndex, rightSiblingIndex);
return [firstPageIndex, DOTS, ...middleRange, DOTS, lastPageIndex];
}
}, [totalCount, pageSize, siblingCount, currentPage]);
return paginationRange;
};
export default function Pagination({
currentPage,
totalCount,
pageSize,
siblingCount = 1,
onPageChange,
}) {
const paginationRange = usePagination({
totalCount,
pageSize,
siblingCount,
currentPage,
});
console.log(totalCount, pageSize, siblingCount, currentPage, paginationRange);
if (currentPage === 0 || paginationRange.length < 2) {
return null;
}
const lastPage = paginationRange[paginationRange.length - 1];
return (
<div className="flex items-center justify-center space-x-1">
<button
className="flex flex-col item-center justify-center w-6 h-6 rounded-full border-2 border-complementary/25"
disabled={currentPage <= 1}
onClick={() => onPageChange(currentPage - 1)}
>
<ChevronLeftIcon className="ml-0.5 w-4 h-4 text-complementary cursor-pointer" />
</button>
{paginationRange.map((pageNumber, i) => {
return (
<div
key={i}
className={`flex items-center justify-center w-6 h-6 rounded-full mx-1 cursor-pointer text-sm
${pageNumber === currentPage ? 'bg-primaryDark text-white' : 'text-complementary'}
`}
onClick={() => onPageChange(pageNumber)}
>
{pageNumber}
</div>
);
})}
<button
className="flex flex-col item-center justify-center w-6 h-6 rounded-full border-2 border-complementary/25"
disabled={currentPage >= lastPage}
onClick={() => onPageChange(currentPage + 1)}
>
<ChevronRightIcon className="ml-0.5 w-4 h-4 text-complementary cursor-pointer" />
</button>
</div>
);
} |
package com.translantik.pages;
import com.translantik.utilities.BrowserUtils;
import com.translantik.utilities.Driver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public abstract class BasePage {
public BasePage() {
PageFactory.initElements(Driver.get(), this);
}
@FindBy(css = "div[class='loader-mask shown']")
@CacheLookup
protected WebElement loaderMask;
@FindBy(css = "h1[class='oro-subtitle']")
public WebElement pageSubTitle;
@FindBy(css = "#user-menu > a")
public WebElement userName;
@FindBy(linkText = "Logout")
public WebElement logOutLink;
@FindBy(linkText = "My User")
public WebElement myUser;
@FindBy (xpath = "(//a[@class='dropdown-toggle'])[1]")
public WebElement userNameDropDown;
/**
* @return page name, for example: Dashboard
*/
public String getPageSubTitle() {
//ant time we are verifying page name, or page subtitle, loader mask appears
waitUntilLoaderScreenDisappear();
// BrowserUtils.waitForStaleElement(pageSubTitle);
return pageSubTitle.getText();
}
/**
* Waits until loader screen present. If loader screen will not pop up at all,
* NoSuchElementException will be handled bu try/catch block
* Thus, we can continue in any case.
*/
public void waitUntilLoaderScreenDisappear() {
try {
WebDriverWait wait = new WebDriverWait(Driver.get(), 10);
wait.until(ExpectedConditions.invisibilityOf(loaderMask));
} catch (Exception e) {
e.printStackTrace();
}
}
public String getUserName(){
waitUntilLoaderScreenDisappear();
BrowserUtils.waitForVisibility(userName, 10);
return userName.getText();
}
public void logOut(){
BrowserUtils.waitFor(2);
BrowserUtils.clickWithJS(userName);
BrowserUtils.clickWithJS(logOutLink);
}
public void goToMyUser(){
waitUntilLoaderScreenDisappear();
BrowserUtils.waitForClickablility(userName, 5).click();
BrowserUtils.waitForClickablility(myUser, 5).click();
}
/**
* This method will navigate user to the specific module in vytrack application.
* For example: if tab is equals to Activities, and module equals to Calls,
* Then method will navigate user to this page: http://qa2.vytrack.com/call/
*
* @param tab
* @param module
*/
public void navigateToModule(String tab, String module) {
String tabLocator = "//span[normalize-space()='" + tab + "' and contains(@class, 'title title-level-1')]";
// String moduleLocator2 = "//span[@class='title title-level-1' and contains(text(),'"+ module + "')]";
String moduleLocator = "//span[normalize-space()='" + module + "' and contains(@class, 'title title-level-2')]";
// String moduleLocator2 = "//span[@class='title title-level-2' and contains(text(),'"+ module + "')]";
try {
BrowserUtils.waitForClickablility(By.xpath(tabLocator), 5);
WebElement tabElement = Driver.get().findElement(By.xpath(tabLocator));
new Actions(Driver.get()).moveToElement(tabElement).pause(200).doubleClick(tabElement).build().perform();
} catch (Exception e) {
BrowserUtils.clickWithWait(By.xpath(tabLocator), 5);
}
try {
BrowserUtils.waitForPresenceOfElement(By.xpath(moduleLocator), 5);
BrowserUtils.waitForVisibility(By.xpath(moduleLocator), 5);
BrowserUtils.scrollToElement(Driver.get().findElement(By.xpath(moduleLocator)));
Driver.get().findElement(By.xpath(moduleLocator)).click();
} catch (Exception e) {
BrowserUtils.clickWithTimeOut(Driver.get().findElement(By.xpath(moduleLocator)), 5);
}
}
} |
import { Injectable } from '@nestjs/common';
import { UserRepository } from './user.repository';
import { InjectRepository } from '@nestjs/typeorm';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from './interface/jwt-payload.interface';
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private readonly userRepository: UserRepository, // this will be injected by Nest when AuthService is created by Nest (dependency injection)
private readonly jwtService: JwtService // this will be injected by Nest when AuthService is created by Nest (dependency injection)
) { }
async signUp(authCrendentialsDto: AuthCredentialsDto) {
return await this.userRepository.createUser(authCrendentialsDto);
}
async signIn(authCrendentialsDto: AuthCredentialsDto) {
const validatedUser = await this.userRepository.validateUserPassword(authCrendentialsDto);
if (!validatedUser) {
return null;
}
const payload: JwtPayload = { username: validatedUser.username };
const accessToken = this.jwtService.sign(payload);
return { accessToken };
}
} |
import { ApiTags } from '@nestjs/swagger';
import { Devices, Prisma } from '@prisma/client';
import { Controller, Get, Param, Post, Body } from '@nestjs/common';
import { DevicesService } from './devices.services';
import { Public } from 'src/common/decorators/isPublic.decorator';
@ApiTags('devices')
@Controller({ version: '1', path: 'device' })
export class DevicesController {
constructor(private readonly devicesService: DevicesService) {}
@Get()
// http://localhost:3000/device
async getAllDevices(): Promise<Devices[]> {
return this.devicesService.getAllDevices();
}
@Public()
@Get(':id')
// http://localhost:3000/device/2
async getDeviceById(@Param('id') id: string): Promise<Devices> {
return this.devicesService.deviceById(id);
}
@Public()
@Post('/create')
// http://localhost:3000/create
/*{
"name": "Szemetes",
"isAvailable": true,
"reservation": {
// Nested reservation data if needed
}
} */
async createDevice(
@Body() data: Prisma.DevicesCreateInput,
): Promise<Devices> {
return this.devicesService.createDevice(data);
}
@Public()
@Post('/update')
/*{
"where": {
"id": "1"
},
"data": {
"name": "Szemet Lapat",
"isAvailable": true,
"reservation": {
// Nested reservation data if needed
}
}
}
*/
async updateDevice(
@Body()
body: {
where: Prisma.DevicesWhereUniqueInput;
data: Prisma.DevicesUpdateInput;
},
): Promise<Devices> {
return this.devicesService.updateDevice(body.where, body.data);
}
@Public()
@Post('/delete')
// http://localhost:3000/delete
async deleteDevice(
@Body()
where: Prisma.DevicesWhereUniqueInput,
): Promise<Devices> {
return this.devicesService.deleteDevice(where);
}
} |
import 'package:flutter/material.dart';
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ussd_data/data/m_model/min_sms_model.dart';
class MSMSScreen extends StatelessWidget {
const MSMSScreen({super.key, required this.sms});
final List<MSMSModel> sms;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('SMS to\'plamlari'),
backgroundColor: Colors.red,
),
body: SingleChildScrollView(
padding: EdgeInsets.symmetric(horizontal: 16.w,vertical: 10.h),
child: Column(children: [
...List.generate(sms.length, (index) {
MSMSModel sm = sms[index];
return Container(
padding: EdgeInsets.all(15.h),
margin: EdgeInsets.symmetric(vertical: 10.h),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16.r),
boxShadow: const [
BoxShadow(
color: Colors.grey,
offset: Offset(3, 3),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
DecoratedBox(
decoration: const BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.red,
width: 1,
),
),
),
child: Text(
'${sm.name} to\'plami',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20.sp,
),
),
),
SizedBox(height: 10.h),
Text(
'${sm.count} sms',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17.sp,
),
),
SizedBox(height: 10.h),
Text(
sm.cost,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 17.sp,
),
),
SizedBox(height: 10.h),
sm.validity == null ? const SizedBox() : Text(sm.validity!),
SizedBox(height: 10.h),
SizedBox(
width: MediaQuery.of(context).size.width,
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red,
),
onPressed: () async {
await FlutterPhoneDirectCaller.callNumber(sm.code);
},
child: const Text("Faollashtirish"),
),
),
],
),
);
})
]),
),
);
}
} |
## Author('Utah ww group')
## Institution('Univeristy of Utah')
## DBsubject('Calculus')
## DBchapter('Differentiation')
## DBsection('Derivatives of Inverse Functions')
## AuthorText1('Dale Varberg, Edwin J. Purcell, and Steve E. Rigdon')
## TitleText1('Calculus')
## EditionText1('9')
## Section1('The Transcendental Functions')
## Problem1('')
## KEYWORDS('calculus')
DOCUMENT();
loadMacros('PG.pl',
'PGbasicmacros.pl',
'PGchoicemacros.pl',
'PGanswermacros.pl',
);
TEXT(beginproblem());
$showPartialCorrectAnswers = 0;
$mc = new_multiple_choice();
#$mc->qa('( x^2 ) is:',
# '\( f^{\prime} > 0 \)'
#);
$mc->qa('',
'\( f^{\prime} > 0 \)'
);
#$mc->extra(
# '\( f^{\prime} < 0 \)',
# 'exponential',
# 'exponential \( f^{\prime} < 0 \)'
#);
$mc->makeLast(
'\( f^{\prime} < 0 \)'
);
BEGIN_TEXT
Let \( f(x) = 1 + x + x^{2} + x^{3} \). Then the derivative is
\[
D_{x}f(x) = 1 + 2x + 3x^{2} = (1+x)^{2} + 2x^{2}.
\]
Thus, \( f(x) \) is monotone on \( \mathbb{R} \) because
$PAR
\{ $mc->print_q() \}
$PAR
\{ $mc->print_a() \}
END_TEXT
ANS(radio_cmp($mc->correct_ans));
BEGIN_TEXT
Hence \(f(x)\) has an inverse function. Since \(f(x)\to\infty\) as
\(x\to\infty\), and \(f(x)\to-\infty\) as \(x\to-\infty\),
it follows that the inverse function \(f^{-1}\) is defined for all numbers.
$PAR
Find the derivative:
$PAR
\( D_x \left( f^{-1} \right)(40) = \) \{ans_rule(40)\}
END_TEXT
$ans = 1/34;
ANS(num_cmp($ans));
ENDDOCUMENT(); |
<template>
<section class="cart_module">
<section v-if="!foods.specifications.length" class="cart_button">
<transition name="showReduce">
<span @click="removeOutCart(foods.category_id, foods.item_id, foods.specfoods[0].food_id, foods.specfoods[0].name, foods.specfoods[0].price, '', foods.specfoods[0].packing_fee, foods.specfoods[0].sku_id, foods.specfoods[0].stock)" v-if="foodNum">
<svg>
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#cart-minus"></use>
</svg>
</span>
</transition>
<transition name="fade">
<span class="cart_num" v-if="foodNum">{{foodNum}}</span>
</transition>
<svg class="add_icon" @click="addToCart(foods.category_id, foods.item_id, foods.specfoods[0].food_id, foods.specfoods[0].name, foods.specfoods[0].price, '', foods.specfoods[0].packing_fee, foods.specfoods[0].sku_id, foods.specfoods[0].stock, $event)">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#cart-add"></use>
</svg>
</section>
<section v-else class="choose_specification">
<section class="choose_icon_container">
<transition name="showReduce">
<svg class="specs_reduce_icon" v-if="foodNum" @click="showReduceTip">
<use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#cart-minus"></use>
</svg>
</transition>
<transition name="fade">
<span class="cart_num" v-if="foodNum">{{foodNum}}</span>
</transition>
<span class="show_chooselist" @click="showChooseList(foods)">选规格</span>
</section>
</section>
</section>
</template>
<script>
import {reactive,toRefs,onMounted,computed}from 'vue'
import {useStore,mapState} from 'vuex'
export default {
name :'buyCart',
props:['foods', 'shopId'],
setup(props,content){
const store=useStore()
const state=reactive({
showMoveDot: [], //控制下落的小圆点显示隐藏
})
onMounted(()=>{})
const cartList=computed(()=>store.state.cartList)
const shopCart=computed(()=>Object.assign({},cartList[props.shopId]))
const foodNum=computed(()=>{
let category_id =props.foods.category_id;
let item_id = props.foods.item_id;
if (shopCart&&shopCart[category_id]&&shopCart[category_id][item_id]) {
let num = 0;
Object.values(shopCart[category_id][item_id]).forEach((item,index) => {
num += item.num;
})
return num;
}else {
return 0;
}
})
const ADD_CART=store.mutation('ADD_CART')
const REDUCE_CART=store.mutation('REDUCE_CART')
const removeOutCart=(category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock)=>{
if (foodNum > 0) {
REDUCE_CART({shopid: this.shopId, category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock});
}
}
//加入购物车,计算按钮位置。
const addToCart=(category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock, event)=>{
ADD_CART({shopid: this.shopId, category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock});
let elLeft = event.target.getBoundingClientRect().left;
let elBottom = event.target.getBoundingClientRect().bottom;
state.showMoveDot.push(true);
content.emit('showMoveDot', state.showMoveDot, elLeft, elBottom);
}
//显示规格列表
const showChooseList=(foodScroll)=>{
content.emit('showChooseList', foodScroll)
}
//点击多规格商品的减按钮,弹出提示
const showReduceTip=()=>{
content.emit('showReduceTip')
}
return {...toRefs(state),removeOutCart,cartList,shopCart,addToCart,showChooseList,foodNum}
}
}
// computed: {
// // ...mapState([
// // 'cartList'
// // ]),
// /**
// * 监听cartList变化,更新当前商铺的购物车信息shopCart,同时返回一个新的对象
// */
// shopCart: function (){
// return Object.assign({},this.cartList[this.shopId]);
// },
// //shopCart变化的时候重新计算当前商品的数量
// foodNum: function (){
// let category_id = this.foods.category_id;
// let item_id = this.foods.item_id;
// if (this.shopCart&&this.shopCart[category_id]&&this.shopCart[category_id][item_id]) {
// let num = 0;
// Object.values(this.shopCart[category_id][item_id]).forEach((item,index) => {
// num += item.num;
// })
// return num;
// }else {
// return 0;
// }
// },
// },
// methods: {
// ...mapMutations([
// 'ADD_CART','REDUCE_CART',
// ]),
// //移出购物车
// removeOutCart(category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock){
// if (this.foodNum > 0) {
// this.REDUCE_CART({shopid: this.shopId, category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock});
// }
// },
// //加入购物车,计算按钮位置。
// addToCart(category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock, event){
// this.ADD_CART({shopid: this.shopId, category_id, item_id, food_id, name, price, specs, packing_fee, sku_id, stock});
// let elLeft = event.target.getBoundingClientRect().left;
// let elBottom = event.target.getBoundingClientRect().bottom;
// this.showMoveDot.push(true);
// this.$emit('showMoveDot', this.showMoveDot, elLeft, elBottom);
// },
// //显示规格列表
// showChooseList(foodScroll){
// this.$emit('showChooseList', foodScroll)
// },
// //点击多规格商品的减按钮,弹出提示
// showReduceTip(){
// this.$emit('showReduceTip')
// },
// },
// }
</script>
<style lang="scss" scoped>
@import '../../style/mixin';
.cart_module{
.add_icon{
position: relative;
z-index: 9;
}
.cart_button{
display: flex;
align-items: center;
}
svg{
@include wh(.9rem, .9rem);
fill: #3190e8;
}
.specs_reduce_icon{
fill: #999;
}
.cart_num{
@include sc(.65rem, #666);
min-width: 1rem;
text-align: center;
font-family: Helvetica Neue,Tahoma;
}
.choose_specification{
.choose_icon_container{
display: flex;
align-items: center;
.show_chooselist{
display: block;
@include sc(.55rem, #fff);
padding: .1rem .2rem;
background-color: $blue;
border-radius: 0.2rem;
border: 1px solid $blue;
}
}
}
}
.showReduce-enter-active, .showReduce-leave-active {
transition: all .3s ease-out;
}
.showReduce-enter, .showReduce-leave-active {
opacity: 0;
transform: translateX(1rem);
}
.fade-enter-active, .fade-leave-active {
transition: all .3s;
}
.fade-enter, .fade-leave-active {
opacity: 0;
}
.fadeBounce-enter-active, .fadeBounce-leave-active {
transition: all .3s;
}
.fadeBounce-enter, .fadeBounce-leave-active {
opacity: 0;
transform: scale(.7);
}
</style> |
<template>
<div class="app-container">
<el-row>
<el-col :span="12">
<el-form ref="form" :model="form" label-width="120px" style="padding-top: 10vh;">
<el-form-item label="电影名称">
<el-autocomplete
v-model="form.name"
:fetch-suggestions="movieSearchSuggest"
placeholder="请输入内容"
style="width: 20vw;"
clearable
@select="handleSelect"
/>
</el-form-item>
<el-row>
<el-col :span="13">
<el-form-item label="电影类别">
<el-select
v-model="form.category"
filterable
remote
clearable
placeholder="请选择电影类别"
:remote-method="categoryRemoteSearch"
:loading="categoryLoading"
>
<el-option
v-for="item in movieCategory"
:key="item.value"
:label="item.value"
:value="item.value"
/>
</el-select>
<!-- <el-select v-model="form.category" placeholder="请选择电影类别">
<el-option label="Zone one" value="shanghai" />
<el-option label="Zone two" value="beijing" />
</el-select> -->
</el-form-item>
</el-col>
<el-col :span="16">
<el-form-item label="上映时间">
<el-date-picker
v-model="form.movieDate"
type="daterange"
align="right"
unlink-panels
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
:picker-options="pickerOptions"
style="width: 80%;"
/>
</el-form-item>
</el-col>
</el-row>
<el-form-item label="导演">
<el-tag
v-for="(tag,index) in form.movieDirectors"
:key="tag"
closable
effect="dark"
:disable-transitions="false"
:color="labelColor[index%labelColor.length]"
style="color: white;"
:hit="true"
@close="handleDirectorTagClose(tag)"
>
{{ tag }}
</el-tag>
<el-autocomplete
v-if="directorInputVisible"
ref="saveDirectorTagInput"
v-model="directorInputValue"
class="input-new-tag"
size="small"
:fetch-suggestions="directorSearchSuggest"
placeholder="请输入内容"
style="width: 20vw;"
clearable
@keyup.enter.native="handleDirectorInputConfirm(true)"
@select="handleDirectorSelect"
/>
<!-- <el-input
class="input-new-tag"
v-if="directorInputVisible"
v-model="directorInputValue"
ref="saveDirectorTagInput"
size="small"
@keyup.enter.native="handleDirectorInputConfirm"
@blur="handleDirectorInputConfirm"
> -->
<el-button
v-if="!directorInputVisible && form.movieDirectors.length<5"
class="button-new-tag"
size="small"
@click="showDirectorInput()"
>
添加导演
</el-button>
</el-form-item>
<el-form-item label="主演">
<el-tag
v-for="(tag,index) in form.movieMainActors"
:key="tag"
closable
effect="dark"
:disable-transitions="false"
:color="labelColor[index%labelColor.length]"
style="color: white;"
:hit="true"
@close="handleMainActorTagClose(tag)"
>
{{ tag }}
</el-tag>
<el-autocomplete
v-if="mainActorInputVisible"
ref="saveMainActorTagInput"
v-model="mainActorInputValue"
class="input-new-tag"
size="small"
:fetch-suggestions="actorSearchSuggest"
placeholder="请输入内容"
style="width: 20vw;"
clearable
@keyup.enter.native="handleMainActorInputConfirm"
@select="handleMainActorSelect"
/>
<!-- <el-input
class="input-new-tag"
v-if="mainActorInputVisible"
v-model="mainActorInputValue"
ref="saveMainActorTagInput"
size="small"
@keyup.enter.native="handleMainActorInputConfirm"
@blur="handleMainActorInputConfirm"
>
</el-input> -->
<el-button
v-if="!mainActorInputVisible && form.movieMainActors.length<5"
class="button-new-tag"
size="small"
@click="showMainActorInput()"
>
添加主演
</el-button>
</el-form-item>
<el-form-item label="演员">
<el-tag
v-for="(tag,index) in form.movieActors"
:key="tag"
closable
effect="dark"
:disable-transitions="false"
:color="labelColor[index%labelColor.length]"
style="color: white;"
:hit="true"
@close="handleActorTagClose(tag)"
>
{{ tag }}
</el-tag>
<el-autocomplete
v-if="actorInputVisible"
ref="saveActorTagInput"
v-model="actorInputValue"
class="input-new-tag"
size="small"
:fetch-suggestions="actorSearchSuggest"
placeholder="请输入内容"
style="width: 20vw;"
clearable
@keyup.enter.native="handleActorInputConfirm"
@select="handleActorSelect"
/>
<!-- <el-input
class="input-new-tag"
v-if="actorInputVisible"
v-model="actorInputValue"
ref="saveActorTagInput"
size="small"
@keyup.enter.native="handleActorInputConfirm"
@blur="handleActorInputConfirm"
>
</el-input> -->
<el-button
v-if="!actorInputVisible && form.movieActors.length<5"
class="button-new-tag"
size="small"
@click="showActorInput()"
>
添加演员
</el-button>
</el-form-item>
<el-form-item label="正面评价">
<el-progress type="dashboard" size="mini" :percentage="form.positive" :color="percentageColors"></el-progress>
<div>
<el-button-group>
<el-input-number v-model="form.positive" :min="0" :max="100" size="mini"></el-input-number>
</el-button-group>
</div>
</el-form-item>
<el-form-item label="评分">
<el-input-number
v-model="form.movieMinScore"
size="mini"
:precision="2"
:step="0.01"
:max="form.movieMaxScore"
:min="0"
/>
至
<el-input-number
v-model="form.movieMaxScore"
size="mini"
:precision="2"
:step="0.01"
:max="5"
:min="form.movieMinScore"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="searchMovie">查询</el-button>
<el-button @click="onCancel">取消</el-button>
</el-form-item>
</el-form>
</el-col>
<el-col :span="1">
<el-divider direction="vertical" />
</el-col>
<el-col :span="10">
<el-tabs v-model="activeName" @tab-click="handleClick">
<el-tab-pane label="查询结果" name="first">
<p v-if="hasResult ">
共有{{ movieNumber }}个结果
</p>
<el-table v-loading="movieLoading" height="460" border stripe :data="movieData" style="width: 100%">
<el-table-column type="expand">
<template slot-scope="props">
<el-form label-position="left" inline class="demo-table-expand">
<!-- <el-form-item>
<el-image src="https://m.media-amazon.com/images/I/81nbTAZ-p3S._SL1500_.jpg"
style="width: 30%;">
</el-image>
</el-form-item> -->
<el-form-item label="asin">
<span>{{ props.row.asin }}</span>
</el-form-item>
<el-form-item label="名称">
<span>{{ props.row.title }}</span>
</el-form-item>
<el-form-item label="版本">
<span>{{ props.row.edition }}</span>
</el-form-item>
<el-form-item label="格式">
<span>{{ props.row.format }}</span>
</el-form-item>
<el-form-item label="上映时间">
<span>{{ props.row.time }}</span>
</el-form-item>
<el-form-item label="正面评价">
<span>{{ props.row.positive }}</span>
</el-form-item>
<el-form-item label="负面评价">
<span>{{ props.row.negative }}</span>
</el-form-item>
<el-form-item v-if="props.row.director.length!==0" label="导演">
<span v-for="i in props.row.director">{{ i }}, </span>
</el-form-item>
<el-form-item v-if="props.row.mainActor.length!==0" label="主演">
<span v-for="i in props.row.mainActor">{{ i }}, </span>
</el-form-item>
<el-form-item v-if="props.row.actor.length!==0" label="演员">
<span v-for="i in props.row.actor">{{ i }}, </span>
</el-form-item>
<el-form-item label="评分">
<span>{{ props.row.score }}</span>
</el-form-item>
<el-form-item label="评论数量">
<span>{{ props.row.commentNum }}</span>
</el-form-item>
</el-form>
</template>
</el-table-column>
<el-table-column prop="asin" label="编号" width="120" />
<el-table-column prop="title" label="名称" width="250" />
<el-table-column prop="time" label="上映时间" />
</el-table>
</el-tab-pane>
<!-- <el-tab-pane label="数据血缘" name="second">
配置管理
</el-tab-pane> -->
<el-tab-pane label="速度对比" name="third"
:disabled="!graphReady || !distributeReady || !relationReady">
<ve-histogram
class="myve"
:data="chartData"
:settings="vchartsConfig.setting"
:extend="vchartsConfig.extend"
width="38vw"
/>
</el-tab-pane>
</el-tabs>
</el-col>
</el-row>
<el-divider />
<el-row>
<el-col :span="12">
<p style="margin-left: 3vw;color: #909399;font-size:8rew;font-weight: revert;">
{{ searchText }}
</p>
</el-col>
<el-col :span="3" style="text-align: center;">
<el-button
:disabled="!hasResult || movieData.length===0"
@click="downloadFile()"
>
导出csv
</el-button>
</el-col>
<el-col :span="3" style="text-align: center;">
<el-button
:disabled="movieData.length===0"
@click="clearResult()"
>
清空数据
</el-button>
</el-col>
<el-col :span="3" style="text-align: center;">
<el-button type="primary" plain @click="exampleTest()">
范例测试
</el-button>
</el-col>
</el-row>
</div>
</template>
<script>
import 'echarts/lib/component/title'
/* eslint-disable */
export default {
filters: {
},
data() {
return {
hasResult:false,
form: {
name: '',
region: '',
delivery: false,
type: [],
resource: '',
desc: '',
category:'',
movieDirectors:[],
movieMainActors:[],
movieActors:[],
actorName:'',
movieMinScore:0,
movieMaxScore:5.0,
movieDate:[],
positive:0,
},
percentageColors: [
{color: '#f56c6c', percentage: 20},
{color: '#e6a23c', percentage: 40},
{color: '#5cb87a', percentage: 60},
{color: '#1989fa', percentage: 80},
{color: '#6f7ad3', percentage: 100}
],
movieLoading:false,
labelColor:["#77C9D4","#57BC90","#015249"],
pickerOptions: {
disabledDate(time) {
return time.getTime() > Date.now();
},
shortcuts: [{
text: '最近一周',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近一个月',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
picker.$emit('pick', [start, end]);
}
}, {
text: '最近三个月',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
picker.$emit('pick', [start, end]);
}
},{
text: '最近半年',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 182);
picker.$emit('pick', [start, end]);
}
},
{
text: '最近一年',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
picker.$emit('pick', [start, end]);
}
},
{
text: '最近三年',
onClick(picker) {
const end = new Date();
const start = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 365 * 3);
picker.$emit('pick', [start, end]);
}
},
]
},
// 速度比较图
vchartsConfig: {
setting:{
// 别称
labelMap: {
'type': '数据库',
'software': '软件',
'speed': '速度',
},
},
extend: {
title:{
show:true,
text:'检索电影',
subtext:'通过关系型数据库MySql、分布式数据库Hive和图数据库Neo4j分别检索电影的速度对比',
// textAlign:'center',
},
// 图标顶部的标题及按钮
legend:{
show:false,
},
// backgroundColor:'red',//整个组件的背景颜色
//X轴线
xAxis: {
// name: "地区",
type:'category',
show:true,
// 坐标轴轴线
axisLine:{
show:false,
},
// 坐标轴刻度
// 坐标轴每项的文字
axisLabel:{
showMaxLabel:true,
showMinLabel:true,
color:'#3a3a3a',
rotate:0, //刻度文字旋转,防止文字过多不显示
margin:8,//文字离x轴的距离
boundaryGap:true,
// backgroundColor:'#0f0',
formatter:(v)=>{
// console.log('x--v',v)
return v
},
},
// X轴下面的刻度小竖线
axisTick:{
show:false,
alignWithLabel:true,//axisLabel.boundaryGap=true时有效
interval:0,
length:4,//长度
},
// x轴对应的竖线
splitLine: {
show: false,
interval: 0,
lineStyle:{
color:'red',
backgroundColor:'red',
}
}
},
yAxis: {
show:true,
offset:0,
// 坐标轴轴线
axisLine:{
show:false,
},
// x轴对应的竖线
splitLine: {
show: true,
},
// 坐标轴刻度
axisTick:{
show:false,
},
boundaryGap:true,
axisLabel:{
color:'#3a3a3a',
formatter:(v)=>{
if (v==0){
return v;
}
return v+' ms'
},
},
},
// 滚动组件参数
dataZoom:[
{
type: 'inside',
show: true,
xAxisIndex: [0],
startValue: 0,
endValue: 4,
zoomLock:true,//阻止区域缩放
}
],
// 每个柱子
series(v) {
// console.log("v", v);
// 设置柱子的样式
v.forEach(i => {
console.log("series", i);
i.barWidth = 30;
i.itemStyle={
barBorderRadius:[15,15,0,0],
borderWidth:20,
};
i.label={
color:'#666',
show:true,
position:'top',
// backgroundColor:'yellow',
};
});
return v;
},
}
},
// v-chats列表数据
chartData: {
columns: ["type","speed"],
rows: [
{ "type":"关系型数据库","software": "mysql", "speed": 0 },
{ "type":"分布式数据库","software": "hive", "speed": 0 },
{ "type":"图数据库","software": "neo4j", "speed": 0 },
],
},
directorInputVisible:false,
directorInputValue:'',
mainActorInputVisible:false,
mainActorInputValue:'',
actorInputVisible:false,
actorInputValue:'',
activeName: 'first',
searchText:'暂无查询',
BASE_URL:'http://localhost:8101',
HIVE_BASE_URL:'http://localhost:8102',
movieData:[],
categoryLoading:false,
movieCategory:[],
movieNumber:0,
relationReady:false,
distributeReady:false,
graphReady:false,
}
},
created() {
},
methods: {
onCancel() {
this.$message({
message: 'cancel!',
type: 'warning'
})
},
handleSelect(item) {
console.log(item);
},
handleDirectorSelect(item) {
this.handleDirectorInputConfirm(false)
},
handleMainActorSelect(item){
this.handleMainActorInputConfirm()
},
handleActorSelect(item){
this.handleActorInputConfirm()
},
/**
* 下面是搜索建议的函数
**/
movieSearchSuggest(queryString, cb){
var axios = require('axios');
var config = {
method: 'get',
url: this.BASE_URL+'/mysql/association/movie',
params:{"movieName":queryString},
headers: { }
};
// 向mysql 发送请求
axios(config)
.then(response=> {
console.log(response.data)
var result=[]
for(let i=0;i<response.data.length;++i){
result.push({"value":response.data[i]})
}
cb(result);
})
.catch(function (error) {
this.$message.error('当前网络异常,请稍后再试');
});
},
directorSearchSuggest(queryString, cb){
var axios = require('axios');
var config = {
method: 'get',
url: this.BASE_URL+'/mysql/association/director',
params:{"directorName":queryString},
headers: { }
};
// 向mysql 发送请求
axios(config)
.then(response=> {
var result=[]
for(let i=response.data.length-1;i>=0;--i){
if(result.length>=25){
break
}
result.push({"value":response.data[i]})
}
cb(result);
})
.catch(function (error) {
this.$message.error('当前网络异常,请稍后再试');
});
},
actorSearchSuggest(queryString, cb){
var axios = require('axios');
var config = {
method: 'get',
url: this.BASE_URL+'/mysql/association/actor',
params:{"actorName":queryString},
headers: { }
};
// 向mysql 发送请求
axios(config)
.then(response=> {
var result=[]
for(let i=response.data.length-1;i>=0;--i){
if(result.length>=25){
break
}
result.push({"value":response.data[i]})
}
cb(result);
})
.catch(function (error) {
this.$message.error('当前网络异常,请稍后再试');
});
},
categoryRemoteSearch(query){
this.categoryLoading = true;
// 发送api请求
var axios = require('axios');
var config = {
method: 'get',
url: this.BASE_URL+'/mysql/association/category',
params:{"category":query},
headers: { }
};
// 向mysql 发送请求
axios(config)
.then(response=> {
var result=[]
for(let i=response.data.length-1;i>=0;--i){
if(result.length>=25){
break
}
result.push({"value":response.data[i]})
}
this.movieCategory=result;
this.categoryLoading=false;
})
.catch(function (error) {
this.$message.error('当前网络异常,请稍后再试');
});
},
handleClick(tab, event) {
console.log(tab, event);
},
decrease(){
this.form.positive=this.form.positive>0?this.form.positive-1:this.form.positive
},
increase(){
this.form.positive=this.form.positive<100?this.form.positive+1:this.form.positive
},
movieDataToString(data) {
if (data.length == 0) {
return ""
}
var temp = "asin,title,edition,format,time,director,mainActor,actor,score,commentNum\n"
for (let j = 0; j < data.length; j++) {
let i = data[j]
temp += i.asin + ','
temp += i.title + ','
if (i.hasOwnProperty("edition")){
temp+=i.edition+','
}
else{
temp+=','
}
if (i.hasOwnProperty("format")){
temp+=i.format+','
}
else{
temp+=','
}
if (i.hasOwnProperty("time")){
temp+=i.time+','
}
else{
temp+=','
}
if (i.director.length!=0){
temp+=String(i.director)+','
}
else{
temp+=','
}
if (i.mainActor.length!=0){
temp+=String(i.mainActor)+','
}
else{
temp+=','
}
if (i.actor.length!=0){
temp+=String(i.actor)+','
}
else{
temp+=','
}
if (i.hasOwnProperty("score")){
temp+=i.score+','
}
else{
temp+=','
}
if (i.hasOwnProperty("commentNum")){
temp+=i.commentNum+','
}
else{
temp+=','
}
temp += '\n'
}
return temp;
},
downloadFile(){
var blob = new Blob([this.movieDataToString(this.movieData)], {type: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'});
const url3 = window.URL.createObjectURL(blob);
var filename = this.searchText + '.csv';
const link = document.createElement('a');
link.style.display = 'none';
link.href = url3;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
},
searchMovie(){
// 清空上一轮查询结果
this.clearResult();
// 跳转到查询结果界面
this.activeName='first'
Date.prototype.format = function(format)
{
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1 ? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
return format;
}
var searchText="查找"
var searchCondition={
}
if (this.form.name!=""){
searchText+=" 电影名为"+this.form.name+""
searchCondition.movieName=this.form.name
}
console.log(this.form)
if(this.form.movieDate!=null && this.form.movieDate.length!=0){
searchCondition.minYear=this.form.movieDate[0].format("yyyy")
searchCondition.minMonth=this.form.movieDate[0].format("MM")
searchCondition.minDay=this.form.movieDate[0].format("dd")
searchCondition.maxYear=this.form.movieDate[1].format("yyyy")
searchCondition.maxMonth=this.form.movieDate[1].format("MM")
searchCondition.maxDay=this.form.movieDate[1].format("dd")
searchText+=" 上映时间在"+searchCondition.minYear+"年"
+searchCondition.minMonth+"月"+searchCondition.minDay+"日"
+"到"+searchCondition.maxYear+"年"
+searchCondition.maxMonth+"月"+searchCondition.maxDay+"日之间"
}
if (this.form.category != ""){
searchText+=" 类别为"+this.form.category+""
searchCondition.category=this.form.category
}
if (this.form.movieDirectors.length!=0){
searchText+=" 导演有"
for(let i=0;i<this.form.movieDirectors.length;++i){
if (i!=0){
searchText+=", "
}
searchText+=this.form.movieDirectors[i]
}
searchCondition.directorNames=this.form.movieDirectors
}
if (this.form.movieMainActors.length!=0){
searchText+=" 主演有"
for(let i=0;i<this.form.movieMainActors.length;++i){
if (i!=0){
searchText+=", "
}
searchText+=this.form.movieMainActors[i]
}
searchCondition.mainActors=this.form.movieMainActors
}
if (this.form.movieActors.length!=0){
searchText+=" 演员有"
for(let i=0;i<this.form.movieActors.length;++i){
if (i!=0){
searchText+=", "
}
searchText+=this.form.movieActors[i]
}
searchCondition.actors=this.form.movieActors
}
if(this.form.movieMinScore!=0 || this.form.movieMaxScore!=5){
searchCondition.minScore=this.form.movieMinScore
searchCondition.maxScore=this.form.movieMaxScore
searchText+=" 评分在"+searchCondition.minScore+"到"+searchCondition.maxScore+"之间"
}
if(this.form.positive!=0){
searchCondition.positive=this.form.positive
searchText+=" 正面评价在"+searchCondition.positive+"之上"
}
// 设置参数
console.log("搜索条件为",searchCondition)
if(Object.keys(searchCondition).length==0){
this.$message({
message: '请至少给出一个条件!',
type: 'warning'
})
return
}
searchText+=" 的电影"
this.searchText=searchText
this.vchartsConfig.extend.title.subtext=searchText
this.relationReady=false
this.distributeReady=false
this.graphReady=false
// 发送api
var axios = require('axios');
var config = {
method: 'post',
url: this.BASE_URL+'/neo4j/movie',
data:searchCondition,
headers: { }
};
this.movieLoading=true;
// 向mysql发送请求,填入请求时间即可
axios({
method: 'post',
url: this.BASE_URL+'/mysql/association/movie/result',
data:searchCondition,
headers: { }
}).then(response=>{
this.chartData.rows[0].speed = response.data.time
this.relationReady=true
})
// 向hive发送请求
axios({
method:'post',
url: this.HIVE_BASE_URL+'/hive/movie/result',
data:searchCondition,
headers: { }
}).then(response=>{
this.chartData.rows[1].speed = response.data.time
this.distributeReady=true
})
// 向neo4j 发送请求
axios(config)
.then(response=> {
this.chartData.rows[2].speed=response.data.time
this.graphReady=true
console.log(response.data)
let movieList=response.data.movies
this.movieNumber = response.data.movieNum
for(let i=0;i<movieList.length;++i){
let newMovie = {}
newMovie.asin = movieList[i].asin
newMovie.title = movieList[i].title
if (movieList[i].hasOwnProperty("edition")) {
newMovie.edition = movieList[i].edition
}
if (movieList[i].hasOwnProperty("format")) {
newMovie.format = movieList[i].format
}
if (movieList[i].hasOwnProperty("score")) {
newMovie.score = movieList[i].score
}
if (movieList[i].hasOwnProperty("commentNum")) {
newMovie.commentNum = movieList[i].commentNum
}
if (movieList[i].hasOwnProperty("positive")) {
newMovie.positive = movieList[i].positive
}
if (movieList[i].hasOwnProperty("negative")) {
newMovie.negative = movieList[i].negative
}
var movieTime=""
if (movieList[i].hasOwnProperty("year")) {
movieTime += movieList[i].year+"年"
}
if (movieList[i].hasOwnProperty("month")) {
movieTime += movieList[i].month+"月"
}
if (movieList[i].hasOwnProperty("day")) {
movieTime += movieList[i].day+"日"
}
newMovie.time=movieTime
this.movieData.push(newMovie)
}
this.movieLoading=false;
// 发送api获取导演信息、主演信息、演员信息
for(let i=0;i<this.movieData.length;++i){
axios({
method: 'get',
url: this.BASE_URL + '/mysql/association/movie/director',
params:{"movieAsin":this.movieData[i].asin, "index": i},
headers: {}
})
.then(response => {
this.movieData[response.data.index].director=response.data.director
})
axios({
method: 'get',
url: this.BASE_URL + '/mysql/association/movie/mainActor',
params:{"movieAsin":this.movieData[i].asin, "index": i},
headers: {}
})
.then(response => {
this.movieData[response.data.index].mainActor=response.data.mainActor
})
axios({
method: 'get',
url: this.BASE_URL + '/mysql/association/movie/actor',
params:{"movieAsin":this.movieData[i].asin, "index": i},
headers: {}
})
.then(response => {
this.movieData[response.data.index].actor=response.data.actor
})
}
})
.catch(error=> {
this.$message.error('当前网络异常,请稍后再试');
});
this.hasResult = true;
},
clearResult(){
this.movieData.splice(0,this.movieData.length)
this.hasResult=false
this.movieLoading=false
for(let i=0;i<3;++i){
this.chartData.rows[i].speed=0
}
this.searchText="暂无查询"
},
/**
* 下面是处理标签的函数
**/
showDirectorInput() {
this.directorInputVisible = true;
this.$nextTick(_ => {
this.$refs.saveDirectorTagInput.$refs.input.focus();
});
},
handleDirectorInputConfirm(showMessage) {
let inputValue = this.directorInputValue
// 有效性判断
if (!inputValue || inputValue.replace(/\s*/g,"").length==0) {
if(!this.directorInputVisible){
return;
}
if(showMessage){
this.$message({
message: '请输入有效的导演名称!',
type: 'warning'
})
this.directorInputVisible=false;
}
return;
}
this.form.movieDirectors.push(inputValue.replace(/^\s*|\s*$/g,""));
this.directorInputVisible = false;
this.directorInputValue = '';
},
handleDirectorTagClose(tag) {
this.form.movieDirectors.splice(this.form.movieDirectors.indexOf(tag), 1);
},
showMainActorInput() {
this.mainActorInputVisible = true;
this.$nextTick(_ => {
this.$refs.saveMainActorTagInput.$refs.input.focus();
});
},
handleMainActorInputConfirm() {
let inputValue = this.mainActorInputValue
// 有效性判断
if (!inputValue || inputValue.replace(/\s*/g,"").length==0) {
if(!this.mainActorInputVisible){
return;
}
this.$message({
message: '请输入有效的主演名称!',
type: 'warning'
})
this.mainActorInputVisible=false;
return;
}
this.form.movieMainActors.push(inputValue.replace(/^\s*|\s*$/g,""));
this.mainActorInputVisible = false;
this.mainActorInputValue = '';
},
handleMainActorTagClose(tag) {
this.form.movieMainActors.splice(this.form.movieMainActors.indexOf(tag), 1);
},
showActorInput() {
this.actorInputVisible = true;
this.$nextTick(_ => {
this.$refs.saveActorTagInput.$refs.input.focus();
});
},
handleActorInputConfirm() {
let inputValue = this.actorInputValue
// 有效性判断
if (!inputValue || inputValue.replace(/\s*/g,"").length==0) {
if(!this.actorInputVisible){
return;
}
this.$message({
message: '请输入有效的演员名称!',
type: 'warning'
})
this.actorInputVisible=false;
return;
}
this.form.movieActors.push(inputValue.replace(/^\s*|\s*$/g,""));
this.actorInputVisible = false;
this.actorInputValue = '';
},
handleActorTagClose(tag) {
this.form.movieActors.splice(this.form.movieActors.indexOf(tag), 1);
},
exampleTest(){
this.form.category='Comedy';
this.form.movieMinScore=2.5;
this.searchMovie();
},
}
}
</script>
<style scoped>
.el-tag + .el-tag {
margin-left: 10px;
}
.button-new-tag {
margin-left: 10px;
height: 32px;
line-height: 30px;
padding-top: 0;
padding-bottom: 0;
}
.input-new-tag {
width: 90px;
margin-left: 10px;
vertical-align: bottom;
}
.el-divider--vertical{
height:75vh;
}
.demo-table-expand {
font-size: 0;
}
.demo-table-expand label {
width: 90px;
color: #99a9bf;
}
.demo-table-expand .el-form-item {
margin-right: 0;
margin-bottom: 0;
width: 100%;
}
</style> |
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2019-2020 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package install
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/snapcore/snapd/gadget"
"github.com/snapcore/snapd/gadget/quantity"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/disks"
"github.com/snapcore/snapd/strutil"
)
var (
ensureNodesExist = ensureNodesExistImpl
)
// reloadPartitionTable reloads the partition table depending on what the gadget
// says - if the gadget has a special marker file, then we will use a special
// reload mechanism, implemented for a specific device.
func reloadPartitionTable(gadgetRoot string, device string) error {
if osutil.FileExists(filepath.Join(gadgetRoot, "meta", "force-partition-table-reload-via-device-rescan")) {
// TODO: remove this method when we are able to, this exists for a very
// specific device + kernel combination which is not compatible with
// using partx and so instead we must use this rescan trick
return reloadPartitionTableWithDeviceRescan(device)
} else {
// use partx like normal
return reloadPartitionTableWithPartx(device)
}
}
type CreateOptions struct {
// The gadget root dir
GadgetRootDir string
// Create all missing partitions. If unset only
// role-{data,boot,save} partitions will get created and it's
// an error if other partition are missing.
CreateAllMissingPartitions bool
}
// CreateMissingPartitions calls createMissingPartitions but returns only
// OnDiskStructure, as it is meant to be used externally (i.e. by
// muinstaller).
func CreateMissingPartitions(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume, opts *CreateOptions) ([]gadget.OnDiskStructure, error) {
odlsStructures, err := createMissingPartitions(dl, pv, opts)
if err != nil {
return nil, err
}
onDiskStructures := []gadget.OnDiskStructure{}
for _, odls := range odlsStructures {
onDiskStructures = append(onDiskStructures, *odls.onDisk)
}
return onDiskStructures, nil
}
// createMissingPartitions creates the partitions listed in the laid out volume
// pv that are missing from the existing device layout, returning a list of
// structures that have been created.
func createMissingPartitions(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume, opts *CreateOptions) ([]onDiskAndLaidoutStructure, error) {
if opts == nil {
opts = &CreateOptions{}
}
buf, created, err := buildPartitionList(dl, pv, opts)
if err != nil {
return nil, err
}
if len(created) == 0 {
return created, nil
}
logger.Debugf("create partitions on %s: %s", dl.Device, buf.String())
// Write the partition table. By default sfdisk will try to re-read the
// partition table with the BLKRRPART ioctl but will fail because the
// kernel side rescan removes and adds partitions and we have partitions
// mounted (so it fails on removal). Use --no-reread to skip this attempt.
cmd := exec.Command("sfdisk", "--append", "--no-reread", dl.Device)
cmd.Stdin = buf
if output, err := cmd.CombinedOutput(); err != nil {
return created, osutil.OutputErr(output, err)
}
// Re-read the partition table
if err := reloadPartitionTable(opts.GadgetRootDir, dl.Device); err != nil {
return nil, err
}
// run udevadm settle to wait for udev events that may have been triggered
// by reloading the partition table to be processed, as we need the udev
// database to be freshly updated
if out, err := exec.Command("udevadm", "settle", "--timeout=180").CombinedOutput(); err != nil {
return nil, fmt.Errorf("cannot wait for udev to settle after reloading partition table: %v", osutil.OutputErr(out, err))
}
// Make sure the devices for the partitions we created are available
if err := ensureNodesExist(created, 5*time.Second); err != nil {
return nil, fmt.Errorf("partition not available: %v", err)
}
return created, nil
}
// buildPartitionList builds a list of partitions based on the current
// device contents and gadget structure list, in sfdisk dump format, and
// returns a partitioning description suitable for sfdisk input and a
// list of the partitions to be created.
func buildPartitionList(dl *gadget.OnDiskVolume, pv *gadget.LaidOutVolume, opts *CreateOptions) (sfdiskInput *bytes.Buffer, toBeCreated []onDiskAndLaidoutStructure, err error) {
if opts == nil {
opts = &CreateOptions{}
}
sectorSize := uint64(dl.SectorSize)
// Keep track what partitions we already have on disk - the keys to this map
// is the starting sector of the structure we have seen.
// TODO: use quantity.SectorOffset or similar when that is available
seen := map[uint64]bool{}
for _, s := range dl.Structure {
start := uint64(s.StartOffset) / sectorSize
seen[start] = true
}
// Check if the last partition has a system-data role
canExpandData := false
if n := len(pv.LaidOutStructure); n > 0 {
last := pv.LaidOutStructure[n-1]
if last.Role() == gadget.SystemData {
canExpandData = true
}
}
// The partition / disk index - note that it will start at 1, we increment
// it before we use it in the loop below
pIndex := 0
// Write new partition data in named-fields format
buf := &bytes.Buffer{}
for _, p := range pv.LaidOutStructure {
// Make loop var per-iter as we store the pointer in the results
p := p
if !p.IsPartition() {
continue
}
pIndex++
s := p.VolumeStructure
// Skip partitions that are already in the volume
startInSectors := uint64(p.StartOffset) / sectorSize
if seen[startInSectors] {
continue
}
// Only allow creating certain partitions, namely the ubuntu-* roles
if !opts.CreateAllMissingPartitions && !gadget.IsCreatableAtInstall(p.VolumeStructure) {
return nil, nil, fmt.Errorf("cannot create partition %s", p)
}
// Check if the data partition should be expanded
newSizeInSectors := uint64(s.Size) / sectorSize
if s.Role == gadget.SystemData && canExpandData && startInSectors+newSizeInSectors < dl.UsableSectorsEnd {
// note that if startInSectors + newSizeInSectors == dl.UsableSectorEnd
// then we won't hit this branch, but it would be redundant anyways
newSizeInSectors = dl.UsableSectorsEnd - startInSectors
}
ptype := partitionType(dl.Schema, p.Type())
// synthesize the node name and on disk structure
node := deviceName(dl.Device, pIndex)
ps := onDiskAndLaidoutStructure{
onDisk: &gadget.OnDiskStructure{
Name: p.Name(),
PartitionFSLabel: p.Label(),
Type: p.Type(),
PartitionFSType: p.Filesystem(),
StartOffset: p.StartOffset,
Node: node,
DiskIndex: pIndex,
Size: quantity.Size(newSizeInSectors * sectorSize),
},
laidOut: &p,
}
// format sfdisk input for creating this partition
fmt.Fprintf(buf, "%s : start=%12d, size=%12d, type=%s, name=%q\n", node,
startInSectors, newSizeInSectors, ptype, s.Name)
toBeCreated = append(toBeCreated, ps)
}
return buf, toBeCreated, nil
}
func partitionType(label, ptype string) string {
t := strings.Split(ptype, ",")
if len(t) < 1 {
return ""
}
if len(t) == 1 {
return t[0]
}
if label == "gpt" {
return t[1]
}
return t[0]
}
func deviceName(name string, index int) string {
if len(name) > 0 {
last := name[len(name)-1]
if last >= '0' && last <= '9' {
return fmt.Sprintf("%sp%d", name, index)
}
}
return fmt.Sprintf("%s%d", name, index)
}
// removeCreatedPartitions removes partitions added during a previous install.
func removeCreatedPartitions(gadgetRoot string, lv *gadget.LaidOutVolume, dl *gadget.OnDiskVolume) error {
sfdiskIndexes := make([]string, 0, len(dl.Structure))
// up to 3 possible partitions are creatable and thus removable:
// ubuntu-data, ubuntu-boot, and ubuntu-save
deletedIndexes := make(map[int]bool, 3)
for i, s := range dl.Structure {
if wasCreatedDuringInstall(lv, s) {
logger.Noticef("partition %s was created during previous install", s.Node)
sfdiskIndexes = append(sfdiskIndexes, strconv.Itoa(i+1))
deletedIndexes[i] = true
}
}
if len(sfdiskIndexes) == 0 {
return nil
}
// Delete disk partitions
logger.Debugf("delete disk partitions %v", sfdiskIndexes)
cmd := exec.Command("sfdisk", append([]string{"--no-reread", "--delete", dl.Device}, sfdiskIndexes...)...)
if output, err := cmd.CombinedOutput(); err != nil {
return osutil.OutputErr(output, err)
}
// Reload the partition table - note that this specifically does not trigger
// udev events to remove the deleted devices, see the doc-comment below
if err := reloadPartitionTable(gadgetRoot, dl.Device); err != nil {
return err
}
// Remove the partitions we deleted from the OnDiskVolume - note that we
// specifically don't try to just re-build the OnDiskVolume since doing
// so correctly requires using only information from the partition table
// we just updated with sfdisk (since we used --no-reread above, and we can't
// really tell the kernel to re-read the partition table without hitting
// EBUSY as the disk is still mounted even though the deleted partitions
// were deleted), but to do so would essentially just be testing that sfdisk
// updated the partition table in a way we expect. The partition parsing
// code we use to build the OnDiskVolume also must not be reliant on using
// sfdisk (since it has to work in the initrd where we don't have sfdisk),
// so either that code would just be a duplication of what sfdisk is doing
// or that code would fail to update the deleted partitions anyways since
// at this point the only thing that knows about the deleted partitions is
// the physical partition table on the disk.
newStructure := make([]gadget.OnDiskStructure, 0, len(dl.Structure)-len(deletedIndexes))
for i, structure := range dl.Structure {
if !deletedIndexes[i] {
newStructure = append(newStructure, structure)
}
}
dl.Structure = newStructure
// Ensure all created partitions were removed
if remaining := createdDuringInstall(lv, dl); len(remaining) > 0 {
return fmt.Errorf("cannot remove partitions: %s", strings.Join(remaining, ", "))
}
return nil
}
func partitionsWithRolesAndContent(lv *gadget.LaidOutVolume, dl *gadget.OnDiskVolume, roles []string) []onDiskAndLaidoutStructure {
roleForOffset := map[quantity.Offset]*gadget.LaidOutStructure{}
for idx, gs := range lv.LaidOutStructure {
if gs.Role() != "" {
roleForOffset[gs.StartOffset] = &lv.LaidOutStructure[idx]
}
}
var odloStructures []onDiskAndLaidoutStructure
for _, part := range dl.Structure {
// Create per-iter var from loop variable as we store the pointer in odls
part := part
gs := roleForOffset[part.StartOffset]
if gs == nil || gs.Role() == "" || !strutil.ListContains(roles, gs.Role()) {
continue
}
// now that we have a match, set the laid out structure such
// that the fields reflect what was declared in the gadget, the
// on-disk-structure already has the right size as read from the
// partition table
odls := onDiskAndLaidoutStructure{
onDisk: &part,
laidOut: gs,
}
odloStructures = append(odloStructures, odls)
}
return odloStructures
}
// ensureNodeExists makes sure the device nodes for all device structures are
// available and notified to udev, within a specified amount of time.
func ensureNodesExistImpl(odloStructures []onDiskAndLaidoutStructure, timeout time.Duration) error {
t0 := time.Now()
for _, odls := range odloStructures {
found := false
for time.Since(t0) < timeout {
if osutil.FileExists(odls.onDisk.Node) {
found = true
break
}
time.Sleep(100 * time.Millisecond)
}
if found {
if err := udevTrigger(odls.onDisk.Node); err != nil {
return err
}
} else {
return fmt.Errorf("device %s not available", odls.onDisk.Node)
}
}
return nil
}
// reloadPartitionTableWithDeviceRescan instructs the kernel to re-read the
// partition table of a given block device via a workaround proposed for a
// specific device in the form of executing the equivalent of:
// bash -c "echo 1 > /sys/block/sd?/device/rescan"
func reloadPartitionTableWithDeviceRescan(device string) error {
disk, err := disks.DiskFromDeviceName(device)
if err != nil {
return err
}
rescanFile := filepath.Join(disk.KernelDevicePath(), "device", "rescan")
logger.Noticef("reload partition table via rescan file %s for device %s as indicated by gadget", rescanFile, device)
f, err := os.OpenFile(rescanFile, os.O_WRONLY, 0644)
if err != nil {
return err
}
defer f.Close()
// this could potentially fail with strange sysfs errno's since rescan isn't
// a real file
if _, err := f.WriteString("1\n"); err != nil {
return fmt.Errorf("unable to trigger reload with rescan file: %v", err)
}
return nil
}
// reloadPartitionTableWithPartx instructs the kernel to re-read the partition
// table of a given block device.
func reloadPartitionTableWithPartx(device string) error {
// Re-read the partition table using the BLKPG ioctl, which doesn't
// remove existing partitions, only appends new partitions with the right
// size and offset. As long as we provide consistent partitioning from
// userspace we're safe.
output, err := exec.Command("partx", "-u", device).CombinedOutput()
if err != nil {
return osutil.OutputErr(output, err)
}
return nil
}
// udevTrigger triggers udev for the specified device and waits until
// all events in the udev queue are handled.
func udevTrigger(device string) error {
if output, err := exec.Command("udevadm", "trigger", "--settle", device).CombinedOutput(); err != nil {
return osutil.OutputErr(output, err)
}
return nil
}
// wasCreatedDuringInstall returns if the OnDiskStructure was created during
// install by referencing the gadget volume. A structure is only considered to
// be created during install if it is a role that is created during install and
// the start offsets match. We specifically don't look at anything on the
// structure such as filesystem information since this may be incomplete due to
// a failed installation, or due to the partial layout that is created by some
// ARM tools (i.e. ptool and fastboot) when flashing images to internal MMC.
func wasCreatedDuringInstall(lv *gadget.LaidOutVolume, s gadget.OnDiskStructure) bool {
// for a structure to have been created during install, it must be one of
// the system-boot, system-data, or system-save roles from the gadget, and
// as such the on disk structure must exist in the exact same location as
// the role from the gadget, so only return true if the provided structure
// has the exact same StartOffset as one of those roles
for _, gs := range lv.LaidOutStructure {
// TODO: how to handle ubuntu-save here? maybe a higher level function
// should decide whether to delete it or not?
switch gs.Role() {
case gadget.SystemSave, gadget.SystemData, gadget.SystemBoot:
// then it was created during install or is to be created during
// install, see if the offset matches the provided on disk structure
// has
if s.StartOffset == gs.StartOffset {
return true
}
}
}
return false
}
// createdDuringInstall returns a list of partitions created during the
// install process.
func createdDuringInstall(lv *gadget.LaidOutVolume, layout *gadget.OnDiskVolume) (created []string) {
created = make([]string, 0, len(layout.Structure))
for _, s := range layout.Structure {
if wasCreatedDuringInstall(lv, s) {
created = append(created, s.Node)
}
}
return created
} |
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/users');
const { JWT_SECRET_KEY } = require('../config');
const NotFoundError = require('../errors/notFoundError');
const ConflictError = require('../errors/conflictError');
module.exports.getUsers = (req, res) => {
User.find({})
.then((users) => res.send({ data: users }))
.catch(() => res.status(500).send({ message: 'Произошла ошибка' }));
};
module.exports.createUser = (req, res) => {
const {
name, about, avatar, email, password,
} = req.body;
User.countDocuments({ email })
.then((count) => {
if (count) throw new ConflictError('Пользователь с таким email уже существует в базе');
return bcrypt.hash(password, 10)
.then((hash) => User.create({
name,
about,
avatar,
email,
password: hash,
}))
.then((user) => res.send({ data: user.omitPrivate() }));
})
.catch((err) => {
const statusCode = err.statusCode || 500;
const message = statusCode === 500 ? 'Произошла ошибка' : err.message;
res.status(statusCode).send({ message });
});
};
module.exports.getUser = (req, res) => {
User.findById(req.params.userId)
.orFail(() => new NotFoundError('Нет пользователя с таким id'))
.then((user) => {
res.send({ data: user });
})
.catch((err) => {
const statusCode = err.statusCode || 500;
const message = statusCode === 500 ? 'Произошла ошибка' : err.message;
res.status(statusCode).send({ message });
});
};
module.exports.modifyUser = (req, res) => {
const { name, about } = req.body;
User.findByIdAndUpdate(req.user._id, { name, about }, { runValidators: true, new: true })
.then((user) => res.send({ data: user }))
.catch(() => res.status(500).send({ message: 'Произошла ошибка' }));
};
module.exports.modifyAvatar = (req, res) => {
const { avatar } = req.body;
User.findByIdAndUpdate(req.user._id, { avatar }, { runValidators: true, new: true })
.then((user) => {
res.send({ data: user });
})
.catch(() => res.status(500).send({ message: 'Произошла ошибка' }));
};
module.exports.login = (req, res) => {
const { email, password } = req.body;
return User.findUserByCredentials(email, password)
.then((user) => {
const token = jwt.sign({ _id: user._id }, JWT_SECRET_KEY, { expiresIn: '7d' });
res.send({ token });
})
.catch((err) => {
const statusCode = err.statusCode || 500;
const message = statusCode === 500 ? 'Произошла ошибка' : err.message;
res.status(statusCode).send({ message });
});
}; |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ThroneGame.Utils;
namespace ThroneGame.Tiles
{
/// <summary>
/// Represents a tile in the game.
/// </summary>
public class Tile : ITile
{
/// <summary>
/// Gets or sets the position of the tile.
/// </summary>
public Vector2 Position { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the tile is collidable.
/// </summary>
public bool IsCollidable { get; set; }
/// <summary>
/// Gets or sets the width of the tile.
/// </summary>
public int Width { get; set; }
/// <summary>
/// Gets or sets the height of the tile.
/// </summary>
public int Height { get; set; }
/// <summary>
/// Gets or sets the bounds of the tile.
/// </summary>
public Rectangle Bounds { get; set; }
/// <summary>
/// Gets or sets the velocity of the tile. (Not used as tiles are static)
/// </summary>
public Vector2 Velocity { get; set; }
/// <summary>
/// Gets or sets the mass of the tile. (Not used as tiles are static)
/// </summary>
public float Mass { get; set; }
private readonly Texture2D _texture;
private readonly Rectangle _sourceRectangle;
/// <summary>
/// Initializes a new instance of the <see cref="Tile"/> class with the specified parameters.
/// </summary>
/// <param name="texture">The texture of the tile.</param>
/// <param name="sourceRectangle">The source rectangle of the tile in the texture.</param>
/// <param name="isCollidable">Whether the tile is collidable.</param>
/// <param name="position">The position of the tile.</param>
/// <param name="width">The width of the tile.</param>
/// <param name="height">The height of the tile.</param>
public Tile(Texture2D texture, Rectangle sourceRectangle, bool isCollidable, Vector2 position, int width, int height)
{
_texture = texture;
_sourceRectangle = sourceRectangle;
IsCollidable = isCollidable;
Position = position;
Width = width;
Height = height;
}
/// <summary>
/// Updates the tile's state. (Not used as tiles are static)
/// </summary>
/// <param name="gameTime">The game time information.</param>
public void Update(GameTime gameTime)
{
// Do nothing as tiles are static
}
/// <summary>
/// Draws the tile using the specified sprite batch.
/// </summary>
/// <param name="spriteBatch">The sprite batch used for drawing.</param>
public void Draw(SpriteBatch spriteBatch, SpriteFont font = null)
{
spriteBatch.Draw(_texture, Position, _sourceRectangle, Color.White);
Bounds = new Rectangle((int)Position.X, (int)Position.Y, Width, Height);
if (this.IsCollidable) TextureUtils.DebugBorder(spriteBatch, Bounds.X, Bounds.Y, Bounds.Width, Bounds.Height);
}
/// <summary>
/// Destroys the tile. This method should be overridden by derived classes to implement destruction logic.
/// </summary>
public void Destroy()
{
// TODO: Implement destruction logic
}
}
} |
import requests
from PIL import Image, ImageOps
import numpy as np
from keras.models import load_model
from io import BytesIO # BytesIO를 임포트합니다.
import os
def predict_cloth(classification, img_url):
# Disable scientific notation for clarity
np.set_printoptions(suppress=True)
current_dir = os.path.dirname(__file__)
model_dir = os.path.join(current_dir, 'KerasModels')
predict_file_path = {
"Top": ["keras_model_top.h5", "labels_top.txt"],
"Bottom": ["keras_model_bottom.h5", "labels_bottom.txt"],
"Outer": ["keras_model_outer.h5", "labels_outer.txt"],
"Shoes": ["keras_model_shoes.h5", "labels_shoes.txt"],
"Hat": ["keras_model_hat.h5", "labels_hat.txt"]
}
# part classification model's load
model_file = predict_file_path[classification][0]
model_path = os.path.join(model_dir, model_file)
model = load_model(model_path, compile=False)
# label load
label_file = predict_file_path[classification][1]
label_path = os.path.join(model_dir, label_file)
class_names = open(label_path, "rt", encoding="UTF-8").readlines()
# Create the array of the right shape to feed into the keras model
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
response = requests.get(img_url)
image_data = response.content
image = Image.open(BytesIO(image_data)).convert("RGB")
# resizing the image to be at least 224x224 and then cropping from the center
size = (224, 224)
image = ImageOps.fit(image, size, Image.LANCZOS)
# turn the image into a numpy array
image_array = np.asarray(image)
# Normalize the image
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
# Load the image into the array
data[0] = normalized_image_array
# Predicts the model
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index]
confidence_score = prediction[0][index]
# Unlock stack memory
del image
style_list = {
"Top" : ["캐주얼 상의\n", "고프고어 상의\n", "포멀 상의\n", "스포티 상의\n", "레트로 상의\n"],
"Bottom": ["캐주얼 하의\n", "고프코어 하의\n", "포멀 하의\n", "스포티 하의\n", "레트로 하의\n"],
"Outer": ["캐주얼 아우터\n", "고프코어 아우터\n", "포멀 아우터\n", "스포티 아우터\n", "레트로 아우터\n"],
"Shoes": ["캐주얼 신발\n", "고프코어 신발\n", "포멀 신발\n", "스포티 신발\n", "레트로 신발\n"],
"Hat": ["캐주얼 모자\n", "고프코어 모자\n", "포멀 모자\n", "스포티 모자\n", "레트로 모자\n"]
}
return img_url, style_list[classification].index(class_name[2:]), str(confidence_score) |
<h1 align=center>Hugo PaperMod | <a href="https://adityatelange.github.io/hugo-PaperMod/" rel="nofollow">Demo</a></h1>
<h4 align=center>☄️ Fast | ☁️ Fluent | 🌙 Smooth | 📱 Responsive</h4>
<br>
> Hugo PaperMod is a theme based on [hugo-paper](https://github.com/nanxiaobei/hugo-paper).
> The goal of this project is to add more features and customization to the og theme.
The [demo](https://adityatelange.github.io/hugo-PaperMod/) includes a lot of documentation about Installation, Features with a few more stuff. Make sure you visit it, to get an awesome hands-on experience and get to know about the features ...
**ExampleSite** can be found here: [exampleSite](https://github.com/adityatelange/hugo-PaperMod/tree/exampleSite). Demo is built up with [exampleSite](https://github.com/adityatelange/hugo-PaperMod/tree/exampleSite) as source.
[](https://github.com/gohugoio/hugo/releases/tag/v0.83.0)
[](https://github.com/adityatelange/hugo-PaperMod/deployments/activity_log?environment=github-pages)
[](https://github.com/adityatelange/hugo-PaperMod/blob/master/LICENSE)
[](https://themes.gohugo.io/themes/hugo-papermod/)
[](https://sonarcloud.io/dashboard?id=adityatelange_hugo-PaperMod)

---
<p align="center">
<kbd><img src="https://user-images.githubusercontent.com/21258296/114303440-bfc0ae80-9aeb-11eb-8cfa-48a4bb385a6d.png" alt="Mockup image" title="Mockup"/></kbd>
</p>
---
## Features/Mods 💥
- Uses Hugo's asset generator with pipelining, fingerprinting, bundling and minification by default.
- 3 Modes:
- [Regular Mode.](https://github.com/adityatelange/hugo-PaperMod/wiki/Features#regular-mode-default-mode)
- [Home-Info Mode.](https://github.com/adityatelange/hugo-PaperMod/wiki/Features#home-info-mode)
- [Profile Mode.](https://github.com/adityatelange/hugo-PaperMod/wiki/Features#profile-mode)
- Table of Content Generation (newer implementation).
- Archive of posts.
- Social Icons (home-info and profile-mode)
- Social-Media Share buttons on posts.
- Menu location indicator.
- Multilingual support. (with language selector)
- Taxonomies
- Cover image for each post (with Responsive image support).
- Light/Dark theme (automatic theme switch a/c to browser theme and theme-switch button).
- SEO Friendly.
- Multiple Author support.
- Search Page with Fuse.js
- Other Posts suggestion below a post
- Breadcrumb Navigation
- Code Block Copy buttons
- No webpack, nodejs and other dependencies are required to edit the theme.
Read Wiki For More Details => **[PaperMod - Features](https://github.com/adityatelange/hugo-PaperMod/wiki/Features)**
---
## Install/Update 📥
Read Wiki For More Details => **[PaperMod - Installation](https://github.com/adityatelange/hugo-PaperMod/wiki/Installation)**
---
## Social-Icons/Share-Icons 🖼️
Read Wiki For More Details => **[PaperMod-Icons](https://github.com/adityatelange/hugo-PaperMod/wiki/Icons)**
---
## FAQs / How To's Guide 🙋
Read Wiki For More Details => **[PaperMod-FAQs](https://github.com/adityatelange/hugo-PaperMod/wiki/FAQs)**
---
## Release Changelog
Release ChangeLog has info about stuff added: **[Releases](https://github.com/adityatelange/hugo-PaperMod/releases)**
---
## [Pagespeed Insights (100% ?)](https://pagespeed.web.dev/report?url=https://adityatelange.github.io/hugo-PaperMod/)
---
## Special Thanks 🌟
- [**Highlight.js**](https://github.com/highlightjs/highlight.js)
- [**Fuse.js**](https://github.com/krisk/fuse)
- [**Feather Icons**](https://github.com/feathericons/feather)
- [**Simple Icons**](https://github.com/simple-icons/simple-icons)
- **All Contributors and Supporters** |
import React, { Component } from 'react'
import {ProductConsumer} from "../context";
import {Link} from "react-router-dom";
import {ButtonContainer} from "./Button";
export default class Details extends Component {
render() {
return (
<ProductConsumer>
{(value)=>{
const {id,company,img,info,info2,info3,price,title,inCart} = value.detailProduct;
return(
<div className="container py-5">
<div className="row">
<div className="col-10 mx-auto text-center text-slanted text-blue my-5">
<h1>{title}</h1>
</div>
</div>
<div className="row">
<div className="col-10 mx-auto col-md-6 my-3">
<img src={img} className="img-fluid" alt="product"/>
</div>
<div className="col-10 mx-auto col-md-6 my-3 text-capitalize">
<h3>model : {title}</h3>
<h4 className="text-title text-uppercase text-muted mt-3 mb-2">
proizvajalec : <span className="text-uppercase">
{company}</span>
</h4>
<h4 className="text-blue">
<strong>
cena : {price}<span>€</span>
</strong>
</h4>
<p className="text-capitalize font-weight-bold mt-3 mb-0">
informacije o izdelku:
</p>
<p className="text-muted lead">{info}</p>
<p className="text-muted lead">{info2}</p>
<p className="text-muted lead">{info3}</p>
<div>
<Link to="/">
<ButtonContainer>nazaj na izdelke</ButtonContainer>
</Link>
<ButtonContainer
cart
disabled={inCart?true:false}
onClick={()=>{
value.addToCart(id);
value.openModal(id);
}}>
{inCart?"v košarici": "dodaj v košarico"}
</ButtonContainer>
</div>
</div>
</div>
</div>
)
}}
</ProductConsumer>
)
}
} |
#!/usr/bin/env python3
import os
import re
import sys
import subprocess
import binascii
# Testing pyaxmlparser existence
try:
import pyaxmlparser
except:
print("Error: >pyaxmlparser< module not found.")
sys.exit(1)
# Testing puremagic existence
try:
import puremagic as pr
except:
print("Error: >puremagic< module not found.")
sys.exit(1)
# Testing rich existence
try:
from rich import print
from rich.table import Table
except:
print("Error: >rich< module not found.")
sys.exit(1)
# Disabling pyaxmlparser's logs
pyaxmlparser.core.log.disabled = True
# Legends
infoS = f"[bold cyan][[bold red]*[bold cyan]][white]"
errorS = f"[bold cyan][[bold red]![bold cyan]][white]"
# Configurating strings parameter
if sys.platform == "darwin":
strings_param = "-a"
else:
strings_param = "--all"
class ResourceScanner:
def __init__(self, target_file):
self.target_file = target_file
def check_target_os(self):
fileType = str(pr.magic_file(self.target_file))
if "PK" in fileType and "Java archive" in fileType:
print(f"{infoS} Target OS: [bold green]Android[white]\n")
return "file_android"
elif "Windows Executable" in fileType:
print(f"{infoS} Target OS: [bold green]Windows[white]\n")
return "file_windows"
else:
return None
def android_resource_scanner(self):
# Categories
categs = {
"Presence of Tor": [], "URLs": [], "IP Addresses": []
}
# Wordlists for analysis
dictionary = {
"Presence of Tor": [
"obfs4",
"iat-mode=",
"meek_lite",
"found_existing_tor_process",
"newnym"
],
"URLs": [
r"http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+"
],
"IP Addresses": [
r'[0-9]+(?:\.[0-9]+){3}:[0-9]+',
"localhost"
]
}
# Tables!!
countTable = Table()
countTable.add_column("File Type", justify="center")
countTable.add_column("File Name", justify="center")
fileTable = Table()
fileTable.add_column("Interesting Files", justify="center")
# Lets begin!
print(f"{infoS} Parsing file contents...\n")
apk = pyaxmlparser.APK(self.target_file)
# Try to find something juicy
empty = {}
ftypes = apk.get_files_types()
for typ in ftypes:
if ftypes[typ] not in empty.keys():
empty.update({ftypes[typ]: []})
for fl in ftypes:
empty[ftypes[fl]].append(fl)
# Count file types
for fl in empty:
if "image" in fl: # Just get rid of them
pass
elif "Dalvik" in fl or "C++ source" in fl or "C source" in fl or "ELF" in fl or "Bourne-Again shell" in fl or "executable" in fl or "JAR" in fl: # Worth to write on the table
for fname in empty[fl]:
countTable.add_row(f"[bold red]{fl}", f"[bold red]{fname}")
elif "data" in fl:
for fname in empty[fl]:
countTable.add_row(f"[bold yellow]{fl}", f"[bold yellow]{fname}")
else:
for fname in empty[fl]:
countTable.add_row(str(fl), str(fname))
print(countTable)
# Finding .json .bin .dex files
for fff in apk.get_files():
if ".json" in fff:
fileTable.add_row(f"[bold yellow]{fff}")
elif ".dex" in fff:
fileTable.add_row(f"[bold red]{fff}")
elif ".bin" in fff:
fileTable.add_row(f"[bold cyan]{fff}")
elif ".sh" in fff:
fileTable.add_row(f"[bold red]{fff}")
else:
pass
print(fileTable)
# Analyzing all files
for key in empty:
try:
for kfile in empty[key]:
fcontent = apk.get_file(kfile)
for ddd in dictionary:
for regex in dictionary[ddd]:
matches = re.findall(regex, fcontent.decode())
if matches != []:
categs[ddd].append([matches[0], kfile])
except:
continue
# Output
counter = 0
for key in categs:
if categs[key] != []:
resTable = Table(title=f"* {key} *", title_style="bold green", title_justify="center")
resTable.add_column("Pattern", justify="center")
resTable.add_column("File", justify="center")
for elements in categs[key]:
resTable.add_row(f"[bold yellow]{elements[0]}", f"[bold cyan]{elements[1]}")
print(resTable)
counter += 1
if counter == 0:
print("\n[bold white on red]There is no interesting things found!\n")
def windows_resource_scanner_strings_method(self):
print(f"{infoS} Using Method 1: [bold yellow]Hidden PE signature scan via strings[white]")
# Scan strings and find potential embedded PE executables
possible_patterns = {
"method_1": {
"patterns": [
r"4D!5A!90",
r"4D-5A-90O"
]
},
"method_2": {
"patterns": [
r"4D5A9ZZZ"
]
},
"method_3": {
"patterns": [
r"~~~9A5D4",
r"09~A5~D4"
]
},
"method_4": {
"patterns": [
r"09}A5}D4",
r"WP09PA5PD4"
]
}
}
strings_data = subprocess.run(["strings", strings_param, self.target_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
executable_buffer = ""
for dat in strings_data.stdout.decode().split("\n"):
for pat in possible_patterns: # Look for methods
for mpat in possible_patterns[pat]["patterns"]:
matcc = re.findall(mpat, dat)
if matcc != []:
print(f"{infoS} Found potential embedded PE executable pattern: [bold green]{mpat}")
executable_buffer = dat
target_method = pat
target_pattern = mpat
# After finding pattern and potential data we need to deobfuscate it
if executable_buffer != "":
print(f"{infoS} Attempting to deobfuscate PE file data. Please wait...")
# Using method 1: Replace characters and split one character
if target_method == "method_1":
if target_pattern == r"4D!5A!90":
self.method_1_replace_split(r1="^", r2="!00", sp1="!", executable_buffer=executable_buffer)
elif target_pattern == r"4D-5A-90O":
self.method_1_replace_split(r1="O", r2="-00", sp1='-', executable_buffer=executable_buffer)
else:
pass
# Using method 2: Double replace
elif target_method == "method_2":
if target_pattern == r"4D5A9ZZZ":
self.method_2_double_replace(r1="ZZ", r2="0", r3="YY", r4="F", executable_buffer=executable_buffer)
# Using method 3: Reverse replace
elif target_method == "method_3":
if target_pattern == r"~~~9A5D4":
self.method_3_reverse_and_replace(r1="~", r2="0", executable_buffer=executable_buffer)
elif target_pattern == r"09~A5~D4":
self.method_3_reverse_and_replace(r1="~", r2="", executable_buffer=executable_buffer)
else:
pass
# Using method 4: Reverse and double replace
elif target_method == "method_4":
if target_pattern == r"09}A5}D4":
self.method_4_reverse_and_double_replace(r1="Q", r2="00", r3="}", r4="", executable_buffer=executable_buffer)
elif target_pattern == r"WP09PA5PD4":
self.method_4_reverse_and_double_replace(r1="W", r2="00", r3="P", r4="", executable_buffer=executable_buffer)
else:
pass
else:
print(f"{errorS} There is no method implemented for that data type!")
else:
print(f"{errorS} There is no embedded PE executable pattern found!\n")
def method_1_replace_split(self, r1, r2, sp1, executable_buffer):
self.r1 = r1 # Replace 1
self.r2 = r2 # Replace 2
self.sp1 = sp1 # Split character
self.executable_buffer = executable_buffer
# First replace and split characters
self.executable_buffer = self.executable_buffer.replace(self.r1, self.r2)
executable_array = self.executable_buffer.split(self.sp1)
# Second extract and sanitize data
output_buffer = ""
for buf in executable_array:
output_buffer += buf
# Data sanitization
sanitized_data = self.buffer_sanitizer(executable_buffer=output_buffer)
# Finally save data into file
self.save_data_into_file("sc0pe_carved_deobfuscated.exe", sanitized_data)
def method_2_double_replace(self, r1, r2, r3, r4, executable_buffer):
self.r1 = r1 # Replace 1
self.r2 = r2 # Replace 2
self.r3 = r3 # Replace 3
self.r4 = r4 # Replace 4
self.executable_buffer = executable_buffer
# Deobfuscation
self.executable_buffer = self.executable_buffer.replace(self.r1, self.r2).replace(self.r3, self.r4)
# Data sanitization
sanitized_data = self.buffer_sanitizer(executable_buffer=self.executable_buffer)
# Finally save data into file
self.save_data_into_file("sc0pe_carved_deobfuscated.exe", sanitized_data)
def method_3_reverse_and_replace(self, r1, r2, executable_buffer):
self.r1 = r1 # Replace 1
self.r2 = r2 # Replace 2
self.executable_buffer = executable_buffer
# Deobfuscation
self.executable_buffer = self.executable_buffer[::-1].replace(self.r1, self.r2)
# Data sanitization
sanitized_data = self.buffer_sanitizer(executable_buffer=self.executable_buffer)
# Finally save data into file
self.save_data_into_file("sc0pe_carved_deobfuscated.exe", sanitized_data)
def method_4_reverse_and_double_replace(self, r1, r2, r3, r4, executable_buffer):
self.r1 = r1 # Replace 1
self.r2 = r2 # Replace 2
self.r3 = r3 # Replace 3
self.r4 = r4 # Replace 4
self.executable_buffer = executable_buffer
# Deobfuscation
self.executable_buffer = self.executable_buffer[::-1].replace(self.r1, self.r2).replace(self.r3, self.r4)
# Data sanitization
sanitized_data = self.buffer_sanitizer(executable_buffer=self.executable_buffer)
# Finally save data into file
self.save_data_into_file("sc0pe_carved_deobfuscated.exe", sanitized_data)
def buffer_sanitizer(self, executable_buffer):
self.executable_buffer = executable_buffer
# Unwanted characters
unwanted = ['@', '\t', '\n']
for uc in unwanted:
if uc in self.executable_buffer:
self.executable_buffer = self.executable_buffer.replace(uc, "")
return self.executable_buffer
def windows_resource_scanner_split_data_carver_method(self):
print(f"{infoS} Using Method 2: [bold yellow]Detecting and merging split data[white]")
# Signature information we needed
resource_sigs = {
"Quartz": {
"signature_start": "74656d61",
"signature_end": "905a4d",
"additional_bytes": 3,
"offset_start": [],
"offset_end": []
},
"Versa": {
"signature_start": "65725078",
"signature_end": "f8afcfc0",
"additional_bytes": 4,
"offset_start": [],
"offset_end": []
},
"Zinc": {
"signature_start": "abf4dbbf",
"signature_end": "abf4dbbf",
"additional_bytes": 0,
"offset_start": [],
"offset_end": []
},
"Zar": {
"signature_start": "4d5a90",
"signature_end": "4d5a90",
"additional_bytes": 0,
"offset_start": [],
"offset_end": []
},
"Yar": {
"signature_start": "051f6d91208e",
"signature_end": "01ff35f8",
"additional_bytes": 4,
"offset_start": [],
"offset_end": []
},
"Xar": {
"signature_start": "f7934c0931",
"signature_end": "f7934c0931",
"additional_bytes": 0,
"offset_start": [],
"offset_end": []
}
}
# We need target executable buffer and file handler
target_executable_buffer = open(self.target_file, "rb").read()
target_file_handler = open(self.target_file, "rb")
# Switch
founder_switch = 0
# Locate start offsets
print(f"{infoS} Locating start offsets...")
for rs in resource_sigs:
find = re.finditer(binascii.unhexlify(resource_sigs[rs]["signature_start"]), target_executable_buffer)
for pos in find:
if pos.start() != 0: # If there is another MZ pattern
resource_sigs[rs]["offset_start"].append(pos.start())
founder_switch += 1
# Locate end offsets
print(f"{infoS} Locating end offsets...")
for rs in resource_sigs:
find = re.finditer(binascii.unhexlify(resource_sigs[rs]["signature_end"]), target_executable_buffer)
for pos in find:
if pos.start() != 0:
resource_sigs[rs]["offset_end"].append(pos.start())
founder_switch += 1
# Okay now we need to retrieve all data for deobfuscation
if founder_switch != 0:
print(f"{infoS} Deobfuscating split data. Please wait...")
output_buffer = b""
for rf in resource_sigs:
if resource_sigs[rf]["offset_start"] != [] and resource_sigs[rf]["offset_end"] != []:
if len(resource_sigs[rf]["offset_start"]) == len(resource_sigs[rf]["offset_end"]):
for ofst, ofnd in zip(resource_sigs[rf]["offset_start"], resource_sigs[rf]["offset_end"]):
temporary_buffer = self.file_carver_for_method_2(
file_handler=target_file_handler,
start_offset=ofst,
end_offset=ofnd,
additional_bytes=resource_sigs[rf]["additional_bytes"],
partition_name=rf
)
if rf == "Quartz":
# Now first we need to convert this data to "bytearray" and reverse it
byte_array = bytearray(temporary_buffer)
byte_array.reverse()
output_buffer += binascii.hexlify(byte_array)
else:
byte_array = bytearray(temporary_buffer)
output_buffer += binascii.hexlify(byte_array)
# After retrieve and obfuscate all data we need to save it!
self.save_data_into_file("sc0pe_carved_deobfuscated_split.exe", output_buffer)
else:
print(f"{errorS} There is no split data found!\n")
def file_carver_for_method_2(self, file_handler, start_offset, end_offset, additional_bytes, partition_name):
self.file_handler = file_handler
self.start_offset = start_offset
self.end_offset = end_offset
self.additional_bytes = additional_bytes
self.partition_name = partition_name
# Seek start offset
self.file_handler.seek(self.start_offset)
# Calculating data size and carving
if self.partition_name == "Zinc":
data_size = 8876 # Fixed size
carved_data = self.file_handler.read(data_size)
elif self.partition_name == "Zar":
data_size = 18090 # Fixed size
carved_data = self.file_handler.read(data_size)
elif self.partition_name == "Xar":
data_size = 18092 # Fixed size
carved_data = self.file_handler.read(data_size)
else:
data_size = self.end_offset - self.start_offset
carved_data = self.file_handler.read(data_size+self.additional_bytes)
# Return carved data for deobfuscation phase
return carved_data
def save_data_into_file(self, output_name, save_buffer):
self.output_name = output_name
self.save_buffer = save_buffer
with open(self.output_name, "wb") as cf:
cf.write(binascii.unhexlify(self.save_buffer))
print(f"{infoS} Data saved into: [bold green]{self.output_name}[white]\n")
# Execution zone
targFile = sys.argv[1]
resource_scan = ResourceScanner(targFile)
if os.path.isfile(targFile):
ostype = resource_scan.check_target_os()
if ostype == "file_android":
resource_scan.android_resource_scanner()
elif ostype == "file_windows":
resource_scan.windows_resource_scanner_strings_method()
resource_scan.windows_resource_scanner_split_data_carver_method()
else:
print("\n[bold white on red]Target OS couldn\'t detected!\n")
else:
print("\n[bold white on red]Target file not found!\n") |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta
name="description"
content="Lisa is a front-end engineer based in England."
/>
<title>Front-end Developer - Lisa Sheehan</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
crossorigin="anonymous"
/>
<script
src="https://kit.fontawesome.com/0f52f24c65.js"
crossorigin="anonymous"
></script>
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
<link rel="stylesheet" href="styles/style.css" />
<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=Playfair+Display:wght@700&family=Poppins:wght@500;700&display=swap"
rel="stylesheet"
/>
</head>
<body>
<div class="nav-container">
<nav class="d-flex justify-content-between">
<a href="/">
<img
src="images/logo.png"
class="logo d-none d-md-block"
alt="shecodes-logo"
/>
<img
src="images/smalllogo.jpeg"
class="logo d-block d-md-none"
alt="shecodes-logo"
/>
</a>
<ul>
<li class="active">
<a href="/" title="Homepage">Home</a>
</li>
<li>
<a href="/about.html" title="About Lisa"> About</a>
</li>
<li>
<a href="/work.html" title="Lisa's portfolio showcase"> Work</a>
</li>
<li>
<a href="/contact.html" title="Contact Lisa"> Contact</a>
</li>
</ul>
</nav>
</div>
<div class="hero">
<p>👋🏻 Hello I am</p>
<h1>Lisa Sheehan</h1>
<h2 class="mb-5">Front-end developer based in England</h2>
<div>
<a href="/contact.html" class="btn btn-branding">Contact Me</a>
</div>
</div>
<div class="container">
<p class="text-center m-5">Check out my featured projects below!</p>
<div class="row mb-5">
<div class="col d-none d-lg-block">
<img
src="images/yoghurt.png"
class="img-fluid"
alt="Yogurt website preview"
/>
</div>
<div class="col">
<div class="project-description">
<h2 class="mb-5">Yoghurt Project</h2>
<p class="mb-5 text-muted">
Far far away, behind the word mountains, far from the countries
Vokalia and Consonantia, there live the blind texts. Separated
they live in Bookmarksgrove right at the coast of the Semantics, a
large language ocean. A small river named Duden flows by
</p>
<a href="/work.html" class="btn btn-branding-outline"
>View my Project</a
>
</div>
</div>
</div>
<div class="row mb-5">
<div class="col">
<div class="project-description">
<h2 class="mb-5">Weather App</h2>
<p class="mb-5 text-muted">
Far far away, behind the word mountains, far from the countries
Vokalia and Consonantia, there live the blind texts. Separated
they live in Bookmarksgrove right at the coast of the Semantics, a
large language ocean. A small river named Duden flows by
</p>
<a href="work.html" class="btn btn-branding-outline"
>View my Project</a
>
</div>
</div>
<div class="col d-none d-lg-block">
<img
src="images/weather.png"
class="img-fluid"
alt="weather app preview"
/>
</div>
</div>
<div class="row mb-5">
<div class="col d-none d-lg-block">
<img
src="images/dictionary.png"
class="img-fluid"
alt="dictionary app preview"
/>
</div>
<div class="col">
<div class="project-description">
<h2 class="mb-5">Dictionary App</h2>
<p class="mb-5 text-muted">
Far far away, behind the word mountains, far from the countries
Vokalia and Consonantia, there live the blind texts. Separated
they live in Bookmarksgrove right at the coast of the Semantics, a
large language ocean. A small river named Duden flows by
</p>
<a href="work.html" class="btn btn-branding-outline"
>View my Project</a
>
</div>
</div>
</div>
<footer>
<div
class="contact-box d-flex justify-content-between mb-5 d-none d-md-flex"
>
<div>
<h3>Work Inquiry</h3>
<p class="text-muted">Let's work together</p>
</div>
<div>
<a href="/contact.html" class="btn btn-branding mb-3">Contact Me</a>
</div>
</div>
<div class="d-flex justify-content-center">
<a
href="mailto:lisa_sheehan@hotmail.com"
title="Email Lisa"
class="email-link"
>lisa_sheehan@hotmail.com</a
>
</div>
<div class="social-links d-flex justify-content-center mt-3">
<a
href="https://twitter.com/Lisa_Sheehan"
title="Twitter Profile"
target="_blank"
><i class="fab fa-twitter"></i>
</a>
<a
href="https://github.com/lsheehan89"
title="Github Profile"
target="_blank"
><i class="fab fa-github"></i>
</a>
<a
href="linkedin.com/in/lisa-sheehan/"
title="Linkedin Profile"
target="_blank"
><i class="fab fa-linkedin"></i>
</a>
</div>
<p class="text-center mt-3">
This website was coded by Lisa Sheehan, and is
<a
href="https://github.com/lsheehan89/portfolio-project"
target="_blank"
>
open-sourced</a
>
</p>
</footer>
</div>
</body>
</html> |
package boj;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/*
현재 무게에 대해
max(현재 무게에 저장된 최대가치, 현재무게-물건무게에 저장된 가치 + 현재물건가치)
물건 N개 -> 무게W, 가치V
가방 최대무게 K
가치 최댓값?
51428kb 148ms
*/
public class Main_B_12865_평범한배낭_노우영 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N,K;
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken()); //물건 개수
K = Integer.parseInt(st.nextToken()); //가방 무게 한도
int[][] dp = new int[N+1][K+1];
int[] weights = new int[N+1];
int[] values = new int[N+1];
//물건무게, 가치 저장
for(int i=1; i<N+1; i++) {
int W,V;
st = new StringTokenizer(br.readLine());
W = Integer.parseInt(st.nextToken());
V = Integer.parseInt(st.nextToken());
weights[i] = W;
values[i] = V;
}
for(int i=1; i<N+1; i++) { //물건 인덱스
int curW = weights[i];
int curV = values[i];
//물건인덱스 0 = 1번물건
//각 무게에 대해 처리 1~K kg, 0kg은 다 0으로 놔두기
for(int w=1; w<K+1; w++) {
if(w>=curW) {
dp[i][w] = Math.max(dp[i-1][w], dp[i-1][w-curW]+curV); //현재 처리하는 무게에서 저장된 값, 현재무게-물건무게에 저장된값+물건가치 중 큰 값 선택
}else {
dp[i][w] = dp[i-1][w];
}
}
}
System.out.println(dp[N][K]);
}
} |
from flask import Flask, request, render_template, jsonify, get_flashed_messages
from flask_sqlalchemy import SQLAlchemy
from os import path
app = Flask(__name__, template_folder='templates')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///mydatabase.db'
db = SQLAlchemy(app)
# app.py
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(120))
birth_year = db.Column(db.Integer)
class_name = db.Column(db.String(80))
def __init__(self, name, birth_year, class_name):
self.name = name
self.birth_year = birth_year
self.class_name = class_name
@app.route('/')
def home():
return render_template("index.html")
@app.route('/add', methods=['POST','GET'])
def students():
if request.method=="POST":
name = request.form.get("name")
birth_year = request.form.get("birth_year")
class_name = request.form.get("class_name")
if name and birth_year and class_name:
new_student = Student(name=name, birth_year=birth_year, class_name=class_name)
db.session.add(new_student)
db.session.commit()
return render_template("add.html", notice="1")
else:
return render_template("add.html", notice="0")
return render_template("add.html")
@app.route('/students_list', methods=['GET'])
def students_list():
students = Student.query.all()
return render_template("students_list.html", students=students)
@app.route('/delete', methods=['POST', 'GET'])
def delete_student():
if request.method == 'POST':
name = request.form.get('name')
student = Student.query.filter_by(name=name).first()
if not student:
return render_template("delete.html", notice="0")
else:
db.session.delete(student)
db.session.commit()
return render_template("delete.html", notice="1")
return render_template("delete.html")
@app.route('/edit', methods=['POST', 'GET'])
def edit_student():
students = Student.query.all()
if request.method=='POST':
# student_id = request.form.get('id')
student_id = 1
name = request.form.get('name')
birth_year = request.form.get('birth_year')
class_name = request.form.get('clas')
student = Student.query.get(student_id)
if student:
student.name = name
student.birth_year = birth_year
student.class_name = class_name
db.session.commit()
return render_template('edit.html' , notice="1")
else:
return render_template('edit.html' , notice="0")
return render_template("edit.html")
# @app.route('/api/students', methods=['GET'])
# def sort_students():
# query_params = request.args.to_dict()
# students = Student.query.filter_by(**query_params).all()
# if 'sort_by' in query_params:
# sort_by = query_params['sort_by']
# students = sorted(students, key=lambda x: getattr(x, sort_by))
# student_list = [{'id': student.id, 'name': student.name, 'birth_year': student.birth_year, 'class_name': student.class_name} for student in students]
# return jsonify(student_list), 200
if __name__ == '__main__':
if not path.exists("mydatabase.db"):
db.create_all(app=app)
app.run(debug=True) |
import { IFindByIdArticleRepository } from '@domain/repositories/articles/find-by-id-article.repository';
import { IShowArticleUseCase } from '@domain/use-cases/articles/show-article.usecase';
import { ShowArticleUseCaseDTO } from '@dtos/articles/show-article.dto';
import { NotFoundModelError } from '@shared/errors/not-found-model.error';
import { left, right } from '@shared/utils/either';
import { notFound } from '@shared/utils/http-response';
export class ShowArticleUseCase implements IShowArticleUseCase {
constructor(
private readonly articlesRepository: IFindByIdArticleRepository,
) {}
public async execute({
articleId,
}: ShowArticleUseCaseDTO.Params): ShowArticleUseCaseDTO.Result {
const articleExists = await this.articlesRepository.findById({ articleId });
if (articleExists.isLeft()) {
return left(notFound(new NotFoundModelError('article')));
}
const { article } = articleExists.value;
return right({
article,
});
}
} |
<template>
<div class="container">
<div class="d-block mt-2">
<div class="card p-3 shadow">
<div class="card-header border-0 mx-3 shadow bg-primary ">
<h1 class="header text-white text-center">
Müşteri Listesi
</h1>
</div>
<b-card class="row mx-3 shadow text-left my-3" no-body>
<b-table
style="text-align: center;"
striped
hover
:items="customers"
:fields="fields"
>
<!-- Müşterinin hesap listesi sayfasına yönlendirecek buton -->
<template #cell(Accounts)="row">
<b-button
size="sm"
@click="$router.push('/account/' + row.item.CustomerId)"
class="mr-2"
variant="primary"
>
Show
</b-button>
</template>
</b-table>
</b-card>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import AuthService from "../services/AuthService";
import CustomerService from "../services/CustomerService";
export default {
name: "CustomerList",
data() {
return {
customers: [],
fields: [
{
key: "FirstName",
sortable: true
},
{
key: "LastName",
sortable: true
},
{
key: "BirthDate",
sortable: true
},
{
key: "Email",
sortable: true
},
{
key: "Accounts"
}
]
};
},
methods: {
// müşteri listesini getir
getAllCustomer() {
CustomerService.GetCustomer()
.then(response => {
if (response.data.IsSuccess == 1 || response.data.IsSuccess == true) {
//başarılı
this.customers = response.data.Result;
} else {
//hatalı
}
})
.catch(err => {
console.error(err);
});
}
},
created() {
// sayfa oluşurken çalışacak scope
this.getAllCustomer();
}
};
</script> |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using dnlib.DotNet;
using dnSpy.Contracts.Documents;
using dnSpy.Contracts.Images;
using dnSpy.Contracts.TreeView;
namespace dnSpy.Analyzer.TreeNodes {
/// <summary>
/// Base class for analyzer nodes that perform a search.
/// </summary>
abstract class SearchNode : AnalyzerTreeNodeData, IAsyncCancellable {
protected SearchNode() {
}
public override void Initialize() => TreeNode.LazyLoading = true;
protected override ImageReference GetIcon(IDotNetImageService dnImgMgr) => DsImages.Search;
public override IEnumerable<TreeNodeData> CreateChildren() {
Debug2.Assert(asyncFetchChildrenHelper is null);
asyncFetchChildrenHelper = new AsyncFetchChildrenHelper(this, () => asyncFetchChildrenHelper = null);
yield break;
}
AsyncFetchChildrenHelper? asyncFetchChildrenHelper;
protected abstract IEnumerable<AnalyzerTreeNodeData> FetchChildren(CancellationToken ct);
internal IEnumerable<AnalyzerTreeNodeData> FetchChildrenInternal(CancellationToken token) => FetchChildren(token);
public override void OnIsVisibleChanged() {
if (!TreeNode.IsVisible && asyncFetchChildrenHelper is not null && !asyncFetchChildrenHelper.CompletedSuccessfully) {
CancelAndClearChildren();
TreeNode.LazyLoading = true;
}
}
public override void OnIsExpandedChanged(bool isExpanded) {
if (!isExpanded && asyncFetchChildrenHelper is not null && !asyncFetchChildrenHelper.CompletedSuccessfully) {
CancelAndClearChildren();
TreeNode.LazyLoading = true;
}
}
public override bool HandleAssemblyListChanged(IDsDocument[] removedAssemblies, IDsDocument[] addedAssemblies) {
// only cancel a running analysis if user has manually added/removed assemblies
bool manualAdd = false;
foreach (var asm in addedAssemblies) {
if (!asm.IsAutoLoaded)
manualAdd = true;
}
if (removedAssemblies.Length > 0 || manualAdd) {
CancelAndClearChildren();
}
return true;
}
public override bool HandleModelUpdated(IDsDocument[] documents) {
CancelAndClearChildren();
return true;
}
void CancelAndClearChildren() {
AnalyzerTreeNodeData.CancelSelfAndChildren(this);
TreeNode.Children.Clear();
TreeNode.LazyLoading = true;
}
public void Cancel() {
asyncFetchChildrenHelper?.Cancel();
asyncFetchChildrenHelper = null;
}
internal static bool CanIncludeModule(ModuleDef targetModule, ModuleDef? module) {
if (module is null)
return false;
if (targetModule == module)
return false;
if (targetModule.Assembly is not null && targetModule.Assembly == module.Assembly)
return false;
return true;
}
internal static HashSet<string> GetFriendAssemblies(IDsDocumentService documentService, ModuleDef mod, out IDsDocument[] modules) {
var asm = mod.Assembly;
Debug2.Assert(asm is not null);
var friendAssemblies = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var attribute in asm.CustomAttributes.FindAll("System.Runtime.CompilerServices.InternalsVisibleToAttribute")) {
if (attribute.ConstructorArguments.Count == 0)
continue;
string assemblyName = attribute.ConstructorArguments[0].Value as UTF8String;
if (assemblyName is null)
continue;
assemblyName = new AssemblyNameInfo(assemblyName).Name;
friendAssemblies.Add(assemblyName);
}
modules = documentService.GetDocuments().Where(a => CanIncludeModule(mod, a.ModuleDef)).ToArray();
foreach (var module in modules) {
Debug2.Assert(module.ModuleDef is not null);
var asm2 = module.AssemblyDef;
if (asm2 is null)
continue;
foreach (var attribute in asm2.CustomAttributes.FindAll("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute")) {
string assemblyName = attribute.ConstructorArguments[0].Value as UTF8String;
if (assemblyName is null)
continue;
assemblyName = new AssemblyNameInfo(assemblyName).Name;
if (StringComparer.OrdinalIgnoreCase.Equals(asm.Name.String, assemblyName))
friendAssemblies.Add(asm2.Name);
}
}
return friendAssemblies;
}
internal static void AddTypeEquivalentTypes(IDsDocumentService documentService, TypeDef analyzedType, List<TypeDef> analyzedTypes) {
Debug.Assert(analyzedTypes.Count == 1 && analyzedTypes[0] == analyzedType);
if (!TIAHelper.IsTypeDefEquivalent(analyzedType))
return;
foreach (var document in documentService.GetDocuments().Where(a => a.ModuleDef is not null)) {
foreach (var type in GetTypeEquivalentTypes(document.AssemblyDef, document.ModuleDef, analyzedType)) {
if (type != analyzedType)
analyzedTypes.Add(type);
}
}
}
static IEnumerable<TypeDef> GetTypeEquivalentTypes(AssemblyDef? assembly, ModuleDef? module, TypeDef type) {
Debug.Assert(TIAHelper.IsTypeDefEquivalent(type));
var typeRef = new ModuleDefUser("dummy").Import(type);
foreach (var mod in GetModules(assembly, module)) {
var otherType = mod.Find(typeRef);
if (otherType != type && TIAHelper.IsTypeDefEquivalent(otherType) &&
new SigComparer().Equals(otherType, type) &&
!new SigComparer(SigComparerOptions.DontCheckTypeEquivalence).Equals(otherType, type)) {
yield return otherType;
}
}
}
static IEnumerable<ModuleDef> GetModules(AssemblyDef? assembly, ModuleDef? module) {
if (assembly is not null) {
foreach (var mod in assembly.Modules)
yield return mod;
}
else {
if (module is not null)
yield return module;
}
}
protected static IEnumerable<(ModuleDef module, ITypeDefOrRef type)> GetTypeEquivalentModulesAndTypes(List<TypeDef> analyzedTypes) {
foreach (var type in analyzedTypes)
yield return (type.Module, type);
}
internal static IEnumerable<ModuleDef> GetTypeEquivalentModules(List<TypeDef> analyzedTypes) {
foreach (var type in analyzedTypes)
yield return type.Module;
}
protected static bool CheckEquals(IMemberRef? mr1, IMemberRef? mr2) => Helpers.CheckEquals(mr1, mr2);
}
} |
/*******************************************************************************
* Copyright (c) 2006 Vladimir Silva and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Vladimir Silva - initial API and implementation
*******************************************************************************/
package org.eclipse.plugin.worldwind.wizard;
import java.net.URL;
import java.util.Hashtable;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.plugin.worldwind.Messages;
import org.eclipse.plugin.worldwind.operation.WMSParseOperation;
import org.eclipse.plugin.worldwind.utils.NewRemoteServerDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import worldwind.contrib.parsers.ParserUtils;
import worldwind.contrib.parsers.WMS_Capabilities;
import worldwind.contrib.parsers.WMS_Capabilities.Layer;
/**
* WMS Wizard Page
* @author vsilva
*
*/
public class WMSWizardPage extends WizardPage
{
private static final Logger logger = Logger.getLogger(WMSWizardPage.class);
// Widgets: Source serverCombo, Layers Table
private TableViewer layerViewer;
private Combo serverCombo;
private Vector<ParserUtils.PublicWMSServer> servers;
// WMS servers caps
private WMS_Capabilities capabilities;
// Indices of the selected layers from caps above
private int[] selectedIndices;
// Used to cache capabilities for increased performance
private static Hashtable<String, WMS_Capabilities> capabilitiesCache
= new Hashtable<String, WMS_Capabilities>();
/**
* WMS Wizard server selection page
* @param pageName
*/
public WMSWizardPage(String pageName) {
super(pageName);
setTitle(Messages.getString("wiz.wms.page1.title"));
setDescription(Messages.getString("wiz.wms.page1.desc"));
setPageComplete(false);
}
/**
* Controls
*/
public void createControl(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
container.setLayout(new GridLayout(2, false));
GridData data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 2;
Label lbl = new Label(container, SWT.NONE);
lbl.setText(Messages.getString("wiz.wms.page1.lbl1"));
lbl.setLayoutData(data); //new GridData(GridData.FILL_HORIZONTAL));
serverCombo = new Combo(container, SWT.READ_ONLY);
serverCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
//serverCombo.addListener(SWT.Selection | SWT.DefaultSelection, this);
serverCombo.addSelectionListener(new SelectionListener()
{
public void widgetDefaultSelected(SelectionEvent e)
{
String text = ((Combo)e.getSource()).getText();
if ( ! text.startsWith("http")) {
setErrorMessage("Invalid text: " + text);
return;
}
handleComboSelection((Combo)e.getSource(), true);
}
public void widgetSelected(SelectionEvent e) {
handleComboSelection((Combo)e.getSource(), false);
}
});
// init serverCombo data
loadServers();
// new srv btn
Button newSrv = new Button(container, SWT.PUSH);
newSrv.setText("New");
newSrv.addSelectionListener(new SelectionAdapter()
{
public void widgetSelected(SelectionEvent e)
{
// Get Server name, WMS Caps URL from user
NewRemoteServerDialog dialog = new NewRemoteServerDialog(getShell());
final int rc = dialog.open();
if ( rc == Dialog.OK )
{
try {
String name = dialog.getName();
String url = dialog.getUrl();
// Add WMS caps to combo box
ParserUtils.PublicWMSServer wms = new ParserUtils.PublicWMSServer(name, new URL(url));
serverCombo.add(name, 0);
servers.add(0, wms);
}
catch (Exception ex) {
Messages.showErrorMessage(getShell(), ex.getMessage());
}
}
}
});
// Layers lbl
lbl = new Label(container, SWT.NONE);
lbl.setText(Messages.getString("wiz.wms.page1.lbl2"));
lbl.setLayoutData(data); //new GridData(GridData.FILL_HORIZONTAL));
data = new GridData(GridData.FILL_BOTH);
data.horizontalSpan = 2;
layerViewer = new TableViewer(container, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
layerViewer.getTable().setLayoutData(data);
layerViewer.addSelectionChangedListener(
new ISelectionChangedListener()
{
public void selectionChanged(SelectionChangedEvent event)
{
int[] indices = ((TableViewer)event.getSource()).getTable().getSelectionIndices();
handleListSelection(indices);
}
}
);
setControl(container);
setPageComplete(false);
}
/*
* Load WMS servers into serverCombo box
*/
private void loadServers()
{
for (ParserUtils.PublicWMSServer server : servers) {
serverCombo.add(server.name);
}
}
/* fires when the list is clicked */
private void handleListSelection ( int[] indices )
{
try {
// Save indices to extract Layers from Caps obj later on
selectedIndices = indices;
loadNextPage();
setPageComplete(true);
getWizard().getContainer().updateButtons();
} catch (Exception e) {
setPageComplete(false);
}
}
/* fires when a serverCombo item is selected */
private void handleComboSelection ( Combo combo, boolean userInput )
{
String server = combo.getText();
int idx = combo.getSelectionIndex();
URL url = null;
if ( idx == -1 && ! userInput ) return;
// Clear any prev error/messages
setErrorMessage(null);
try {
if ( userInput) {
// Load WMS layers from user input
url = new URL(server);
}
else {
// Load from public list
url = servers.get(idx).capabilitiesURL;
}
logger.debug("Server=" + server + " idx=" + idx + " url:" + url);
if ( capabilitiesCache.containsKey(url.toString()))
{
// load from cache
capabilities = capabilitiesCache.get(url.toString());
// Populate list: remove any previous elements
layerViewer.getTable().removeAll();
// Ad layers to the list box
for (WMS_Capabilities.Layer layer : capabilities.getLayers()) {
layerViewer.add(layer.Title);
}
}
else
{
WMSParseOperation operation = new WMSParseOperation(server, url
, layerViewer, getWizard().getContainer().getShell().getDisplay());
// run a Jface operation (it will populate the layers list)
getWizard().getContainer().run(true, true, operation);
capabilities = operation.getCapabilities();
// cache for repeated use
capabilitiesCache.put(url.toString(), capabilities);
}
final WMS_Capabilities.Service service = capabilities.getService();
String name = (service.Title != null )
? service.Name + ": " + service.Title
: service.Name;
name += " has "
+ capabilities.getLayers().size() + "/"
+ capabilities.getTotalLayers()
+ " renderable layers. ";
setMessage(name + "Select a layer to continue.", IMessageProvider.INFORMATION);
}
catch (Exception e) {
//e.printStackTrace();
setErrorMessage(e.getClass().getName() + ": " + e.getMessage());
}
}
public void setServers(Vector<ParserUtils.PublicWMSServer> servers) {
this.servers = servers;
}
public Vector<ParserUtils.PublicWMSServer> getServers() {
return servers;
}
public WMS_Capabilities getCapabilities () {
return capabilities;
}
public int[] getSelectedIndices () {
return selectedIndices;
}
private boolean isLayerSelected () {
int[] indices = layerViewer.getTable().getSelectionIndices();
return indices != null && indices.length > 0;
}
@Override
public boolean canFlipToNextPage() {
if ( isLayerSelected()) return true;
else return false;
}
/**
* Load page 2 data
*/
private void loadNextPage()
{
DimSelectionPage page2 = (DimSelectionPage)getWizard().getPage("page2");
try {
if ( capabilities != null )
{
// extract date range/bbox of the 1st layer only
int idx = selectedIndices[0];
Layer layer = capabilities.getLayers().get(idx);
boolean showDates = false;
String[] dates = null;
if ( layer.ISOTimeSpan != null ) {
showDates = true;
// Comma sep string of ISO dates for this layer time span
logger.debug("Building ISO time list for " + layer.ISOTimeSpan);
final String csvDates = WMS_Capabilities.buildWMSTimeList(layer.ISOTimeSpan);
// split csv string to generate dates
dates = csvDates.split(",");
}
// Layer formats
String[] formats = new String[capabilities.getMapRequest().formats.size()];
capabilities.getMapRequest().formats.toArray(formats);
logger.debug("Using WMS layer "
+ layer.Name + " " + ((dates != null) ? dates.length: 0) + " time steps "
+ " # combo items=" + page2.startDate.getItemCount()
+ " formats size=" + formats.length);
page2.loadData(showDates
, layer.bbox.isValid() // show latlon
, dates // time steps
, layer.bbox // bbox
, formats); // layer formats
}
}
catch (Exception e) {
//e.printStackTrace();
setErrorMessage(e.getMessage());
}
}
} |
using Eshop.Infrastructure.Infrastructure;
using Eshop.Infrastructure.Persistence;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Eshop.Presentation.Mvc
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
if(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")== "Development")
{
var developmentConfig = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true).Build();
services.AddSingleton(developmentConfig);
}
services.AddPersistenceServices(Configuration.GetConnectionString("ConnectionString"));
services.AddInfrastructureServices();
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
} |
package com.wujia.ui.utils;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Build;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import androidx.appcompat.app.AppCompatActivity;
import com.wujia.ui.R;
/**
* Screen utils.
*
* @author WuJia.
* @version 1.0
* @date 2020/10/20
*/
public class ScreenUtils {
private ScreenUtils() {
}
/**
* 获取屏幕的宽度
*
* @param context
* @return
*/
public static int getDisplayWidthInPx(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
if (manager != null) {
Display display = manager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.x;
}
return 0;
}
/**
* 获取屏幕的高度
*
* @param context
* @return
*/
public static int getDisplayHeightInPx(Context context) {
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
if (manager != null) {
Display display = manager.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
return size.y;
}
return 0;
}
/**
* 获得状态栏的高度
*
* @param context
* @return mStatusHeight
*/
public static int getStatusHeightInPx(Context context) {
int statusHeight = -1;
try {
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
statusHeight = context.getResources().getDimensionPixelSize(resourceId);
}
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 获取当前屏幕截图,不包含状态栏
*
* @param activity Activity
* @return bp
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
if (bmp == null) {
return null;
}
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
Bitmap bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, bmp.getWidth(), bmp.getHeight() - statusBarHeight);
view.destroyDrawingCache();
view.setDrawingCacheEnabled(false);
return bp;
}
/**
* 获取actionbar的像素高度,默认使用android官方兼容包做actionbar兼容
*
* @return
*/
public static int getActionBarHeight(Context context) {
int actionBarHeight = 0;
if (context instanceof AppCompatActivity && ((AppCompatActivity) context).getSupportActionBar() != null) {
Log.d("isAppCompatActivity", "==AppCompatActivity");
actionBarHeight = ((AppCompatActivity) context).getSupportActionBar().getHeight();
} else if (context instanceof Activity && ((Activity) context).getActionBar() != null) {
Log.d("isActivity", "==Activity");
actionBarHeight = ((Activity) context).getActionBar().getHeight();
} else if (context instanceof ActivityGroup) {
Log.d("ActivityGroup", "==ActivityGroup");
if (((ActivityGroup) context).getCurrentActivity() instanceof AppCompatActivity && ((AppCompatActivity) ((ActivityGroup) context).getCurrentActivity()).getSupportActionBar() != null) {
actionBarHeight = ((AppCompatActivity) ((ActivityGroup) context).getCurrentActivity()).getSupportActionBar().getHeight();
} else if (((ActivityGroup) context).getCurrentActivity() != null && ((Activity) ((ActivityGroup) context).getCurrentActivity()).getActionBar() != null) {
actionBarHeight = ((Activity) ((ActivityGroup) context).getCurrentActivity()).getActionBar().getHeight();
}
}
if (actionBarHeight != 0)
return actionBarHeight;
final TypedValue tv = new TypedValue();
if (context.getTheme().resolveAttribute(R.attr.actionBarSize, tv, true)) {
if (context.getTheme().resolveAttribute(R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
} else {
if (context.getTheme().resolveAttribute(R.attr.actionBarSize, tv, true))
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
}
Log.d("actionBarHeight", "====" + actionBarHeight);
return actionBarHeight;
}
/**
* 设置view margin
*
* @param v
* @param l
* @param t
* @param r
* @param b
*/
public static void setMargins(View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.