text
stringlengths 184
4.48M
|
|---|
require("dotenv").config();
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
const port = 8000;
const expressLayouts = require('express-ejs-layouts');
const path = require('path')
const db = require('./config/mongoose');
// used for session cookie
const session = require('express-session');
const passport = require('passport');
const passportLocal = require('./config/passport-local-strategy');
const { default: mongoose } = require('mongoose');
const MongoStore = require('connect-mongo')(session);
app.use(express.urlencoded());
app.use(cookieParser());
// use static files like .css
app.use(express.static('./assets'));
// use layout
app.use(expressLayouts);
// extract style and scripts from subpages into the layout
app.set('layout extractStyles', true);
app.set('layout extractScripts', true);
// set up the view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// mongo store is used to store the session cookie in the db
app.use(session({
name: 'placement',
// TODO change the secret key before deployement
secret: process.env.SECRET,
saveUninitialized: false,
resave: false,
cookie: {
maxAge: (1000*60*100)
},
store: new MongoStore(
{
mongooseConnection: db,
autoRemove: 'disabled'
},
function(err){
console.log(err || 'connect-mongodb setup ok')
}
)
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.setAuthenticatedUser);
// use express router
app.use('/', require('./routes/index'))
app.listen(port, function(err){
if (err){
console.log(`Error in running the server: ${err}`);
}
console.log(`Server is running on port: ${port}`);
});
|
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {background-color: black;}
pre {
font-weight: normal;
color: #bbb;
white-space: -moz-pre-wrap;
white-space: -o-pre-wrap;
white-space: -pre-wrap;
white-space: pre-wrap;
word-wrap: break-word;
overflow-wrap: break-word;
}
b {font-weight: normal}
b.BOLD {color: #fff}
b.ITA {font-style: italic}
b.UND {text-decoration: underline}
b.STR {text-decoration: line-through}
b.UNDSTR {text-decoration: underline line-through}
b.BLK {color: #000000}
b.RED {color: #aa0000}
b.GRN {color: #00aa00}
b.YEL {color: #aa5500}
b.BLU {color: #0000aa}
b.MAG {color: #aa00aa}
b.CYN {color: #00aaaa}
b.WHI {color: #aaaaaa}
b.HIK {color: #555555}
b.HIR {color: #ff5555}
b.HIG {color: #55ff55}
b.HIY {color: #ffff55}
b.HIB {color: #5555ff}
b.HIM {color: #ff55ff}
b.HIC {color: #55ffff}
b.HIW {color: #ffffff}
b.BBLK {background-color: #000000}
b.BRED {background-color: #aa0000}
b.BGRN {background-color: #00aa00}
b.BYEL {background-color: #aa5500}
b.BBLU {background-color: #0000aa}
b.BMAG {background-color: #aa00aa}
b.BCYN {background-color: #00aaaa}
b.BWHI {background-color: #aaaaaa}
</style>
</head>
<body>
<pre>dir_colors(5) File Formats Manual dir_colors(5)
NAME
dir_colors - configuration file for dircolors(1)
DESCRIPTION
The program ls(1) uses the environment variable LS_COLORS to determine the colors in which the filenames are to be dis‐
played. This environment variable is usually set by a command like
eval `dircolors some_path/dir_colors`
found in a system default shell initialization file, like /etc/profile or /etc/csh.cshrc. (See also dircolors(1).) Usu‐
ally, the file used here is /etc/DIR_COLORS and can be overridden by a .dir_colors file in one's home directory.
This configuration file consists of several statements, one per line. Anything right of a hash mark (#) is treated as a
comment, if the hash mark is at the beginning of a line or is preceded by at least one whitespace. Blank lines are ignored.
The global section of the file consists of any statement before the first TERM statement. Any statement in the global sec‐
tion of the file is considered valid for all terminal types. Following the global section is one or more terminal-specific
sections, preceded by one or more TERM statements which specify the terminal types (as given by the TERM environment vari‐
able) the following declarations apply to. It is always possible to override a global declaration by a subsequent terminal-
specific one.
The following statements are recognized; case is insignificant:
TERM terminal-type
Starts a terminal-specific section and specifies which terminal it applies to. Multiple TERM statements can be used
to create a section which applies for several terminal types.
COLOR yes|all|no|none|tty
(Slackware only; ignored by GNU dircolors(1).) Specifies that colorization should always be enabled (yes or all),
never enabled (no or none), or enabled only if the output is a terminal (tty). The default is no.
EIGHTBIT yes|no
(Slackware only; ignored by GNU dircolors(1).) Specifies that eight-bit ISO 8859 characters should be enabled by de‐
fault. For compatibility reasons, this can also be specified as 1 for yes or 0 for no. The default is no.
OPTIONS options
(Slackware only; ignored by GNU dircolors(1).) Adds command-line options to the default ls command line. The op‐
tions can be any valid ls command-line options, and should include the leading minus sign. Note that dircolors does
not verify the validity of these options.
NORMAL color-sequence
Specifies the color used for normal (nonfilename) text.
Synonym: NORM.
FILE color-sequence
Specifies the color used for a regular file.
DIR color-sequence
Specifies the color used for directories.
LINK color-sequence
Specifies the color used for a symbolic link.
Synonyms: LNK, SYMLINK.
ORPHAN color-sequence
Specifies the color used for an orphaned symbolic link (one which points to a nonexistent file). If this is unspeci‐
fied, ls will use the LINK color instead.
MISSING color-sequence
Specifies the color used for a missing file (a nonexistent file which nevertheless has a symbolic link pointing to
it). If this is unspecified, ls will use the FILE color instead.
FIFO color-sequence
Specifies the color used for a FIFO (named pipe).
Synonym: PIPE.
SOCK color-sequence
Specifies the color used for a socket.
DOOR color-sequence
(Supported since fileutils 4.1) Specifies the color used for a door (Solaris 2.5 and later).
BLK color-sequence
Specifies the color used for a block device special file.
Synonym: BLOCK.
CHR color-sequence
Specifies the color used for a character device special file.
Synonym: CHAR.
EXEC color-sequence
Specifies the color used for a file with the executable attribute set.
SUID color-sequence
Specifies the color used for a file with the set-user-ID attribute set.
Synonym: SETUID.
SGID color-sequence
Specifies the color used for a file with the set-group-ID attribute set.
Synonym: SETGID.
STICKY color-sequence
Specifies the color used for a directory with the sticky attribute set.
STICKY_OTHER_WRITABLE color-sequence
Specifies the color used for an other-writable directory with the executable attribute set.
Synonym: OWT.
OTHER_WRITABLE color-sequence
Specifies the color used for an other-writable directory without the executable attribute set.
Synonym: OWR.
LEFTCODE color-sequence
Specifies the left code for non-ISO 6429 terminals (see below).
Synonym: LEFT.
RIGHTCODE color-sequence
Specifies the right code for non-ISO 6429 terminals (see below).
Synonym: RIGHT.
ENDCODE color-sequence
Specifies the end code for non-ISO 6429 terminals (see below).
Synonym: END.
*extension color-sequence
Specifies the color used for any file that ends in extension.
.extension color-sequence
Same as *.extension. Specifies the color used for any file that ends in .extension. Note that the period is in‐
cluded in the extension, which makes it impossible to specify an extension not starting with a period, such as ~ for
emacs backup files. This form should be considered obsolete.
ISO 6429 (ANSI) color sequences
Most color-capable ASCII terminals today use ISO 6429 (ANSI) color sequences, and many common terminals without color capa‐
bility, including xterm and the widely used and cloned DEC VT100, will recognize ISO 6429 color codes and harmlessly elimi‐
nate them from the output or emulate them. ls uses ISO 6429 codes by default, assuming colorization is enabled.
ISO 6429 color sequences are composed of sequences of numbers separated by semicolons. The most common codes are:
0 to restore default color
1 for brighter colors
4 for underlined text
5 for flashing text
30 for black foreground
31 for red foreground
32 for green foreground
33 for yellow (or brown) foreground
34 for blue foreground
35 for purple foreground
36 for cyan foreground
37 for white (or gray) foreground
40 for black background
41 for red background
42 for green background
43 for yellow (or brown) background
44 for blue background
45 for purple background
46 for cyan background
47 for white (or gray) background
Not all commands will work on all systems or display devices.
ls uses the following defaults:
NORMAL 0 Normal (nonfilename) text
FILE 0 Regular file
DIR 32 Directory
LINK 36 Symbolic link
ORPHAN undefined Orphaned symbolic link
MISSING undefined Missing file
FIFO 31 Named pipe (FIFO)
SOCK 33 Socket
BLK 44;37 Block device
CHR 44;37 Character device
EXEC 35 Executable file
A few terminal programs do not recognize the default properly. If all text gets colorized after you do a directory listing,
change the NORMAL and FILE codes to the numerical codes for your normal foreground and background colors.
Other terminal types (advanced configuration)
If you have a color-capable (or otherwise highlighting) terminal (or printer!) which uses a different set of codes, you can
still generate a suitable setup. To do so, you will have to use the LEFTCODE, RIGHTCODE, and ENDCODE definitions.
When writing out a filename, ls generates the following output sequence: LEFTCODE typecode RIGHTCODE filename ENDCODE, where
the typecode is the color sequence that depends on the type or name of file. If the ENDCODE is undefined, the sequence
LEFTCODE NORMAL RIGHTCODE will be used instead. The purpose of the left- and rightcodes is merely to reduce the amount of
typing necessary (and to hide ugly escape codes away from the user). If they are not appropriate for your terminal, you can
eliminate them by specifying the respective keyword on a line by itself.
NOTE: If the ENDCODE is defined in the global section of the setup file, it cannot be undefined in a terminal-specific sec‐
tion of the file. This means any NORMAL definition will have no effect. A different ENDCODE can, however, be specified,
which would have the same effect.
Escape sequences
To specify control- or blank characters in the color sequences or filename extensions, either C-style \-escaped notation or
stty-style ^-notation can be used. The C-style notation includes the following characters:
\a Bell (ASCII 7)
\b Backspace (ASCII 8)
\e Escape (ASCII 27)
\f Form feed (ASCII 12)
\n Newline (ASCII 10)
\r Carriage Return (ASCII 13)
\t Tab (ASCII 9)
\v Vertical Tab (ASCII 11)
\? Delete (ASCII 127)
\nnn Any character (octal notation)
\xnnn Any character (hexadecimal notation)
\_ Space
\\ Backslash (\)
\^ Caret (^)
\# Hash mark (#)
Note that escapes are necessary to enter a space, backslash, caret, or any control character anywhere in the string, as well
as a hash mark as the first character.
FILES
/etc/DIR_COLORS
System-wide configuration file. (Slackware, SuSE and RedHat only; ignored by GNU dircolors(1) and thus Debian.)
~/.dir_colors
+. (Slackware, SuSE and RedHat only; ignored by GNU dircolors(1) and thus Debian.) Per-user configuration file.
This page describes the dir_colors file format as used in the fileutils-4.1 package; other versions may differ slightly.
NOTES
The default LEFTCODE and RIGHTCODE definitions, which are used by ISO 6429 terminals are:
LEFTCODE \e[
RIGHTCODE m
The default ENDCODE is undefined.
SEE ALSO
dircolors(1), ls(1), stty(1), xterm(1)
Linux man-pages 6.03 2023-02-05 dir_colors(5)
</pre>
</body>
</html>
|
import styled from 'styled-components';
const ProgressBarContainer = styled.div`
background: #ccc;
height: 20px;
border-radius: 5px;
overflow: hidden;
`;
const ProgressBarFill = styled.div`
display: flex;
align-items: right;
justify-content: right;
width: ${props => `${props.percentage}%`};
background: green;
height: 100%;
color: white;
font-weight: bold;
transition: width 0.3s ease-in-out;
`;
const calculatePercentage = (correct, wordsLength) => {
if (wordsLength!== 0) {
return ((correct/ wordsLength) * 100).toFixed(2);
}
return 0;
};
export default ({correct,totalWords}) => {
const percentage = calculatePercentage(correct, totalWords);
return (
<ProgressBarContainer>
<ProgressBarFill percentage={percentage}>{`${percentage}%`}
<img
src='/car.svg'
width='58'
height='24'
/>
</ProgressBarFill>
</ProgressBarContainer>
);
};
|
import React from 'react';
import styled from 'styled-components';
import { MetadataItem } from '../metadata.const';
const TableContainer = styled.div`
margin: 15px;
`;
const GroupDiv = styled.div`
margin-bottom: 15px;
border: 3px solid #007bff;
`;
const TableStyled = styled.table`
width: 100%;
margin: 0px;
`;
const Th = styled.th`
padding: 15px !important;
border-right: 1px solid #007bff;
width: 50%;
`;
const Td = styled.td`
padding: 15px !important;
width: 50%;
`;
const SelectedNameHeader = styled.h2`
background-color: #007bff;
color: #fff;
padding: 10px;
margin: 0px;
`;
const TableBottomLine = styled.div`
border-bottom: 1px solid #007bff;
`;
interface TableProps {
metadata: MetadataItem[];
selectedChannels: string[];
}
const formatDate = (utcString: string): string => {
const dateObj = new Date(utcString);
return dateObj.toLocaleString();
};
const Table: React.FC<TableProps> = ({ metadata, selectedChannels }) => {
return (
<TableContainer>
{selectedChannels.map((selectedName, nameIndex) => {
const selectedMetadata = metadata.filter((item) => item.name === selectedName);
return (
<GroupDiv key={selectedName}>
<center>
<SelectedNameHeader>{selectedName}</SelectedNameHeader>
</center>
{selectedMetadata.map((metadataItem, index) => (
<div key={index}>
<TableStyled className="table table-striped">
<tbody>
{Object.entries(metadataItem).map(([key, value]) => (
<tr key={key}>
<Th>{key}</Th>
<Td>{key === 'injection_utc' ? formatDate(value as string) : value}</Td>
</tr>
))}
</tbody>
</TableStyled>
{!(index === selectedMetadata.length - 1) && <TableBottomLine />}
</div>
))}
</GroupDiv>
);
})}
</TableContainer>
);
};
export default Table;
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sg.flooringmastery.ui;
import com.sg.flooringmastery.dto.Order;
import com.sg.flooringmastery.service.FlooringMasteryDataValidationException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
*
* @author Al Rahman
*/
public class FlooringMasteryView {
private UserIO io;
public FlooringMasteryView(UserIO io) {
this.io = io;
}
public void displayTitleBanner() {
+ "|| ||\n"
+ "|| SWG Corp ||\n"
+ "|| Flooring Program ||\n"
+ "|| ||\n"
}
public int printMenuAndGetSelection() throws FlooringMasteryDataValidationException {
return io.readInt("<<Flooring Program Menu>>\n"
+ "1. Display Orders By Date\n"
+ "2. Display All Orders\n"
+ "3. Display All Dates\n"
+ "4. Add an Order\n"
+ "5. Edit an Order\n"
+ "6. Remove an Order\n"
+ "7. Save Current Work\n"
+ "8. Quit\n"
+ "Please select a number from the menu above:", 1, 8);
}
public Order getNewOrderInfo(Order newOrder) throws FlooringMasteryDataValidationException {
String customerName = io.readString("Please enter the Customer Name:");
String state = io.readString("Please select a State from the following selection [OH, PA, MI, IN]:");
String productType = io.readString("Please select a Product Type from the following selection [wood, laminate, tile, carpet]:");
double area = io.readDouble("Please enter the Area amount:");
newOrder.setCustomerName(customerName);
newOrder.getTaxData().setStateAbbr(state.toUpperCase());
newOrder.getProductData().setProductType(productType.toLowerCase());
newOrder.setArea(area);
return newOrder;
}
public String[] getEditOrderInfo(Order currentOrder) throws FlooringMasteryDataValidationException {
String customerName = "", state = "", productType = "", area = "";
if (currentOrder != null) {
io.readString("Instructions:\n"
+ "* The previous order data will be shown in parentheses.\n"
+ "* Press enter to leave a field unchanged.\n"
+ "* Edit the data for this order by entering new information for each field. This will\n"
+ " overwrite the previous order data (in parentheses) with the new information entered.");
customerName = io.readString("Please enter the Customer Name: (" + currentOrder.getCustomerName() + ")");
if (customerName.trim().length() == 0
&& customerName.isEmpty()
|| customerName.equalsIgnoreCase(currentOrder.getCustomerName())) {
io.print("* Field is left unchanged. [" + currentOrder.getCustomerName() + "] is kept as Customer Name.\n");
} else {
io.print("* You have edited Customer Name from: [" + currentOrder.getCustomerName() + "] to : " + customerName + ".\n");
}
String stateFullName = currentOrder.getTaxData().getStateFullName().substring(0, 1).toUpperCase()
+ currentOrder.getTaxData().getStateFullName().substring(1);
state = io.readString("Please select a State from the following selection [OH, PA, MI, IN]: ("
+ stateFullName + " - " + currentOrder.getTaxData().getStateAbbr() + ")");
if (state.trim().length() == 0
&& state.isEmpty()
|| state.equalsIgnoreCase(currentOrder.getTaxData().getStateAbbr())
|| state.equalsIgnoreCase(currentOrder.getTaxData().getStateFullName())) {
io.print("* Field is left unchanged. [" + stateFullName + " - " + currentOrder.getTaxData().getStateAbbr()
+ "] is kept as State.\n");
} else {
io.print("* You have edited State from: [" + stateFullName + " - " + currentOrder.getTaxData().getStateAbbr()
+ "] to : " + state.toUpperCase() + ".\n");
}
productType = io.readString("Please select a Product Type from the following selection "
+ "[wood, laminate, tile, carpet]: (" + currentOrder.getProductData().getProductType() + ")");
if (productType.trim().length() == 0
&& productType.isEmpty()
|| productType.equalsIgnoreCase(currentOrder.getProductData().getProductType())) {
io.print("* Field is left unchanged. [" + currentOrder.getProductData().getProductType()
+ "] is kept as Product Type.\n");
} else {
io.print("* You have edited Product Type from: [" + currentOrder.getProductData().getProductType()
+ "] to : " + productType.toLowerCase() + ".\n");
}
area = io.readString("Please enter the Area amount: (" + currentOrder.getArea() + " sq ft.)");
if (area.trim().length() == 0
&& area.isEmpty()
|| area.equalsIgnoreCase(Double.toString(currentOrder.getArea()))) {
io.print("* Field is left unchanged. [" + currentOrder.getArea() + " sq ft.] is kept as Area.\n");
} else {
io.print("* You have edited Area from: [" + currentOrder.getArea() + " sq ft.] to : " + area + " sq ft.\n");
}
} else {
io.print("No order exists for that date or order number.");
}
return new String[]{customerName, state.toUpperCase(), productType.toLowerCase(), area};
}
public void displayOrder(List<Order> orderList) {
if (!orderList.isEmpty()) {
io.print("\n*******************************"
+ "Order Summary"
+ "*******************************");
for (Order currentOrder : orderList) {
String state = currentOrder.getTaxData().getStateFullName().substring(0, 1).toUpperCase()
+ currentOrder.getTaxData().getStateFullName().substring(1);
io.print(displayLineSeparators() + "\n");
io.print("[Date]: " + currentOrder.getOrderDate() + " || "
+ "[Order Number]: " + currentOrder.getOrderNumber() + " || "
+ "[Customer Name]: " + currentOrder.getCustomerName() + " || "
+ "[State]: " + state + " (" + currentOrder.getTaxData().getStateAbbr() + ") || "
+ "[State Tax Rate]: " + currentOrder.getTaxData().getTaxRate() + "% || "
+ "[Product Type]: " + currentOrder.getProductData().getProductType() + " || "
+ "[Area]: " + currentOrder.getArea() + " sq ft. || "
+ "[Cost Per Square Foot]: $" + currentOrder.getProductData().getCostPerSquareFoot() + " || "
+ "[Labor Cost Per Square Foot]: $" + currentOrder.getProductData().getLaborCostPerSquareFoot() + " || "
+ "[Material Cost]: $" + currentOrder.getMaterialCost() + " || "
+ "[Labor Cost]: $" + currentOrder.getLaborCost() + " || "
+ "[Total Tax]: $" + currentOrder.getTotalTax() + " || "
+ "[Total Amount]: $" + currentOrder.getTotalAmount() + " || ");
}
io.print(displayLineSeparators() + "\n");
} else {
io.print("No order exists for that date or order number.");
}
}
public void displayOrders(List<Order> orderList) {
if (!orderList.isEmpty()) {
io.print("\n*******************************"
+ "Order Summary"
+ "*******************************");
for (Order currentOrder : orderList) {
String state = currentOrder.getTaxData().getStateFullName().substring(0, 1).toUpperCase()
+ currentOrder.getTaxData().getStateFullName().substring(1);
io.print(displayLineSeparators() + "\n");
io.print("[Date]: " + currentOrder.getOrderDate() + " || "
+ "[Order Number]: " + currentOrder.getOrderNumber() + " || "
+ "[Customer Name]: " + currentOrder.getCustomerName() + " || "
+ "[State]: " + state + " (" + currentOrder.getTaxData().getStateAbbr() + ") || "
+ "[State Tax Rate]: " + currentOrder.getTaxData().getTaxRate() + "% || "
+ "[Product Type]: " + currentOrder.getProductData().getProductType() + " || "
+ "[Area]: " + currentOrder.getArea() + " sq ft. || "
+ "[Cost Per Square Foot]: $" + currentOrder.getProductData().getCostPerSquareFoot() + " || "
+ "[Labor Cost Per Square Foot]: $" + currentOrder.getProductData().getLaborCostPerSquareFoot() + " || "
+ "[Material Cost]: $" + currentOrder.getMaterialCost() + " || "
+ "[Labor Cost]: $" + currentOrder.getLaborCost() + " || "
+ "[Total Tax]: $" + currentOrder.getTotalTax() + " || "
+ "[Total Amount]: $" + currentOrder.getTotalAmount() + " || ");
}
io.print(displayLineSeparators() + "\n");
} else {
io.print("No order exists for that date or order number.");
}
}
public void displayOrderDates(List<String> listOfDates, List<String> listOfFileNames) {
if (!listOfDates.isEmpty()) {
io.print("---------- List of Order Dates in File ----------");
listOfDates.forEach(currentDate -> io.print(currentDate));
} else {
io.print("There are no dates listed in file yet.");
}
if (!listOfFileNames.isEmpty()) {
io.print("---------- List of File Names ----------");
listOfFileNames.forEach(currentFile -> io.print(currentFile));
} else {
io.print("There are no file names yet.");
}
io.print("\n");
}
public boolean promptSaveData() {
String input = "";
do {
input = io.readString("Would you like to keep this data? [Y/N]");
if (this.readYesOrNo(input)) {
this.displayYesNoInputError();
} else if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
return true;
}
} while (this.readYesOrNo(input));
return false;
}
public String promptRemoveData() {
String input = "";
do {
input = io.readString("Would you like to remove this order? [Y/N]");
if (this.readYesOrNo(input)) {
this.displayYesNoInputError();
} else if (input.equalsIgnoreCase("y") || input.equalsIgnoreCase("yes")) {
input = io.readString("Are you sure?");
}
} while (this.readYesOrNo(input));
return input;
}
public boolean promptUserToContinue(boolean hasErrors, String message) {
String input;
if (hasErrors) {
do {
input = io.readString("Would you like to continue " + message + "? Press [Y] "
+ "to contine or [N] to return to the main menu.");
if (this.readYesOrNo(input)) {
this.displayYesNoInputError();
} else if (input.equalsIgnoreCase("n") || input.equalsIgnoreCase("no")) {
return true;
}
} while (this.readYesOrNo(input));
}
return false;
}
public String promptUserForDate() {
return io.readString("Please enter the date in MM-dd-yyyy format:");
}
public int promptUserForOrderNum() throws FlooringMasteryDataValidationException {
return io.readInt("Please enter the order number:");
}
public void prompEnterToContinue() {
io.readString("Please hit enter to continue.");
}
public void displayAllOrdersByDateBanner() {
}
public void displayAllOrdersBanner() {
}
public void displayAllDatesBanner() {
}
public void displayAddOrderBanner() {
}
public void displayRemoveOrderBanner() {
}
public void displayEditOrderBanner() {
}
public void displayAddOrderSuccessBanner(Order order) {
if (order != null) {
io.readString("Order successfully added. Please hit enter to continue.");
} else {
io.readString("New order data discarded. Please hit enter to continue.");
}
}
public void displayEditOrderSuccessBanner(boolean orderInfoEmpty) {
// List<String> CheckOrderInfo = Arrays.asList(orderInfo).stream()
// .filter(s -> !s.isEmpty()).collect(Collectors.toList());
// !CheckOrderInfo.isEmpty()
if (!orderInfoEmpty) {
io.readString("Order successfully edited. Please hit enter to continue.");
} else {
io.readString("Order data was left unchanged. Please hit enter to continue.");
}
}
public void displayRemoveOrderSuccessBanner(Order order) {
if (order == null) {
io.readString("Order successfully removed from file. Please hit enter to continue.");
} else {
io.readString("Order was not removed from file. Please hit enter to continue.");
}
}
public void displaySaveSucessBanner() {
io.readString("All order data was successfully saved in file. Please hit enter to continue.");
}
public void displayExitBanner() {
io.print("Current data saved.\n"
+ "Thank you for using SWG Corp Flooring Program.");
}
public String displayLineSeparators() {
String line = "";
for (int i = 0; i < 8; i++) {
line += "-------------------------------------------";
}
return line;
}
public void displayUnknownCommandBanner() {
io.print("Unknown Command!!!");
}
public void displayErrorMessage(String errorMessage) {
+ errorMessage);
io.readString("Hit enter to continue.");
}
public void displayYesNoInputError() {
io.print("<Error> Please enter [Y/N].");
io.readString("Hit enter to continue.");
}
public boolean readYesOrNo(String input) {
return !(input.equalsIgnoreCase("y"))
&& !(input.equalsIgnoreCase("n"))
&& !(input.equalsIgnoreCase("yes"))
&& !(input.equalsIgnoreCase("no"));
}
}
|
import mongoose from "mongoose";
import { User, Product } from "./models";
const url = process.env.MONGO;
export const connectToDB = async () => {
const connection = {};
try {
if (connection.isConnected) return;
const db = await mongoose.connect(url);
connection.isConnected = db.connections[0].readyState;
} catch (error) {
console.log("error", error);
throw new Error(error);
}
};
export const fetchUsers = async (q, page) => {
const regex = new RegExp(q, "i");
const ITEM_PER_PAGE = 2;
try {
connectToDB();
const count = await User.find({ username: { $regex: regex } }).count();
const users = await User.find({ username: { $regex: regex } })
.limit(ITEM_PER_PAGE)
.skip(ITEM_PER_PAGE * (page - 1));
return { count, users };
} catch (err) {
console.log("err", err);
throw new Error("failed to fetch users");
}
};
export const fetchUser = async (id) => {
try {
connectToDB();
const user = await User.findById(id);
return user;
} catch (err) {
console.log("err", err);
throw new Error("failed to fetch users");
}
};
export const fetchProduct = async (id) => {
try {
connectToDB();
const product = await Product.findById(id);
return product;
} catch (err) {
console.log("err", err);
throw new Error("failed to fetch users");
}
};
export const fetchProducts = async (q, page) => {
const regex = new RegExp(q, "i");
const ITEM_PER_PAGE = 2;
try {
connectToDB();
const count = await Product.find({ title: { $regex: regex } }).count();
const products = await Product.find({ title: { $regex: regex } })
.limit(ITEM_PER_PAGE)
.skip(ITEM_PER_PAGE * (page - 1));
return { count, products };
} catch (err) {
console.log("err", err);
throw new Error("failed to fetch users");
}
};
|
package com.itheima.reggie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author 金宗文
* @version 1.0
*/
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
@Resource
private RedisTemplate redisTemplate;
/**
* 发送
* @param user
* @return
*/
@PostMapping("/sendMsg")
public R<String> sendMsg(@RequestBody User user, HttpSession session){
//获取手机号
String phone = user.getPhone();
if(StringUtils.isNotEmpty(phone)){
//生成随机4位验证码
String code = ValidateCodeUtils.generateValidateCode(4).toString();
log.info("验证码为:{}",code);
// //调用阿里云短信服务发送验证码
// SMSUtils.sendMessage("阿里云短信测试","SMS_154950909","18512891272",code);
//将生成的验证码保存到Session中
session.setAttribute(phone,code);
//将生成的验证码缓存到Redis中,设置有效期为5分钟
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
return R.success("手机验证码短信发送成功");
}
return R.error("短信操作失败");
}
/**
* 移动端用户登录
* @return
*/
@PostMapping("/login")
public R<User> login(@RequestBody Map map,HttpSession session){
log.info(map.toString());
//获取手机号
String phone = map.get("phone").toString();
//获取验证码
String code = map.get("code").toString();
//获取Session中的验证码
// Object codeInSession = session.getAttribute(phone);
//从Redis中获取验证码
Object codeInSession = redisTemplate.opsForValue().get(phone);
//比较验证码是否一致
if (codeInSession != null && codeInSession.equals(code)){
//如果一致,则登录成功,将用户信息保存到Session中
//如果为新用户,自动完成注册
LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
userLambdaQueryWrapper.eq(User::getPhone,phone);
User user = userService.getOne(userLambdaQueryWrapper);
if (user == null){
//新用户
user = new User();
user.setPhone(phone);
user.setStatus(1);
userService.save(user);
}
//将用户信息保存到Session中
session.setAttribute("user",user.getId());
//如果用户登录成功,则删除Redis中的验证码
redisTemplate.delete(phone);
return R.success(user);
}
return R.error("登录失败");
}
}
|
#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include "MpptDisplay.h"
#include "icons.h"
#include "mydelay.h"
#ifndef SD1306MPPT_DISPLAY
#define SD1306MPPT_DISPLAY
//Rotated display draw lines
const int y1 = 9;
const int y2 = 23;
const int y3 = 38;
const int y4 = 53;
//Rotated display draw rectangle at the top
const int rx1 = 0;
const int ry1 = 0;
const int x1 = 5;
const int x2 = 50;
const int x3 = 95;
const int rw = 128;
const int rh = 8;
class SD1306MpptDisplay: public MpptDisplay {
public:
SD1306MpptDisplay(Adafruit_SSD1306* ssdDisplay, uint8_t i2cAddr) {
display = ssdDisplay;
address = i2cAddr;
};
void setup();
void clear();
void init(float vcc, float Vsolb, float Vbatb);
void sweepUpdate(int pwm, float Vsol, float Isol, float Psol);
void update(float vcc, float Vsol, float Isol, float Vbat, float Ibat, float batPerc, int dc, float eff, int mode);
private:
Adafruit_SSD1306* display;
uint8_t address;
int px, py1, py2, py3;
void drawHeader(int bat, float efficiency, int mode);
};
void SD1306MpptDisplay::drawHeader(int bat, float efficiency, int mode) {
display->setTextSize(1);
display->setTextColor(SSD1306_WHITE);
display->cp437(true);
display->setCursor(x1, y1);
display->write("SOL");
display->drawBitmap(30, y1, solar_icon, 8, 8, SSD1306_WHITE);
display->setCursor(x2, y1);
display->write("BAT");
display->drawBitmap(75, y1, bat_icons[bat], 8, 8, SSD1306_WHITE);
display->setCursor(x3, y1);
display->write("PWM");
display->drawBitmap(120, y1, pwm_icon, 8, 8, SSD1306_WHITE);
display->setCursor(95, y3);
if (mode == 0) {
display->write("Off");
}
else if (mode == 1) {
display->write("CC");
}
else if (mode == 2) {
display->write("CV");
}
// display->write("VCC");
// display->drawBitmap(120, y3, vcc_icon, 8, 8, SSD1306_WHITE);
display->fillRect(rx1, ry1, rw, rh, SSD1306_BLACK);
}
void SD1306MpptDisplay::setup() {
while (!display->begin(SSD1306_SWITCHCAPVCC, address, false)) {
Serial.begin(115200);
Serial.println(F("SSD1306 allocation failed"));
mydelay(1000);
}
display->clearDisplay();
// drawHeader(0, 0, 0);
display->display();
}
void SD1306MpptDisplay::init(float vcc, float Vsolb, float Vbatb) {
display->setCursor(x1, y1);
display->write("VCC");
display->setCursor(x1, y2);
display->print(vcc, 3);
display->print("V");
display->setCursor(x2, y1);
display->write("Vsol");
display->setCursor(x2, y2);
display->print(Vsolb, 3);
display->print("V");
display->setCursor(x3, y1);
display->write("Vbat");
display->setCursor(x3, y2);
display->print(Vbatb, 3);
display->print("V");
mydelay(3000);
}
void SD1306MpptDisplay::clear() {
display->clearDisplay();
px = 0;
py1 = 60;
py2 = 60;
py3 = 60;
}
void SD1306MpptDisplay::sweepUpdate(int pwm, float Vsol, float Isol, float Psol) {
if (pwm % 2 == 0) return;
int x = pwm / 2;
int y1 = (int)(60 - 2 * Vsol); //Max 25V so Max 50 pixels
// int y2 = (int)(60 - 30 * Isol); //Max 2A so Max 60 Pixels
int y3 = (int)(60 - 2 * Psol); //Max 30W so Max 60 Pixels
if (pwm == 1) {
py1 = y1;
py2 = y2;
py3 = y3;
}
display->drawLine(px, py1, x, y1, SSD1306_WHITE);
// display->drawLine(px, py2, x, y2, SSD1306_WHITE);
display->drawLine(px, py3, x, y3, SSD1306_WHITE);
display->drawLine(px, 60, px, 60, SSD1306_WHITE);
display->display();
px = x;
py1 = y1;
py2 = y2;
py3 = y3;
}
void SD1306MpptDisplay::update(float vcc, float Vsol, float Isol, float Vbat, float Ibat, float batPerc, int dc, float eff, int mode) {
display->clearDisplay();
int indicator = (int)(min(batPerc, 100) * 6 / 100);
drawHeader(indicator, eff, mode);
display->setCursor(x1, y2);
display->print(Vsol, 1);
display->print('V');
display->setCursor(x1, y3);
display->print(Isol, 2);
display->print("A");
display->setCursor(x1, y4);
display->print(Vsol * Isol, 1);
display->print("W");
display->setCursor(x2, y2);
display->print(Vbat, 1);
display->print('V');
display->setCursor(x2, y3);
display->print(Ibat, 2);
display->print("A");
display->setCursor(x2, y4);
display->print(batPerc, 0);
display->print('%');
display->setCursor(x3, y2);
display->print(dc);
display->print('%');
display->setCursor(x3, y4);
if (eff > 0) {
display->print(eff, 0);
display->print("%");
}
else {
display->print(vcc, 1);
display->print("V");
}
display->fillRect(rx1, ry1, rw, rh, SSD1306_BLACK);
display->display();
}
#endif
|
import React, {useState} from 'react';
import {SafeAreaView} from 'react-native-safe-area-context';
import {View, Text} from 'react-native';
import {locationSerialization} from '../../shared/lib/locationSerialization';
import {useTrackingLocations} from '../../shared/lib/useLocations';
import {CustomButton} from '../../shared/ui/atoms/CustomButton';
import YandexMap from '../../shared/ui/organisms/yandexMap/YandexMap';
import {useStyles} from './styles';
import {
$trackingHistory,
setTrackingHistory,
} from '../../entities/RoadTracker/model/historyRoads';
import {useStore} from 'effector-react';
import {$initialLocation} from '../../entities/RoadTracker/model/initialLocation';
export const RoadTrackerScreen: React.FC = () => {
const styles = useStyles();
const [isTracing, setIsTracing] = useState(false);
const trackingItem = useTrackingLocations(isTracing);
const trackingHistory = useStore($trackingHistory);
const initialLocation = useStore($initialLocation);
return (
<SafeAreaView style={styles.containerArea}>
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.textHeader}>My tracker</Text>
</View>
<View style={styles.location}>
{initialLocation !== undefined && (
<YandexMap
locations={locationSerialization(trackingItem.locations)}
initialLocation={initialLocation}
/>
)}
</View>
{trackingItem.timer > 0 && (
<Text style={styles.textTimer}>{trackingItem.timer}s</Text>
)}
<CustomButton
text={isTracing ? 'Pause' : 'Go'}
onPress={() => setIsTracing(!isTracing)}
/>
<CustomButton
text="Сохранить"
onPress={() => {
if (!trackingItem) {
return;
}
setTrackingHistory([...trackingHistory, trackingItem]);
setIsTracing(false);
trackingItem.resetTracking();
}}
/>
</View>
</SafeAreaView>
);
};
|
pragma solidity ^0.4.24;
import "../base/BurnableToken.sol";
import "./DelegateBurnable.sol";
// See DelegateBurnable.sol for more on the delegation system.
contract CanDelegateToken is BurnableToken {
// If this contract needs to be upgraded, the new contract will be stored
// in 'delegate' and any BurnableToken calls to this contract will be delegated to that one.
DelegateBurnable private _delegate;
event DelegateToNewContract(address indexed newContract);
function balanceOf(address who) public view returns (uint256) {
if (!_hasDelegate()) {
return super.balanceOf(who);
} else {
return _delegate.delegateBalanceOf(who);
}
}
function getTheNumberOfHolders() public view returns (uint256) {
if (!_hasDelegate()) {
return super.getTheNumberOfHolders();
} else {
return _delegate.delegateGetTheNumberOfHolders();
}
}
function getHolder(uint256 _index) public view returns (address) {
if (!_hasDelegate()) {
return super.getHolder(_index);
} else {
return _delegate.delegateGetHolder(_index);
}
}
function delegate() public view returns (address) {
return _delegate;
}
// Can undelegate by passing in newContract = address(0)
function delegateToNewContract(
DelegateBurnable newContract
)
public
onlyOwner
{
_delegate = newContract;
emit DelegateToNewContract(_delegate);
}
function totalSupply() public view returns (uint256) {
if (!_hasDelegate()) {
return super.totalSupply();
} else {
return _delegate.delegateTotalSupply();
}
}
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
if (!_hasDelegate()) {
return super.allowance(owner, spender);
} else {
return _delegate.delegateAllowance(owner, spender);
}
}
function _approve(
address spender,
uint256 value,
address holder
)
internal
{
if (!_hasDelegate()) {
super._approve(spender, value, holder);
} else {
require(_delegate.delegateApprove(spender, value, holder));
}
}
function _decreaseAllowance(
address spender,
uint256 subtractedValue,
address holder
)
internal
{
if (!_hasDelegate()) {
super._decreaseAllowance(spender, subtractedValue, holder);
} else {
require(
_delegate.delegateDecreaseAllowance(
spender,
subtractedValue,
holder)
);
}
}
function _increaseAllowance(
address spender,
uint256 addedValue,
address holder
)
internal
{
if (!_hasDelegate()) {
super._increaseAllowance(spender, addedValue, holder);
} else {
require(
_delegate.delegateIncreaseAllowance(spender, addedValue, holder)
);
}
}
// If a delegate has been designated, all ERC20 calls are forwarded to it
function _transfer(address from, address to, uint256 value) internal {
if (!_hasDelegate()) {
super._transfer(from, to, value);
} else {
require(_delegate.delegateTransfer(to, value, from));
}
}
function _transferFrom(
address from,
address to,
uint256 value,
address spender
)
internal
{
if (!_hasDelegate()) {
super._transferFrom(from, to, value, spender);
} else {
require(_delegate.delegateTransferFrom(from, to, value, spender));
}
}
function _burn(address burner, uint256 value, string note) internal {
if (!_hasDelegate()) {
super._burn(burner, value, note);
} else {
_delegate.delegateBurn(burner, value , note);
}
}
function _hasDelegate() internal view returns (bool) {
return !(_delegate == address(0));
}
}
|
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="unqualified">
<xs:annotation>
<xs:documentation xml:lang="en">
This is the XSD schema definition for oTMS web services.
Please refer to collection of oTMS Web Services Specification documents for
further details.
</xs:documentation>
</xs:annotation>
<xs:element name="orderImportRequest" type="orderImportRequest" />
<xs:element name="orderImportResponse" type="orderImportResponse" />
<xs:complexType name="orderImportRequest">
<xs:annotation>
<xs:documentation xml:lang="en">
The request for order
import. Request contains the necessary
information to authenticate
into oTMS and
the list of order data to import.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="orders">
<xs:annotation>
<xs:documentation xml:lang="en">
Contains the list of
order data to import.
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="100" minOccurs="0" name="order" type="importedOrder" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="version" type="shortString" use="required">
<xs:annotation>
<xs:documentation xml:lang="en">
The version number of
the request.
</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="login" type="remarksType" use="required">
<xs:annotation>
<xs:documentation xml:lang="en">
Login name granted to
perform import order for oTMS registered
company.
</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="password" type="shortString" use="required">
<xs:annotation>
<xs:documentation xml:lang="en">
Supplied password for
login.
</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
<xs:complexType name="importedOrder">
<xs:annotation>
<xs:documentation xml:lang="en">
Single order data to
import.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="clientCode" type="clientCode">
<xs:annotation>
<xs:documentation xml:lang="en">
Offline client code in
case of SP oTMS perspective. This is skip in
case of SR
perspective.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="clientReferenceNumber" type="remarksType">
<xs:annotation>
<xs:documentation xml:lang="en">
Customer reference
number. It can be order identifier of a calling
system.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="branch" type="mediumString">
<xs:annotation>
<xs:documentation xml:lang="en">
Branch name.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="erpNumber" type="mediumString">
<xs:annotation>
<xs:documentation xml:lang="en">
Order Erp Number
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="orderRemarks" type="remarksType">
<xs:annotation>
<xs:documentation xml:lang="en">
Order remarks.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="allowUpdate" type="xs:boolean">
<xs:annotation>
<xs:documentation xml:lang="en">
True/false flag - if
true then the order will be updated if
orders imported by API
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:choice minOccurs="0">
<xs:annotation>
<xs:documentation xml:lang="en">
ShipFrom location can
be given in two ways:
1) by ShipFrom externalId - defined in
MasterData
2) full location specification
</xs:documentation>
</xs:annotation>
<xs:element name="shipFromExternalId" type="xs:string" />
<xs:element name="shipFrom" type="location" />
</xs:choice>
<xs:choice minOccurs="0">
<xs:annotation>
<xs:documentation xml:lang="en">
ShipTo location can be
given in two ways:
1) by ShipTo externalId - defined in
MasterData
2) full location specification
</xs:documentation>
</xs:annotation>
<xs:element name="shipToExternalId" type="xs:string" />
<xs:element name="shipTo" type="location" />
</xs:choice>
<xs:element name="timeSchedule" type="importedTimeSchedule" />
<xs:element minOccurs="0" maxOccurs="1" name="orderLines">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines many
cargo/product lines. May be missing.
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="500" minOccurs="0" name="orderLine" type="importedOrderLine" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element minOccurs="0" name="concealOrderLines" type="xs:boolean">
<xs:annotation>
<xs:documentation xml:lang="en">
True/false flag - if
true then no cargo/product details will be concealed
from vendor.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="rejectDraft" type="xs:boolean">
<xs:annotation>
<xs:documentation xml:lang="en">
True/false flag - if
true then the order will be rejected if it
reaches only draft status (only orders that
qualify for inbox will be imported)
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="autoProcessMode" type="AutoProcessMode" />
<xs:element minOccurs="0" name="dispatchBy" type="AutoDispatchTariffSelectionMode" />
<xs:element minOccurs="0" name="toTruck" type="importedTruck" />
<xs:element name="cargoDetails" type="importedCargoDetails" />
<xs:element name="transportMode" type="importedTransportMode" />
<xs:element minOccurs="0" name="revenue" type="importedRevenue"/>
<xs:element minOccurs="0" name="cost" type="importedRevenue"/>
<xs:element minOccurs="0" name="vendorCode" type="clientCode">
<xs:annotation>
<xs:documentation xml:lang="en">
Online vendor code
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="tempThreshold" type="importedTemperature"/>
<xs:element minOccurs="0" name="customFields" type="importedCustomFields" />
</xs:sequence>
<xs:attribute name="sequence" type="xs:int" use="required">
<xs:annotation>
<xs:documentation xml:lang="en">
Each order to import must contain the unique sequence value. The order
responses contain
these too. This way user can match incoming order to outgoing order
response.
</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
<xs:complexType name="location">
<xs:annotation>
<xs:documentation xml:lang="en">
Describes geographical
location of ShipFrom/ShipTo points.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="companyName" type="mediumString">
<xs:annotation>
<xs:documentation xml:lang="en">
ShipFrom/ShipTo
location name.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="postcode" type="zipcodeType">
<xs:annotation>
<xs:documentation xml:lang="en">
Full Chinese postcode
of the location. 6 digits.
Based on the full postcode and the
town of the location, oTMS
platform uses its Zipcode Engine
to
select right geography area.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="town" type="shortString">
<xs:annotation>
<xs:documentation xml:lang="en">
The town name (in
native Chinese).
Based on town, oTMS pltaform uses its Zipcode
Engine to select right
geography area.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="address" type="addressLine">
<xs:annotation>
<xs:documentation xml:lang="en">
The address line.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="loading" type="xs:boolean">
<xs:annotation>
<xs:documentation xml:lang="en">
true/false flag saying
if loading takes place in case of ShipFrom location
or unloading
in case of ShipTo location.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="xttSupport" type="xs:boolean">
<xs:annotation>
<xs:documentation xml:lang="en">
true/false flag saying
if order does support xtt
and should send e-mails to contact persons
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="contact" type="importedContactPerson" />
<xs:element minOccurs="0" name="locationRemarks" type="remarksType">
<xs:annotation>
<xs:documentation xml:lang="en">
ShipFrom/ShipTo point remarks.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="timeWindow" type="pickupDeliveryTime" />
<xs:element minOccurs="0" name="weekdays" type="weekdays" />
<xs:element minOccurs="0" name="customFields" type="importedCustomFields" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedContactPerson">
<xs:annotation>
<xs:documentation xml:lang="en">
The contact details of
the person available at point.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="name" type="mediumString">
<xs:annotation>
<xs:documentation xml:lang="en">
Family and surname of
contact person available at point.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="phone" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Desktop phone name.
Must conform to the following regexp pattern:
\d{6,10}(-[0-9]{1,5})?
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="phoneAreaCode" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Area code for phone
number.
Regexp:
\d{1,4}
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="mobile" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Mobile phone name.
Must confirm to the following regexp pattern:
\d{11}
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="email" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Email of contact
person. Must be a valid email.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedTimeSchedule">
<xs:annotation>
<xs:documentation xml:lang="en">
Time schedule for the
order. Defines the pickup and delivery dates.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="pickupDate" type="xs:date">
<xs:annotation>
<xs:documentation xml:lang="en">
Pickup date in Chinese
Standard Time.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="pickupDateRemarks" type="remarksType">
<xs:annotation>
<xs:documentation xml:lang="en">
Pickup date remarks.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="deliveryDate" type="xs:date">
<xs:annotation>
<xs:documentation xml:lang="en">
Delivery date in
Chinese Standard Time.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="deliveryDateRemarks" type="remarksType">
<xs:annotation>
<xs:documentation xml:lang="en">
Delivery date remarks.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="pickupTimeFrom" type="xs:time">
<xs:annotation>
<xs:documentation xml:lang="en">
PickupTimeFrom time in
Chinese Standard Time.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="pickupTimeTo" type="xs:time">
<xs:annotation>
<xs:documentation xml:lang="en">
PickupTimeTo time in
Chinese Standard Time.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="deliveryTimeFrom" type="xs:time">
<xs:annotation>
<xs:documentation xml:lang="en">
DeliveryTimeFrom time in
Chinese Standard Time.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="deliveryTimeTo" type="xs:time">
<xs:annotation>
<xs:documentation xml:lang="en">
DeliveryTimeTo time in
Chinese Standard Time.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedOrderLine">
<xs:annotation>
<xs:documentation xml:lang="en">
Contains the
cargo/product definition and its amounts in the order.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:choice minOccurs="1">
<xs:annotation>
<xs:documentation xml:lang="en">
The cargo/product
definition may be referred in two ways:
1) by externalId, a
unique identifier of the cargo definition
within company
master
data
2) cargo/product definition is fully supplied here
</xs:documentation>
</xs:annotation>
<xs:element name="externalId" type="mediumString" />
<xs:element name="cargoDescription" type="importedCargoDescription" />
</xs:choice>
<xs:element minOccurs="0" name="quantity" type="quantityType">
<xs:annotation>
<xs:documentation xml:lang="en">
Number of
cargo/product units.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="weight" type="weightType">
<xs:annotation>
<xs:documentation xml:lang="en">
Total weight of all
units.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="volume" type="volumeType">
<xs:annotation>
<xs:documentation xml:lang="en">
Total volume of all
units.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="insuranceValue" type="priceType">
<xs:annotation>
<xs:documentation xml:lang="en">
Total insurance value
of all units.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="remarks" type="remarksType">
<xs:annotation>
<xs:documentation xml:lang="en">
User remarks to the
cargo/product line.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="customFields" type="importedCustomFields" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedCargoDescription">
<xs:annotation>
<xs:documentation xml:lang="en">
Cargo description
provides the definition of the product/cargo.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="productCode" type="mediumString">
<xs:annotation>
<xs:documentation xml:lang="en">
The product code.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="productName" type="addressLine">
<xs:annotation>
<xs:documentation xml:lang="en">
The product name.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="unitType" type="unitType" />
<xs:element minOccurs="0" name="stackable" type="stackable" />
<xs:element minOccurs="0" name="unitLength" type="dimensionType">
<xs:annotation>
<xs:documentation xml:lang="en">
Unit length.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="unitWidth" type="dimensionType">
<xs:annotation>
<xs:documentation xml:lang="en">
Unit width.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="unitHeight" type="dimensionType">
<xs:annotation>
<xs:documentation xml:lang="en">
Unit height.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="unitWeight" type="weightType">
<xs:annotation>
<xs:documentation xml:lang="en">
The single unit
weight.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedTruck">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the main
information of the truck details.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="driver" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Driver name of the truck.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="truckPlate" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
The plate of the truck.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="phone" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Phone number of the truck driver.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedCargoDetails">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the main
information of the shipping cargo.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="totalQuantity" type="quantityType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the quantity
of physical items to ship.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="totalWeight" type="weightType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the total
weight of the cargo.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="totalVolume" type="volumeType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the total
volume of the cargo.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="totalInsurance" type="priceType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the total
insurance amount of the cargo.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="cargoType" type="cargoType" />
<xs:element minOccurs="0" name="packageType" type="packageType" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedTransportMode">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the transport
aspect for the order.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="transportType" type="transportType" />
<xs:element minOccurs="0" name="truckType" type="truckType" />
<xs:element minOccurs="0" name="transportRemarks" type="remarksType">
<xs:annotation>
<xs:documentation xml:lang="en">
User defined remarks
about the transport mode.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="loadingMeter" type="loadingMeterType">
<xs:annotation>
<xs:documentation xml:lang="en">
The number of loading
meters.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="truckLength" type="truckLengthType">
<xs:annotation>
<xs:documentation xml:lang="en">
The truck length. If
given, must be selected from predefined
values. The truck lengths
are
configured per company. The oTMS defines the global set of
supported truck
lengths.
If truck length cannot be matched within
oTMS system - error code
1006 is returned.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="truckCbmCapacity" type="truckCbmCapacityType">
<xs:annotation>
<xs:documentation xml:lang="en">
The truck CBM
capacity. If given, must be selected from predefined
values.
Truck lengths
define a subset of available CBM truck capacities.
The oTMS defines
the global set of truck lengths
and their
capacities (CBM and MT). If truck CBM capacity cannot be
matched
within oTMS system - error code 1006 is returned.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="truckMtCapacity" type="truckMtCapacityType">
<xs:annotation>
<xs:documentation xml:lang="en">
The truck MT capacity.
If given, must be selected from predefined
values. Truck lengths
define a subset of available MT truck capacities. The oTMS
defines the
global set of
truck lengths and their capacities (CBM
and MT). If truck MT capacity
cannot be matched within oTMS
system - error code 1007 is
returned.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedRevenue">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines revenue for order.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="lineHaul" type="priceType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines base rate of order.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="baseRateDescription" type="description">
<xs:annotation>
<xs:documentation xml:lang="en">
Base rate description.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="other" type="priceType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines other fees of order.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="otherFeesDescription" type="description">
<xs:annotation>
<xs:documentation xml:lang="en">
Other fees description.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="importedTemperature">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines temperature threshold for order.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="minTemp" type="tempType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the minimum temperature
of the cargo.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="maxTemp" type="tempType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines the maximum temperature
of the cargo.
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:complexType name="orderImportResponse">
<xs:annotation>
<xs:documentation xml:lang="en">
Response of order import
service. Contains global response code for import
operation and
list of
responses per incoming orders - in the same sequence as
orders arrived.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="responseCode" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Global response code.
If not empty - indicates general error with the
response:
0 - service call not authorised
1 - unsupported version
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="1" name="processedOrders" type="xs:string">
<xs:annotation>
<xs:documentation>
Number of processed orders.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="orders">
<xs:annotation>
<xs:documentation xml:lang="en">
Contains the list of
order responses in the same sequence as order came
in the
request.
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" minOccurs="0" name="order" type="orderResponse" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="version" type="xs:string" use="required">
<xs:annotation>
<xs:documentation xml:lang="en">
Returns back the
response version.
</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
<xs:complexType name="orderResponse">
<xs:annotation>
<xs:documentation xml:lang="en">
A response record for
order being imported.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="clientReferenceNumber" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Returns back the
client reference number for the order.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="orderNumber" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Returns back the order
number assigned by oTMS system for imported
order.
If order
couldn't be imported. This may be empty in case of NOT
IMPORTED
status.
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element name="importStatus" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Returns import status
of the order. Three values possible:
INBOX - an order was
qualified as complete in terms of oTMS system
DRAFT - an order
has some missing information, thus it was
qualified as DRAFT
NOT
IMPORTED - an order couldn't be imported at all
</xs:documentation>
</xs:annotation>
</xs:element>
<xs:element minOccurs="0" name="responseCodes">
<xs:annotation>
<xs:documentation xml:lang="en">
Contains a list of
response codes that describes more precisely the
problems during
the import of this order.
</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element maxOccurs="unbounded" minOccurs="0" name="responseCode" type="responseCode" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="sequence" type="xs:int" use="required">
<xs:annotation>
<xs:documentation xml:ns="en">
This is the value of sequence that corresponds to incoming order entry.
This way the order
response can be matched with order to import.
</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
<xs:complexType name="responseCode">
<xs:sequence>
<xs:element minOccurs="0" name="code" type="xs:string">
<xs:annotation>
<xs:documentation xml:lang="en">
Following response
codes are enumerated:
1000 Client short code not found for order – Order NOT IMPORTED
1001 Invalid datatype in order fields – Order NOT IMPORTED
1002 Reserved for future use
1003 ShipFrom externalId not found
1004 ShipTo externalId not found
1005 Cargo/Product line externalId not found
1006 Truck length mismatch
1007 Truck MT capacity mismatch
1008 Truck CBM capacity mismatch
1009 Multiple ShipFrom externalId found
1010 Multiple ShipTo externalId found
1011 Multiple Cargo/Product line externalId found
1012 No order revenue – this happens at SP perspective - order will be
only a draft
1013 ShipFrom oTMS zipcode cluster matched solely by town
1014 ShipFrom oTMS zipcode cluster matched solely by full postcode
1015 ShipFrom oTMS zipcode cluster unmatched
1016 ShipFrom oTMS zipcode cluster matched by both full postcode and
town
1017 ShipTo oTMS zipcode cluster matched solely by town
1018 ShipTo oTMS zipcode cluster matched solely by full postcode
1019 ShipTo oTMS zipcode cluster unmatched
1020 ShipTo oTMS zipcode cluster matched by both full postcode and
town
1021 No Cargo/Product line definition nor externalId, but
quantities/weights/volumes set
1022 External order number not unique
1030 Custom fields disabled for company
1031 Some custom field ignored - disabled in configuration
1032 Missing value of required custom field
1033 Enum value does not exist
1040 Branch not found
1100 Other failure
</xs:documentation>
</xs:annotation>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="clientCode">
<xs:restriction base="xs:string">
<xs:maxLength value="8" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="addressLine">
<xs:restriction base="xs:string">
<xs:maxLength value="120" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="shortString">
<xs:restriction base="xs:string">
<xs:maxLength value="32" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="zipcodeType">
<xs:restriction base="xs:string">
<xs:length value="6" fixed="true" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="mediumString">
<xs:restriction base="xs:string">
<xs:maxLength value="50" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="description">
<xs:restriction base="xs:string">
<xs:maxLength value="64"/>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="remarksType">
<xs:restriction base="xs:string">
<xs:maxLength value="250" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="quantityType">
<xs:restriction base="xs:int">
<xs:minInclusive value="0" />
<xs:maxExclusive value="1000000000" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="priceType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0" />
<xs:maxExclusive value="10000000000" />
<xs:fractionDigits value="2" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="weightType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0" />
<xs:maxExclusive value="1000000000000" />
<xs:fractionDigits value="3" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="volumeType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0" />
<xs:maxExclusive value="10000000000" />
<xs:fractionDigits value="6" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="dimensionType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0" />
<xs:maxExclusive value="1000" />
<xs:fractionDigits value="2" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="truckLengthType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0" />
<xs:maxExclusive value="100" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="truckMtCapacityType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0" />
<xs:maxExclusive value="100" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="truckCbmCapacityType">
<xs:restriction base="xs:decimal">
<xs:minInclusive value="0" />
<xs:maxExclusive value="100" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="loadingMeterType">
<xs:restriction base="xs:int">
<xs:minInclusive value="0" />
<xs:maxExclusive value="1000000000" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="AutoProcessMode">
<xs:annotation>
<xs:documentation xml:lang="en">
Specifying what operation should be
automatically applied to an order
after import if such operation
enabled.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:enumeration value="1">
<xs:annotation>
<xs:documentation xml:lang="en">
Import only.
No other operations.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="2">
<xs:annotation>
<xs:documentation xml:lang="en">
Order should be
released after import.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="3">
<xs:annotation>
<xs:documentation xml:lang="en">
Order should be
dispatched after import.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="AutoDispatchTariffSelectionMode">
<xs:annotation>
<xs:documentation xml:lang="en">
When auto dispatching, whether tariff
selection should base on price or
lead time. Will be ignored if auto
dispatch not enabled.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:enumeration value="1">
<xs:annotation>
<xs:documentation xml:lang="en">
Tariff should be chosen by
cheapest price.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="2">
<xs:annotation>
<xs:documentation xml:lang="en">
Tariff should be chosen by
shortest lead time
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="pickupDeliveryTime">
<xs:annotation>
<xs:documentation xml:lang="en">
Pickup / delivery time
divides the civil day into time ranges. The
pickup or delivery must
hit
these ranges.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:int">
<xs:enumeration value="1">
<xs:annotation>
<xs:documentation xml:lang="en">
whole day = 0:00 -
23:59
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="2">
<xs:annotation>
<xs:documentation xml:lang="en">
business hours = 8:00
- 18:00
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="3">
<xs:annotation>
<xs:documentation xml:lang="en">
morning = 6:00 - 12:00
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="4">
<xs:annotation>
<xs:documentation xml:lang="en">
afternoon = 12:00 -
18:00
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="5">
<xs:annotation>
<xs:documentation xml:lang="en">
evening = 18:00 -
23:59
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="6">
<xs:annotation>
<xs:documentation xml:lang="en">
night = 0:00 - 6:00
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="weekdays">
<xs:annotation>
<xs:documentation xml:lang="en">
Describes the working
days within the week that ShipFrom/ShipTo operates.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:int">
<xs:enumeration value="1">
<xs:annotation>
<xs:documentation xml:lang="en">
Weekdays from Monday to Friday
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="2">
<xs:annotation>
<xs:documentation xml:lang="en">
Weekdays from Monday to Saturday
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="3">
<xs:annotation>
<xs:documentation xml:lang="en">
Weekdays from Monday to Sunday
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="unitType">
<xs:annotation>
<xs:documentation xml:lang="en">
Specifies the unit type
of cargo/product line.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:int">
<xs:enumeration value="1">
<xs:annotation>
<xs:documentation xml:lang="en">
A palett.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="2">
<xs:annotation>
<xs:documentation xml:lang="en">
A box.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="3">
<xs:annotation>
<xs:documentation xml:lang="en">
A bag.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="4">
<xs:annotation>
<xs:documentation xml:lang="en">
A piece.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="stackable">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines if cargo/product
can be stacked and on how many layers.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:int">
<xs:enumeration value="1">
<xs:annotation>
<xs:documentation xml:lang="en">
Not stackable.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="2">
<xs:annotation>
<xs:documentation xml:lang="en">
2 layers.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="3">
<xs:annotation>
<xs:documentation xml:lang="en">
3 layers.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="4">
<xs:annotation>
<xs:documentation xml:lang="en">
4 layers.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="5">
<xs:annotation>
<xs:documentation xml:lang="en">
5 layers.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="6">
<xs:annotation>
<xs:documentation xml:lang="en">
6 layers.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="7">
<xs:annotation>
<xs:documentation xml:lang="en">
7 layers.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="8">
<xs:annotation>
<xs:documentation xml:lang="en">
8 layers.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="cargoType">
<xs:annotation>
<xs:documentation xml:lang="en">
Defines cargo type for
the order.
Cargo classification allows for common understanding
among oTMS users
about nature of transport orders exchange.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:enumeration value="1">
<xs:annotation>
<xs:documentation xml:lang="en">
Ambient regular cargo.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="2">
<xs:annotation>
<xs:documentation xml:lang="en">
Temperature controlled
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="3">
<xs:annotation>
<xs:documentation xml:lang="en">
Dangerous goods,
ambient, all classes
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="4">
<xs:annotation>
<xs:documentation xml:lang="en">
Dangerous goods
and temperature controlled
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="packageType">
<xs:annotation>
<xs:documentation xml:lang="en">
Transport Unit (TU)
Class - oTMS classifies cargo outer package for
transport purposes
into 4 classes.
TU classification allows for common understanding
among oTMS users
about nature of transport orders exchange. In case
of order
contains different TU classes please highest one
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:enumeration value="A">
<xs:annotation>
<xs:documentation xml:lang="en">
A. Loose &
Stackable - stackable by hand on truck with no specific
limitations - it means available truck capacity can be fully
utilised and transport provider doesn't need special loading
equipment.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="B">
<xs:annotation>
<xs:documentation xml:lang="en">
B. Stackable
Pallets/Crates - stackable by forklift to maximum
truck height -
it means generally high truck utilisation, pallet
double stacking
is allowed & possible. Transport provider need
forklift to
reload/unload cargo.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="C">
<xs:annotation>
<xs:documentation xml:lang="en">
C. Non-stackable
Pallets/Crates/Odd Shapes - it means truck height
cannot be fully
utilised. It is recommended that for LTL tariffs
with such cargo
parties agree rates based on LDM (truck floor
loading meters)
instead of CBM/MT.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="D">
<xs:annotation>
<xs:documentation xml:lang="en">
D. FTL-only
-Consolidation not allowed. In such order only FTL
tariffs (pay
by truck size) are found since shipper does not
allow any
consolidation irrespective of shipment size.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="transportType">
<xs:annotation>
<xs:documentation xml:lang="en">
Freight type.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:string">
<xs:enumeration value="FTL">
<xs:annotation>
<xs:documentation xml:lang="en">
Full truckload
freight.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="LTL">
<xs:annotation>
<xs:documentation xml:lang="en">
Less than truckload
shipping.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="AIR">
<xs:annotation>
<xs:documentation xml:lang="en">
Airplane transport.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="EXPRESS">
<xs:annotation>
<xs:documentation xml:lang="en">
Express transport.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="RAIL">
<xs:annotation>
<xs:documentation xml:lang="en">
Rail transport.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="truckType">
<xs:annotation>
<xs:documentation xml:lang="en">
Type of the truck.
</xs:documentation>
</xs:annotation>
<xs:restriction base="xs:int">
<xs:enumeration value="0">
<xs:annotation>
<xs:documentation xml:lang="en">
Open truck.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="1">
<xs:annotation>
<xs:documentation xml:lang="en">
Closed truck.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="2">
<xs:annotation>
<xs:documentation xml:lang="en">
Any truck.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
<xs:enumeration value="3">
<xs:annotation>
<xs:documentation xml:lang="en">
Car Trailer. To set up truck capacity use MT capacity with one of the value: 1, 4, 6, 8, 10, 12, 14, 18, 21, 24.
</xs:documentation>
</xs:annotation>
</xs:enumeration>
</xs:restriction>
</xs:simpleType>
<xs:complexType name="importedCustomFields">
<xs:annotation>
<xs:documentation xml:lang="en">
Custom fields that company has defined.
It contains up to 10 text fields,
10 numerical fields,
10 enum fields.
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="0" name="customText1" type="customTextType" />
<xs:element minOccurs="0" name="customText2" type="customTextType" />
<xs:element minOccurs="0" name="customText3" type="customTextType" />
<xs:element minOccurs="0" name="customText4" type="customTextType" />
<xs:element minOccurs="0" name="customText5" type="customTextType" />
<xs:element minOccurs="0" name="customText6" type="customTextType" />
<xs:element minOccurs="0" name="customText7" type="customTextType" />
<xs:element minOccurs="0" name="customText8" type="customTextType" />
<xs:element minOccurs="0" name="customText9" type="customTextType" />
<xs:element minOccurs="0" name="customText10" type="customTextType" />
<xs:element minOccurs="0" name="customNum1" type="customNumType" />
<xs:element minOccurs="0" name="customNum2" type="customNumType" />
<xs:element minOccurs="0" name="customNum3" type="customNumType" />
<xs:element minOccurs="0" name="customNum4" type="customNumType" />
<xs:element minOccurs="0" name="customNum5" type="customNumType" />
<xs:element minOccurs="0" name="customNum6" type="customNumType" />
<xs:element minOccurs="0" name="customNum7" type="customNumType" />
<xs:element minOccurs="0" name="customNum8" type="customNumType" />
<xs:element minOccurs="0" name="customNum9" type="customNumType" />
<xs:element minOccurs="0" name="customNum10" type="customNumType" />
<xs:element minOccurs="0" name="customEnum1" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum2" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum3" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum4" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum5" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum6" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum7" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum8" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum9" type="customEnumValue" />
<xs:element minOccurs="0" name="customEnum10" type="customEnumValue" />
</xs:sequence>
</xs:complexType>
<xs:simpleType name="customTextType">
<xs:restriction base="xs:string">
<xs:maxLength value="255" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="customEnumValue">
<xs:restriction base="xs:string">
<xs:maxLength value="64" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="customNumType">
<xs:restriction base="xs:decimal">
<xs:minExclusive value="-1000000000000" />
<xs:maxExclusive value="1000000000000" />
<xs:fractionDigits value="6" />
</xs:restriction>
</xs:simpleType>
<xs:simpleType name="tempType">
<xs:restriction base="xs:decimal">
<xs:minExclusive value="-10000" />
<xs:maxExclusive value="10000" />
<xs:fractionDigits value="2" />
</xs:restriction>
</xs:simpleType>
</xs:schema>
|
/**
* ---
* {
* "useMath": true,
* "visualizers": [
* {"path": "./src/visualizers/visualizer.ts"}
* ]
* }
* ---
* # Surface Normals
*
* > First, let’s get ourselves a surface normal so we can shade. This is a vector that is perpendicular to the surface, and by convention, points out.
*
* This part is corresponding to [Ray Tracing In One Weekend: Surface Normals and Multiple Objects](https://raytracing.github.io/books/RayTracingInOneWeekend.html#surfacenormalsandmultipleobjects).
*
* ### Hit sphere
*
*/
//#region -c todo
/**
* bug of three.js: result of Ray.intersectSphere is wrong
*/
//#endregion
function HitSphere(center: Vector3, radius: number, ray: Ray) {
/**
*
* <<v:custom-image fig-1-06-1.jpg https://raytracing.github.io/books/RayTracingInOneWeekend.html#surfacenormalsandmultipleobjects>>
*
* For a sphere, the normal is in the direction of the hitpoint minus the center.
*
* oc: origin to center
*
*/
const oc = ray.origin.clone().sub(center);
/**
* To get points of intersection, we need to solve the [quadratic equation](https://raytracing.github.io/books/RayTracingInOneWeekend.html#addingasphere):
*
* $$ \begin{cases}A & \text{origin}\\B & \text{direction} \\C & \text{center} \\ t & \text{distance from origin to intersection}\end{cases}$$
*
* $$t^2 \cdot dot(B,B) + 2t \cdot dot(B,A-C) + dot(A-C,A-C) - R^2 = 0$$
*/
const a = ray.direction.dot(ray.direction);
const b = 2.0 * oc.dot(ray.direction);
const c = oc.dot(oc) - radius * radius;
/**
* <<v:custom-image fig-1-05-1.jpg https://raytracing.github.io/images/fig-1-05-1.jpg>>
*
* Let’s assume the closest hit point (smallest t):
*/
const Δ = b * b - 4 * a * c;
if (Δ < 0) {
return null;
}
return (-b - Math.sqrt(Δ)) / (2.0 * a);
}
/**
*
* ### Generate color
*/
function GenerateColor(ray: Ray, hitSphere: (center: Vector3, radius: number, ray: Ray) => number | null) {
//#region -c setup sphere
const center = new Vector3(0, 0, 1);
const radius = 0.5;
//#endregion
const intersection = hitSphere(center, radius, ray);
if (intersection != null) {
/**
* > Let’s just visualize the normals with a color map. A common trick used for visualizing normals (because it’s easy and somewhat intuitive to assume N is a unit length vector — so each component is between −1 and 1) is to map each component to the interval from 0 to 1, and then map x/y/z to r/g/b.
*
* To get the same color as that in [Ray Tracing In One Weekend](https://raytracing.github.io/images/img-1-06-1.jpg), we need to deal with coordinate conversion:
* $y$ -> $-y$ and $z$ -> $-z$.
*
*/
const normal = ray
.at(intersection, new Vector3())
.sub(center)
.normalize();
return new Vector3(
0.5 * (normal.x + 1),
0.5 * (-normal.y + 1),
0.5 * (-normal.z + 1)
);
}
//#region -c normal previous work
const unitDirection = ray.direction.clone().normalize();
const t = 0.5 * (unitDirection.y + 1);
const blend = new Vector3(0.5, 0.7, 1.0).lerp(new Vector3(1, 1, 1), t);
return blend;
}
/**
* ### Render image
*/
function RenderImage(canvas: HTMLCanvasElement, generateColor: (ray: Ray) => Vector3) {
const topLeftCorner = new Vector3(-2, -1, 1);
const horizontal = new Vector3(4, 0, 0);
const vertical = new Vector3(0, 2, 0);
const origin = new Vector3(0, 0, 0);
const width = canvas.width;
const height = canvas.height
const context = canvas.getContext('2d');
const imageData = context.getImageData(0, 0, width, height);
for (let x = 0; x < width; ++x) {
for (let y = 0; y < height; ++y) {
const u = x / width;
const v = y / height;
const direction = topLeftCorner.clone()
.addScaledVector(horizontal, u)
.addScaledVector(vertical, v);
const ray = new Ray(origin, direction);
const color: Vector3 = generateColor(ray);
const n = (y * width + x) * 4;
imageData.data[n] = color.x * 255;
imageData.data[n + 1] = color.y * 255;
imageData.data[n + 2] = color.z * 255;
imageData.data[n + 3] = 255;
}
}
context.putImageData(imageData, 0, 0);
}
//#endregion
/**
* ## Result
*
* <<v:illustrator normal 100% 400px>>
*
*/
//#region -c normal trivial setup
//#region -c normal imports
import { onMount } from 'svelte';
import { Vector3, Ray, Sphere } from 'three';
//#endregion
export default function Section() {
let canvas: HTMLCanvasElement;
onMount(() => {
function hitSphere(center: Vector3, radius: number, ray: Ray) {
//@ts-ignore
<HitSphere />;
}
function generateColor(ray: Ray) {
//@ts-ignore
<GenerateColor />;
};
//@ts-ignore
<RenderImage />;
});
let width = 600;
let height = 300;
<div class="container">
<canvas bindRef={canvas} width={width} height={height}></canvas>
</div>
}
//#endregion
|
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
$products = Product::latest()->paginate(5);
// Get the currently signed-in user
$user = Auth::user();
return view('products.index', compact('products', 'user'));
}
/**
* Show the form for creating a new resource.
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//Validate user input
$request ->validate([
'name'=> 'required',
'details'=> 'required',
'industry'=> 'required',
'rate'=> 'required',
'phone'=> 'required'
]);
// Create a new product with user association
$product = new Product($request->all());
$product->user_id = auth()->id(); // Set the user who created the product
$product->save();
//Redirect the user and send friendly message
return redirect()->route('products.index')->with('success','Product created successfully');
}
/**
* Display the specified resource.
*/
public function show(Product $product)
{
return view('products.show',compact('product'));
}
/**
* Show the form for editing the specified resource.
*/
public function edit(Product $product)
{
return view('products.edit',compact('product'));
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Product $product)
{
$request->validate([
'name' => 'required',
'details' => 'required',
]);
$product->update($request->all());
return redirect()->route('products.index')
->with('success','Product updated successfully');
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Product $product)
{
$product->delete();
return redirect()->route('products.index')
->with('success','Product deleted successfully');
}
}
|
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { catchError, Observable, of } from 'rxjs';
import { faStar, faCodeFork } from '@fortawesome/free-solid-svg-icons';
import { ProjectService } from '../services/project/project.service';
import { Project } from '../../models/project.model';
@Component({
selector: 'app-details',
templateUrl: './details.component.html',
styleUrls: ['./details.component.css']
})
export class DetailsComponent implements OnInit {
project$: Observable<Project> = of({
name: '',
stars: 0,
forks: 0,
owner: '',
avatar: '',
description: '',
url: ''
});
faStar = faStar;
faCodeFork = faCodeFork;
constructor(private route: ActivatedRoute, private router: Router, private projectService: ProjectService) { }
ngOnInit(): void {
this.project$ = this.getProject().pipe(catchError(() => {
this.router.navigate(['/not-found'])
return of();
}));
}
getProject(): Observable<Project> {
const owner = this.route.snapshot.params['owner'];
const project = this.route.snapshot.params['project'];
return this.projectService.fetchProject(owner, project);
}
}
|
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<link rel="stylesheet" href="./style.css">
<title>Cardápio Online Teste</title>
</head>
<body>
<div class="container-fluid head-title bg-black bg-gradient">
<div class="row">
<div class="col">
<span>Cardápio Online v1.0</span>
</div>
</div>
</div>
<div class="container-fluid header-div">
<div class="d-flex flex-row justify-content-center">
<img src="./img/logo.png" class="header-logo" alt="Logo">
</div>
<div class="d-flex flex-row justify-content-center align-items-center">
<img src="./img/local.png" class="header-gps" alt="gps">
<p class="address-line">Rua Teste, 2, Perus - São Paulo - SP - Brasil</p>
</div>
</div>
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#">Categorias</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarText">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" href="#promocoes">Promoções</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#frangofrito">Frango Frito</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#porcoes">Porções</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#bebidas">Bebidas</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid">
<div class="category row bg-black bg-gradient">
<p id="promocoes">Promoções</p>
</div>
<div class="row row-cols-1 row-cols-md-3 g-4 products">
<div class="col">
<div class="card">
<img src="./img/promo1.png" class="card-img-top" alt="Promoção 1">
<div class="card-body">
<h5 class="card-title">Promoção 1</h5>
<p class="card-text">Caixa com 500g de frango de frito e 200g de batata rústica.<br>Serve 2 pessoas<br>R$45,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/promo1.png" class="card-img-top" alt="Promoção 2">
<div class="card-body">
<h5 class="card-title">Promoção 2</h5>
<p class="card-text">Caixa com 800g de frango frito e 400g de batata rústica.<br>Serve 3 pessoas<br>R$55,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/promo1.png" class="card-img-top" alt="Promoção 3">
<div class="card-body">
<h5 class="card-title">Promoção 3</h5>
<p class="card-text">Caixa com 1.3kg de frango frito e 800g de batata rústica.<br>Serve 4 pessoas<br>R$75,00</p>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="category row bg-black bg-gradient">
<p id="frangofrito">Frango Frito</p>
</div>
<div class="row row-cols-1 row-cols-md-3 g-4 products">
<div class="col">
<div class="card">
<img src="./img/combo1.png" class="card-img-top" alt="Combo 1">
<div class="card-body">
<h5 class="card-title">Combo 1</h5>
<p class="card-text">Combo com 1.2kg de frango frito e uma garrafa de Coca Cola 2L.<br>Serve 3 pessoas<br>R$70,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/combo1.png" class="card-img-top" alt="Combo 2">
<div class="card-body">
<h5 class="card-title">Combo 2</h5>
<p class="card-text">Combo com 1.5kg de frango frito e uma garrafa de Coca Cola 2L.<br>Serve 4 pessoas<br>R$80,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/combo1.png" class="card-img-top" alt="Combo 3">
<div class="card-body">
<h5 class="card-title">Combo 3</h5>
<p class="card-text">Combo com 2kg de frango frito e uma garrafa de Coca Cola 2L.<br>Serve 5 pessoas<br>R$90,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/combo1.png" class="card-img-top" alt="Combo 4">
<div class="card-body">
<h5 class="card-title">Combo 4</h5>
<p class="card-text">Combo com 1.2kg de frango frito, 800g de batata rústica e uma garrafa de Coca Cola 2L.<br>Serve 4 pessoas<br>R$85,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/combo1.png" class="card-img-top" alt="Combo 5">
<div class="card-body">
<h5 class="card-title">Combo 5</h5>
<p class="card-text">Combo com 1.5kg de frango frito, 1kg de batata rústica e uma garrafa de Coca Cola 2L.<br>Serve 5 pessoas<br>R$90,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/combo1.png" class="card-img-top" alt="Combo 6">
<div class="card-body">
<h5 class="card-title">Combo 6</h5>
<p class="card-text">Combo com 500g de frango frito e uma garrafa de Coca Cola 1L.<br>Serve 1 pessoas<br>R$40,00</p>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="category row bg-black bg-gradient">
<p id="porcoes">Porções</p>
</div>
<div class="row row-cols-1 row-cols-md-3 g-4 products">
<div class="col">
<div class="card">
<img src="./img/porcao1.png" class="card-img-top" alt="Porção de batata frita">
<div class="card-body">
<h5 class="card-title">Porção de batata</h5>
<p class="card-text">600g de batatas fritas.<br>Serve 2 pessoas<br>R$20,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/porcao2.png" class="card-img-top" alt="Porção de mandioca frita">
<div class="card-body">
<h5 class="card-title">Porção de Mandioca</h5>
<p class="card-text">Porção de 1kg de mandioca frita.<br>Serve 2 pessoas<br>R$27,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/porcao3.png" class="card-img-top" alt="Porção de polenta frita">
<div class="card-body">
<h5 class="card-title">Porção de Polenta</h5>
<p class="card-text">Porção de 1kg de polenta frita.<br>Serve 3 pessoas<br>R$30,00</p>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="category row bg-black bg-gradient">
<p id="bebidas">Bebidas</p>
</div>
<div class="row row-cols-1 row-cols-md-3 g-4 products">
<div class="col">
<div class="card">
<img src="./img/bebida1.png" class="card-img-top" alt="Coca Cola 2L">
<div class="card-body">
<h5 class="card-title">Coca Cola 2L</h5>
<p class="card-text">Garrafa de 2 litros de Coca Cola<br>R$14,00</p>
</div>
</div>
</div>
<div class="col">
<div class="card">
<img src="./img/bebida2.png" class="card-img-top" alt="Pepsi 2L">
<div class="card-body">
<h5 class="card-title">Pepsi 2L</h5>
<p class="card-text">Garrafa de 2 litros de Pepsi<br>R$12,00</p>
</div>
</div>
</div>
</div>
</div>
<div class="container-fluid footer-rights bg-black bg-gradient text-center">
<p>Cardápio Online 1.0 - Todos os direitos reservados © - Desenvolvido por <a class="footer-link" href="http://www.github.com/lucasribeiroc">Lucas Ribeiro</a></p>
</div>
<button type="button" class="btn btn-danger btn-floating btn-lg" id="btn-back-to-top">
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-arrow-bar-up" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M8 10a.5.5 0 0 0 .5-.5V3.707l2.146 2.147a.5.5 0 0 0 .708-.708l-3-3a.5.5 0 0 0-.708 0l-3 3a.5.5 0 1 0 .708.708L7.5 3.707V9.5a.5.5 0 0 0 .5.5zm-7 2.5a.5.5 0 0 1 .5-.5h13a.5.5 0 0 1 0 1h-13a.5.5 0 0 1-.5-.5z" />
</svg>
</button>
<script src="./script.js"></script>
</body>
</html>
|
from heapq import heappop, heappush
from itertools import count
import pandas as pd
# ๋࣭ ⭑ ݁ ˖๋ ࣭ ⭑ Identicar Limiares dos Datasets ๋࣭ ⭑ ݁ ˖๋ ࣭ ⭑
def read_datasets_info(file_path):
# lê o arquivo pulando o cabeçalho
df = pd.read_csv(file_path, skiprows=1, delim_whitespace=True, names=["Dataset", "Nodes", "Threshold"])
df["Nodes"] = df["Nodes"].astype(int)
df["Threshold"] = df["Threshold"].astype(int)
# criação do dicionario ✩°。 ⋆⸜
datasets_info = df.set_index("Dataset").to_dict(orient="index")
return datasets_info
# ๋࣭ ⭑ ݁ ˖๋ ࣭ ⭑ Caminho e Custo ݁ ˖๋ ࣭ ⭑ ๋࣭ ⭑
def make_hamiltonian(euler_circuit):
hamiltonian_circuit = []
visited_nodes = set()
for edge in euler_circuit:
if edge[0] not in visited_nodes:
hamiltonian_circuit.append(edge[0])
visited_nodes.add(edge[0])
hamiltonian_circuit.append(hamiltonian_circuit[0])
return hamiltonian_circuit
def circuit_cost(graph, circuit):
cost = sum(graph[circuit[i]][circuit[i + 1]]['weight'] for i in range(len(circuit) - 1))
return cost
# ๋࣭ ⭑ ݁ ˖๋ ࣭ ⭑ Minimum Spanning Tree ݁ ˖๋ ࣭ ⭑ ๋࣭ ⭑
def prim_mst_edges(G, weight="weight"):
# baseado no source do networkx
push, pop = heappush, heappop
nodes, c = set(G), count()
while nodes:
u = nodes.pop()
frontier, visited = [], {u}
for v, data in G.adj[u].items():
# pega o peso da aresta u-v (ou 1 se não existir) e adiciona no frontier
wt = data.get(weight, 1)
push(frontier, (wt, next(c), u, v, data))
while nodes and frontier:
W, _, u, v, data = pop(frontier) # tira do frontier
if v in visited or v not in nodes:
continue
yield (u, v, data) if data else (u, v)
# retorna a aresta (u, v, data) se 'data' existir, caso contrário, retorna apenas (u,v)
# yield é usada em funções geradoras ٩(ˊᗜˋ*)و
visited.add(v)
nodes.discard(v)
for w, d2 in G.adj[v].items():
if w not in visited:
# pega o peso da aresta v-w (ou 1 se não existir) e adiciona no frontier
new_weight = d2.get(weight, 1)
push(frontier, (new_weight, next(c), v, w, d2))
def minimum_spanning_tree(G, weight="weight"):
min_edges = prim_mst_edges(G, weight=weight)
# cria de maneira esperta um grafo com as arestas geradas ⋆。⭒˚。⋆
T = G.__class__()
T.graph.update(G.graph)
T.add_nodes_from(G.nodes.items())
T.add_edges_from(min_edges)
return T
|
<!DOCTYPE html>
<html>
<head>
<title>File Upload and Content Parsing</title>
<style>
* {
box-sizing: border-box;
font-family: Arial, sans-serif;
}
body {
margin: 0;
padding: 20px;
background-color: #f2f2f2;
color: #333;
transition: background-color 0.3s ease, color 0.3s ease;
}
#header {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
#header h1 {
text-align: center;
margin: 0;
}
#toggleButton {
background-color: #ccc;
color: #333;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
margin-left: 10px;
}
#fileInput {
display: block;
margin: 0 auto 20px;
padding: 10px;
border: 2px solid #ccc;
border-radius: 5px;
background-color: #ccc;
color: #333;
font-size: 1rem;
cursor: pointer;
}
#fileInput:hover {
border-color: #999;
}
#countsContainer {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
#rawTextBox {
width: 100%;
min-height: 200px;
max-height: 1000px;
margin-top: 20px;
padding: 10px;
border: 2px solid #ccc;
border-radius: 5px;
background-color: #f2f2f2;
color: #333;
font-family: Arial, sans-serif;
font-size: 1rem;
resize: none;
overflow-y: auto;
transition: background-color 0.3s ease, color 0.3 ease;
}
.item {
display: flex;
flex-direction: column;
align-items: center;
margin: 10px;
padding: 10px;
background-color: #fff;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
transition: background-color 0.3s ease;
}
.item-name {
font-size: 1.2rem;
font-weight: bold;
text-align: center;
margin-bottom: 10px;
}
.value {
font-size: 1rem;
text-align: center;
margin-bottom: 5px;
}
.value-count {
font-weight: bold;
margin-left: 5px;
}
.dark-mode {
background-color: #333;
color: #fff;
}
.dark-mode .item {
background-color: #444;
}
.dark-mode #rawTextBox {
background-color: #444;
color: #fff;
}
.transition {
transition: background-color 0.3s ease, color 0.3s ease;
}
</style>
<script>
function handleFileSelect(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function (event) {
const fileContents = event.target.result;
const itemsToCount = [
{ id: 'BTRY', name: 'Battery', searchDepth: 0 },
{ id: 'BTCL', name: 'Battery Clip', searchDepth: 0 },
{ id: 'BRAN', name: 'Brain', searchDepth: 0 },
{ id: 'MOTR', name: 'Motor', searchDepth: 0 },
{ id: 'RDIO', name: 'Radio', searchDepth: 0 },
{ id: 'BLCK', name: 'Block Bearing', searchDepth: 0 },
{ id: 'BRNG', name: 'Flat Bearing', searchDepth: 1 },
{ id: 'GEAR', name: 'Gear', searchDepth: 2 },
{ id: 'SPKT', name: 'Sprocket', searchDepth: 2 },
{ id: 'LKBR', name: 'Lock Bar', searchDepth: 1 },
{ id: 'SHFT', name: 'Shaft', searchDepth: 2},
{ id: 'CLMP', name: 'Shaft Collar', searchDepth: 2 },
{ id: 'SPCR', name: 'Spacer', searchDepth: 2 },
{ id: 'WSHR', name: 'Washer', searchDepth: 1 },
{ id: 'FWHL', name: 'Flex Wheel', searchDepth: 2 },
{ id: 'MECN', name: 'Mecanum Wheel', searchDepth: 0 },
{ id: 'OMNI', name: 'Omni Wheel', searchDepth: 1 },
{ id: 'TWHL', name: 'Traction Wheel', searchDepth: 1 },
{ id: 'ANGL', name: 'Angle', searchDepth: 2 },
{ id: 'BSPT', name: 'Baseplate', searchDepth: 0 },
{ id: 'CCHL', name: 'C-Channel', searchDepth: 2 },
{ id: 'GSET', name: 'Gusset', searchDepth: 2 },
{ id: 'NUT', name: 'Nut', searchDepth: 1 },
{ id: 'PLTE', name: 'Plate', searchDepth: 2 },
{ id: 'RAIL', name: 'Rail', searchDepth: 1 },
{ id: 'SCRW', name: 'Screw', searchDepth: 1 },
{ id: 'SNDF', name: 'Standoff', searchDepth: 1 },
{ id: 'UCHL', name: 'U-Channel', searchDepth: 2 },
{ id: 'Potentiometer', name: 'Potentiometer', searchDepth: 0 },
{ id: 'Distance', name: 'Distance', searchDepth: 0 },
{ id: 'Rotation', name: 'Rotation', searchDepth: 0 },
{ id: 'Optical', name: 'Optical', searchDepth: 0 },
{ id: 'Vision', name: 'Vision', searchDepth: 0 },
{ id: 'Inertial', name: 'Inertial', searchDepth: 0 },
{ id: 'Line Tracker', name: 'Line Tracker', searchDepth: 0 },
{ id: 'Bumper', name: 'Bumper', searchDepth: 0 },
{ id: 'Limit', name: 'Limit', searchDepth: 0 },
]; // List of items to count with assigned names
const counts = {};
for (const item of itemsToCount) {
if (item.searchDepth === 0) {
const regex = new RegExp(`${item.id}`, 'g');
const matches = fileContents.match(regex);
if (matches && matches.length > 0) {
counts[item.name] = {
'': matches.length,
};
}
} else {
const regex = new RegExp(`${item.id}((?:-[\\w\\/\\.]+){${item.searchDepth}})`, 'g');
const matches = fileContents.match(regex);
if (matches && matches.length > 0) {
counts[item.name] = {};
for (const match of matches) {
const value = match.split('-').slice(1).join('-');
counts[item.name][value] = (counts[item.name][value] || 0) + 1;
}
}
}
}
displayCounts(counts);
};
reader.readAsText(file);
}
function displayCounts(counts) {
const countsContainer = document.getElementById('countsContainer');
const rawTextBox = document.getElementById('rawTextBox');
countsContainer.innerHTML = '';
rawTextBox.value = '';
for (const item in counts) {
const itemContainer = document.createElement('div');
itemContainer.classList.add('item');
itemContainer.textContent = item;
countsContainer.appendChild(itemContainer);
const itemCounts = counts[item];
for (const value in itemCounts) {
const count = itemCounts[value];
const valueElement = document.createElement('div');
valueElement.classList.add('value');
valueElement.textContent = value === '' ? `(${count})` : `${value} (${count})`;
itemContainer.appendChild(valueElement);
// Append to raw text box
rawTextBox.value += `${item} ${value}: ${count}\n`;
}
}
}
function toggleDarkMode() {
const body = document.querySelector('body');
body.classList.toggle('dark-mode');
body.classList.add('transition');
setTimeout(() => {
body.classList.remove('transition');
}, 300);
}
function checkSystemColorScheme() {
const prefersDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (prefersDarkMode) {
document.body.classList.add('dark-mode');
}
}
document.addEventListener('DOMContentLoaded', checkSystemColorScheme);
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
</script>
</head>
<body>
<div id="header">
<h1>ProtoBot Parts List</h1>
<button id="toggleButton" onclick="toggleDarkMode()">Toggle Dark Mode</button>
</div>
<input type="file" id="fileInput" accept=".pbb" />
<div id="countsContainer"></div>
<textarea id="rawTextBox" readonly></textarea>
<div id="countsContainer"></div>
<script>
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
function adjustRawTextBoxHeight() {
const rawTextBox = document.getElementById('rawTextBox');
rawTextBox.style.height = 'auto';
rawTextBox.style.height = rawTextBox.scrollHeight + 'px';
}
// Call the adjustRawTextBoxHeight function whenever the content of the text box changes
document.getElementById('rawTextBox').addEventListener('input', adjustRawTextBoxHeight);
</script>
</body>
</html>
|
"use client";
import { Link } from "nextjs13-progress";
import { ArrowUpDown } from "lucide-react";
import { ColumnDef } from "@tanstack/react-table";
import { Button, buttonVariants } from "@/components/ui/button";
import { Badge, BadgeVariants } from "@/components/ui/badge";
import { CaseColumn } from "@/types/CaseColumns";
export const columns: ColumnDef<CaseColumn>[] = [
{
accessorKey: "order_id",
header: ({ column }) => {
return (
<Button
variant="ghost"
onClick={() => column.toggleSorting(column.getIsSorted() === "asc")}
>
ID
<ArrowUpDown className="ml-2 h-4 w-4" />
</Button>
);
},
cell: ({ row }) => {
const caseData = row.original;
return (
<Link
href={"/cases/" + caseData.case_id}
className={buttonVariants({ variant: "ghost", size: "xs" })}
>
{caseData.order_id}
</Link>
);
},
},
{
accessorKey: "status",
header: "Status",
cell: ({ row }) => {
const order = row.original;
let variant: BadgeVariants;
switch (order.status) {
case "answered":
variant = "success";
break;
case "pending":
variant = "processing";
break;
}
return (
<Badge variant={variant} className="mx-auto">
{order.status}
</Badge>
);
},
},
{
accessorKey: "companyId",
header: "Company",
},
{
accessorKey: "external_id",
header: "External No",
},
{
accessorKey: "enduser_name",
header: "End user",
},
{
accessorKey: "initials",
header: "Creator Initials",
},
{
accessorKey: "created_at",
header: "Created Date",
cell: ({ row }) => {
const order = row.original;
return order.created_at.toLocaleDateString("en-US", {
day: "2-digit",
month: "long",
year: "numeric",
});
},
},
];
|
const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator');
const auth = require('../middleware/auth');
const Post = require('../../models/Post');
const User = require('../../models/User');
//
// POST api/posts
// Create a post
router.post(
'/',[auth,
[
check('text', 'text is required').not().isEmpty()
]],
async(req,res)=>{
const errors = validationResult(req)
if(!errors.isEmpty()){
return res.status(400).json({errors: errors.array()})
}
try {
const user = await User.findById(req.user.id).select('-password')
const newPost = new Post({
text: req.body.text,
name: user.name,
avatar: user.avatar,
user: req.user.id
})
const post = await newPost.save()
console.log(post)
res.json(post)
} catch (error) {
console.error(error.message);
res.status(500).send('Server Error');
}
}
)
//get api/posts
//get all posts
router.get('/', async(req,res)=>{
try {
const posts = await Post.find().sort({date: -1})
res.json(posts)
console.log(posts)
} catch (error) {
console.error(err.message);
res.status(500).send('Server Error');
}
})
//get api/posts/:id
//get a single post by id
router.get('/:id', auth, async(req,res)=>{
try {
const post = await Post.findById(req.params.id)
if(!post){
res.status(404).json({msg: 'Post not found'})
}
res.json(post)
} catch (error) {
console.error(error.message);
if(error.kind === 'ObjectId'){
res.status(404).json({msg: 'Post not found'})
}
res.status(500).send('Server Error');
}
})
//DELETE api/posts/:id
router.delete('/:id', auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) {
return res.status(404).json({ msg: 'Post not found' });
}
// Check user
if (post.user.toString() !== req.user.id) {
return res.status(401).json({ msg: 'User not authorized' });
}
// Use the deleteOne method to remove the post from the database
await Post.deleteOne({ _id: req.params.id });
res.json({ msg: 'Post removed' });
} catch (error) {
console.error(error.message);
res.status(500).send("Server error");
}
});
// @route PUT api/posts/like/:id
// @desc Like a post
// @access Private
router.put('/like/:id', auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Check if the post has already been liked
if (post.likes.some((like) => like.user.toString() === req.user.id)) {
return res.status(400).json({ msg: 'Post already liked' });
}
post.likes.unshift({ user: req.user.id });
console.log(post)
await post.save();
return res.json(post.likes);
} catch (err) {
console.error(err.message);
res.status(500).send('server Error');
}
});
// @route PUT api/posts/unlike/:id
// @desc Unlike a post
// @access Private
router.put('/unlike/:id', auth, async (req, res) => {
try {
const post = await Post.findById(req.params.id);
// Check if the post has not yet been liked
if (!post.likes.some((like) => like.user.toString() === req.user.id)) {
return res.status(400).json({ msg: 'Post has not yet been liked' });
}
// remove the like
post.likes = post.likes.filter(
({ user }) => user.toString() !== req.user.id
);
await post.save();
return res.json(post.likes);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
//POST api/comments/:id
router.post(
'/comment/:id',
[
auth,
[
check('text', 'text is required').not().isEmpty()
]
],
async(req,res)=>{
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
try {
const user = await User.findById(req.user.id)
const post = await Post.findById(req.params.id)
const newComment= {
text: req.body.text,
name: user.name,
avatar: user. avatar,
user: req.user.id
};
post.comments.unshift(newComment)
console.log(post.comments)
await post.save()
res.json(post.comments)
} catch (error) {
console.log(error.message);
res.status(500).send(error.message);
}
}
)
//delete comment
//DELETE api/posts/comment/:id/:comment_id
router.delete('/comment/:id/:comment_id', auth,
async(req,res)=>{
try {
const post = await Post.findById(req.params.id)
const comment = post.comments.find(comment=> comment.id === req.params.comment_id)
if(!comment){
return res.status(404).json({msg: "comment does not exist"})
}
if(comment.user.toString() !== req.user.id){
return res.status(401).json({msg: "User not auhtorized"})
}
//remove index
const removeIndex = post.comments.map(comment=> comment.user.toString()).indexOf(req.user.id)
post.comments.splice(removeIndex,1)
await post.save()
res.json(post.comments)
} catch (error) {
console.log(error.message);
res.status(500).send(error.message);
}
})
module.exports = router;
|
package com.example.restaurantapp.presentation.screens.take_away_screen
import com.example.restaurantapp.presentation.models.MenuUi
import com.example.restaurantapp.presentation.models.User
import javax.annotation.concurrent.Immutable
sealed class TakeAwayUiState {
data object Loading : TakeAwayUiState()
data class Error(val message: String) : TakeAwayUiState()
@Immutable
data class Loaded(
val drinks: List<MenuUi> = emptyList(),
val desserts: List<MenuUi> = emptyList(),
val hotDishes: List<MenuUi> = emptyList(),
val fastFoot: List<MenuUi> = emptyList(),
val salads: List<MenuUi> = emptyList(),
val user: User = User.unknown,
) : TakeAwayUiState()
}
|
<?php
// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$
/**
* "Inline" character diff renderer.
*
* This class renders the diff in "inline" format by characters.
*
* @package Text_Diff
*/
class Text_Diff_Renderer_character_inline extends Tiki_Text_Diff_Renderer
{
protected $orig;
protected $final;
public function __construct($context_lines = 0)
{
$this->_leading_context_lines = $context_lines;
$this->_trailing_context_lines = $context_lines;
$this->diff = "";
$this->change = "";
}
protected function _startDiff()
{
}
protected function _endDiff()
{
return [$this->diff, $this->change];
}
protected function _blockHeader($xbeg, $xlen, $ybeg, $ylen)
{
}
protected function _startBlock($header)
{
echo $header;
}
protected function _endBlock()
{
}
protected function _getChange($lines)
{
return str_replace("<br />", "↵<br />", join("", $lines));
}
protected function _lines($lines, $prefix = '', $suffix = '', $type = '')
{
if ($type == 'context') {
$this->diff .= join("", $lines);
} elseif ($type == 'added' || $type == 'change-added') {
$t = $this->_getChange($lines);
if (! empty($t)) {
$this->diff .= "<span class='diffadded'>$t</span>";
}
} elseif ($type == 'deleted' || $type == 'change-deleted') {
$t = $this->_getChange($lines);
if (! empty($t)) {
$this->diff .= "<span class='diffinldel'>$t</span>";
}
} elseif ($type == 'changed') {
$t = $this->_getChange($lines[0]);
if (! empty($t)) {
$this->diff .= "<span class='diffinldel'>$t</span>";
}
$t = $this->_getChange($lines[1]);
if (! empty($t)) {
$this->diff .= "<span class='diffadded'>$t</span>";
}
}
}
protected function _context($lines)
{
$this->_lines($lines, '', '', 'context');
}
protected function _added($lines, $changemode = false)
{
if (! $this->change) {
$this->change = "added";
}
if ($this->change != "added") {
$this->change = "changed";
}
if ($changemode) {
$this->_lines($lines, '+', '', 'change-added');
} else {
$this->_lines($lines, '+', '', 'added');
}
}
protected function _deleted($lines, $changemode = false)
{
if (! $this->change) {
$this->change = "deleted";
}
if ($this->change != "deleted") {
$this->change = "changed";
}
if ($changemode) {
$this->_lines($lines, '-', '', 'change-deleted');
} else {
$this->_lines($lines, '-', '', 'deleted');
}
}
protected function _changed($orig, $final)
{
$this->change = 'changed';
$this->_lines([$orig, $final], '*', '', 'changed');
}
}
|
// Binary Search (https://leetcode.com/problems/remove-element)
// Leetcode Solution: https://www.youtube.com/watch?v=Pcd1ii9P9ZI
// Time: O(log n), Space: O(1)
function search(nums: number[], target: number): number {
let left = 0,
right = nums.length - 1
while (left <= right) {
const middle = Math.round((left + right) / 2)
const guess = nums[middle]
const isTarget = guess === target
if (isTarget) return middle
const isTargetGreater = guess < target
if (isTargetGreater) left = middle + 1
const isTargetSmaller = guess > target
if (isTargetSmaller) right = middle - 1
}
return -1
}
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include "carnet.h"
using namespace std;
// función que resuelve el problema
// Resuelve un caso de prueba, leyendo de la entrada la
// configuración, y escribiendo la respuesta
bool resuelveCaso() {
// leer los datos de la entrada
string orden, dni;
carnet_puntos tabla;
int puntos;
cin >> orden;
if (!cin)
return false;
while (orden != "FIN") {
try {
if (orden == "nuevo") {
cin >> dni;
tabla.nuevo(dni);
}
if (orden == "quitar") {
std::cin >> dni >> puntos;
tabla.quitar(dni, puntos);
}
if (orden == "recuperar") {
std::cin >> dni >> puntos;
tabla.recuperar(dni, puntos);
}
if (orden == "consultar") {
cin >> dni;
int p = tabla.consultar(dni);
cout << "Puntos de " + dni + ": ";
cout << p << '\n';
}
if (orden == "cuantos_con_puntos") {
cin >> puntos;
int M = tabla.cuantos_con_puntos(puntos);
cout << "Con " << puntos << " puntos hay ";
cout << M << '\n';
}
if (orden == "lista_por_puntos") {
cin >> puntos;
list<string> res = tabla.lista_por_puntos(puntos);
cout << "Tienen " << puntos << " puntos:";
for (string cond : res) {
cout << " " << cond;
}
cout << '\n';
}
}
catch (std::domain_error const & a) {
std::cout << "ERROR: " << a.what() << '\n';
}
cin >> orden;
}
cout << "---\n";
return true;
}
int main() {
// Para la entrada por fichero.
// Comentar para acepta el reto
#ifndef DOMJUDGE
std::ifstream in("casos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
while (resuelveCaso());
// Para restablecer entrada. Comentar para acepta el reto
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
}
|
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component, ElementRef, ViewChild, ViewEncapsulation } from '@angular/core';
import { Title } from '@angular/platform-browser';
import * as tt from '@tomtom-international/web-sdk-maps';
import SearchBox from '@tomtom-international/web-sdk-plugin-searchbox';
import { services } from '@tomtom-international/web-sdk-services';
import { Observable } from 'rxjs';
import { ThemeService } from '../theme.service';
@Component({
selector: 'app-explore',
templateUrl: './explore.component.html',
styleUrls: ['./explore.component.css']
})
export class ExploreComponent implements AfterViewInit {
// DOM elements
@ViewChild("inputStart") inputStart!: ElementRef;
@ViewChild("inputEnd") inputEnd!: ElementRef;
@ViewChild("inputStartAutocomplete") inputStartAutocomplete!: ElementRef;
@ViewChild("inputEndAutocomplete") inputEndAutocomplete!: ElementRef;
@ViewChild("mapNotificationContainer") mapNotificationContainer!: ElementRef;
@ViewChild("infoContentContainer") infoContentContainer!: ElementRef;
@ViewChild("alertTitle") alertTitle!: ElementRef;
@ViewChild("alertContainer") alertContainer!: ElementRef;
@ViewChild("distanceKilometers") distanceKilometers!: ElementRef;
@ViewChild("distanceMiles") distanceMiles!: ElementRef;
@ViewChild("rideDuration") rideDuration!: ElementRef;
@ViewChild("caloriesBurned") caloriesBurned!: ElementRef;
@ViewChild("altitudeChange") altitudeChange!: ElementRef;
@ViewChild("weatherForcast") weatherForcast!: ElementRef;
@ViewChild("temperature") temperature!: ElementRef;
// Instance variables
lightTheme: string = "https://api.tomtom.com/style/1/style/22.2.1-9?key=ImJQ5OE7KBtQRP09rOL4mQXtlKm4qydm&map=2/basic_street-light";
darkTheme: string = "https://api.tomtom.com/style/1/style/22.2.1-9?key=ImJQ5OE7KBtQRP09rOL4mQXtlKm4qydm&map=2/basic_street-dark";
searchUrl: string = "https://api.tomtom.com/search/2/search";
altitudeUrl: string = "https://api.open-elevation.com/api/v1/lookup?locations=";
weatherUrl: string = "https://api.weatherapi.com/v1/forecast.json?key=38a24f8373a94d8e872173145231007&days=1&aqi=yes&alerts=yes&q=";
map: any;
position: any;
startPosition: any;
endPosition: any;
routeData: any;
calculatingRoute: boolean = false;
startingPointAutocompleteResults: any = [];
endingPointAutocompleteResults: any = [];
// Constructor
constructor(private titleService: Title, private http: HttpClient, private themeService: ThemeService) {
this.titleService.setTitle("RideWise - Explore");
}
// Methods
ngAfterViewInit() {
this.map = tt.map({
key: "ImJQ5OE7KBtQRP09rOL4mQXtlKm4qydm",
container: "map",
style: this.themeService.theme ? this.lightTheme : this.darkTheme,
})
this.map.dragRotate.disable();
navigator.geolocation.getCurrentPosition((position: any) => {
this.position = position;
this.map.setZoom(15);
this.map.setCenter([position.coords.longitude, position.coords.latitude]);
})
// Changing map theme
this.themeService.subscription.subscribe((res) => {
if (res) {
this.map.setStyle(this.lightTheme)
} else {
this.map.setStyle(this.darkTheme);
}
})
this.map.on("style.load", () => {
if (this.routeData != null) {
this.removeRoute();
this.map.addLayer({
"id" : "route",
"type" : "line",
"source" : {
"type" : "geojson",
"data" : this.routeData.toGeoJson()
},
"layout" : {
"line-join" : "round",
"line-cap" : "round"
},
"paint" : {
"line-color" : "rgb(46, 135, 240)",
"line-width" : 5,
}
});
}
})
// Clicking off search bars
document.addEventListener("click", (event) => {
const target = event.target as HTMLElement;
if (target.classList.contains("map-configuration-input")) {
if (target.isSameNode(this.inputStart.nativeElement)) {
this.inputEndAutocomplete.nativeElement.style.display = "none";
} else {
this.inputStartAutocomplete.nativeElement.style.display = "none";
}
} else {
this.inputStartAutocomplete.nativeElement.style.display = "none";
this.inputEndAutocomplete.nativeElement.style.display = "none";
}
})
}
toggleMapTheme() {
this.map.setStyle(this.darkTheme);
}
hideInfo(callback: any) {
this.infoContentContainer.nativeElement.style.opacity = "0";
this.alertContainer.nativeElement.innerHTML = "";
this.alertTitle.nativeElement.style.display = "none";
setTimeout(() => {
callback();
}, 300);
}
showInfo() {
this.infoContentContainer.nativeElement.style.opacity = "1";
if (this.alertContainer.nativeElement.childElementCount > 0) {
this.alertTitle.nativeElement.style.display = "block";
}
}
spawnMapNotification(message: string, type: string, duration: number) {
var notificationElement = document.createElement("div");
notificationElement.classList.add("map-notification");
notificationElement.classList.add("transparent");
notificationElement.innerHTML = message;
if (type == "error") {
notificationElement.classList.add("map-notification-error");
} else if (type == "success") {
notificationElement.classList.add("map-notification-success");
}
this.mapNotificationContainer.nativeElement.append(notificationElement);
setTimeout(() => {
notificationElement.classList.remove("transparent");
}, 10);
setTimeout(() => {
notificationElement.classList.add("transparent");
setTimeout(() => {
notificationElement.remove();
}, 200);
}, duration);
}
spawnAlert(text: string, severity: string) {
var alertElement = document.createElement("div");
alertElement.innerHTML = text;
alertElement.classList.add("alert");
alertElement.classList.add(severity);
this.alertContainer.nativeElement.append(alertElement);
}
fitBounds(routePoints: any) {
var bounds = new tt.LngLatBounds();
bounds.extend(new tt.LngLat(this.startPosition.lon as number, this.startPosition.lat as number));
bounds.extend(new tt.LngLat(this.endPosition.lon as number, this.endPosition.lat as number));
for (var boundItem of routePoints) {
bounds.extend(new tt.LngLat(boundItem.lng as number, boundItem.lat as number));
}
this.map.fitBounds(bounds, {
padding: {top: 30, right: 30, bottom: 30, left: 30}
})
}
createMarker(position: any) {
var markerElement = document.createElement("div");
new tt.Marker({
element: markerElement,
offset: [0, 15]
}).setLngLat(position).addTo(this.map);
return markerElement;
}
removeRoute() {
if (this.map.getLayer("route")) {
this.map.removeLayer("route");
this.map.removeSource('route');
}
}
createRoute() {
if (this.startPosition && this.endPosition && !this.calculatingRoute) {
this.calculatingRoute = true;
this.removeRoute();
this.spawnMapNotification("Calculating route...", "", 1500);
var routeOptions = {
key: "ImJQ5OE7KBtQRP09rOL4mQXtlKm4qydm",
locations: [this.startPosition, this.endPosition],
travelMode: "bicycle" as any
}
this.hideInfo(() => {
this.map.resize();
services.calculateRoute(routeOptions).then((data) => {
this.routeData = data;
const summaryData = data.routes[0].summary;
const lengthInMeters = summaryData.lengthInMeters;
const timeData = new Date(summaryData.travelTimeInSeconds * 1000).toISOString().substring(11, 16).split(":").map(Number);
var timeDataString = "";
const days = Math.floor(summaryData.travelTimeInSeconds / 86400);
// Displaying time information
if (days > 0) {
timeDataString = days + (days > 1 ? " Days " : " Day ");
}
if (timeData[0] > 0) {
timeDataString += timeData[0] + (timeData[0] > 1 ? " Hours " : " Hour ");
}
if (timeData[1] > 0) {
timeDataString += timeData[1] + (timeData[1] > 1 ? " Minutes " : " Minute");
}
if (timeData[0] == 0 && timeData[1] == 0) {
timeDataString = "Less Than 1 Minute";
}
this.rideDuration.nativeElement.innerHTML = timeDataString;
// Displaying distance information
if (lengthInMeters < 1000) {
this.distanceKilometers.nativeElement.innerHTML = `${Math.round(lengthInMeters / 10) / 100} Kilometers`;
this.distanceMiles.nativeElement.innerHTML = `${Math.round(lengthInMeters * 0.621371 / 10)/ 100} Miles`;
} else if (lengthInMeters < 10000) {
this.distanceKilometers.nativeElement.innerHTML = `${Math.round(lengthInMeters / 100) / 10} Kilometers`;
this.distanceMiles.nativeElement.innerHTML = `${Math.round(lengthInMeters * 0.621371 / 100)/ 10} Miles`;
} else {
this.distanceKilometers.nativeElement.innerHTML = `${Math.round(lengthInMeters / 1000)} Kilometers`;
this.distanceMiles.nativeElement.innerHTML = `${Math.round(lengthInMeters * 0.621371 / 1000)} Miles`;
}
// Nesting info API calls so the info section can be shown when requests are complete
// Displaying elevation information
this.http.get(this.altitudeUrl + this.startPosition.lat + "," + this.startPosition.lon).subscribe((dataStart: any) => {
if (dataStart.results) {
this.http.get(this.altitudeUrl + this.endPosition.lat + "," + this.endPosition.lon).subscribe((dataEnd: any) => {
if (dataEnd.results) {
const start = dataStart.results[0].elevation;
const end = dataEnd.results[0].elevation;
if (end == start) {
this.altitudeChange.nativeElement.innerHTML = `0 Difference In Elevation`;
} else {
this.altitudeChange.nativeElement.innerHTML = `${Math.abs(start - end)} Meter ${start > end ? "Decrease" : "Increase"} In Elevation`;
}
// Displaying weather information
this.http.get(this.weatherUrl + this.startPosition.lat + "," + this.startPosition.lon).subscribe((weatherData: any) => {
if (weatherData.current) {
this.temperature.nativeElement.innerHTML = weatherData.current.temp_c + " °C";
this.weatherForcast.nativeElement.innerHTML = weatherData.current.condition.text;
// Severe weather alerts
if (weatherData.current.temp_c > 45) {
this.spawnAlert("Heat Warning", "severe");
}
if (weatherData.current.air_quality["us-epa-index"] > 3) {
this.spawnAlert("Air Quality Warning", "severe");
}
if (weatherData.current.air_quality["us-epa-index"] > 30) {
this.spawnAlert("Strong Wind Warning", "severe");
}
if (weatherData.current.air_quality["us-epa-index"] > 70) {
this.spawnAlert("High Humidity Warning", "severe");
}
if (weatherData.current.precip_mm > 8) {
this.spawnAlert("Heavy Rain Warning", "severe");
}
// Moderate weather alerts
if (weatherData.current.temp_c > 30 && weatherData.current.temp_c < 45) {
this.spawnAlert("Heat Warning", "moderate");
} else if (weatherData.current.temp_c < 0) {
this.spawnAlert("Cold Warning", "moderate");
}
if (weatherData.current.air_quality["us-epa-index"] > 1 && weatherData.current.air_quality["us-epa-index"] <= 3) {
this.spawnAlert("Air Quality Warning", "moderate");
}
if (weatherData.current.gust_mph > 25 && weatherData.current.gust_mph <= 30) {
this.spawnAlert("Strong Wind Warning", "moderate");
}
if (weatherData.current.humidity > 60 && weatherData.current.gust_mph <= 70) {
this.spawnAlert("High Humidity Warning", "moderate");
}
if (weatherData.current.precip_mm > 2.5 && weatherData.current.precip_mm <= 8) {
this.spawnAlert("Rain Warning", "moderate");
}
// Adding route layer
this.map.addLayer({
"id" : "route",
"type" : "line",
"source" : {
"type" : "geojson",
"data" : data.toGeoJson()
},
"layout" : {
"line-join" : "round",
"line-cap" : "round"
},
"paint" : {
"line-color" : "rgb(46, 135, 240)",
"line-width" : 5,
}
});
this.spawnMapNotification("Route successfully calculated.", "success", 1500);
this.showInfo();
this.calculatingRoute = false;
this.map.resize();
this.fitBounds(data.routes[0].legs[0].points);
} else {
this.spawnMapNotification("An error occured when fetching weather information.", "error", 3000);
}
})
} else {
this.spawnMapNotification("An error occured when fetching altitude information.", "error", 3000);
}
})
} else {
this.spawnMapNotification("An error occured when fetching altitude information.", "error", 3000);
}
})
}).catch((error) => {
console.log(error);
this.spawnMapNotification("ERROR: " + error.detailedError.message, "error", 3000);
this.calculatingRoute = false;
})
})
}
}
selectStartPoint(result: any) {
for (var element of Array.from(document.getElementsByClassName("start-marker"))) {
element.remove();
}
var startMarkerElement = this.createMarker(result.position);
var designatorElement = document.createElement("div");
designatorElement.classList.add("start-marker-designator");
startMarkerElement.classList.add("start-marker");
startMarkerElement.append(designatorElement);
this.startPosition = result.position;
this.inputStart.nativeElement.value = result.address.freeformAddress;
this.routeData = null;
this.searchStartPoint(this.inputStart.nativeElement.value);
this.removeRoute();
if (this.endPosition) {
this.fitBounds([]);
} else {
this.map.setCenter(this.startPosition);
}
}
selectEndPoint(result: any) {
for (var element of Array.from(document.getElementsByClassName("end-marker"))) {
element.remove();
}
var endMarkerElement = this.createMarker(result.position);
var designatorElement = document.createElement("div");
designatorElement.classList.add("end-marker-designator");
endMarkerElement.classList.add("end-marker");
endMarkerElement.append(designatorElement);
this.endPosition = result.position;
this.inputEnd.nativeElement.value = result.address.freeformAddress;
this.routeData = null;
this.searchEndPoint(this.inputEnd.nativeElement.value);
this.removeRoute();
if (this.startPosition) {
this.fitBounds([]);
} else {
this.map.setCenter(this.endPosition);
}
}
searchStartPoint(query: String) {
if (query.length > 1) {
this.inputStartAutocomplete.nativeElement.style.display = "block";
this.search(query).subscribe((data) => {
this.startingPointAutocompleteResults = data;
})
} else {
this.inputStartAutocomplete.nativeElement.style.display = "none";
}
}
searchEndPoint(query: String) {
if (query.length > 1) {
this.inputEndAutocomplete.nativeElement.style.display = "block";
this.search(query).subscribe((data) => {
this.endingPointAutocompleteResults = data;
})
} else {
this.inputEndAutocomplete.nativeElement.style.display = "none";
}
}
search(query: String) {
return new Observable<any>((observer) => {
this.http.get(this.searchUrl + `/${query}.json?limit=5${this.position ? "&lat=" + this.position.coords.latitude + "&lon=" + this.position.coords.longitude : ""}&minFuzzyLevel=1&maxFuzzyLevel=2&view=Unified&key=ImJQ5OE7KBtQRP09rOL4mQXtlKm4qydm`).subscribe((data: any) => {
observer.next(data.results);
})
})
}
}
|
Character Arrays
Introduction
You can declare an array of any data type. In this lab we will examine arrays of characters. An array of characters is declared similar to other types of arrays. The following example declares myString to be an array of 30 characters.
char myString[30];
We often refer to such an array as a C-style string. This is because this is the way that strings are represented in the C language, which has no string class. The string class we have been using up to this point is the more modern way of handling strings of character data, but you should be familiar with C-style strings, because they are still widely used.
The Null Terminating Character
Consider the declaration
char myString[ ] = "I Love C++";
This style of declaration stores the characters I Love C++ in the array myString. Note that you are not required to specify the size of the array. The compiler will figure it out for you. In this case, the size of the array will be 11 characters. The string I Love C++ is only 10 characters long. What is the extra character for? In order for many of operations on C-style strings to work properly, we must know where the end of the string is. In our C-style string, the end of the string is marked with a Null terminating character, '\0'. Thus, in storage myString would look like this:
The null terminating character is literally the value of zero, and takes up one character space in the array. In the array declaration above, the compiler automatically creates the null terminating character for you, and adds it to the end of the array. When you declare an array of characters, you must always account for the space required for the null terminating character. So, for example, if you think that the longest string of characters you will ever store in an array will be 100, then you should declare the array with 101 spaces so that there is always room for the null terminating character.
Note that you can declare an array of characters this way:
char myString[ ] = {'B', 'l', 'u', 'e'};
In this rare case, the space allocated for the array will just be enough to hold the characters B, l, u, and e. No space is allocated for the null terminating character. This is truly just an array of characters. It is not considered a C-style string, since it has no null terminating character at the end.
Peculiarities of char Arrays
There are some peculiarities with char arrays that you should be familiar with. Otherwise, you are likely to write programs that won't work correctly. Consider once again the declaration
char myString[30];
After making this declaration, you might be tempted to assign a string of characters to the array by writing
myString = "Hello Bob!";
This statement won't compile. Although you can assign a value to the array initially by writing
char myString[ ] = "Hello Bob!";
you cannot assign a value to the array once the array has been declared. To do this, you must use the strcpy family of functions. For example, to do the assignment above, we would have to write
strcpy(myString, "Hello Bob!";
In this example, the strcpy( ) function copies the characters Hello Bob! into the character array myString. The null terminating character will be placed at the end the array myArray after the characters have been copied. Notice that the strcpy( ) function does not bother to see if the target array is big enough to hold the characters that are being copied into it. This makes the use of the strcpy( ) function very dangerous to use, because it may result in array over-runs. A much safer version of the strcpy( ) function is strncpy( ). If the array myString had been declared to have a length of 30, we might write
strcpy(myString, "Hello Bob!", 29);
This statement guarantees that no more than 29 characters will be copied into myString. This leaves room for the null terminating character at the end of the array.
Another problem with character arrays is doing comparisons. For example, if you were to write the statement
if (myString == anotherString)
cout << "\nThe strings are equal!";
your program would compile okay, but you might not get the expected results. The problem is that the expression
(myString == anotherString)
does not compare the contents of the two arrays. It actually compares the addresses of the two arrays. The reason for this will become more apparent later on. Obviously, this is not what we want. To compare the contents of two character arrays, you must use the family of strcmp( ) functions. The proper code to write to compare the two arrays is
if (strcmp(myString, anotherString)==0)
cout << "\nThe strings are equal!";
The strcmp( ) function works this way: if the two strings are equal, the function returns a zero. If the left hand string is less than the right hand string, the function returns a value less than zero. If the left hand string is larger than the right hand string, the function returns a value greater than zero. What does greater than or less than mean for an array of characters? Comparisons of character arrays are done in lexicographic order. Lexicographic order is sometimes called dictionary order. So, when comparing, think of the order that the words in the array would appear in a dictionary. For example, "cat" would compare as less than "dog".
I/O with char Arrays
C-style strings can be ouptut using the normal stream insertion operator. For example, to send the contents of myString to standard output we would write
cout << myString;
This statement outputs characters from the array myString until a null terminating character is encountered.
You can use the stream extraction operator to fill a char array. Conveniently, the stream extraction operator will store a null terminating character automatically at the end of the array. However, you should be careful to note that the stream extraction operator stops at white space. So given the statement
cin >> myString;
if the user types in the string
I Love C++,
only the character ' I ' would get stored in the character array. To read in an entire line of test, including spaces, you need to use the getline( ) function. The form of the getline( ) function is slightly different than the one that you are used to using with the string class. To use it you would write
cin.getline(myString, 80);
This form of the getline( ) function is preferred because it limits the number of characters that will be read into the array. In this case, the statement would read no more than 80 characters, and it will store a null terminating character at the end of the array. In this case, the array must have enough space for 81 characters.
Finally, we will look at the get( ) function. The get( ) function reads one character from the input stream, no matter what the character is. In particular, it will read blanks and the newline character just like any other characters. For example
char inputChar;
cin.get(inputChar);
will read in a single character and store it in the char variable inputChar. The character just read in can be tested using the character manipulation functions described in the other reading assignment for this lab.
|
import { FunctionComponent, useState } from "react";
import { createContainer } from "unstated-next";
import { IconGauge, IconKeyboard, TablerIconsProps } from "@tabler/icons-react";
export interface KeyboardShortcuts {
"app.settings": Array<string>;
"app.exit": Array<string>;
"app.command_palette": Array<string>;
"file.new": Array<string>;
"file.open": Array<string>;
"file.close": Array<string>;
"file.save": Array<string>;
"file.export": Array<string>;
"edit.undo": Array<string>;
"edit.redo": Array<string>;
"edit.cut": Array<string>;
"edit.copy": Array<string>;
"edit.paste": Array<string>;
"select.all": Array<string>;
"select.none": Array<string>;
}
export interface Settings {
keyboard_shortcuts: KeyboardShortcuts;
}
export type KeyboardShortcutName = keyof KeyboardShortcuts;
const DEFAULT_SETTINGS: Settings = {
keyboard_shortcuts: {
"app.settings": [],
"app.exit": [],
"app.command_palette": ["CTRL", "P"],
"file.new": ["CTRL", "N"],
"file.open": ["CTRL", "O"],
"file.close": ["CTRL", "F4"],
"file.save": ["CTRL", "S"],
"file.export": ["CTRL", "E"],
"edit.undo": ["CTRL", "Z"],
"edit.redo": ["CTRL", "Y"],
"edit.cut": ["CTRL", "X"],
"edit.copy": ["CTRL", "C"],
"edit.paste": ["CTRL", "V"],
"select.all": ["CTRL", "A"],
"select.none": ["CTRL", "SHIFT", "A"],
},
};
type TabId = "user_interface" | "keyboard_shortcuts";
interface SettingsTab {
id: TabId;
icon: FunctionComponent<TablerIconsProps>;
label: string;
}
function useSettings() {
const [settings, _setSettings] = useState<Settings>(DEFAULT_SETTINGS);
const [isOpen, setIsOpen] = useState<boolean>(false);
const tabs: Array<SettingsTab> = [
{
id: "user_interface",
icon: IconGauge,
label: "User interface",
},
{
id: "keyboard_shortcuts",
icon: IconKeyboard,
label: "Keyboard shortcuts",
},
];
const [activeTabId, setActiveTabId] = useState<string>("user_interface");
const activeTab: SettingsTab = tabs.find((tab) => tab.id === activeTabId) || tabs[0];
const openSettingsTab = (tabId: TabId) => {
setActiveTabId(tabId);
};
return {
tabs,
activeTab,
isOpen,
open: () => setIsOpen(true),
close: () => setIsOpen(false),
openSettingsTab,
keyboardShortcuts: settings.keyboard_shortcuts,
};
}
export const SettingsContext = createContainer(useSettings);
|
"use client";
import React, { useState, useEffect } from "react";
import { DocumentData, QueryDocumentSnapshot, collection, getDocs } from '@firebase/firestore';
import { Project } from '../../../type';
import { db } from '../../../firebase-config';
import Image from "next/image";
import styles from "./style.module.css";
import Link from "next/link";
import { motion } from "framer-motion";
const anim = {
initial: { width: 0 },
open: {
width: "auto",
transition: { duration: 0.4, ease: [0.33, 2, 0.42, 2] },
},
closed: { width: 0 },
};
export default function ProjectPro() {
const [project, setProject] = useState<Project[]>([]);
const [loading, setLoading] = useState<Boolean>(true);
const [isActive, setIsActive] = useState(false);
const blogsCollectionRef = collection(db, "project1");
useEffect(() => {
setLoading(true);
const getProjs = async () => {
try {
const data = await getDocs(blogsCollectionRef);
console.log("db filteredData ---->", data);
const filteredData = data.docs.map(
(doc: QueryDocumentSnapshot<DocumentData>) => ({
...doc.data(),
id: doc.id,
})
) as Project[];
setProject(filteredData);
setLoading(false);
} catch (err) {
console.log(err);
}
};
getProjs();
}, []);
return (
<div className="bg-blue-500">
{project.map((data) => (
// eslint-disable-next-line react/jsx-key
<div
onMouseEnter={() => {
setIsActive(true);
}}
onMouseLeave={() => {
setIsActive(false);
}}
className={styles.project}
>
<p>{data.name}</p>
<motion.div
variants={anim}
animate={isActive ? "open" : "closed"}
className={styles.imgContainer}
>
{/* <Link href={`/projectDetail/${data.id}`}> */}
<Image
src={data.image}
alt="photo"
width={280}
height={140}
className={styles.img}
/>
{/* </Link> */}
</motion.div>
<p>{data.tags}</p>
</div>
))}
</div>
);
}
|
import { React, useState } from "react";
import Layout from "../Layout/Layout";
import {
CircularProgress,
Paper,
Typography,
TextField,
Button,
Snackbar,
} from "@material-ui/core";
import MuiAlert from "@material-ui/lab/Alert";
import { makeStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
import { usePage } from "@inertiajs/inertia-react";
import axios from "axios";
import { Helmet } from "react-helmet";
const useStyles = makeStyles((theme) => ({
root: {
display: "grid",
width: "500px",
margin: "auto",
marginTop: "2rem",
padding: "40px",
flexGrow: 1,
},
paper: {
padding: theme.spacing(2),
color: theme.palette.text.secondary,
},
title: {
textAlign: "center",
marginBottom: "35px",
},
snackbar: {
maxWidth: "500px",
},
}));
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
const MarketExceptionForm = () => {
const classes = useStyles();
const [values, setValues] = useState();
const [loading, setLoading] = useState(false);
const { allMarkets, allCampaigns, allStates } = usePage().props;
const [open, setOpen] = useState(false);
const [response, setResponse] = useState();
const handleClose = (event, reason) => {
if (reason === "clickaway") {
return;
}
setOpen(false);
};
const handleChange = (e) => {
const { name, value } = e.target;
setValues((oldValues) => ({
...oldValues,
[name]: value,
}));
};
const handleSubmit = (e) => {
e.preventDefault();
setLoading(true);
axios
.post(route("add.market.exception"), values)
.then((res) => {
setLoading(false);
if (res.status === 200) {
setResponse(res.data.msg);
setOpen(true);
}
})
.catch((err) => { });
};
return (
<>
<Helmet title="Add Exceptions" />
<Paper className={classes.root}>
<Typography variant="h5" className={classes.title}>
Add Exceptions
</Typography>
<form validate='true' onSubmit={handleSubmit} className={classes.form}>
<Grid container spacing={4}>
<Grid item xs={12}>
<TextField
id="campaign_id"
select
name="campaign_id"
onChange={handleChange}
SelectProps={{
native: true,
}}
fullWidth
// required={true}
>
<option value="">Select Campaign</option>
{allCampaigns.map((option, indx) => (
<option key={indx} value={option.id}>
{option.campaign_name}
</option>
))}
</TextField>
</Grid>
<Grid item xs={12}>
<TextField
id="state"
select
name="state"
onChange={handleChange}
SelectProps={{
native: true,
}}
fullWidth
// required={true}
>
<option value="">Select State</option>
{allStates.map((option, indx) => (
<option key={indx} value={option.state}>
{option.state}
</option>
))}
</TextField>
</Grid>
<Grid item xs={12}>
<TextField
id="market"
select
name="market"
onChange={handleChange}
SelectProps={{
native: true,
}}
fullWidth
// required={true}
>
<option value="">Select Market</option>
{allMarkets.map((option, indx) => (
<option key={indx} value={option.market}>
{option.market}
</option>
))}
</TextField>
</Grid>
<Grid item xs={12}>
<TextField
id="call_type"
select
name="call_type"
onChange={handleChange}
SelectProps={{
native: true,
}}
fullWidth
// required={true}
>
<option value="">Call Type</option>
<option value="L">Landline (L)</option>
<option value="W">Wireless (W)</option>
<option value="B">Both L & W</option>
</TextField>
</Grid>
<Grid item xs={12}>
<TextField
id="date"
label="Start Date"
type="date"
name="start_date"
onChange={handleChange}
defaultValue="2021-01-06"
className={classes.textField}
InputLabelProps={{
shrink: true,
}}
fullWidth
required={true}
/>
</Grid>
<Grid item xs={12}>
<Button variant="contained" color="primary" type="submit">
{loading ? <CircularProgress color="inherit" thickness={3} size="1.5rem" /> : "Submit"}
</Button>
</Grid>
</Grid>
</form>
</Paper>
<>
<Snackbar
open={open}
autoHideDuration={3000}
onClose={handleClose}
className={classes.snackbar}
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
>
<Alert severity="success">{response}</Alert>
</Snackbar>
</>
</>
);
};
MarketExceptionForm.layout = (page) => (
<Layout title="Market Exception">{page}</Layout>
);
export default MarketExceptionForm;
|
import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { finalize, map } from 'rxjs/operators';
import { CartItem } from 'src/app/models/cart-item';
import { CustomDialogComponent } from 'src/app/models/custom-dialog/custom-dialog.component';
import { AuthService } from 'src/app/services/auth.service';
import { CartService } from 'src/app/services/cart.service';
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html',
styleUrls: ['../../../assets/css/cart.css', './cart.component.css']
})
export class CartComponent {
public cartList: CartItem[] = [];
public isLoading: boolean = false; // true時show blockUI
constructor(private cartService: CartService, private authService: AuthService, private router: Router, public dialog: MatDialog) {}
ngOnInit(): void {
if(this.authService.isAuthenticated()){ // 檢查是否為登入狀態
this.cartService.getUserCart().subscribe(
cartList => {
if(cartList) {
this.cartList = cartList;
}
}
)
// this.cartService.getUserCart().subscribe({ // 取得購物車內容
// next: (resp) =>{
// this.cartList = resp.data.map((productData: any[]) => {
// const product = new CartItem();
// product.productId = productData[resp.fieldIndex.productId];
// product.orderQuantity = Number(productData[resp.fieldIndex.orderQuantity]);
// product.curOrderQuantity = Number(productData[resp.fieldIndex.orderQuantity]);
// product.name = productData[resp.fieldIndex.name];
// product.price = productData[resp.fieldIndex.price];
// product.inventories = productData[resp.fieldIndex.inventories];
// product.img = productData[resp.fieldIndex.img];
// return product;
// });
// // console.log('carList=>' + this.cartList);
// },
// error: (err)=> console.log('Error:', err)
// });
}
}
// 刪除購物車商品
public deleteCartProduct(productId: number) {
const token: string = this.authService.getUserToken();
this.isLoading = true; // blockUI
this.cartService.deleteUserCart(token, productId)
.pipe(finalize(() => this.isLoading = false))
.subscribe({
next: (resp)=>{
console.log(resp.message);
this.cartList = this.cartList.filter(product => product.productId !== productId);
this.cartService.updateCartItemCount(); // 更新購物車icon數量
},
error: (err)=> console.log('Error', err)
})
}
// 更新購物車商品數量
public updateCart(productId: number, newOrderQuantity: number): void {
this.isLoading = true; //blockUI
const curQuantity = this.cartList.find(p => p.productId === productId)?.curOrderQuantity || 0;
const newQuantity: number = Number(newOrderQuantity);
const token: string = this.authService.getUserToken(); // 取得token
if (newQuantity >= 1) { // 如果更新後數量 >= 1
this.cartService.updateUserCart(token, productId, newQuantity)
.pipe(finalize(() => this.isLoading = false))
.subscribe({
next: (resp) => {
console.log('Cart updated successfully', resp);
const index = this.cartList.findIndex(p => p.productId === productId);
if (index !== -1) {
this.cartList[index].orderQuantity = newQuantity;
this.cartList[index].curOrderQuantity = newQuantity;
this.cartService.updateCartItemCount(); // 更新購物車icon數量
}
},
error: (err) => {
const index = this.cartList.findIndex(p => p.productId === productId);
this.openDialog('庫存不足!');
console.error('Error updating cart', err);
if (index !== -1) {
this.cartList[index].orderQuantity = curQuantity;
console.log(curQuantity);
}
}
});
}
else { // 刪除購物車內該商品
this.deleteCartProduct(productId);
this.cartService.updateCartItemCount(); // 更新購物車icon數量
}
}
// 進入結帳頁面前檢查
public toCheckoutPage() {
// 是否登入
if(!this.authService.isAuthenticated()){
this.openDialog('您尚未登入會員 請先登入!');
this.router.navigate(['/login']);
return;
}
// 購物車是否為空
if(!this.cartList.length){
this.openDialog('您的購物車沒有商品');
}
else{
const token = this.authService.getUserToken();
if (token) {
const data = {
token: token,
userCarts: this.cartList.map(product => ({
productId: product.productId,
orderQuantity: product.orderQuantity
}))
};
// 檢查庫存數量
this.cartService.batchUpdateUserCart(data).subscribe({
next: (resp) => {
this.router.navigate(['/checkout/step1']);
},
error: (err) => {
console.error('Error updating cart quantities', err);
this.openDialog('庫存不足!');
}
});
}
else { // Token過期需重新登入
this.openDialog('驗證過期 請重新登入');
this.router.navigate(['/login']);
}
}
}
// 計算總金額
public getTotalAmount(): number {
return this.cartList.reduce((acc, product) => acc + (product.orderQuantity * product.price), 0);
}
// Dialog
public openDialog(msg: string): void {
this.dialog.open(CustomDialogComponent, {
width: '250px',
data: { message: msg },
});
}
}
|
% Facts representing variables and their dependencies in a nearly tree-structured CSP
dependency(a, b).
dependency(b, c).
dependency(b, d).
dependency(c, e).
% Rule: is_tree_structured_csp(+Variable)
% Checks if a CSP is tree-structured based on variable dependencies.
is_tree_structured_csp(Variable) :-
\+ has_multiple_parents(Variable).
% Rule: has_multiple_parents(+Variable)
% Checks if a variable has multiple parents in the CSP.
has_multiple_parents(Variable) :-
dependency(Variable, Parent1),
dependency(Variable, Parent2),
Parent1 \= Parent2.
% Rule: transform_to_tree_structured_csp(+NearlyTreeStructuredCSP, -TreeStructuredCSP)
% Transforms a nearly tree-structured CSP into a strictly tree-structured CSP.
transform_to_tree_structured_csp(NearlyTreeStructuredCSP, TreeStructuredCSP) :-
findall(Variable, is_tree_structured_csp(Variable), TreeVariables),
filter_variables(NearlyTreeStructuredCSP, TreeVariables, TreeStructuredCSP).
% Rule: filter_variables(+Variables, +AllowedVariables, -FilteredVariables)
% Filters variables based on those allowed in the tree-structured CSP.
filter_variables([], _, []).
filter_variables([Variable | Rest], AllowedVariables, [Variable | FilteredRest]) :-
member(Variable, AllowedVariables),
filter_variables(Rest, AllowedVariables, FilteredRest).
filter_variables([Variable | Rest], AllowedVariables, FilteredRest) :-
\+ member(Variable, AllowedVariables),
filter_variables(Rest, AllowedVariables, FilteredRest).
% Example Usage:
% Query: TransformToTreeStructuredCsp([a, b, c, d, e], TreeStructuredCSP).
|
import { ApiProperty } from '@nestjs/swagger';
import { Exclude, Expose, Type } from 'class-transformer';
import { RoleDto } from '../../roles/dto/role.dto';
import { SkillDto } from '../../skills/dto/skill.dto';
@Exclude()
export class User {
@Expose()
@ApiProperty()
id: string;
@Expose()
@ApiProperty({
required: false,
})
userName?: string;
@Expose()
@ApiProperty()
firstName: string;
@Expose()
@ApiProperty()
lastName: string;
@Expose()
@ApiProperty()
@Type(() => RoleDto)
role: RoleDto;
@Expose()
@ApiProperty({ isArray: true, type: SkillDto })
@Type(() => SkillDto)
skills: Array<SkillDto>;
}
|
using AwoDevProxy.Shared;
using AwoDevProxy.Shared.Messages;
using AwoDevProxy.Shared.Proxy;
using AwoDevProxy.Shared.Utils.Tasks;
using MessagePack;
using Microsoft.Extensions.Logging;
using Microsoft.IO;
using System;
using System.Buffers;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading.Tasks;
using System.Web;
namespace AwoDevProxy.Lib
{
public partial class ProxyEndpoint
{
private readonly HttpClient _http;
public ProxyEndpointConfig Config { get; init; }
private CancellationTokenSource _cancelToken;
private RecyclableMemoryStreamManager _streamManager;
private TaskManager _taskManager;
private ClientWebSocket _webSocket;
private ILogger _logger;
private const int RECONNECT_DELAY = 5;
private const int MAX_RECCONECT_DELAY = 60;
public ProxyEndpoint(ProxyEndpointConfig config, ILoggerFactory factory = null, RecyclableMemoryStreamManager manager = null)
{
Config = config;
_http = new HttpClient() { BaseAddress = new Uri(config.LocalAddress) };
if (config.RequestTimeout.HasValue)
_http.Timeout = config.RequestTimeout.Value;
_buffer = new byte[config.BufferSize];
_logger = factory?.CreateLogger<ProxyEndpoint>();
_streamManager=manager ?? new RecyclableMemoryStreamManager();
_webSocketProxies = new Dictionary<Guid, WebSocketProxy>();
_taskManager = new TaskManager(factory);
SetupTasks(_taskManager);
}
private void SetupTasks(TaskManager manager)
{
manager.WithWakupAfterInactivity(TimeSpan.FromSeconds(30));
manager.WithTaskSource<ClientWebSocket, WebSocketReceiveResult>(GetTask_Client, opts =>
{
opts.HandleResult(Handle_Client_ReadResultAsync);
opts.HandleException<TaskCanceledException>(Handle_Client_TaskCancelledException);
});
manager.WithTaskSource<WebSocketProxy, WebSocketProxyReadResult>(GetTask_WebSocket, opts =>
{
opts.HandleResult(Handle_WebSocket_ReadResultAsync);
});
manager.WithTaskSource<ProxyHttpRequest, ProxyHttpResponse>(Handle_Client_HttpRequestAsync, opts =>
{
opts.HandleResult(HandlePacketResultAsync);
});
manager.WithTaskSource<ProxyWebSocketOpen, ProxyWebSocketOpenAck>(Handle_WebSocket_OpenAsync, opts =>
{
opts.HandleResult(HandlePacketResultAsync);
});
}
private async Task HandlePacketAsync(Stream stream)
{
var packet = PacketSerializer.Deserialize<MessageType>(stream, out var type);
switch (type)
{
case MessageType.HttpRequest:
case MessageType.WebSocketOpen:
_taskManager.SubmitSource(packet.GetType(), packet);
break;
case MessageType.WebSocketData:
await Handle_WebSocket_DataAsync((ProxyWebSocketData)packet);
break;
case MessageType.WebSocketClose:
await Handle_WebSocket_CloseAsync((ProxyWebSocketClose)packet);
break;
}
}
private async Task<bool> HandlePacketResultAsync<TRequest, TResponse>(TRequest resquest, TResponse response)
{
if (resquest != null)
await SendPacketAsync(response);
return false;
}
private async Task SendPacketAsync(object packet)
{
var mem = _streamManager.GetStream();
PacketSerializer.Serialize<MessageType>(packet, (IBufferWriter<byte>)mem);
await _webSocket.SendAsync(mem.GetReadOnlySequence(), _cancelToken.Token);
await mem.DisposeAsync();
}
private async Task<bool> TryRunAsync(Uri uri)
{
bool connected = false;
try
{
_webSocket = new ClientWebSocket();
await _webSocket.ConnectAsync(uri, _cancelToken.Token);
connected = true;
_logger?.LogInformation("Connected to ProxyServer");
_taskManager.SubmitSource(_webSocket);
while (await _taskManager.AwaitNextTask()) ;
return true;
}
catch (TaskCanceledException)
{
return connected;
}
catch (Exception ex)
{
if (_cancelToken.IsCancellationRequested == false)
_logger?.LogError(ex, "Unexpected exception occured in receive loop");
return connected;
}
}
public async Task DisposeAsync()
{
_taskManager.Stop();
if (_webSocket != null && _webSocket.State.HasFlag(WebSocketState.Open))
await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
foreach (var proxy in _webSocketProxies.Values)
await proxy.CloseAsync();
_webSocketProxies.Clear();
}
private string BuildQurey()
{
Dictionary<string, string> queryValues = new Dictionary<string, string>
{
{ "authKey", Config.AuthKey },
{ "bufferSize", Config.BufferSize.ToString() },
{ "name", Config.Name }
};
if(Config.RequestTimeout.HasValue)
queryValues.Add("requestTimeout", Config.RequestTimeout.Value.ToString());
if(string.IsNullOrEmpty(Config.Password) == false)
queryValues.Add("password", Config.Password);
if (Config.ForceOpen.HasValue)
queryValues.Add("force", Config.ForceOpen.Value.ToString());
return string.Join("&", queryValues.Select(x => $"{x.Key}={HttpUtility.UrlEncode(x.Value)}"));
}
public async Task RunAsync(CancellationTokenSource cts)
{
_cancelToken = cts ?? new CancellationTokenSource();
var query = BuildQurey();
var url = new Uri( $"{Config.ProxyAddress}/ws?{query}");
int retryCount = 0;
do
{
var result = await TryRunAsync(url);
if (_cancelToken.IsCancellationRequested)
{
_logger?.LogInformation("Shutting down...");
await DisposeAsync();
return;
}
if (result)
{
retryCount = 0;
_logger?.LogInformation($"Disconnected, attempting to recconect in {RECONNECT_DELAY} seconds");
await Task.Delay(TimeSpan.FromSeconds(RECONNECT_DELAY));
}
else
{
retryCount++;
var delay = Math.Min(MAX_RECCONECT_DELAY, retryCount*RECONNECT_DELAY);
_logger?.LogInformation($"Reconnection attempt failed, trying again in {delay} seconds");
await Task.Delay(TimeSpan.FromSeconds(delay));
}
} while (_cancelToken.IsCancellationRequested == false && Config.TryReopen);
}
}
}
|
import {
Typography,
Grid,
TextField,
Button,
MenuItem,
FormControl,
InputLabel,
Select,
IconButton,
} from "@mui/material";
import React, { useState, useEffect } from "react";
import axios from "axios";
import { Box } from "@mui/system";
import _ from "lodash";
import { AddCircle, IndeterminateCheckBox } from "@mui/icons-material";
const AddInmate = () => {
const [name, setName] = useState("");
const [age, setAge] = useState(0);
const [gender, setGender] = useState("M");
const [bloodGroup, setBloodGroup] = useState("");
const [sentenceStart, setSentenceStart] = useState("");
const [releaseDate, setReleaseDate] = useState("");
const [caseDetail, setCaseDetail] = useState("");
const [jobID, setJobID] = useState("");
const [cellID, setCellID] = useState("");
const [jobs, setJobs] = useState([]);
const [cells, setCells] = useState([]);
const [offences, setOffences] = useState([]);
const [loading, setLoading] = useState(true);
const [crimeCount, setCrimeCount] = useState(1);
const [options, setOptions] = useState([]);
useEffect(() => {
(async () => {
try {
let jobs = await axios.get(
"http://localhost:5000/api/prisoner/get-jobs"
);
let cells = await axios.get(
"http://localhost:5000/api/prisoner/get-cells"
);
let offences = await axios.get(
"http://localhost:5000/api/prisoner/get-offence-records"
);
jobs = jobs.data.map((elem) => elem.jobID);
cells = cells.data.map((elem) => elem.cellID);
offences = offences.data.map((elem) => [
elem.offenceID,
elem.offence_description,
]);
setJobs(jobs);
setCells(cells);
setOffences(offences);
setLoading(false);
} catch (e) {
console.log(e);
}
})();
}, []);
const handleSubmit = async () => {
try {
await axios.post("http://localhost:5000/api/prisoner/add-inmate", {
cellID,
jobID,
name,
age,
gender,
bloodgroup: bloodGroup,
sentence_start: sentenceStart,
release_date: releaseDate,
case_detail: caseDetail,
offenceIDs: options,
});
} catch (e) {
console.log(e);
}
};
const deleteCount = (index) => {
let tempArr = [...options];
tempArr.splice(index, 1);
setOptions(tempArr);
setCrimeCount(crimeCount - 1);
};
return (
<div>
{!loading && (
<>
<Typography variant="h5" style={{ fontFamily: "Roboto Condensed" }}>
<b>Add Inmate</b>
</Typography>
<Grid container>
<Grid item md={9}>
<Box sx={{ width: "50%", marginBottom: 5, marginTop: 5 }}>
<FormControl fullWidth>
<InputLabel>Cell ID</InputLabel>
<Select
value={cellID}
onChange={(e) => setCellID(e.target.value)}
>
{cells.map((elem, key) => (
<MenuItem value={elem} key={key}>
{elem}
</MenuItem>
))}
</Select>
</FormControl>
</Box>
</Grid>
<Grid item md={9}>
<Box sx={{ width: "50%" }}>
<FormControl fullWidth>
<InputLabel>Job ID</InputLabel>
<Select
value={jobID}
onChange={(e) => setJobID(e.target.value)}
>
{jobs.map((elem, key) => (
<MenuItem value={elem} key={key}>
{elem}
</MenuItem>
))}
</Select>
</FormControl>
</Box>
</Grid>
{_.times(crimeCount, (index) => {
return (
<Box sx={{ width: "50%", marginTop: 3 }} key={index}>
<Grid container>
<Grid item md={9}>
<FormControl fullWidth>
<InputLabel>Select Crime {index + 1}</InputLabel>
<Select
value={options[index] ? options[index] : ""}
onChange={(e) => {
let tempArr = [...options];
tempArr[index] = e.target.value;
setOptions(tempArr);
}}
>
{offences.map((elem, key) => (
<MenuItem value={elem[0]} key={key}>
{elem.join(" - ")}
</MenuItem>
))}
</Select>
</FormControl>
</Grid>
<Grid item>
<IconButton
style={{ marginTop: "0.25em" }}
onClick={() => setCrimeCount(crimeCount + 1)}
>
<AddCircle color="primary" />
</IconButton>
</Grid>
{index !== 0 && (
<Grid item>
<IconButton
style={{ marginTop: "0.25em" }}
onClick={() => deleteCount(index)}
>
<IndeterminateCheckBox color="secondary" />
</IconButton>
</Grid>
)}
</Grid>
</Box>
);
})}
<Grid item md={9}>
<TextField
variant="outlined"
value={name}
onChange={(e) => setName(e.target.value)}
label="Name"
color="secondary"
required
style={{ margin: "1.5em 0 0.75em 0", width: "50%" }}
/>
</Grid>
<Grid item md={9}>
<TextField
variant="outlined"
value={age}
onChange={(e) => setAge(e.target.value)}
label="Age"
color="secondary"
required
style={{ margin: "1.5em 0 0.75em 0", width: "50%" }}
/>
</Grid>
<Grid item md={9}>
<TextField
variant="outlined"
value={gender}
onChange={(e) => setGender(e.target.value)}
label="Gender"
color="secondary"
required
style={{ margin: "1.5em 0 0.75em 0", width: "50%" }}
/>
</Grid>
<Grid item md={9}>
<TextField
variant="outlined"
value={bloodGroup}
onChange={(e) => setBloodGroup(e.target.value)}
label="Blood Group"
color="secondary"
required
style={{ margin: "1.5em 0 0.75em 0", width: "50%" }}
/>
</Grid>
<Grid item md={9}>
<TextField
variant="outlined"
value={sentenceStart}
onChange={(e) => setSentenceStart(e.target.value)}
color="secondary"
required
style={{ margin: "1.5em 0 0.75em 0", width: "50%" }}
type="date"
/>
</Grid>
<Grid item md={9}>
<TextField
variant="outlined"
value={releaseDate}
onChange={(e) => setReleaseDate(e.target.value)}
color="secondary"
required
style={{ margin: "1.5em 0 0.75em 0", width: "50%" }}
type="date"
/>
</Grid>
<Grid item md={9}>
<TextField
variant="outlined"
value={caseDetail}
onChange={(e) => setCaseDetail(e.target.value)}
label="Case Detail"
color="secondary"
required
style={{ margin: "1.5em 0 0.75em 0", width: "50%" }}
type="text"
/>
</Grid>
<Grid item md={9} mt={2}>
<Button variant="outlined" onClick={handleSubmit}>
Submit
</Button>
</Grid>
</Grid>
</>
)}
</div>
);
};
export default AddInmate;
|
require('dotenv').config();
import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser'; //이 미들웨어는 post/put/patch 같은 메서드의 request body에 JSON 형식으로 데이터를 넣어주면, 이를 파싱해서 서버에서 사용할 수 있게 하고, router를 적용하는 코드의 윗부분에서 사용해야 한다.
import mongoose from 'mongoose';
import api from './api';
import jwtMiddleware from './lib/jwtMiddleware';
//import createFakeData from './createFakeData';
const { PORT, MONGO_URI } = process.env; //비구조화 할당을 통해 process.env 내부 값에 대한 레퍼런스 만들기
mongoose.connect("mongodb://localhost:27017/blog", {useNewUrlParser: true})//window에서는 string으로 보내야 된다 21.11.08
.then(()=> {
//createFakeData();
console.log('Connected to MONGoDB');
})
.catch(e=> {
console.error(e)
});
const app = new Koa();
const router = new Router();
router.use('/api', api.routes()); //api 라우트 적용
app.use(bodyParser());//라우터 적용 전에 bodyparser 적용
app.use(jwtMiddleware);
//app 인스턴스에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());
const port = PORT || 4000;
app.listen(port, ()=> {
console.log('Listening to port %d', port);
})
|
<template>
<div>
<d-file-input
v-model="fileModel"
:label="label"
v-bind="attrs$"
hide-details="auto"
/>
<slot name="existList" :files="existsFiles">
<d-stack v-if="existsFiles && existsFiles.length" class="mt-2" :gap="8">
<div
v-for="(file, index) of existsFiles"
:key="`link-${index}`"
class="d-flex align-center"
>
<v-icon size="16" class="mr-1">
{{ fileIcon(file) }}
</v-icon>
<a
:href="urlBuilder(file)"
class="link text-caption text--secondary"
>
{{ file }}
</a>
</div>
</d-stack>
</slot>
</div>
</template>
<script>
import Proxyable from 'vuetify/lib/mixins/proxyable';
import BindsAttrs from 'vuetify/lib/mixins/binds-attrs';
import { filesChore } from '@/mixins/chores';
import { wrapInArray } from 'vuetify/lib/util/helpers';
import DFileInput from '@/components/Deipify/DInput/DFileInput';
import DStack from '@/components/Deipify/DStack/DStack';
export default {
name: 'DFileInputExtended',
components: { DStack, DFileInput },
mixins: [Proxyable, BindsAttrs, filesChore],
props: {
urlBuilder: {
type: Function,
default: (val) => val
},
label: {
type: String,
default: undefined
}
},
data() {
return {
fileModel: undefined,
existsFiles: undefined
};
},
watch: {
fileModel(files) {
if (this.multiple) {
this.internalValue = [
...this.existsFiles,
...wrapInArray(files)
];
} else {
this.internalValue = files || this.existsFiles[0];
}
}
},
created() {
if (this.internalValue) {
const exist = wrapInArray(this.internalValue);
this.existsFiles = this.multiple
? exist
: wrapInArray(exist[0]);
// normalize not multiple value
if (!this.multiple) {
[this.internalValue] = exist;
}
} else {
this.existsFiles = [];
}
}
};
</script>
|
import "./project.css";
import ProjectCard from "../../Components/ProjectCard/ProjectCard";
import projectData from "../../data/Project";
import ScreenSize from "../../Components/Screen/ScreenSize";
import Button from "../../Components/Button/Button";
function Project() {
const { width } = ScreenSize();
return (
<div className="py-12 px-12 ">
<div className="flex justify-center mb-5">
<div className="text-6xl text-white font-bold font-raleway">
2021 Projects Highlight
</div>
</div>
{(() => {
if (width > 800) {
return (
<div className="snap-x overflow-scroll pl-4 flex scroll-pl-4 no-scrollbar py-5 gap-5">
{projectData["2021-2022"].map((project, index) => (
<div className="snap-start project" key={index}>
<ProjectCard
key={project.title}
title={project.title}
description={project.description}
image={project.image}
/>
</div>
))}
</div>
);
} else {
return (
<div>
{projectData["2021-2022"].map((project) => (
<div className="flex justify-center project my-5">
<ProjectCard
key={project.title}
title={project.title}
description={project.description}
image={project.image}
/>
</div>
))}
</div>
);
}
})()}
<div className="flex justify-center">
<Button name="View All" size={2} />
</div>
</div>
);
}
export default Project;
|
import { VerificationTokenType } from '@prisma/client';
import { render } from '@react-email/render';
import { TRPCError } from '@trpc/server';
import { addMinutes } from 'date-fns';
import { z } from 'zod';
import { SITE_URL } from '@/config/environment.config';
import { prismaClient } from '@/config/prisma.config';
import EmailVerification from '@/emails/email-verification';
import PasswordResetEmail from '@/emails/password-reset';
import Welcome from '@/emails/welcome';
import { singleSendEmail } from '@/lib/email';
import { generateRandomString, hashPassword } from '@/lib/utils';
import { privateProcedure, publicProcedure } from '@/trpc/trpc';
import {
ChangePasswordDto,
PasswordResetDto,
RegisterDto,
UpdateUserProfileDto,
UserProfileDto,
} from '@/types/user.types';
export const registerUser = publicProcedure.input(RegisterDto).mutation(async (opts): Promise<UserProfileDto> => {
const { password, ...data } = opts.input;
const user = await prismaClient.user.create({
data: {
...data,
password: hashPassword(password),
},
select: {
email: true,
firstName: true,
lastName: true,
phone: true,
address: true,
id: true,
},
});
const verificationToken = await prismaClient.verificationToken.create({
data: {
user: {
connect: {
id: user.id,
},
},
token: generateRandomString(32),
expires: addMinutes(new Date(), 15),
type: VerificationTokenType.Email,
},
});
singleSendEmail({
to: user.email,
subject: 'Üdvözlünk az Almuni Weben 👋',
html: render(
Welcome({
name: user.firstName,
verificationLink: `${SITE_URL}/api/verify/${verificationToken.token}`,
})
),
});
return user;
});
export const requestEmailVerification = privateProcedure.mutation(async (opts) => {
if (!opts.ctx.session?.user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Unauthorized' });
const user = await prismaClient.user.findUnique({
where: {
id: opts.ctx.session.user.id,
},
});
if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
await createEmailVerificationSession(user.id);
});
export const resetPassword = publicProcedure.input(PasswordResetDto).mutation(async (opts) => {
const user = await prismaClient.user.findUnique({
where: {
email: opts.input.email,
},
});
if (!user) return;
const verificationToken = await prismaClient.verificationToken.create({
data: {
user: {
connect: {
id: user.id,
},
},
token: generateRandomString(32),
expires: addMinutes(new Date(), 15),
type: VerificationTokenType.Password,
},
});
singleSendEmail({
to: user.email,
subject: 'Jelszó visszaállítás',
html: render(
PasswordResetEmail({
name: user.firstName,
resetLink: `${SITE_URL}/password-reset/${verificationToken.token}`,
})
),
});
});
export const newPassword = publicProcedure
.input(z.object({ token: z.string(), password: z.string() }))
.mutation(async (opts) => {
const verificationToken = await prismaClient.verificationToken.findUnique({
where: {
token: opts.input.token,
},
});
if (!verificationToken) throw new TRPCError({ code: 'NOT_FOUND', message: 'Invalid token' });
if (verificationToken.expires < new Date()) {
await prismaClient.verificationToken.delete({
where: {
token: verificationToken.token,
},
});
throw new TRPCError({ code: 'FORBIDDEN', message: 'Token expired' });
}
const user = await prismaClient.user.findUnique({
where: {
id: verificationToken.userId,
},
});
if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
await prismaClient.user.update({
where: {
id: user.id,
},
data: {
password: hashPassword(opts.input.password),
},
});
await prismaClient.verificationToken.delete({
where: {
token: verificationToken.token,
},
});
});
export const updateProfile = privateProcedure
.input(UpdateUserProfileDto)
.mutation(async (opts): Promise<UserProfileDto> => {
if (!opts.ctx.session?.user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Unauthorized' });
const existingUser = await prismaClient.user.findUnique({
where: {
id: opts.ctx.session.user.id,
},
});
if (!existingUser) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
const user = await prismaClient.user.update({
where: {
id: opts.ctx.session.user.id,
},
data: opts.input,
select: {
email: true,
firstName: true,
lastName: true,
phone: true,
address: true,
},
});
if (existingUser.email !== user.email) {
await createEmailVerificationSession(opts.ctx.session.user.id);
}
return user;
});
export const getUserById = privateProcedure.input(z.string()).query(async (opts) => {
return prismaClient.user.findUnique({
where: {
id: opts.input,
},
});
});
export const getMyUser = privateProcedure.query(async (opts) => {
if (!opts.ctx.session?.user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Unauthorized' });
return prismaClient.user.findUnique({
where: {
id: opts.ctx.session.user.id,
},
});
});
async function createEmailVerificationSession(userId: string) {
const user = await prismaClient.user.update({
where: {
id: userId,
},
data: {
emailVerified: null,
},
});
if (!user) {
throw new Error('User not found');
}
await prismaClient.verificationToken.deleteMany({
where: {
userId: user.id,
type: VerificationTokenType.Email,
},
});
const token = await prismaClient.verificationToken.create({
data: {
user: {
connect: {
id: userId,
},
},
token: generateRandomString(32),
expires: addMinutes(new Date(), 15),
type: VerificationTokenType.Email,
},
});
singleSendEmail({
to: user.email,
subject: 'E-mail cím megerősítése',
html: render(
EmailVerification({
name: user.firstName,
verificationLink: `${SITE_URL}/api/verify/${token.token}`,
})
),
});
}
export const toggleSuperAdmin = privateProcedure.input(z.string()).mutation(async (opts) => {
if (!opts.ctx.session?.user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Unauthorized' });
const user = await prismaClient.user.findUnique({
where: {
id: opts.input,
},
});
if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found' });
await prismaClient.user.update({
where: {
id: user.id,
},
data: {
isSuperAdmin: !user.isSuperAdmin,
},
});
});
export const deleteMyUser = privateProcedure.mutation(async (opts) => {
if (!opts.ctx.session?.user.id) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Unauthorized' });
await prismaClient.user.delete({
where: {
id: opts.ctx.session.user.id,
},
});
});
export const changePassword = privateProcedure.input(ChangePasswordDto).mutation(async (opts) => {
if (!opts.ctx.session?.user) throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Unauthorized' });
const user = await prismaClient.user.findUnique({
where: {
id: opts.ctx.session.user.id,
},
});
if (!user) throw new TRPCError({ code: 'NOT_FOUND', message: 'Felhasználó nem található' });
if (user.password !== hashPassword(opts.input.oldPassword)) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Hibás jelszó' });
}
await prismaClient.user.update({
where: {
id: user.id,
},
data: {
password: hashPassword(opts.input.newPassword),
},
});
});
|
#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <glew.h>
#include <glfw3.h>
#include <glm.hpp>
#include <vec3.hpp>
#include <vec4.hpp>
#include <mat4x4.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/type_ptr.hpp>
#include "Vertex.h"
static std::vector<Vertex> loadObj(const char* filename) {
//Vertex vectors
std::vector<glm::fvec3> vertexPosition;
std::vector<glm::fvec2> vertexTexcoord;
std::vector<glm::fvec3> vertexNormal;
//Face vectors
std::vector<GLint> vertexPositionIndices;
std::vector<GLint> vertexTexcoordIndices;
std::vector<GLint> vertexNormalIndices;
//Vertex array
std::vector<Vertex> vertices;
std::stringstream ss;
std::ifstream inFile(filename);
std::string line = "";
std::string prefix = "";
glm::vec3 tempVec3;
glm::vec2 tempVec2;
GLuint tempGlint = 0;
if (!inFile.is_open()) {
std::cout << "ERROR::OBJLOADER::COULD_NOT_OPEN_FILE\n";
}
else {
while (std::getline(inFile, line)) {
ss.clear();
ss.str(line);
ss >> prefix;
if (prefix =="#") {
//ignore
}
else if (prefix == "o") {
//ignore
}
else if (prefix == "s") {
//ignore
}
else if (prefix == "use_ntl") {
//ignore
}
else if (prefix == "v") { //vertex pos
ss >> tempVec3.x >> tempVec3.y >> tempVec3.z;
vertexPosition.push_back(tempVec3);
}
else if (prefix == "vn") { //vertex normals
ss >> tempVec3.x >> tempVec3.y >> tempVec3.z;
vertexNormal.push_back(tempVec3);
}
else if (prefix == "vt") { //vertex texcoords
ss >> tempVec2.x >> tempVec2.y;
vertexTexcoord.push_back(tempVec2);
}
else if (prefix == "f") { //
int counter = 0;
while (ss >> tempGlint) {
if (counter == 0)
vertexPositionIndices.push_back(tempGlint);
else if (counter == 1)
vertexTexcoordIndices.push_back(tempGlint);
else if (counter == 2)
vertexNormalIndices.push_back(tempGlint);
if (ss.peek() == '/') {
++counter;
ss.ignore(1, '/');
}
else if (ss.peek() == ' ') {
++counter;
ss.ignore(1, ' ');
}
if (counter > 2) counter = 0;
}
}
else {
}
//debug
//std::cout << line << "\n";
//std::cout << "nr of vertices" << vertexPosition.size() << "\n";
}
}
//final vertex array
vertices.resize(vertexPositionIndices.size(), Vertex());
//load in indices
for (size_t i = 0; i < vertices.size(); i++)
{
vertices[i].position = vertexPosition[vertexPositionIndices[i]-1];
vertices[i].texcoord = vertexTexcoord[vertexTexcoordIndices[i]-1];
vertices[i].normal = vertexNormal[vertexNormalIndices[i]-1];
vertices[i].color = glm::vec3(1.f, 1.f, 1.f);
}
//Loaded success
return vertices;
}
|
import { Avatar, Button, Typography } from '@mui/material';
import { useContext } from 'react';
import { Link } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import { templateList } from '../../data/templates';
import { UserContext } from '../../main';
import { ActionsMenu } from './ActionsMenu';
import { useTranslation } from 'react-i18next';
export function Home() {
const { t } = useTranslation();
const user = useContext(UserContext);
const { userImg, name, description } = user.data;
const navigate = useNavigate();
return (
<div className="home">
<div className="home__header">
<div className="user flex flex-wrap w-70">
{userImg && (
<Avatar src={userImg} sx={{ width: 128, height: 128 }} alt={`picture-${name}`} />
)}
<div className="user__text">
<Typography variant="h6">{user.data.name}</Typography>
<Typography>{description}</Typography>
</div>
</div>
<div className="home__header__actions">
<Button variant="contained" color="primary" onClick={() => navigate(`/fill-data`)}>
{t`Edit My data`}
</Button>
<ActionsMenu />
</div>
</div>
<div className="home__designs">
<Typography variant="h6">{t`Available designs`}</Typography>
<section className="designs">
{templateList.map((templateName) => {
return (
<article key={templateName}>
<Link className="designs__item dim" to={`/preview?design=${templateName}`}>
<img
className="designs__item__img"
src={`/assets/templates/${templateName}.webp`}
alt={templateName}
/>
</Link>
</article>
);
})}
</section>
</div>
</div>
);
}
|
# Архиватор на основе алгоритма LZW
**LZW** — это метод сжатия данных. Оригинальная версия метода была создана Лемпелем и Зивом в 1978 году (LZ78) и доработана Уэлчем в 1984 году, отсюда и аббревиатура LZW (Lempel, Ziv and Welch).
В ходе выполнения работы мной был реализован алгоритм сжатия и распоковки на языке Python.
## Результаты сжатия
Для проверки эффективности работы программы я использовала два разных текстовых файла:
1. Первые 40 страниц "Ромео и Джульетты"
2. Английский алфавит - просто все буквы алфавита подряд
Посмотрим каких результатов удалось достичь, пропустив файлы через кодировщик:
<img src="/imgs/1.jpg" height="70">
<img src="/imgs/2.jpg" height="70">
Рассчитаем коэффициент сжатия - это основная характеристика алгоритма сжатия. Она определяется как отношение объёма
исходных несжатых данных к объёму сжатых
В первом случае коэффициент сжатия **k = 1.43**, а во втором - **k = 0.50**
Таким образом, в случае с Ромео и Джульеттой сжатие **эффективное**, а для алфавита - наоборот, архивный алфавит по
объему занял в 2 раза больше места.
_Почему так происходит?_ Проведем анализ алгоритма.
## Анализ сжатия
Основная идея алгоритма LZ состоит в том, что второе и последующие вхождения некоторой строки символов в сообщение
заменяются ссылкой на ее первое появление в сообщении.
Следовательно наилучший результат сжатия можно будет наблюдать на текстах, где:
- используется маленький алфавит символов,
- велика вероятность вхождения части строк в другие - например текст объемный;
Становится понятно, что файл с алфавитом дал плохой результат, потому что каждый символ в файле уникален и
кодировался 2 символами -> получаем расширение исходного файла в 2 раза. А трагедия Шекспира наоборот хорошо сжалась,
так как она достаточно объемная и в ней часто повторяются не то что подстроки, а целые слова - например имена
действующих персонажей, их LZW эффективно сжимал до ссылки на первое вхождение.
## Преимущества и недостатки метода
К **плюсам** алгоритма LZW можно отнести то, что:
- Алгоритм работает без потери данных;
- Алгоритм является однопроходным;
- Для декодирования не надо сохранять вспомагательную таблицу-словарь в файл для распаковки.
Из **минусов**:
- Алгоритм не всегда эффективен;
- Алгоритм не проводит анализ входных данных, поэтому не оптимален.
## Используемая литература
- [Сжатие данных LZW - статья на Хабре](https://habr.com/ru/companies/otus/articles/581728/)
- [Обзор алгоритмов сжатия без потерь](https://mf.grsu.by/UchProc/livak/po/comprsite/theory_lzw.html#%D0%90%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC%20LZW)
|
import { useQuiz } from "../../context";
import "./QuizBoard.css";
export const QuizBoard = () => {
const { currentQuiz } = useQuiz();
console.log({ currentQuiz });
return (
<div>
<h1 className='text-3xl font-bold mx-9'>Quiz Leader Board</h1>
<table className='quizscore table-auto shadow-lg divide-y divide-gray-200 mx-11'>
<thead className='bg-gray-50'>
<tr>
<th
scope='col'
className='px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider'
>
User Name
</th>
<th
scope='col'
className='px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider'
>
Score
</th>
</tr>
</thead>
<tbody className='bg-white divide-y divide-gray-200'>
{currentQuiz?.highScore
?.sort((a, b) => (a.score > b.score ? -1 : 1))
.map((item) => {
return (
<tr key={item.userId.username}>
<td className=' px-6 py-4 whitespace-nowrap'>
<div className='flex items-center'>
<div className='ml-4'>
<div className='text-sm font-medium text-gray-900'>
{item.userId.username}
</div>
</div>
</div>
</td>
<td className=' px-6 py-4 whitespace-nowrap'>
<div className='text-sm text-gray-900'>{item.score}</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
|
[](https://www.npmjs.com/package/@creadigme/au-i18n-audit)
[](https://github.com/creadigme/aurelia-i18n-audit/actions/workflows/ci.yml)
[](https://github.com/creadigme/aurelia-docgen/actions/workflows/codeql-analysis.yml)
[](https://codecov.io/gh/creadigme/aurelia-i18n-audit)
[](LICENSE)
<br />
# Aurelia I18N Audit
Aurelia I18N Audit brings more control over your translations. With the integrated CLI you can check if all your translations keys are used, more importantly, you will be able to find the ones that are not defined.
This tool is intended to be used with projects based on [Aurelia framework](https://aurelia.io/) + [i18next](https://www.i18next.com/). It could also work with projects using only [i18next](https://www.i18next.com/).
[](https://aurelia.io/)
<a href="https://www.i18next.com/" target="_blank"><img src="https://gblobscdn.gitbook.com/spaces%2F-L9iS6Wm2hynS5H9Gj7j%2Favatar.png?alt=media" alt="i18next logo" height="100"/></a>
## 📝 License
[The MIT License](LICENSE) - Copyright © 2022 [Creadigme](https://www.creadigme.net).
Do not hesitate to [contact us](https://creadigme.net/contact/).
## 💾 Installation
```shell
yarn add @creadigme/au-i18n-audit -D
# or
npm i @creadigme/au-i18n-audit --save-dev
```
## ⚙ CLI parameters
| Parameter | Description | Sample | Mandatory | Multiple
|---|---|---|---|---|
| --src | Sources directory *(js, ts or html)* | `./src/` | true | true
| --i18n | i18n files directory *(json or yml)* | `./i18n/` | false<sup>1</sup> | true
| --remote-i18n | i18n backend | `http://localhost:8085/i18n/{{ns}}/{{lang}}` | false<sup>1</sup> | true
| --reporter | Reporter : [`summary`](#summary), [`text`](#text), [`csv`](#csv), [`xls`](#excel) | `summary` | false | true
| --output | Directory or file path of report (*only used with reporter `csv` and `xls`*) | `./i18n_report/` | false | false
| --level | Figure out if we finish with 0 code error or 1 (see Level bellow) | false | false
| --lang | Language | `en` | false | true
| --namespace | Namespace | `cart` | false | true
| --namespace-sep | NS separator (default `:`) | `$` | false | false
| --nested-sep | Sub key separator (default `.`) | `~` | false | false
| --default-ns | Default namespace (default `translation` or the first namespace) | `easy` | false | false
| --ignore-keys | Provide the ability to ignore specific keys | `^(shop\|other)\\.` | false | false
| --discovery | Provide the ability to discover i18n keys everywhere (you must provide `--namespace` & `--lang`) | | false | false
---
1. `--i18n` or `--remote-i18n` must be specified (or both).
---
| Level | Description
|---|---|
| `1` | Easy: just have all languages ok
| **`2`** | Medium: no missing keys & all languages ok (default)
| `3` | Hard: no missing keys && no unused keys & all languages ok
## Usage
### Local I18N
1. Check the directories of your project, example :
i18n with a specific file per namespace (`--i18nMode tree`):
```shell
├── i18n
│ ├── fr
│ │ ├── NS1.{yml,yaml,json}
│ │ └── NS2.{yml,yaml,json}
│ └── en
│ ├── NS1.{yml,yaml,json}
│ └── NS2.{yml,yaml,json}
└── src
├── file1.{js,ts}
├── file2.{js,ts}
└── file3.{js,ts}
```
i18n with a specific file for each language (`--i18nMode root`):
```shell
├── i18n
│ ├── fr.{yml,yaml,json}
│ └── en.{yml,yaml,json}
└── src
├── file1.{js,ts}
├── file2.{js,ts}
└── file3.{js,ts}
```
2. Add i18n script
```diff
"scripts": {
+ "i18n" : "au-i18n-audit --src ./src/ --i18n ./i18n --i18nMode tree --reporter summary"
! "i18n" : "au-i18n-audit --src ./src/ --i18n ./i18n --i18nMode root --reporter summary"
}
```
3. Launch i18n script
```shell
yarn i18n
# or
npm run i18n
# [i18n] @creadigme/au-i18n-audit v0.8.0.
# [i18n] 2 languages detected (en, fr).
# [i18n] 132 keys seems not to be used (maybe server side?).
# [i18n] 21 keys are not defined.
# [i18n] 1 keys do not have all the languages translated.
```
### Remote I18N
You must provide:
- `--remote-i18n` of your i18n backend, with `{{ns}}` and `{{lang}}`.
Example: `http://localhost:8085/i18n/{{ns}}/{{lang}}`
- `--namespace` for iterate over your namespaces.
- `--lang` for iterate over your languages.
```json
"scripts": {
"i18n" : "au-i18n-audit --src ./src/ --remote-i18n http://localhost:8085/i18n/{{ns}}/{{lang}} --namespace NS --lang en --lang fr --reporter summary"
}
```
### API
```typescript
import { I18NAudit } from '@creadigme/au-i18n-audit';
async () => {
const audit = new I18NAudit({
srcPaths : [path.resolve(".\\src")],
local : {
i18nPaths : [path.resolve(".\\i18n")]
}
});
await audit.initializeAsync();
const details = await audit.validateAsync();
console.log(details.isOk);
}();
```
## 📝 Reporters
### Summary
> `--reporter summary`

### Text
> `--reporter text`

*:information_source: The paths to the sources (rows, columns) are clickable under Visual Studio Code.*
### CSV
> `--reporter csv`


*:information_source: The default folder is the working directory. Use `--output` to specify another one or a filename (`xx.csv`).*
### Excel
> `--reporter xls`


*:information_source: The default folder is the working directory. Use `--output` to specify another one or a filename (`xx.xlsx`).*
|
import React, { Component } from 'react';
import uuid from 'uuid'
import PropTypes from 'prop-types'
const stateInicial= {
cita: {
mascota: '',
propietario: '',
fecha:'',
hora:'',
sintomas:'',
},
error:false,
}
class NuevaCita extends Component {
state={
...stateInicial
}
handleChange = (e)=>{
this.setState({
cita: {
...this.state.cita,
[e.target.name]: e.target.value,
}
})
}
handleSubmit = (e)=>{
e.preventDefault()
const { mascota, propietario, fecha, hora, sintomas }= this.state.cita
if(mascota==='' || propietario==='' || fecha==='' || hora==='' || sintomas===''){
this.setState({
error:true,
})
return
}
const nuevaCita = {...this.state.cita}
nuevaCita.id=uuid()
this.props.crearNuevaCita(nuevaCita)
this.setState({
...stateInicial
})
}
render() {
const {error} = this.state
return (
<div className="card mt-5 py-5">
<div className="card-body">
<h2 className="card-title text-center mb-5">
Llena el formulario para crear una nueva cita
</h2>
{ error
? <div className="alert alert-danger mt-2 mb-5 text-center">
Todos los campos son obligatorios
</div>
: null
}
<form onSubmit={this.handleSubmit}>
<div className="form-group row">
<label className="col-sm-4 col-lg-2 col-form-label">
Nombre Mascota
</label>
<div className="col-sm-8 col-lg-10">
<input
type="text"
className="form-control"
placeholder="Nombre Mascota"
name="mascota"
onChange={this.handleChange}
value={this.state.cita.mascota}
/>
</div>
</div>
<div className="form-group row">
<label className="col-sm-4 col-lg-2 col-form-label">
Nombre Dueño
</label>
<div className="col-sm-8 col-lg-10">
<input
type="text"
className="form-control"
placeholder="Nombre Dueño Mascota"
name="propietario"
onChange={this.handleChange}
value={this.state.cita.propietario}
/>
</div>
</div>
<div className="form-group row">
<label className="col-sm-4 col-lg-2 col-form-label">
Fecha
</label>
<div className="col-sm-8 col-lg-4">
<input
type="date"
className="form-control"
name="fecha"
onChange={this.handleChange}
value={this.state.cita.fecha}
/>
</div>
<label className="col-sm-4 col-lg-2 col-form-label">
Hora
</label>
<div className="col-sm-8 col-lg-4">
<input
type="time"
className="form-control"
name="hora"
onChange={this.handleChange}
value={this.state.cita.hora}
/>
</div>
</div>
<div className="form-group row">
<label className="col-sm-4 col-lg-2 col-form-label">
Sintomas
</label>
<div className="col-sm-8 col-lg-10">
<textarea
className="form-control"
name="sintomas"
placeholder="Describe los Sintomas"
onChange={this.handleChange}
value={this.state.cita.sintomas}
>
</textarea>
</div>
</div>
<input
type="submit"
className="py-3 mt-2 btn btn-success btn-block"
value="Agregar nueva cita"
/>
</form>
</div>
</div>
);
}
}
NuevaCita.propTypes={
crearNuevaCita: PropTypes.func.isRequired
}
export default NuevaCita;
|
import React from 'react';
import styles from './Filter.module.css';
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux';
import { fetchProducts, fetchProductsByQuery, filterBrand, filterCategorieAction, filterPriceAction } from '../../redux/slice/ProductsSlice';
import { TfiReload } from 'react-icons/tfi';
let listCate = [
"smartphones"
, "laptops"
, "fragrances"
, "skincare"
, "groceries"
, "home-decoration"
, "furniture"
, "tops"
, "womens-dresses"
, "womens-shoes"
, "mens-shirts"
, "mens-shoes"
, "mens-watches"
, "womens-watches"
, "womens-bags"
, "womens-jewellery"
, "sunglasses"
, "automotive"
, "motorcycle"
, "lighting"
]
let listBrand = [
"Apple"
, "Samsung"
, "OPPO"
, "Huawei"
, "Microsoft Surface"
, "Infinix"
, "HP Pavilion"
, "Impression of Acqua Di Gio"
, "Royal_Mirage"
, "Fog Scent Xpressio"
, "Al Munakh"
, "Lord - Al-Rehab"
, "L'Oreal Paris"
, "Hemani Tea"
, "Dermive"
, "ROREC White Rice"
, "Fair & Clear"
, "Saaf & Khaas"
, "Bake Parlor Big"
, "Baking Food Items"
, "fauji"
, "Dry Rose"
, "Boho Decor"
, "Flying Wooden"
, "LED Lights"
, "luxury palace"
, "Golden"
, "Furniture Bed Set"
, "Ratttan Outdoor"
, "Kitchen Shelf"
, "Multi Purpose"
, "AmnaMart"
, "Professional Wear"
, "Soft Cotton"
, "Top Sweater"
, "RED MICKY MOUSE.."
, "Digital Printed"
, "Ghazi Fabric"
, "IELGY"
, "IELGY fashion"
, "Synthetic Leather"
, "Sandals Flip Flops"
, "Maasai Sandals"
, "Arrivals Genuine"
, "Vintage Apparel"
, "FREE FIRE"
, "The Warehouse"
, "Sneakers"
, "Rubber"
, "Naviforce"
, "SKMEI 9117"
, "Strap Skeleton"
, "Stainless"
, "Eastern Watches"
, "Luxury Digital"
, "Watch Pearls"
, "Bracelet"
, "LouisWill"
, "Copenhagen Luxe"
, "Steal Frame"
, "Darojay"
, "Fashion Jewellery"
, "Cuff Butterfly"
, "Designer Sun Glasses"
, "mastar watch"
, "Car Aux"
, "W1209 DC12V"
, "TC Reusable"
, "Neon LED Light"
, "METRO 70cc Motorcycle - MR70"
, "BRAVE BULL"
, "shock absorber"
, "JIEPOLLY"
, "Xiangle"
, "lightingbrilliance"
, "Ifei Home"
, "DADAWU"
, "YIOSI"
]
const Filter = () => {
const dispatch = useDispatch<any>()
const [price, setPrice] = useState({
max: '',
min: '',
})
const [selectedValue, setSelectedValue] = useState('');
const [selectedBrand, setSelectedBrand] = useState('');
useEffect(() => {
dispatch(filterPriceAction({ max: price.max, min: price.min }))
}, [price])
const [hiddenOption, setHiddenOption] = useState<any>(
{
Categories: true,
Brand: true,
Price: true
}
)
const HiddenOptions = (option: string): void => {
setHiddenOption({ ...hiddenOption, [option]: !hiddenOption[option] })
return
}
const searchBrands = (brand: string) => {
// dispatch(fetchProductsByQuery(`?brand=${brand}`));
dispatch(filterBrand(brand))
}
const filtrePrice = (e: React.ChangeEvent<HTMLInputElement>) => {
let valor = e.target.value.replace(/\D/g, '');
if (valor !== '') {
setPrice({ ...price, [e.target.name]: valor });
} else {
setPrice({ ...price, [e.target.name]: '' });
}
}
const searchCategory = (category: string) => {
dispatch(fetchProductsByQuery(`/category/${category}`));
}
const checkboxCategorie = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.checked == false) {
dispatch(fetchProducts());
setSelectedValue('')
return
}
searchCategory(e.target.name)
setSelectedValue(e.target.name)
console.log(e.target.checked)
}
const checkboxBrand = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log(e.target.name)
if (e.target.checked == false) {
dispatch(fetchProducts());
setSelectedBrand('')
return
}
setSelectedBrand(e.target.name)
dispatch(filterBrand(e.target.name))
}
return (
<div className={styles.container}>
<h2 className={styles.title} >Filter <TfiReload onClick={() => dispatch(fetchProducts())} /></h2>
<button className={styles.button} onClick={() => HiddenOptions('Categories')}>Categories {hiddenOption.Categories ? '+' : '-'}</button>
<ul className={styles.Categories} style={hiddenOption.Categories ? { 'display': 'none' } : { 'display': '' }} >
{listCate.map((e) => {
return (
<li> <p>{e}</p> <input checked={selectedValue == e} name={e} onChange={(e) => checkboxCategorie(e)} type="checkbox" /></li>
)
})}
</ul>
<button className={styles.button} onClick={() => HiddenOptions('Brand')}>Brand {hiddenOption.Brand ? '+' : '-'}</button>
<ul style={hiddenOption.Brand ? { 'display': 'none' } : { 'display': '' }}>
{listBrand.map((e) => {
return (
<li><p>{e}</p><input checked={selectedBrand == e} name={e} onChange={(i) => checkboxBrand(i)} type="checkbox" /></li>
)
})}
</ul>
<button className={styles.button} onClick={() => HiddenOptions('Price')}>Price {hiddenOption.Price ? '+' : '-'}</button>
<ul style={hiddenOption.Price ? { 'display': 'none' } : { 'display': '' }}>
<div className={styles.rangeint}>
<div>
<input max={price.max} maxLength={6} min={0} value={price.min} name='min' onChange={(e) => filtrePrice(e)} placeholder='Min' />
{price.min == '' ? null : <p>$</p>}
</div>
<div>
<input maxLength={6} min={price.min} value={price.max} name='max' onChange={(e) => filtrePrice(e)} placeholder='Max' />
{price.min == '' ? null : <p>$</p>}
</div>
</div>
</ul>
</div>
);
};
export default Filter;
|
# What is Nginx?
Nginx is the internet's traffic cop. Imagine you search for a website in your browser. Your request is sent accross the internet to that website's server. When the request reaches the website's server, it first has to go through Nginx. Nginx then directs your request to the correct place on the website's server, whether that might be querying a backend server like Django, fetching an image or other static content, or doing some other kind of task on the website's server. Nginx is really good at rerouting these requests really quickly, so that it can handle lots of requests at a time, keeping things moving quickly for everyone using the website. Nginx is essentially the middleman between the internet and a website.
<img src="https://miro.medium.com/max/1400/1*rFCyG1YbQwHWnadRIE0Ddg.png" alt="System Diagram With Nginx" width="500"/>
Nginx can do many things, like:
1. Serve web traffic over HTTPS
2. Load balance requests between multiple backend servers
3. Serve static content without a backend server like Django or Express
You can find a more exhaustive list on the [offical Nginx docs](https://nginx.org/en/)
# Nginx vs. Apache
Apache is another popular webserver that is often used in place of Nginx. Nginx has several advantages over Apache:
- Due to its asynchronous, event-driven architecture, Nginx tends to have better performance when serving static content and dealing with many concurrent connections
- Nginx's configuration is easier to set up for reverse-proxying and load balancing than Apache, so it is often preferred as a gateway between your application and the public internet.
There are also advantages to Apache, including:
- Maturity. Apache has been around for a long time and has a large, stable ecosystem of modules available to extend its use-cases.
- Apache also uses `.htaccess` files for configuration, which some developers argue are simpler than Nginx's configurations
At the end of the day though, they're both highly reliable, tried-and-true technologies, so there's really no wrong choice. That said, developers tend to prefer Nginx nowadays, since it's more well-known than Apache and has better performance at scale.
# Installation and Setup
The installation processes varies depending upon your OS. It's most common to install Nginx on a Linux server, since this is what most of the cloud runs on. Here, we'll demonstrate how to install and setup Nginx on a cloud server running on Ubuntu 22.04. In case you want to install Nginx on Mac or Windows, try these tutorials:
- [Install Nginx on MacOS](https://nginxtutorials.com/install-nginx-on-mac/)
- [Install Nginx on Windows](https://medium.com/@chandramuthuraj/installing-nginx-on-windows-a-step-by-step-guide-6750575c63e2)
We assume that you have the following:
1. A cloud server running Ubuntu 22.04 accessible from the public internet
- Digital Ocean is one of the simplest and most user friendly cloud providers. If you need help, checkout this [tutorial](https://docs.digitalocean.com/products/droplets/how-to/create/) on how to create a server on Digital Ocean!
- Make sure you can connect to your server over ssh by uploading your ssh key to the server.
2. A domain name which points to your server
- You can buy a domain and configure where it points through [NameCheap](https://www.namecheap.com/). If you need extra help, you can follow this great [YouTube tutorial](https://www.youtube.com/watch?v=95BC1b5FVps&ab_channel=codebubb) on how to point a NameCheap domain at a Digital Ocean server.
## Connecting to your server
In order to install Nginx on our server, we will first need to be connected to our server. Open a new terminal window and enter `ssh root@<your-server-ip>`, where `<your-server-ip>` is the IP address of your server. You should now be connected to your server.
## Install Nginx
On your server, run the following commands to refresh your server's package index and install Nginx onto your server:
```
sudo apt update
sudo apt install nginx
```
Now, configure your server's firewall to allow HTTP traffic via Nginx:
```
sudo ufw allow 'Nginx HTTP'
```
You can confirm HTTP traffic is now allowed with:
```
sudo ufw status
```
The output should indicate that HTTP traffic is now allowed, like this:
<img width="470" alt="Screenshot 2023-11-22 at 1 05 44 AM" src="https://github.com/learning-software-engineering/learning-software-engineering.github.io/assets/36282235/a455f501-3f79-49da-84f3-c19747422de9">
When we installed Nginx with `apt`, the operating system should have started the Nginx service at the end of the installation process. We can confirm Nginx is running by entering:
```
systemctl status nginx
```
<img width="756" alt="Screenshot 2023-11-22 at 1 08 52 AM" src="https://github.com/learning-software-engineering/learning-software-engineering.github.io/assets/36282235/c5d42a9e-8c98-4310-a90c-9c265c26cf01">
If we ever need to restart or stop the Nginx service, we can do so with `systemctl restart nginx` and `systemctl stop nginx`.
Now, let's navigate to our server in the browser, and see what's there. Go to `http://yourdomain.com`, where `yourdomain.com` is the domain name you have pointed at your server. If all goes well, you should see the default Nginx landing page, letting you know that the web server is running!

# Next Steps
Now that we have Nginx installed and running on our server, the possibilities are endless. Here's a few ideas:
1. To configure Nginx as a reverse proxy for an application server like Django or Express, try this [tutorial](https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-as-a-reverse-proxy-on-ubuntu-22-04) from Digital Ocean explaining how to reverse proxy a simple Gunicorn server.
2. To serve static content like prebuilt websites or images using Nginx, try this excellent [tutorial](https://docs.nginx.com/nginx/admin-guide/web-server/serving-static-content/) from the official Nginx website on how to serve static content.
3. To secure Nginx with Let's Encrypt SSL and allow your websites to be accessed over HTTPS, try this [tutorial](https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-20-04) from Digital Ocean on how to set up secure SSL encryption with Nginx.
|
# Personal Budgeting Database
Welcome to the Personal Budgeting Database repository! This project is a semester-long effort to create a robust and efficient personal budgeting database to help manage finances effectively.
# Team
- Bryan Lizama Montecino
- Corbin Allen Nash
## Table of Contents
- [Overview](#overview)
- [Repository Structure](#repository-structure)
- [Features](#features)
- [Getting Started](#getting-started)
- [Usage](#usage)
- [Contributing](#contributing)
# Overview
Managing personal finances is essential for financial well-being. This project provides a user-friendly and feature-rich database system for tracking income, expenses, savings, and investments. It aims to give you better control over your financial situation.
This repository contains all deliverables for our semester-long project, including Deliverables 4 through 7.
# Repository Structure
- `./src`: Contains Python/Flask source code.
- `./reports`: Holds deliverable reports. Files follow a consistent naming convention, e.g., `deliver4.qmd`, `deliver5.qmd`, etc.
- `finance db.session.sql`: SQL session file for the database.
- `poetry.lock`, `pyproject.toml`: Project dependencies and settings.
- `.DS_Store`, `.gitignore`: System and git-related configurations.
- `README.md`: This documentation file.
# Features
- **Expense Tracking**: Record and categorize expenses.
- **Income Management**: Track various income sources.
- **Budget Planning**: Set spending limits and financial goals.
- **Savings and Investments**: Monitor savings and investment accounts.
- **Reports and Visualization**: Visualize financial data through reports and charts.
- **User-Friendly Interface**: Intuitive use for all technical levels.
# Getting Started
1. **Clone the Repository**:
```bash
git clone https://github.com/cmsc-vcu/cmsc508-fa2023-prj-personal-financial-budgeting.git
2. **Database Setup**:
Follow instructions in database-setup.md.
3. **Installation**:
Install dependencies as per requirements.txt.
4. **Configuration**:
Set application settings (database details, authentication).
Available Folders:
- *./src* - to hold python/flask source code
- *./reports* - to hold deliverable reports. Maintain a consistent naming convention for files, such as *deliver4.qmd*, *deliver5.qmd*, etc.
-
## Usage
1. Run the application by executing the main script or command provided in the project.
2. Access the application through your web browser or application interface.
3. Start managing your personal finances by adding income, expenses, setting budgets, and monitoring your savings and investments.
4. Explore the reporting and visualization features to gain insights into your financial data.
## Contributing
Contributions to this project are highly welcome! If you have ideas for new features, bug fixes, or improvements, please follow these steps:
1. Fork the repository to your GitHub account.
2. Create a new branch for your feature or bug fix: `git checkout -b feature/new-feature`.
3. Make your changes and commit them: `git commit -m 'Add new feature'`.
4. Push your changes to your forked repository: `git push origin feature/new-feature`.
5. Create a Pull Request on the original repository, explaining your changes and why they should be merged.
---
Thank you for using the Personal Budgeting Database! We hope it helps you achieve your financial goals and gain better control of your finances. If you have any questions or encounter issues, please don't hesitate to reach out. Happy budgeting!
|
// This file is part of Metaplay SDK which is released under the Metaplay SDK License.
using JWT;
using Metaplay.Core;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
namespace Metaplay.Cloud.Services
{
public class JWKSPublicKeyCache
{
public class NoSuchKeyException : Exception
{
public readonly string KeyId;
public NoSuchKeyException(string keyId) : base($"no public key in JWKS: {keyId}")
{
KeyId = keyId;
}
}
public class KeyCacheTemporarilyUnavailable : Exception
{
}
class JWKSet
{
public JWK[] keys = default;
}
class JWK
{
public string alg = default;
public string e = default;
public string kid = default;
public string kty = default;
public string n = default;
public string use = default;
}
readonly Serilog.ILogger _log;
readonly HttpClient _httpClient;
readonly JwtBase64UrlEncoder _base64UrlEncoder;
readonly string _jwksUrl;
readonly object _renewLock;
Task<bool> _renewTask; // protected by the lock
long _cacheStaleAt; // volatile
long _nextAutoUpdateAt; // volatile
Dictionary<string, RSA> _volatileKeys; // volatile
Timer _autoRenewTimer;
MetaTime _failureThrottleNextRequestEarliestAt; // task worker only
int _failureThrottleNumFailedRequestsInARow; // task worker only
public string JWKSUrl => _jwksUrl;
/// <summary>
/// The product name of the service this Key Cache serves
/// </summary>
public readonly string ProductName;
/// <summary>
/// Controls if logging of error messages is enabled. Used to control console spam in tests.
/// </summary>
public bool EnableLogging = true;
public JWKSPublicKeyCache(string jwksUrl, string productName)
{
_log = Serilog.Log.ForContext("SourceContext", GetType().Name);
_httpClient = HttpUtil.CreateJsonHttpClient();
_base64UrlEncoder = new JwtBase64UrlEncoder();
_jwksUrl = jwksUrl;
_renewLock = new object();
_renewTask = null;
_cacheStaleAt = 0;
_nextAutoUpdateAt = 0;
_volatileKeys = new Dictionary<string, RSA>();
_failureThrottleNextRequestEarliestAt = MetaTime.Epoch;
_failureThrottleNumFailedRequestsInARow = 0;
ProductName = productName;
}
RSA GetKeyOrNull(string keyId, out object observedCache)
{
Dictionary<string, RSA> keys = Volatile.Read(ref _volatileKeys);
observedCache = keys;
if (keys.TryGetValue(keyId, out RSA value))
return value;
return null;
}
class CertFetchResult
{
public Dictionary<string, RSA> Certs;
public TimeSpan? CacheMaxAge;
}
async Task<CertFetchResult> FetchCertsAsync()
{
using(HttpResponseMessage response = await _httpClient.GetAsync(_jwksUrl).ConfigureAwait(false))
{
string responsePayload = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.EnsureSuccessStatusCode();
TimeSpan? cacheDuration = response.Headers.CacheControl?.MaxAge;
JWKSet jwkSet = JsonConvert.DeserializeObject<JWKSet>(responsePayload);
Dictionary<string, RSA> certById = new Dictionary<string, RSA>();
foreach (JWK jwk in jwkSet.keys)
{
if (TryCreatePublicSigKeyFromJWK(jwk, out RSA rsa))
certById[jwk.kid] = rsa;
}
return new CertFetchResult() { Certs = certById, CacheMaxAge = cacheDuration };
}
}
bool TryCreatePublicSigKeyFromJWK(JWK jwk, out RSA outCert)
{
if (jwk.use != "sig" || // signatures
jwk.kty != "RSA" || // RSA only
jwk.alg != "RS256") // in RS256 algo
{
outCert = null;
return false;
}
try
{
RSAParameters parameters = new RSAParameters();
parameters.Exponent = _base64UrlEncoder.Decode(jwk.e);
parameters.Modulus = _base64UrlEncoder.Decode(jwk.n);
outCert = RSACryptoServiceProvider.Create(parameters);
return true;
}
catch(Exception ex)
{
if (EnableLogging)
_log.Error("Failed to parse JWK: {Cause}", ex);
outCert = null;
return false;
}
}
async Task RenewTaskWorkerInner()
{
// We fetch the result and inspect the service-reported Cache-control header and we cap it to max
// 5 minutes. The renew-timer still uses the real cache headers, if available.
CertFetchResult result = await TaskUtil.RetryUntilSuccessAsync(maxNumRetries: 3, FetchCertsAsync);
TimeSpan? cacheDuration = result.CacheMaxAge;
TimeSpan validDuration = Util.Min(cacheDuration ?? TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5));
DateTime cacheStaleAt = DateTime.UtcNow + validDuration;
// Schedule next. Next should be a bit before the expiration, but still at least
// MinRenewPeriodMilliseconds in the future, but no longer than MaxRenewPeriod in
// the future. The max future creates an upper bound for the updateless period.
TimeSpan RenewBeforeExpiration = TimeSpan.FromMinutes(1);
TimeSpan MinRenewPeriod = TimeSpan.FromSeconds(10);
TimeSpan MaxRenewPeriod = TimeSpan.FromHours(1);
DateTime nextAutoUpdateAt;
if (cacheDuration.HasValue)
{
TimeSpan timeToExpiration = cacheDuration.Value;
TimeSpan timeToRenew = new TimeSpan(ticks: Math.Max(MinRenewPeriod.Ticks, Math.Min(MaxRenewPeriod.Ticks, timeToExpiration.Ticks - RenewBeforeExpiration.Ticks)));
nextAutoUpdateAt = DateTime.UtcNow + timeToRenew;
}
else
nextAutoUpdateAt = DateTime.UtcNow + TimeSpan.FromMinutes(5);
if (EnableLogging)
_log.Information("JWKS key cache updated for {Product}. Keys in cache: {KeysInCache}. Valid for {Duration}.", ProductName, new List<string>(result.Certs.Keys), validDuration);
// \note: order matters, see UpdateCacheAsync()
Volatile.Write(ref _volatileKeys, result.Certs);
Volatile.Write(ref _cacheStaleAt, cacheStaleAt.Ticks);
Volatile.Write(ref _nextAutoUpdateAt, nextAutoUpdateAt.Ticks);
}
async Task<bool> RenewTaskWorker()
{
try
{
MetaDuration failureThrottle = _failureThrottleNextRequestEarliestAt - MetaTime.Now;
if (failureThrottle > MetaDuration.Zero)
{
if (EnableLogging)
_log.Warning("Too many failures while trying to fetch JWKS key update. Next query is throttled for {Duration}", failureThrottle);
await Task.Delay((int)failureThrottle.Milliseconds);
}
await RenewTaskWorkerInner().ConfigureAwait(false);
_failureThrottleNumFailedRequestsInARow = 0;
return true;
}
catch(Exception ex)
{
if (EnableLogging)
_log.Error("JWKS key cache update failed from {URL}: {Cause}", _jwksUrl, ex);
_failureThrottleNumFailedRequestsInARow++;
// 1 second first, double on each failure until reaching the cap of 64 seconds.
MetaDuration failureThrottle = MetaDuration.FromSeconds(1 << Util.Clamp<int>(_failureThrottleNumFailedRequestsInARow, 0, 6));
_failureThrottleNextRequestEarliestAt = MetaTime.Now + failureThrottle;
return false;
}
finally
{
lock(_renewLock)
{
_renewTask = null;
}
}
}
/// <summary>
/// Fetches _cacheStaleAt such that the memory access is not reordered, and converts it to DateTime of UTC kind.
/// </summary>
DateTime FetchCacheStaleAtUtcWithMemoryOrder()
{
return new DateTime(ticks: Volatile.Read(ref _cacheStaleAt), DateTimeKind.Utc);
}
/// <summary>
/// Fetches _nextAutoUpdateAt such that the memory access is not reordered, and converts it to DateTime of UTC kind.
/// </summary>
DateTime FetchNextAutoUpdateAtUtcWithMemoryOrder()
{
return new DateTime(ticks: Volatile.Read(ref _nextAutoUpdateAt), DateTimeKind.Utc);
}
enum UpdateReason
{
AutoRenew,
RequestedKeyMissing,
}
enum RenewResult
{
AlreadyUpToDate,
Updated,
CouldNotUpdate
}
/// <summary>
/// If cert cache is still observably up to date (i.e. equal to <paramref name="lastObservedCache"/>), returns <see cref="RenewResult.AlreadyUpToDate"/>. Otherwise attempts to update cert
/// cache. If update is successful, returns <see cref="RenewResult.Updated"/>. Else, returns <see cref="RenewResult.CouldNotUpdate"/>.
/// </summary>
async Task<RenewResult> UpdateCacheAsync(UpdateReason reason, object lastObservedCache)
{
// For auto-renew, we don't check timer validations. But for key-missing-requests, we
// need to do some throttling.
if (reason == UpdateReason.RequestedKeyMissing)
{
// \note: use 64bit timer to get atomic reads
if (DateTime.UtcNow < FetchCacheStaleAtUtcWithMemoryOrder())
{
// it looks like the cache is up-to-date. But did the renew just update
// cache? Expires-At is updated last, so if we now check the cache,
// it has changed if that was the case.
if (!Object.ReferenceEquals(lastObservedCache, Volatile.Read(ref _volatileKeys)))
return RenewResult.Updated;
else
return RenewResult.AlreadyUpToDate;
}
}
Task<bool> renewTask;
lock(_renewLock)
{
// has the renew completed after caller last looked into the cache
if (!Object.ReferenceEquals(lastObservedCache, Volatile.Read(ref _volatileKeys)))
return RenewResult.Updated;
if (_renewTask == null)
{
// keep locked region small. Dont run the actual work, just enqueue an async task
_renewTask = Task.Run(async () => await RenewTaskWorker().ConfigureAwait(false));
}
renewTask = _renewTask;
}
if (await renewTask.ConfigureAwait(false))
return RenewResult.Updated;
else
return RenewResult.CouldNotUpdate;
}
async Task AutoRenewTimerHandler()
{
// Renew
object observedCache = Volatile.Read(ref _volatileKeys);
_ = await UpdateCacheAsync(UpdateReason.AutoRenew, lastObservedCache: observedCache).ConfigureAwait(false);
// Note that expiresAt can be in the past
DateTime nextAutoUpdateAt = FetchNextAutoUpdateAtUtcWithMemoryOrder();
TimeSpan timeToAutoUpdate = nextAutoUpdateAt - DateTime.UtcNow;
TimeSpan delayToWait = new TimeSpan(ticks: Math.Max(0, timeToAutoUpdate.Ticks));
if (EnableLogging)
_log.Information("Scheduled JWKS key cache (source {URL}) auto renew in {TimeToRenew}", _jwksUrl, delayToWait);
_autoRenewTimer.Change(delayToWait, period: TimeSpan.FromMilliseconds(-1));
}
/// <summary>
/// Starts automatic renew timer that updates the key cache a bit before it expires.
/// </summary>
public void RenewAutomatically()
{
if (_autoRenewTimer == null)
{
_autoRenewTimer = new Timer((obj) =>
{
_ = Task.Run(async () => await AutoRenewTimerHandler());
}, null, dueTime: TimeSpan.Zero, period: TimeSpan.FromMilliseconds(-1));
}
}
/// <summary>
/// Returns the public key with the given key id. If no such key is found, throws <see cref="NoSuchKeyException"/>.
/// If cache cannot determine whether a key exists or not, throws <see cref="KeyCacheTemporarilyUnavailable"/>.
/// </summary>
public async ValueTask<RSA> GetPublicKeyAsync(string keyId)
{
// Fast path, key is in the observable cache
RSA fastKey = GetKeyOrNull(keyId, out object observedCache);
if (fastKey != null)
return fastKey;
// The key was not in cache. Was this because we had old key in the cache?
RenewResult renewResult = await UpdateCacheAsync(UpdateReason.RequestedKeyMissing, lastObservedCache: observedCache).ConfigureAwait(false);
if (renewResult == RenewResult.CouldNotUpdate)
{
throw new KeyCacheTemporarilyUnavailable();
}
else if (renewResult == RenewResult.Updated)
{
RSA key = GetKeyOrNull(keyId, out object _);
if (key != null)
return key;
// fallthru
}
throw new NoSuchKeyException(keyId);
}
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TinDog</title>
<!-- Google fonts -->
<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=Montserrat:wght@900&family=Ubuntu&display=swap" rel="stylesheet">
<!-- Font Awesome -->
<script src="https://kit.fontawesome.com/b4502003ed.js" crossorigin="anonymous"></script>
<!-- bootstrap script-->
<!-- bootstrap link must go before the our own css stylesheet -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa" crossorigin="anonymous"></script>
<!-- css stylesheet -->
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<section class="colored-section" id="title">
<div class="container-fluid">
<!-- Nav Bar -->
<nav class="navbar navbar-expand-lg navbar-dark">
<a class="navbar-brand" href="">tindog</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarTogglerDemo02">
<ul class="navbar-nav ms-auto">
<li class="nav-item">
<a class="nav-link" href="#footer">Contact</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#pricing">Products</a>
</li>
</ul>
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#cta">Download</a>
</li>
</ul>
</div>
</nav>
<!-- Title -->
<div class="row">
<div class="col-lg-6">
<h1 class="big-heading">Meet new and interesting dogs nearby.</h1>
<!-- i and span html tag can be use but i tag is not good practice but its short so we use it. -->
<!-- <i> </i> tag is -->
<button type="button" class="btn btn-dark btn-lg download-button"><i class="fa-brands fa-apple"></i> Download</button>
<button type="button" class="btn btn-outline-light btn-lg download-button"><span class="fa-brands fa-google-play"></span> Download</button>
</div>
<div class="col-lg-6">
<img class="title-image" src="images/iphone6.png" alt="iphone-mockup">
</div>
</div>
</div>
</section>
<!-- Features -->
<section class="white-section" id="features">
<div class="container-fluid">
<div class="container text-center">
<div class="row">
<div class="feature-box col-lg-4">
<i class="fa-solid fa-circle-check fea-icons fa-4x"></i>
<h3 class="feature-text">Easy to use.</h3>
<p class="features-paragrapgh">So easy to use, even your dog could do it.</p>
</div>
<div class="feature-box col-lg-4">
<i class="fa-solid fa-bullseye fea-icons fa-4x"></i>
<h3 class="feature-text">Elite Clientele</h3>
<p class="features-paragrapgh">We have all the dogs, the greatest dogs.</p>
</div>
<div class="feature-box col-lg-4">
<i class="fa-solid fa-heart fea-icons fa-4x"></i>
<h3 class="feature-text">Guaranteed to work.</h3>
<p class="features-paragrapgh">Find the love of your dog's life or your money back.</p>
</div>
</div>
</div>
</div>
</section>
<!-- Testimonials -->
<section class="colored-section" id="testimonials">
<div id="testmonials-carousel" class="carousel" data-bs-ride="false">
<div class="carousel-inner">
<!-- slide items -->
<div class="carousel-item active container-fluid">
<h2 class="testimonial-text">I no longer have to sniff other dogs for love. I've found the hottest Corgi on TinDog. Woof.</h2>
<img class="testimonial-image" src="images/dog-img.jpg" alt="dog-profile">
<em>Pebbles, New York</em>
</div>
<div class="carousel-item container-fluid">
<h2 class="testimonial-text">My dog used to be so lonely, but with TinDog's help, they've found the love of their life. I think.</h2>
<img class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile">
<em>Beverly, Illinois</em>
</div>
</div>
<!-- buttons to slide -->
<button class="carousel-control-prev" type="button" data-bs-target="#testmonials-carousel" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#testmonials-carousel" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>
</div>
</section>
<!-- Press -->
<section class="colored-section" id="press">
<img class="press-logo" src="images/techcrunch.png" alt="tc-logo">
<img class="press-logo" src="images/tnw.png" alt="tnw-logo">
<img class="press-logo" src="images/bizinsider.png" alt="biz-insider-logo">
<img class="press-logo" src="images/mashable.png" alt="mashable-logo">
</section>
<!-- Pricing -->
<section class="white-section" id="pricing">
<h2 class="testimonial-text">A Plan for Every Dog's Needs</h2>
<p>Simple and affordable price plans for your and your dog.</p>
<!-- grid is used of bootstrap -->
<!-- setting all have 4 grid to each cards we use col-lg-4 -->
<div class="row">
<div class="pricing-column col-lg-4 col-md-6">
<div class="card">
<div class="card-header">
<h3 class="pricing-text">Chihuahua</h3>
</div>
<div class="card-body">
<h2 class="testimonial-text">Free</h2>
<p>5 Matches Per Day</p>
<p>10 Messages Per Day</p>
<p>Unlimited App Usage</p>
<button type="button" class="w-100 btn btn-lg btn-block btn-outline-dark">Sign Up</button>
</div>
</div>
</div>
<div class="pricing-column col-lg-4 col-md-6">
<div class="card">
<div class="card-header">
<h3 class="pricing-text">Labrador</h3>
</div>
<div class="card-body">
<h2 class="testimonial-text">$49 / mo</h2>
<p>Unlimited Matches</p>
<p>Unlimited Messages</p>
<p>Unlimited App Usage</p>
<button type="button" class=" w-100 btn btn-dark btn-lg">Sign Up</button>
</div>
</div>
</div>
<div class="pricing-column col-lg-4">
<!-- here left with the default which is 100% for size less the lg (like desktop or laptop)
or we can put col-sm-12 -->
<div class="card">
<div class="card-header">
<h3 class="pricing-text">Mastiff</h3>
</div>
<div class="card-body">
<h2 class="testimonial-text">$99 / mo</h2>
<p>Pirority Listing</p>
<p>Unlimited Matches</p>
<p>Unlimited Messages</p>
<p>Unlimited App Usage</p>
<button type="button" class=" w-100 btn btn-lg btn-dark">Sign Up</button>
</div>
</div>
</div>
</div>
</section>
<!-- Call to Action -->
<section class="colored-section" id="cta">
<div class="container-fluid">
<h3 class="big-heading">Find the True Love of Your Dog's Life Today.</h3>
<button type="button" class="btn btn-dark btn-lg download-button"><i class="fa-brands fa-apple"></i> Download</button>
<button type="button" class="btn btn-light btn-lg download-button"><i class="fa-brands fa-google-play"></i> Download</button>
</div>
</section>
<!-- Footer -->
<footer class="white-section" id="footer">
<div class="container-fluid">
<i class=" social-icons fa-brands fa-facebook"></i>
<i class=" social-icons fa-brands fa-instagram"></i>
<i class=" social-icons fa-brands fa-twitter"></i>
<i class=" social-icons fa-solid fa-envelope"></i>
<p>© Copyright TinDog</p>
</div>
</footer>
</body>
</html>
|
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ page import="dto.ResultRow" %>
<%@ page import="dto.ResultStorage" %>
<%@ page import="utils.TableFormatter" %>
<jsp:useBean id="resultStorage" scope="session" class="dto.ResultStorage" />
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lab 2</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<style>
body {
font-family: sans-serif;
margin: 0;
}
header {
background-color: #f0f0f0;
padding: 20px;
text-align: center;
}
main {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 20px;
}
.input-group {
margin-bottom: 10px;
margin-right: 232px;
min-width: 200px;
}
label {
display: inline-block;
width: 200px;
text-align: right;
margin-right: 10px;
}
.x-button {
padding: 10px 20px;
transition: all 0.2s;
}
.x-button.active {
padding: 14px 24px;
}
input[type="text"],
button[type="submit"] {
padding: 8px;
}
button[type="submit"] {
margin-left: 245px;
}
.error {
border: 2px solid red;
}
.result {
margin-top: 5px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
max-width: 400px;
width: 342px;
max-height: 150px;
float: right;
margin-right: 4px;
}
.image-container{
padding-right: 10px;
}
.image-container img {
width: 250px;
height: auto;
border: 2px solid black;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: center;
}
th {
background-color: #f0f0f0;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
.dot {
fill: black;
stroke: none;
visibility: hidden;
}
.radio-group{
margin-left: 210px;
margin-top: -18px;
}
</style>
<script src="./js/hit.js" defer></script>
<script src="./js/validate.js" defer></script>
</head>
<body>
<header>
<h1>Лабораторная работа #2</h1>
<p>ФИО: </p>
<p>Вариант: </p>
</header>
<main>
<div class="image-container">
<svg id="graphic" class="graphic" width="250" xmlns="http://www.w3.org/2000/svg" height="250">
<-- 125,125 215,125 215,215 125,215 >
<polygon points="125,125 170,125 125,215"
fill="dodgerblue" fill-opacity="1" stroke-width="0"></polygon>
<path d="M 80 125 A 45 45 90 0 0 125 170 L 125 125 Z"
fill="dodgerblue" fill-opacity="1" stroke-width="0"></path>
<polygon points="35,125 35,80 125,80 125,125 "
fill="dodgerblue" fill-opacity="1" stroke-width="0"></polygon>
<line x1="0" x2="250" y1="125" y2="125" stroke="black"></line>
<line x1="125" x2="125" y1="0" y2="250" stroke="black"></line>
<polygon points="125,0 120,10 130,10" stroke="black"></polygon>
<polygon points="250,125 240,130 240,120" stroke="black"></polygon>
<line x1="170" x2="170" y1="130" y2="120" stroke="black"></line>
<line x1="215" x2="215" y1="130" y2="120" stroke="black"></line>
<line x1="80" x2="80" y1="130" y2="120" stroke="black"></line>
<line x1="35" x2="35" y1="130" y2="120" stroke="black"></line>
<line x1="130" x2="120" y1="170" y2="170" stroke="black"></line>
<line x1="130" x2="120" y1="215" y2="215" stroke="black"></line>
<line x1="130" x2="120" y1="80" y2="80" stroke="black"></line>
<line x1="130" x2="120" y1="35" y2="35" stroke="black"></line>
<text x="240" y="115">x</text>
<text x="135" y="10">y</text>
<text x="160" y="115">R/2</text>
<text x="210" y="115">R</text>
<text x="30" y="115" >-R</text>
<text x="80" y="115">-R/2</text>
<text x="130" y="80">R/2</text>
<text x="130" y="40">R</text>
<text x="130" y="172">-R/2</text>
<text x="130" y="220">-R</text>
<circle class="dot" cx="0" cy="0" r="1"></circle>
</svg>
</div>
<form id="coordinateForm" action="${pageContext.request.contextPath}/controller-servlet">
<div class="input-group">
<label for="x">Выберите X:</label>
<select id="selectX">
<option value=""></option>
<option value="-5">-5</option>
<option value="-4">-4</option>
<option value="-3">-3</option>
<option value="-2">-2</option>
<option value="-1">-1</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="hidden" id="x" name="x">
<div id="result-container"></div>
</div>
<div class="input-container">
<div class="input-group">
<label for="y">Введите Y: </label>
<input type="text" id="y" name="y" placeholder="(-5..3)" required>
</div>
<div class="input-group">
<label>Выберите R:</label>
<div class="radio-group">
<input type="radio" id="r1" name="r" value="1" required>1
<input type="radio" id="r2" name="r" value="2" required>2
<input type="radio" id="r3" name="r" value="3" required>3
<input type="radio" id="r4" name="r" value="4" required>4
<input type="radio" id="r5" name="r" value="5" required>5
</div>
</div>
</div>
<div class ="input-group">
<input type="hidden" id="hitTime" name="hitTime">
<script>
document.getElementById('hitTime').value = new Date().toLocaleString();
</script>
</div>
<button id="submit" type="submit">Испытать удачу</button>
</form>
<table>
<thead>
<tr>
<th>X</th>
<th>Y</th>
<th>R</th>
<th>Результат</th>
<th>Время выполнения (ms)</th>
<th>Дата</th>
</tr>
</thead>
<tbody id="results-table"></tbody>
</table>
</main>
<script>
let attemptsArray = [];
function resetDots(newAttemptsArray) {
if (newAttemptsArray.length !== 0) {
newAttemptsArray.forEach(dotString => {
const dot = JSON.parse(dotString);
attemptsArray.push(dot);
});
drawPoints();
updateTable();
}
}
function updateTable() {
const tableBody = document.getElementById('results-table');
attemptsArray.forEach(dot => {
const newRow = tableBody.insertRow(0);
const cellX = newRow.insertCell(0);
const cellY = newRow.insertCell(1);
const cellR = newRow.insertCell(2);
const cellResult = newRow.insertCell(3);
const cellExecutionTime = newRow.insertCell(4);
const cellDate = newRow.insertCell(5);
cellX.textContent = dot.x;
cellY.textContent = dot.y;
cellR.textContent = dot.r;
cellResult.textContent = dot.result;
cellExecutionTime.textContent = dot.executionTime;
cellDate.textContent = dot.hitTime;
});
}
function drawPoints() {
const svg = document.getElementById('graphic');
attemptsArray.forEach(dot => {
const x = parseFloat(dot.x);
const y = parseFloat(dot.y);
const rValue = parseFloat(dot.r);
const x_coordinate = parseFloat(124 + (90 / rValue) * x);
const y_coordinate = parseFloat(124 + (90 / rValue) * (-y));
const dotElement = document.createElementNS("http://www.w3.org/2000/svg", "circle");
dotElement.setAttribute("cx", x_coordinate);
dotElement.setAttribute("cy", y_coordinate);
dotElement.setAttribute("r", "2");
dotElement.setAttribute("fill", "red");
svg.appendChild(dotElement);
});
}
resetDots(<%=TableFormatter.getJson(resultStorage)%>);
</script>
</body>
</html>
|
package de.fhdo.lemma.service.openapi
import de.fhdo.lemma.data.CollectionType
import de.fhdo.lemma.data.Context
import de.fhdo.lemma.data.DataFactory
import de.fhdo.lemma.data.DataField
import de.fhdo.lemma.data.DataModel
import de.fhdo.lemma.data.DataStructure
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.media.ArraySchema
import io.swagger.v3.oas.models.media.Schema
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory
/**
* This class is responsible for handling the generation of a LEMMA data model from an OpenAPI file
* in the JSON or YAML format.
*
* @author <a href="mailto:jonas.sorgalla@fh-dortmund.de">Jonas Sorgalla</a>
*/
class LemmaDataSubGenerator {
/* SLF4j LOGGER */
static val LOGGER = LoggerFactory.getLogger(LemmaDataSubGenerator)
/* Separator is used to build the full qualified names during the generation */
static val SEP = "."
/*
* Map of all created DataStructures during a generation. The key contains the fully-qualified
* name while the value contains the actual data structure created.
*/
val createdDataStructures = <String, DataStructure>newHashMap
/*
* Map of all collection types created during a generation. The key contains the fully-qualified
* name while the value contains the actual structured collection type created.
*/
val createdStructuredCollectionTypes = <String, CollectionType>newHashMap
/* Factory to actually create and manipulate a LEMMA DataModel */
val dataFactory = DataFactory.eINSTANCE
/*
* Predefined instances of the data model, version, and context which are enriched with the data
* structures from the OpenAPI source
*/
val targetDataModel = dataFactory.createDataModel
val targetVersion = dataFactory.createVersion
val targetContext = dataFactory.createContext
/* OpenAPI schema which will be used as source for generation */
val OpenAPI openAPI
/* Log of all encountered exceptions during the data transformation */
@Accessors(PUBLIC_GETTER)
val transMsgs = <String>newArrayList
/* Location where the generated file is written */
val String targetFile
/**
* Constructor
*/
new(OpenAPI openAPI, String targetFile) {
this.openAPI = openAPI
this.targetFile = targetFile
}
/**
* Generate LEMMA data model from a previously parsed OpenAPI specification file. This method
* returns the created model instance and also serializes it to the user's harddrive.
*/
def DataModel generate() {
LOGGER.debug("Initializing model instance...")
initialize()
LOGGER.debug("... data model initialized")
LOGGER.debug("Creating data structures...")
openAPI?.components?.schemas?.forEach[key, value |
try {
getOrCreateDataStructure(targetContext, key, value)
} catch (Exception ex) {
transMsgs.add('''Error for data structure «key». Structure will be skipped. ''' +
"Please refer to the debug log for details.")
LOGGER.debug(ex.message)
}
]
LOGGER.debug("...data structures created")
if (OpenApiUtil.writeModel(targetDataModel, targetFile)) {
LOGGER.debug("Data model generation successful")
LOGGER.debug('''Model written to «targetFile»''')
} else
throw new Exception("Generated data model could not be written to hard disk")
return targetDataModel
}
/**
* Initialize the data model instance
*/
private def initialize() {
targetDataModel.versions.add(targetVersion)
targetVersion.name = OpenApiUtil.removeInvalidCharsFromName(openAPI.info.version)
targetVersion.contexts.add(targetContext)
targetContext.name = OpenApiUtil.removeInvalidCharsFromName(openAPI.info.title)
targetContext.version = targetVersion
}
/**
* Return a LEMMA data structure with the given name from an OpenAPI component object. In case a
* data structure with the given name was already created, because OpenAPI allows the multiple
* definition of a component object, it is returned. Otherwise, a new structure is created,
* cached, and returned.
*/
private def DataStructure getOrCreateDataStructure(Context context, String name,
Schema<?> schema) {
val structureName = name.toFirstUpper
val fullyQualifiedStructureName = '''«context.buildQualifiedName(SEP)»«SEP»''' +
structureName
val existingStructure = createdDataStructures.get(fullyQualifiedStructureName)
if (existingStructure !== null) {
LOGGER.debug('''Found and reuse existing data structure «existingStructure.name»''')
return existingStructure
}
val newStructure = dataFactory.createDataStructure
newStructure.name = structureName
context.complexTypes.add(newStructure)
newStructure.addDataFieldsFromSchema(schema)
createdDataStructures.put(fullyQualifiedStructureName, newStructure)
LOGGER.debug('''Created new data structure «newStructure.name»''')
return newStructure
}
/**
* Add fields to a given LEMMA data structure from information of a given OpenAPI schema
*/
private def void addDataFieldsFromSchema(DataStructure structure, Schema<?> structureSchema) {
structure.addDataFieldsFromSchema(null, structureSchema)
}
/**
* Add field of the given name to the given LEMMA data structure based on the given OpenAPI
* schema. This method recursively creates fields for inline-defined OpenAPI structures
* identified by schemas that have properties. In case a schema has no properties, a single data
* field is added to the LEMMA data structure, which requires the given field name to be
* non-null. In case a schema has no properties and no field name was given, the method yields
* an IllegalArgumentException.
*/
private def void addDataFieldsFromSchema(DataStructure structure, String fieldName,
Schema<?> structureSchema) {
if (structureSchema.properties !== null)
structureSchema.properties.forEach[name, schema |
structure.addDataFieldsFromSchema(name, schema)
]
else if (fieldName !== null)
structure.dataFields.add(generateDataField(fieldName, structureSchema))
else
throw new IllegalArgumentException("Can't add data field(s) from OpenAPI schema to " +
'''structure «structure.buildQualifiedName(".")» because the schema has no ''' +
"properties and no field name was given")
}
/**
* Generate a LEMMA data field with the given name from the type of an OpenAPI schema. Primitive
* schema types such as "boolean" or "integer" are mapped to the corresponding LEMMA primitive
* types. OpenAPI arrays and references are mapped to LEMMA collection types and data
* structures, respectively.
*/
private def DataField generateDataField(String name, Schema<?> structureSchema) {
val newDataField = dataFactory.createDataField
newDataField.name = name
switch (structureSchema.type) {
case "array":
newDataField.complexType = getOrCreateStructuredCollectionType(targetContext, name,
(structureSchema as ArraySchema).items)
case "boolean":
newDataField.primitiveType = dataFactory.createPrimitiveBoolean
case "integer":
newDataField.primitiveType = OpenApiUtil.deriveIntType(structureSchema.format)
case "number":
newDataField.primitiveType = OpenApiUtil.deriveFloatType(structureSchema.format)
case "string":
newDataField.primitiveType = OpenApiUtil.deriveStringType(structureSchema.format)
case null: {
// Currently, we only support references for untyped schemas
if (structureSchema.get$ref === null)
throwUnsupportedSchemaType(structureSchema)
val ref = structureSchema.get$ref
val refName = ref.substring(ref.lastIndexOf("/") + 1)
val refSchema = openAPI.components.schemas.get(refName)
if (refName !== null && refSchema !== null)
newDataField.complexType = getOrCreateDataStructure(targetContext, refName,
refSchema)
else
LOGGER.info("Encountered reference without a parseable name and/or schema. " +
"The generated LEMMA data model may be incomplete.")
}
default:
throwUnsupportedSchemaType(structureSchema)
}
return newDataField
}
/**
* Throw an IllegalArgumentException in case an OpenAPI schema type cannot be transformed into a
* corresponding LEMMA type
*/
private def throwUnsupportedSchemaType(Schema<?> schema) {
throw new IllegalArgumentException('''Schema type «schema.type» is not supported.''')
}
/**
* Return a LEMMA collection type with the given name from an OpenAPI schema. In case a
* collection type with the given name was already created, because OpenAPI allows the multiple
* definition of schema types, it is returned. Otherwise, a new collection type is created,
* cached, and returned.
*/
private def getOrCreateStructuredCollectionType(Context context, String name,
Schema<?> schema) {
val typeName = name.collectionTypeName
val fullyQualifiedTypeName = '''«context.buildQualifiedName(SEP)»«SEP»«typeName»'''
val existingType = createdStructuredCollectionTypes.get(fullyQualifiedTypeName)
if (existingType !== null) {
LOGGER.debug("Found and reuse existing structured collection type " +
existingType.name)
return existingType
}
val newType = dataFactory.createCollectionType
newType.name = typeName
context.complexTypes.add(newType)
newType.dataFields.add(generateDataField(name, schema))
createdStructuredCollectionTypes.put(fullyQualifiedTypeName, newType)
LOGGER.debug('''Created new structured collection type «newType.name»''')
return newType
}
/**
* Helper method to get the name of a LEMMA collection type from an OpenAPI array schema
*/
static def getCollectionTypeName(ArraySchema schema) {
schema.type.collectionTypeName
}
/**
* Helper method to derive the name of a LEMMA collection type from a given base name
*/
static def getCollectionTypeName(String name) {
'''«name.toFirstUpper»Collection'''.toString
}
}
|
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreRequest;
use Illuminate\Http\Request;
use App\Models\Store;
use App\Models\Region;
use App\Models\User;
use App\Models\ViewStock;
use DB;
use Illuminate\Support\Facades\Auth;
class storesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
if(Auth::user()->can(['Shaw all stores'])){
$stores = Store::all();
}else{
$stores = Auth::user()->stores;
}
$users = User::all();
$states = Region::allStates()->get();
return view('dashboard.stores.index', compact(['stores', 'users', 'states']));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$users = User::all();
$states = Region::allStates()->get();
return view('dashboard.stores.create', compact('users', 'states'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\StoreRequest $request
* @return \Illuminate\Http\Response
*/
public function store(StoreRequest $request)
{
DB::beginTransaction();
$inputs = $request->except('_token');
$inputs['is_active'] = (!$request->has('is_active')) ? 0 : 1;
$inputs['user_id'] = Auth::id();
$store = Store::create($inputs);
if($request->users)
$store->users()->sync($request->users);
if($request->regions)
$store->regions()->sync($request->regions);
DB::commit();
$notification = array(
'message' => 'تم الإضافة بنجاح',
'alert-type' => 'success',
'success' => 'تم الإضافة بنجاح',
);
return redirect()->route('stores.index')->with($notification);
}
/**
* Display the specified resource.
*
* @param \App\Models\Store $store
* @return \Illuminate\Http\Response
*/
public function show(Store $store)
{
$users = User::all();
$states = Region::allStates()->get();
$is_StoreOwner = (Auth::user()->stores->where('id', $store->id)->first()) ? true : false;
if(Auth::user()->can(['Shaw all stores']) || $is_StoreOwner){
$users = User::all();
return view('dashboard.stores.show', compact(['store', 'users', 'states']));
}else {
abort(403, 'Unauthorized action.');
}
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Store $store
* @return \Illuminate\Http\Response
*/
public function edit(Store $store)
{
$users = User::all();
$states = Region::allStates()->get();
return view('dashboard.stores.edit', compact(['store', 'users', 'states']));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\StoreRequest $request
* @param \App\Models\Store $store
* @return \Illuminate\Http\Response
*/
public function update(StoreRequest $request, Store $store)
{
DB::beginTransaction();
$inputs = $request->except('_token');
$inputs['is_active'] = (!$request->has('is_active')) ? 0 : 1;
if($store->id == 1) $inputs['is_active'] = 1;
if($request->users)
$store->users()->sync($request->users);
if($request->regions)
$store->regions()->sync($request->regions);
$store = $store->update($inputs);
DB::commit();
$notification = array(
'message' => 'تم الحفظ بنجاح',
'alert-type' => 'success',
'success' => 'تم الحفظ بنجاح',
);
return redirect()->route('stores.index')->with($notification);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Store $store
* @return \Illuminate\Http\Response
*/
public function destroy($store_id)
{
if($store_id == 1){
$notification = array(
'message' => 'لا يمكن حذف أو تعطيل المخزن الرئيسي',
'alert-type' => 'error',
'error' => 'لا يمكن حذف أو تعطيل المخزن الرئيسي',
);
return redirect()->route('stores.index')->with($notification);
}
$store = Store::findOrFail($store_id);
$count = $store->products->where('q_net', '>' , 0)->count();
if($count){
$notification = notification('عذرا، لا يمكن حذف مخزن به منتجات...', false);
return redirect()->route('stores.index')->with($notification);
}
try {
$store->forceDelete();
} catch (\Throwable $th) {
$store = Store::findOrFail($store_id);
$store->delete();
}
$notification = array(
'message' => 'تم الحذف بنجاح',
'alert-type' => 'success',
'success' => 'تم الحذف بنجاح',
);
return redirect()->route('stores.index')->with($notification);
}
public function delete(Request $request)
{
DB::beginTransaction();
$store_ids = $request->stores;
if($store_ids){
foreach($store_ids as $store_id){
$store = Store::find($store_id);
if($store && $store->id != 1){
$count = $store->products->where('q_net', '>' , 0)->count();
if($count){
$notification = notification('عذرا، لا يمكن حذف مخزن به منتجات...', false);
return redirect()->route('stores.index')->with($notification);
}
try {
$store->forceDelete();
} catch (\Throwable $th) {
$store = Store::find($store_id);
$store->delete();
}
}
}
DB::commit();
$notification = array(
'message' => 'تم الحذف بنجاح',
'alert-type' => 'success',
'success' => 'تم الحذف بنجاح',
);
}else{
DB::commit();
$notification = array(
'message' => 'حدث خطأ حاول مرة أخري، إذا تكررت المشكلة تواصل مع الدعم الفني.',
'alert-type' => 'error',
'error' => 'حدث خطأ حاول مرة أخري، إذا تكررت المشكلة تواصل مع الدعم الفني.',
);
}
return redirect()->route('stores.index')->with($notification);
}
public function updateIsActive(Request $request, $store_id)
{
if($store_id == 1){
$notification = array(
'message' => 'لا يمكن حذف أو تعطيل المخزن الرئيسي',
'alert-type' => 'error',
'error' => 'لا يمكن حذف أو تعطيل المخزن الرئيسي',
);
return redirect()->route('stores.index')->with($notification);
}
try {
$store = Store::findOrFail($store_id);
DB::beginTransaction();
if($store){
$is_active = ($store->is_active)? 0 : 1;
}
$store->update(['is_active'=>$is_active]);
DB::commit();
$notification = array(
'message' => 'تم حفظ التعديلات بنجاح',
'alert-type' => 'success',
'success' => 'تم حفظ التعديلات بنجاح',
);
return redirect()->route('stores.index')->with($notification);
} catch (\Exception $ex) {
return redirect()->route('stores.index')->with(['error' => $this->getFileNameError('updateIsActive')]);
}
}
}
|
package br.com.alura.screenmatch.principal;
import br.com.alura.screenmatch.calculos.Classificavel;
import br.com.alura.screenmatch.model.Filme;
import br.com.alura.screenmatch.model.Serie;
import br.com.alura.screenmatch.model.Titulo;
import java.util.*;
public class PrincipalComListas {
public static void main(String[] args) {
Filme meuFilme = new Filme("O poderoso chefão",1970);
meuFilme.avaliar(9);
var filmeDoPaulo = new Filme("Dogville",2003);
filmeDoPaulo.avaliar(8);
Filme outroFilme = new Filme("Avatar",2023);
outroFilme.avaliar(10);
Serie lost = new Serie("Lost",2000);
List<Titulo> lista = new ArrayList<>();
lista.add(filmeDoPaulo);
lista.add(meuFilme);
lista.add(outroFilme);
lista.add(lost);
for (Titulo item:lista) {
if (item instanceof Filme filme && filme.getClassificacao() > 2){
System.out.println(item.getNome());
/*Instanceof verifica o tipo do objeto*/
System.out.println(filme.getClassificacao());
}
}
ArrayList<String> buscaPorArtistas = new ArrayList<>();
buscaPorArtistas.add("Adam Sandler");
buscaPorArtistas.add("Zé Ruela");
buscaPorArtistas.add("Gabriel");
buscaPorArtistas.add("Olivia");
Collections.sort(buscaPorArtistas);
System.out.println(buscaPorArtistas);
Collections.sort(lista);
System.out.println(lista);
lista.sort(Comparator.comparing(Titulo::getAnoDeLancamento));
System.out.println("Ordem por ano "+lista);
}
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2018 Bhojpur Consulting Private Limited, India. All rights reserved.
#
# 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.
"""
Tests webclient login
"""
from django.conf import settings
from django.conf.urls import url
from django.utils.importlib import import_module
from django.test.utils import override_settings
from engine.webclient.views import WebclientLoginView
from engine.testlib import IWebTest, post, get
from django.core.urlresolvers import reverse
from django.test import Client
from random import random
import pytest
tag_url = reverse('load_template', kwargs={'menu': 'usertags'})
class CustomWebclientLoginView(WebclientLoginView):
pass
urlpatterns = import_module(settings.ROOT_URLCONF).urlpatterns
urlpatterns += [
url(r'^test_login/$',
CustomWebclientLoginView.as_view(), name="test_weblogin"),
]
class TestLogin(IWebTest):
"""
Tests login
"""
@pytest.mark.parametrize("credentials", [
[{'username': 'guest', 'password': 'fake', 'server': 1},
"Guest account is not supported."],
[{'username': 'nobody', 'password': '', 'server': 1},
"This field is required."],
[{'password': 'fake'},
"This field is required."],
[{'username': 'g', 'password': str(random()), 'server': 1},
"please check your user name and password."]
])
def test_login_errors(self, credentials):
"""
Tests handling of various login errors.
E.g. missing fields, invalid credentials and guest login
"""
django_client = self.django_root_client
request_url = reverse('weblogin')
data = credentials[0]
data['server'] = 1
message = credentials[1]
rsp = post(django_client, request_url, data, status_code=200)
assert message in rsp.content
def test_get_login_page(self):
"""
Simply test if a GET of the login url returns login page
"""
django_client = Client()
request_url = reverse('weblogin')
rsp = get(django_client, request_url, {}, status_code=200)
assert 'ODE.web - Login' in rsp.content
@pytest.mark.parametrize("redirect", ['', tag_url])
def test_login_redirect(self, redirect):
"""
Test that a successful login redirects to /webclient/
or to specified url
"""
django_client = self.django_root_client
# redirect = reverse('load_template', kwargs={'menu': 'usertags'})
request_url = "%s?url=%s" % (reverse('weblogin'), redirect)
data = {'username': self.ctx.userName,
'password': self.ctx.userName,
'server': 1}
rsp = post(django_client, request_url, data, status_code=302)
if len(redirect) == 0:
redirect = reverse('webindex')
assert rsp['Location'].endswith(redirect)
@override_settings(ROOT_URLCONF=__name__, LOGIN_VIEW='test_weblogin')
def test_login_view(self):
"""
Test that a successful logout redirects to custom login view
"""
django_client = self.django_root_client
request_url = reverse('test_weblogin')
data = {
'server': 1,
'username': self.ctx.userName,
'password': self.ctx.userName,
}
rsp = post(django_client, request_url, data, status_code=302)
request_url = reverse('weblogout')
rsp = post(django_client, request_url, {}, status_code=302)
assert rsp['Location'].endswith(reverse('test_weblogin'))
assert not rsp['Location'].endswith(reverse('weblogin'))
|
<!doctype html>
<html class="no-js" lang="ru" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Колесник</title>
<meta content="" name="description">
<meta content="" name="keywords">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="telephone=no" name="format-detection">
<!-- This make sence for mobile browsers. It means, that content has been optimized for mobile browsers -->
<meta name="HandheldFriendly" content="true">
<!--[if (gt IE 9)|!(IE)]><!-->
<link th:href="@{/css/main.min.css}" rel="stylesheet" type="text/css">
<!--<![endif]-->
<meta property="og:title" content=""/>
<meta property="og:url" content=""/>
<meta property="og:description" content=""/>
<meta property="og:image" content=""/>
<meta property="og:image:type" content="image/jpeg"/>
<meta property="og:image:width" content="500"/>
<meta property="og:image:height" content="300"/>
<meta property="twitter:description" content=""/>
<link rel="image_src" href=""/>
<link rel="icon" type="image/x-icon" th:href="@{/favicon.ico}">
<script>
(function (H) {
H.className = H.className.replace(/\bno-js\b/, 'js')
})(document.documentElement)
</script>
</head>
<body class="page ">
<div class="page__top ">
<div th:replace="~{fragments/header.html :: #header}"></div>
<main class="page__inner page__inner--light">
<section class="section">
<div class="container">
<div class="section__header">Личный кабинет
<br>инвестора
</div>
<div class="section__body">
<div class="row gy-lg-6 gy-7">
<div class="col-xl-3">
<div class="row gy-xl-2 g-lg-1 g-1">
<div class="col-xl-12 col-lg-6">
<div th:replace="~{fragments/person-info-card.html :: #person-info-card}"></div>
</div>
<div class="col-xl-12 col-lg-6">
<div class="row gy-xl-2 g-lg-1 g-1">
<div class="col-12">
<div th:replace="~{fragments/account-info-card.html :: #account-info-card}"></div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-5 offset-xl-1">
<form action="#" th:action="@{/update}" th:method="POST" th:object="${user}" id="details"
enctype="multipart/form-data" class="form v-form">
<div class="form__group">
<div class="form__name">Анкетные данные</div>
<div class="form__desc">
Заполните анкетные данные для получения аккредитации
</div>
<div class="form__field form__field--info">
<div class="form__field-name">
ФИО
<input name="fio" type="hidden" th:field="*{fullName}">
<span th:text="*{fullName}"></span>
</div>
<div class="form__field-name">
Телефон (логин)
<input name="phone" type="hidden" th:field="*{phone}">
<span id="phone" th:field="*{phone}" th:text="*{formattedPhone}"></span>
</div>
<div class="form__field-name">
Электронная почта
<input name="email" type="hidden" th:field="*{email}">
<span id="email" th:text="*{email}"></span>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
Налоговый статус
</div>
<div class="form__field-item">
<div class="f-select__wrapper js-select-shell">
<select name="tax-status" id="tax-status" class="f-select" required
th:field="*{taxStatus}" placeholder="ВЫБЕРИТЕ В КАКОМ СТАТУСЕ БУДЕТЕ ИНВЕСТИРОВАТЬ">
<option th:if="*{taxStatus == null}" data-placeholder="true" value=""></option>
<option th:each="tStatus, iter : ${T(com.ddkolesnik.userservice.model.bitrix.enums.TaxStatus).values()}"
th:value="${tStatus}" th:text="${tStatus.title}" th:selected="*{taxStatus}" ></option>
</select>
<div class="f-select__error">* Выберите в каком статусе будете инвестировать
</div>
<div class="f-select__icon">
<svg class="icon__arrow" width="7px" height="7px">
<use xlink:href="/img/svg-symbols.svg#arrow"></use>
</svg>
</div>
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
ИНН
</div>
<div class="form__field-item v-field">
<div class="f-input__wrapper ">
<input data-phone-mask="999999999999" name="inn" type="text" placeholder="720000000001"
class="f-input " id="inn" th:field="*{inn}" data-pristine-required-message='* Обязательно для заполнения' minlength='12' required data-pristine-minlength-message='* ИНН должен
содержать 12 цифр'>
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
СНИЛС
</div>
<div class="form__field-item v-field">
<div class="f-input__wrapper ">
<input data-phone-mask="99999999999" name="snils" type="text" placeholder="12345678999"
class="f-input " id="snils" th:field="*{snils.number}" minlength='11' data-pristine-required-message='* Обязательно для заполнения' required data-pristine-minlength-message='* СНИЛС должен
содержать 11 цифр'>
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
Дата рождения
</div>
<div class="form__field-item">
<div class="f-input__wrapper ">
<input data-phone-mask="99.99.9999" name="birthdate" type="text"
placeholder="01.01.1980" class="f-input " id="birthdate"
th:field="*{birthdate}">
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
Место рождения
</div>
<div class="form__field-item">
<div class="f-input__wrapper ">
<input name="place-of-birth" type="text" placeholder="Место рождения"
class="f-input " id="place-of-birth" th:field="*{placeOfBirth}">
</div>
</div>
</div>
</div>
<div class="form__group">
<div class="form__name">Паспортные данные</div>
<div class="form__field-group">
<div class="form__field">
<div class="form__field-name">
Серия
</div>
<div class="form__field-item">
<div class="f-input__wrapper ">
<input data-phone-mask="9999" name="serial" type="text"
placeholder="6701" class="f-input " id="serial"
th:field="*{passport.serial}">
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
Номер
</div>
<div class="form__field-item">
<div class="f-input__wrapper ">
<input data-phone-mask="999999" name="passport-number" type="text"
placeholder="340220" class="f-input " id="passport-number"
th:field="*{passport.number}">
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
Код подразделения
</div>
<div class="form__field-item">
<div class="f-input__wrapper ">
<input data-phone-mask="999-999" name="department-code" type="text"
placeholder="222-222" class="f-input " id="department-code"
th:field="*{passport.departmentCode}">
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
Дата выдачи
</div>
<div class="form__field-item">
<div class="f-input__wrapper ">
<input data-phone-mask="99.99.9999" name="issued-at" type="text"
placeholder="__.__.____" class="f-input " id="issued-at"
th:field="*{passport.issuedAt}">
</div>
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
Кем выдан
</div>
<div class="form__field-item">
<div class="f-input__wrapper ">
<input name="issued-by" type="text" placeholder="Кем выдан"
class="f-input " id="issued-by" th:field="*{passport.issuedBy}">
</div>
</div>
</div>
<div class="form__field">
<div class="form__field-name">
Адрес регистрации
</div>
<div class="form__field-item">
<div class="f-input__wrapper ">
<input name="default" type="text" placeholder="Адрес регистрации"
class="f-input " id="" th:field="*{address}">
</div>
</div>
</div>
</div>
<div class="form__group">
<div class="form__name">Сканы паспорта</div>
<div class="form__help">
<p>Загрузите сканы или фото следующих страниц:</p>
<p style="font-weight: bold;">разворот с фото и страницу с пропиской</p>
</div>
<div class="form__field">
<div class="form__field-item">
<div class="f-drop__shell">
<label class="f-drop">
<input type="file" multiple="multiple" class="f-file__input" th:field="*{passport.scans}"/>
<svg class="icon__cloud" width="40px" height="30px">
<use xlink:href="/img/svg-symbols.svg#cloud"></use>
</svg>
<div class="f-drop__text">Перетащите файлы сюда или</div>
<a href="/">Выберите файл на компьютере</a>
</label>
<div class="f-drop__list">
</div>
</div>
</div>
</div>
</div>
<div class="form__group">
<div class="form__name">Скан снилс</div>
<div class="form__help">
<p>Загрузите скан СНИЛС</p>
</div>
<div class="form__field">
<div class="form__field-item">
<div class="f-drop__shell">
<label class="f-drop">
<input type="file" multiple="multiple" class="f-file__input" th:field="*{snils.scans}"/>
<svg class="icon__cloud" width="40px" height="30px">
<use xlink:href="/img/svg-symbols.svg#cloud"></use>
</svg>
<div class="f-drop__text">Перетащите файлы сюда или</div>
<a href="/">Выберите файл на компьютере</a>
</label>
<div class="f-drop__list">
</div>
</div>
</div>
</div>
</div>
<div class="form__group">
<div class="form__name">Банковские реквизиты</div>
<div class="form__help">
<p>Загрузите скан или фото банковских реквизитов
<br>Если вы инвестируете как физ. лицо, то указывайте реквизиты физ. лица,
если вы инвестируете как ИП, то нужны реквизиты ИП.</p>
</div>
<div class="form__field">
<div class="form__field-item">
<div class="f-drop__shell">
<label class="f-drop">
<input type="file" multiple="multiple" class="f-file__input" th:field="*{bankRequisites.scans}"/>
<svg class="icon__cloud" width="40px" height="30px">
<use xlink:href="/img/svg-symbols.svg#cloud"></use>
</svg>
<div class="f-drop__text">Перетащите файлы сюда или</div>
<a href="/">Выберите файл на компьютере</a>
</label>
<div class="f-drop__list">
</div>
</div>
</div>
</div>
</div>
<div class="form__submit">
<button class="button " type="submit" id="submit">
<span>Отправить</span>
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
</main>
</div>
<aside class="page__bottom">
<div th:replace="~{fragments/footer.html :: #footer}"></div>
<script th:src="@{/js/separate-js/svg4everybody.min.js}"></script>
<script>
svg4everybody();
</script>
<script th:src="@{/js/main.min.js}"></script>
</aside>
<script th:src="@{https://code.jquery.com/jquery-3.5.1.min.js}"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script type="text/javascript" th:src="@{/js/common.js}"></script>
<script type="text/javascript" th:src="@{/js/change-phone.js}"></script>
<script type="text/javascript" th:src="@{/js/change-password.js}"></script>
<script type="text/javascript" th:src="@{/js/profile.js}"></script>
<div th:replace="~{forms/change-password-form.html :: #change-password-form-modal}"></div>
<div th:replace="~{forms/change-phone-form.html :: #change-phone-form-modal}"></div>
<div th:replace="~{fragments/message-form.html :: #message-form-modal}"></div>
<div th:replace="~{forms/confirm-form.html :: #confirm-form-modal}"></div>
</body>
</html>
|
---
title: OAuth 2.0 구현
date: 2024-06-07 13:00:00 +09:00
categories: [Backend]
author: yehoon
tags: [Authentication, Django, Flask]
image: /assets/img/oauth/thumbnail.png
---
1. Django 기반 웹을 Resource Owner로서 OAuth 2.0 기능 구현
2. OAuth 2.0을 Flask 앱에 Client로서 구현
## 1. Django 기반 웹에 OAuth 2.0 기능 구현
### 1.1. Django OAuth Toolkit 설치
```bash
pip install django-oauth-toolkit
```
### 1.2. INSTALLED_APPS에 oauth2_provider 추가
Django 프로젝트의 `settings.py` 파일에서 `oauth2_provider`를 `INSTALLED_APPS` 목록에 추가
```python
INSTALLED_APPS = [
...
'oauth2_provider',
]
```
### 1.3. oauth2_provider URL 추가
`urls.py`
```python
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('oauth/', include('oauth2_provider.urls', namespace='oauth2_provider')),
]
```
### 1.4. 마이그레이션 실행
OAuth 2.0에 필요한 데이터베이스 테이블을 생성하기 위해 마이그레이션을 실행
```bash
python manage.py migrate
```
### 1.5. 서버 실행
```bash
python manage.py runserver
```
### 1.6. OAuth 2.0 애플리케이션 생성
1. Django Admin 이동하여 Application 추가

2. Application 설정
- Client Type: Confidential
- Authorization Grant Type: Authorization Code
- Redirect URIs: `http://localhost:5000/callback`
> Redirect URI: 승인 후에 어디로 가는지
3. Client id와 Client secret 복사해두기
## 2. OAuth 2.0을 Flask 앱에 Client로서 구현
### 2.1. 라이브러리 설치
```bash
pip install flask flask_session flask_sqlalchemy pkce
```
### 2.2. Flask 앱 구현
```python
from flask import Flask, redirect, url_for, session, request, jsonify
import requests
import pkce
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# Configure Flask-Session
app.config['SESSION_TYPE'] = 'sqlalchemy'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sessions.db'
db = SQLAlchemy(app)
app.config['SESSION_SQLALCHEMY'] = db
Session(app)
CLIENT_ID = 'ihfF8TmV2ggMuUgsbDEpDvSGvKG2xMT4T3qAhmHS'
CLIENT_SECRET = 'Pko6fQYlEIcg3CcLRe1mqqF2X5ZbcKBMExan42iAmQmJKpri1T35dYfoNbIHZo2UsdTAN0aL6BxIMvHgOGCRDv1jg2XXYBjA8n2jj4GEiLaMFBhx2w3kpyAWfo3AvMl3'
AUTHORIZATION_BASE_URL = 'http://localhost:8000/oauth/authorize/'
TOKEN_URL = 'http://localhost:8000/oauth/token/'
REDIRECT_URI = 'http://localhost:5000/callback'
@app.route('/')
def home():
return '''
<h1>Flask OAuth Client</h1>
<a href="/login">Login with OAuth</a>
'''
@app.route('/login')
def login():
code_verifier = pkce.generate_code_verifier(length=128)
session['code_verifier'] = code_verifier
code_challenge = pkce.get_code_challenge(code_verifier)
authorization_url = f"{AUTHORIZATION_BASE_URL}?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&code_challenge={code_challenge}&code_challenge_method=S256"
return redirect(authorization_url)
@app.route('/callback')
def callback():
print(session)
error = request.args.get('error')
if error:
return f"Error: {error}"
code = request.args.get('code')
if not code:
return 'Missing code parameter.'
code_verifier = session.get('code_verifier')
if not code_verifier:
return 'Missing code verifier in session.'
token_response = requests.post(TOKEN_URL, data={
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'code_verifier': code_verifier,
})
token_json = token_response.json()
if 'error' in token_json:
return f"Error: {token_json['error']} - {token_json.get('error_description')}"
session['oauth_token'] = token_json['access_token']
return redirect(url_for('profile'))
@app.route('/profile')
def profile():
token = session.get('oauth_token')
if token is None:
return redirect(url_for('login'))
response = requests.get('http://localhost:8000/protected/', headers={
'Authorization': f'Bearer {token}'
})
return jsonify(response.json())
if __name__ == '__main__':
app.run(debug=True, port=5000)
```
### 2.3. Flask 앱 실행
```bash
python app.py
```
## 3. 결과
<https://github.com/yehoon17/recipe_management_system/tree/oauth>
### 3.1. Flask 앱 접속
`http://127.0.0.1:5000/`

### 3.2. 로그인
1. Django 웹사이트의 로그인 페이지로 이동하게 됨

2. 로그인하면 권한 요청 페이지로 이동함

3. Flask 앱이 Access Token을 요청
4. Django 웹사이트에서 Access Token을 발급
5. Access Token을 사용하여 Django의 view 접근
|
#include <iostream>
#include <math.h>
class Fixed {
private:
int value;
static const int fpb = 8;
public:
Fixed();
Fixed(const int value);
Fixed(const float value);
Fixed(const Fixed &other);
~Fixed();
float toFloat() const;
int toInt() const;
void operator=(const Fixed &other);
bool operator>(const Fixed &other) const;
bool operator>=(const Fixed &other) const;
bool operator<(const Fixed &other) const;
bool operator<=(const Fixed &other) const;
bool operator==(const Fixed &other) const;
bool operator!=(const Fixed &other) const;
Fixed operator+(const Fixed &other);
Fixed operator-(const Fixed &other);
Fixed operator*(const Fixed &other);
Fixed operator/(const Fixed &other);
Fixed &operator++();
Fixed operator++(const int);
Fixed &operator--();
Fixed operator--(const int);
friend std::ostream& operator<<(std::ostream& os, const Fixed& value);
static const Fixed &min(const Fixed &a, const Fixed &b);
static const Fixed &max(const Fixed &a, const Fixed &b);
int getRawBits( void ) const;
void setRawBits( int const raw );
};
|
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './pages/home/home.component';
import { ErrorComponent } from './pages/error/error.component';
import { ProductsComponent } from './pages//products/products.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products/:asin', component: ProductsComponent },
{ path: 'not-found', component: ErrorComponent },
{ path: '**', component: ErrorComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
|
---
title: "Choosing the Perfect Business Partner"
description: "key factors to consider when selecting a business partner, from shared vision and complementary skills to trust and long-term compatibility, to ensure a successful and harmonious collaboration..."
pubDate: "Jul 02 2023"
heroImage: "/post_img.webp"
---
Selecting the right business partner is a critical decision that can significantly impact the success and growth of your venture. In this blog post, we will explore essential factors to consider when choosing a business partner to ensure a harmonious and productive collaboration.
**Shared Vision and Goals:**
Start by aligning your vision and goals with potential partners. Ensure that everyone involved has a clear understanding of the business's purpose, mission, and long-term objectives. A shared vision creates a strong foundation for a successful partnership.
**Complementary Skills and Expertise:**
Look for a partner whose skills and expertise complement your own. A well-rounded partnership brings diverse perspectives and abilities to the table, enhancing problem-solving capabilities and overall efficiency.
**Trust and Reliability:**
Trust is the cornerstone of any successful partnership. Evaluate the reliability and integrity of potential partners, seeking out individuals with a track record of honesty and commitment to their responsibilities.
**Communication and Compatibility:**
Open and effective communication is vital in any business relationship. Assess how well you and your potential partner communicate and whether you share compatible communication styles and preferences.
**Financial Alignment:**
Ensure that your potential partner shares the same financial values and expectations regarding investments, risk tolerance, and financial planning. Clarity on financial matters helps avoid conflicts down the road.
**Commitment and Dedication:**
Determine the level of commitment each partner is willing to bring to the business. Assess their dedication to the venture's success and their willingness to put in the effort and time required to achieve shared goals.
**Conflict Resolution Skills:**
Recognize that disagreements can arise in any partnership. Assess each partner's conflict resolution skills and their ability to handle disagreements constructively, with the best interest of the business in mind.
**Long-Term Compatibility:**
Consider the long-term implications of the partnership. Analyze whether your potential partner's personal and professional aspirations align with yours and whether you see a sustainable collaboration over the years.
**Financial and Legal Agreements:**
Draft a comprehensive partnership agreement that outlines the roles, responsibilities, and expectations of each partner. Include provisions for profit-sharing, decision-making, dispute resolution, and exit strategies.
**Shared Values and Culture:**
Evaluate the values and work culture of potential partners. A cohesive team with shared values and work ethics creates a positive and productive working environment.
|
<?php
// Actions
add_action( 'save_post', array( 'WPGeo_Distance_Cache', 'clear_cache' ) );
/**
* WP Geo Distance Cache
*
* A collection of functions for managing and caching distance results.
*/
class WPGeo_Distance_Cache {
/**
* Get Query Key
*
* @since 0.1
*
* @param array $query Query array to convert into a key string.
* @return string Key string.
*/
public static function get_query_key( $query ) {
return md5( serialize( $query ) );
}
/**
* Get Cache
*
* @since 0.1
*
* @param string $key Cache key.
* @return string Cached value.
*/
public static function get_cache( $key ) {
$wpgeo_distances = get_transient( 'wpgeo_distances' );
if ( isset( $wpgeo_distances[$key]) )
return $wpgeo_distances[$key];
return false;
}
/**
* Set Cache
*
* @since 0.1
*
* @param string $key Cache key.
* @param string $value Value.
*/
public static function set_cache( $key, $value ) {
$wpgeo_distances = get_transient( 'wpgeo_distances' );
$wpgeo_distances[$key] = $value;
set_transient( 'wpgeo_distances', $wpgeo_distances );
}
/**
* Clear Cache
*
* Deletes the transient that stores cached distance query results.
* $post_id is only passed when used by the 'save_post' action.
* Calling this function with no parameters will just clear the transient.
*
* @since 0.1
*
* @param int $post_id Optional. Post ID.
*/
public static function clear_cache( $post_id = 0 ) {
if ( wp_is_post_revision( $post_id ) )
return;
delete_transient( 'wpgeo_distances' );
}
}
|
<div class="topNav">
<mat-paginator [length]="rowLength" [pageSize]="pageSize" [pageSizeOptions]="pageSizeArray"
class="mat-paginator-container" (page)="onChangePage($event)"></mat-paginator>
<button type="button" class="firstBtn" mat-flat-button color="primary" (click)="add()">Add Bill</button>
</div>
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="sno">
<th mat-header-cell *matHeaderCellDef> S.No </th>
<td mat-cell *matCellDef="let bill; let i=index"> {{i+1}} </td>
</ng-container>
<ng-container matColumnDef="tblno">
<th mat-header-cell *matHeaderCellDef> Table No </th>
<td mat-cell *matCellDef="let bill"> {{bill.tableNo}} </td>
</ng-container>
<ng-container matColumnDef="amount">
<th mat-header-cell *matHeaderCellDef> Amount </th>
<td mat-cell *matCellDef="let bill"> {{bill.totalAmount}} </td>
</ng-container>
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef> Actions </th>
<tr>
<td mat-cell *matCellDef="let bill" class="btnGroup">
<button type="button" mat-button color="primary" (click)="edit(bill.id)">Edit</button> |
<button type="button" mat-button color="warn" (click)="delete(bill.id)">Delete</button>
</tr>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let bill; columns: displayedColumns;"></tr>
</table>
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
abstract class RemoteDataSource {
Future<bool> getAppStatus();
Future<void> registerToDataBase({
required String firstName,
required String lastName,
required String gender,
required int age,
required String email,
required String phoneNumber,
required String job,
required DateTime createdAt,
});
Future<void> registerToAuth({
required String email,
required String password,
});
// Future<bool> isUserInDataBase(String email);
Future<void> login({
required String email,
required String password,
});
}
class RemoteDataSourceImpl implements RemoteDataSource {
final FirebaseFirestore _firestore;
final FirebaseAuth _firebaseAuth;
RemoteDataSourceImpl(this._firestore, this._firebaseAuth);
@override
Future<bool> getAppStatus() async {
late bool appStatus;
await _firestore
.collection('GlobalVariables')
.doc('variables')
.get()
.then((value) {
appStatus = value.data()?['appStatus'];
});
return appStatus;
}
@override
Future<void> registerToDataBase({
required String firstName,
required String lastName,
required String gender,
required int age,
required String email,
required String phoneNumber,
required String job,
required DateTime createdAt,
}) async {
await _firestore.collection('users').doc(email).set({
'first_name': firstName,
'last_name': lastName,
'gender': gender,
'age': age,
'email': email,
'phone_number': phoneNumber,
'job': job,
'created_at': createdAt,
});
}
@override
Future<void> registerToAuth({
required String email,
required String password,
}) async {
await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
}
@override
Future<void> login({
required String email,
required String password,
}) async {
await _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: password,
);
}
}
|
import { Module } from '@nestjs/common';
import { AuthModule } from './auth/auth.module';
import { MoviesModule } from './movies/movies.module';
import { UsersModule } from './users/users.module';
import { ConfigModule } from '@nestjs/config';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { TagsModule } from './tags/tags.module';
import { RentModule } from './rent/rent.module';
import { OrderModule } from './order/order.module';
@Module({
imports: [
AuthModule,
MoviesModule,
UsersModule,
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRoot(),
TagsModule,
RentModule,
OrderModule,
],
})
export class AppModule {
constructor(private readonly connection: Connection) {}
}
|
<div class="container mt-4">
<div class="row mb-3">
<div class="col text-center">
<h2>Check the Status of Seats in Particular Buses</h2>
</div>
</div>
<form (ngSubmit)="onSubmit()">
<div class="row mb-3">
<div class="col">
<div class="form-group">
<label for="pathID">Select Bus Route</label>
<select
class="form-control"
id="pathID"
[(ngModel)]="selectedPathNameBasedID"
name="pathID"
[ngModelOptions]="{ standalone: true }"
(ngModelChange)="onPathChange()"
>
<option disabled selected>Select Bus Route</option>
<option *ngFor="let path of busPaths" [value]="path.pathID">
{{ path.pathName }}
</option>
</select>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="busID">Select Bus</label>
<select
class="form-control"
id="busID"
[(ngModel)]="selectedBus"
name="busID"
[ngModelOptions]="{ standalone: true }"
(ngModelChange)="onBusChange()"
>
<option disabled selected>Select Bus</option>
<option *ngFor="let bus of uniqueBuses" [value]="bus.busID">
{{ bus.licensePlate }} - [ {{ bus.model }} ({{ bus.type }}) ]
</option>
</select>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col">
<h4>Bus Timeings</h4>
<div class="form-check" *ngFor="let item of busTimings; let i = index">
<input
type="checkbox"
class="form-check-input"
[(ngModel)]="selectedCheckboxes[i]"
[name]="'checkbox' + (i + 1)"
[id]="'checkbox' + (i + 1)"
[value]="item.scheduleID"
(ngModelChange)="OnBusTimingsSelected(item.scheduleID)"
/>
<label [for]="'checkbox' + (i + 1)" class="form-check-label"
>{{ helperService.formatDateTime(item.departureTime) }} -
{{ helperService.formatDateTime(item.arrivalTime) }}</label
>
</div>
</div>
</div>
</form>
<div class="container">
<ul class="nav nav-pills">
<li class="nav-item" *ngFor="let item of scheduleIDs; let i = index">
<a
class="nav-link"
[class.active]="i == activeTabIndex"
(click)="setActiveTab(i)"
>{{ item.busTitle }}</a
>
</li>
</ul>
<div class="tab-content">
<ng-container *ngFor="let scheduleID of scheduleIDs; let i = index">
<div class="tab-pane" [class.show]="i === activeTabIndex" [id]="'tabPane' + i">
<div class="container">
<app-seat-layout
[busID]="selectedBus"
[scheduleID]="scheduleID.id"
[fareAmount]="fareAmount"
></app-seat-layout>
</div>
</div>
</ng-container>
</div>
</div>
</div>
|
import React from 'react';
import { shallow, configure, mount } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import { StyleSheetTestUtils } from 'aphrodite';
import App, { mapStateToProps } from './App';
import Notifications from './Notifications/Notifications';
import Header from './Header/Header';
import Footer from './Footer/Footer';
import Login from './Login/Login';
import CourseList from './CourseList/CourseList';
import AppContext from './App/AppContext';
import { fromJS } from 'immutable';
configure({ adapter: new Adapter() });
describe('App', () => {
beforeEach(() => {
StyleSheetTestUtils.suppressStyleInjection();
});
afterEach(() => {
StyleSheetTestUtils.clearBufferAndResumeStyleInjection();
});
test('App renders without crashing', () => {
const wrapper = shallow(<App />);
expect(wrapper.exists()).toBe(true);
});
test('contains Notifications, Header, Footer, Login', () => {
const wrapper = shallow(<App />);
expect(wrapper.find(Notifications).exists()).toBe(true);
expect(wrapper.find(Header).exists()).toBe(true);
expect(wrapper.find(Footer).exists()).toBe(true);
expect(wrapper.find(Login).exists()).toBe(true);
});
test('Login and logout update the UI accordingly', () => {
const wrapper = mount(
<AppContext.Provider value={{ user: { isLoggedIn: false }, logOut: jest.fn() }}>
<App />
</AppContext.Provider>
);
expect(wrapper.find(Login).exists()).toBe(true);
expect(wrapper.find(CourseList).exists()).toBe(false);
// Simulating login
wrapper.setContext({ user: { isLoggedIn: true, email: 'test@example.com' }, logOut: jest.fn() });
wrapper.update();
expect(wrapper.find(CourseList).exists()).toBe(true);
expect(wrapper.find(Login).exists()).toBe(false);
// Simulating logout
wrapper.setContext({ user: { isLoggedIn: false }, logOut: jest.fn() });
wrapper.update();
expect(wrapper.find(CourseList).exists()).toBe(false);
expect(wrapper.find(Login).exists()).toBe(true);
});
describe('mapStateToProps', () => {
it('should map the state correctly', () => {
const mockState = fromJS({
ui: {
isUserLoggedIn: true,
isNotificationDrawerVisible: true
}
});
const state = mapStateToProps(mockState);
expect(state.isLoggedIn).toBe(true);
expect(state.displayDrawer).toBe(true);
});
});
});
|
import React, { useState, useEffect } from 'react';
import dynamic from "next/dynamic";
import 'suneditor/dist/css/suneditor.min.css'; // Import Sun Editor's CSS File
const SunEditor = dynamic(() => import("suneditor-react"), {
ssr: false,
});
const defaultFonts = [
"Arial",
"Comic Sans MS",
"Courier New",
"Impact",
"Georgia",
"Tahoma",
"Trebuchet MS",
"Verdana"
];
const Editor = ({defaultValue = "", setEditorValue = (a:any, b:any)=>{} }) => {
const [value, setValue] = useState("");
useEffect( () => {
setValue(defaultValue);
}, []);
const setSunEditorValue = function (editorValue: any) {
setValue(editorValue);
if( typeof setEditorValue === "function" ) {
setEditorValue(editorValue, "content");
}
};
return (
<div>
<SunEditor
setContents={value}
onChange={setSunEditorValue}
setOptions={{
buttonList: [
["undo", "redo"],
["font", "fontSize"],
['paragraphStyle', 'blockquote'],
[
"bold",
"underline",
"italic",
"strike",
"subscript",
"superscript"
],
["fontColor", "hiliteColor"],
["align", "list", "lineHeight"],
["outdent", "indent"],
["table", "horizontalRule", "link", "image", "video"],
// ['math'], //You must add the 'katex' library at options to use the 'math' plugin.
// ['imageGallery'], // You must add the "imageGalleryUrl".
["fullScreen", "showBlocks", "codeView"],
// ["print"],
// ["preview", "print"],
["removeFormat"],
// ['save', 'template'],
// '/', Line break
], // Or Array of button list, eg. [['font', 'align'], ['image']]
defaultTag: "div",
// minHeight: "300px",
showPathLabel: false,
font: defaultFonts
}}
/>
</div>
);
};
export default Editor;
|
import { expect, it, describe, beforeEach } from 'vitest'
import { InMemoryUsersRepository } from '@/repositories/inMemory/inMemoryUsersRepository'
import { AuthenticateUseCase } from './authenticate'
import { hash } from 'bcryptjs'
import { InvalidCredentialsError } from './errors/invalidCredentialsError'
let usersRepository: InMemoryUsersRepository
let sut: AuthenticateUseCase
describe('Authenticate Use Case', () => {
beforeEach(() => {
usersRepository = new InMemoryUsersRepository()
sut = new AuthenticateUseCase(usersRepository)
})
it('Should be able to authenticate an user', async () => {
const password = '123456'
const email = 'johndoeauthenticate@example.com'
const passwordHash = await hash(password, 6)
await usersRepository.create({
name: 'John Doe',
email,
password_hash: passwordHash,
})
const { user } = await sut.execute({
email,
password,
})
expect(user.id).toEqual(expect.any(String))
})
it('Should not be able to authenticate with wrong email', async () => {
const password = '123456'
const email = 'johndoeauthenticate@example.com'
await expect(
async () =>
await sut.execute({
email,
password,
}),
).rejects.toBeInstanceOf(InvalidCredentialsError)
})
it('Should not be able to authenticate with wrong password', async () => {
const password = '123456'
const email = 'johndoeauthenticate@example.com'
const passwordHash = await hash(password, 6)
await usersRepository.create({
name: 'John Doe',
email,
password_hash: passwordHash,
})
await expect(
async () =>
await sut.execute({
email,
password: '654321',
}),
).rejects.toBeInstanceOf(InvalidCredentialsError)
})
})
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<h1> 内置组件 slot </h1>
<dousongting>
<!-- 利用slot 传递值 -->
<span slot="url">{{dstData.url}}</span>
<span slot="name">{{dstData.name}}</span>
</dousongting>
<hr>
</div>
<template id="tep">
<div>
<!-- 在模板中利用 slot 接收 -->
<p>网址:<slot name="url"></slot></p>
<p>名称:<slot name="name"></slot></p>
</div>
</template>
<script src="./vue.js"></script>
<script>
var dousongting = {
template:'#tep'
}
var vm = new Vue({
el:"#app",
data:{
dstData:{
url:'http://baidu.com',
name:'百度一下你就知道'
}
},
components:{
//起的名字 // 模板的名称
'dousongting':dousongting
}
})
</script>
</body>
</html>
|
import { nanoid } from 'nanoid';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import ContactForm from '../components/Form/Form';
import Filter from '../components/FilterContacts/Filter';
import CreatContactList from './ContactList/CreatContactList';
import { Section } from './App.styled';
import { useDispatch, useSelector } from 'react-redux';
import { getError, getIsLoading, getUserInf } from 'redux/contactSlice';
import { useEffect } from 'react';
import { addUser, fetchContacts } from 'redux/operations';
import Loader from './Loader';
export function App() {
const state = useSelector(getUserInf);
const dispatch = useDispatch();
const isLoading = useSelector(getIsLoading);
const error = useSelector(getError);
useEffect(() => {
dispatch(fetchContacts());
}, [dispatch]);
function hendleSubmit(values, { resetForm }) {
const contact = {
id: nanoid(),
...values,
};
const isAdded = checkContactIsAdded(contact);
if (isAdded) {
resetForm();
return toast(`${contact.name} is already in contacts`);
} else {
dispatch(addUser({ id: nanoid(), ...values }));
resetForm();
}
}
function checkContactIsAdded({ name }) {
const normalizedContactName = name.toLowerCase();
return state.find(
({ name }) => name.toLowerCase() === normalizedContactName
);
}
return (
<Section>
<ContactForm hendleSubmit={hendleSubmit} />
{isLoading && !error && (
<p
style={{
position: 'absolute',
top: '100px',
left: '50px',
}}
>
<Loader />
</p>
)}
<h2>Contacts</h2>
<h2>Find Contacts by name</h2>
<Filter />
<CreatContactList />
<ToastContainer />
</Section>
);
}
|
//
// Created by captain on 2021/4/5.
// 图片加载与解析
//
#ifndef UNTITLED_TEXTURE2D_H
#define UNTITLED_TEXTURE2D_H
#define STB_IMAGE_IMPLEMENTATION
#include <iostream>
#include <glad/gl.h>
class Texture2D
{
private:
Texture2D();
public:
~Texture2D();
/// 加载一个图片文件
/// \param image_file_path
/// \return
static Texture2D* LoadFromFile(std::string image_file_path);
/// 从ttf字体创建贴图
/// \param ttf_file_path
/// \param word
/// \return
static Texture2D* CreateFromTrueTypeFont(std::string ttf_file_path, const char* word);
public:
//cpt文件头
struct CptFileHead
{
char type_[3];
int mipmap_level_;
int width_;
int height_;
int gl_texture_format_;
int compress_size_;
};
int mipmap_level(){return mipmap_level_;}
int width(){return width_;}
int height(){return height_;}
GLenum gl_texture_format(){return gl_texture_format_;}
GLuint gl_texture_id(){return gl_texture_id_;}
private:
int mipmap_level_;
int width_;
int height_;
GLenum gl_texture_format_;
GLuint gl_texture_id_;//纹理ID
};
#endif //UNTITLED_TEXTURE2D_H
|
package com.levelgroup.bot;
import com.levelgroup.model.ChatMessage;
import com.levelgroup.services.ChatMessageService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.TelegramBotsApi;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import org.telegram.telegrambots.updatesreceivers.DefaultBotSession;
import java.util.ArrayList;
import java.util.List;
@Component
@PropertySource("classpath:telegram.properties")
public class ChatBot extends TelegramLongPollingBot {
@Value("${bot.name}")
private String botName;
@Value("${bot.token}")
private String botToken;
private final ChatMessageService chatMessageService;
public ChatBot(ChatMessageService chatMessageService) {
this.chatMessageService = chatMessageService;
}
@EventListener({ContextRefreshedEvent.class})
public void init() throws TelegramApiException {
TelegramBotsApi telegramBotsApi = new TelegramBotsApi(DefaultBotSession.class);
try {
telegramBotsApi.registerBot(this);
} catch (TelegramApiException e) {
System.out.println("Error occurred: " + e.getMessage());
}
}
@Override
public String getBotUsername() {
return botName;
}
@Override
public String getBotToken() {
return botToken;
}
@Override
public void onUpdateReceived(Update update) {
try {
if (update.hasMessage() && update.getMessage().hasText()) {
long chatId = update.getMessage().getChatId();
if (update.getMessage().isReply()) {
String receivedMessage = update.getMessage().getText();
Message repliedMessage = update.getMessage().getReplyToMessage();
String repliedText = repliedMessage.getText();
String userName = getUserName(repliedText);
long repliedChatId = repliedMessage.getChatId();
ChatMessage chatMessage = new ChatMessage();
chatMessage.setMessageText(receivedMessage);
chatMessage.setUserName(userName);
chatMessageService.add(chatMessage);
sendMessage(repliedChatId, "Message: " + receivedMessage + " sent to: " + userName);
} else {
sendMessage(chatId, "Reply to an individual user's message!");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessage(long chatId, String text) {
SendMessage message = new SendMessage();
message.setChatId(Long.toString(chatId));
message.setText(text);
try {
execute(message);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
private static String getUserName(String message) {
int colonIndex = message.indexOf(":");
if (colonIndex != -1) {
return message.substring(0, colonIndex).trim();
} else {
return message.trim();
}
}
}
|
<div class="main-page" ng-show="loading">
<img class="loader-gif main-page" src="/movie-ticketing/Assets/Images/load.gif" />
</div>
<div ng-hide="loading">
<div ng-controller="CreateAudiController" class="modal dataModal">
<form name="audiModal" novalidate>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" ng-if="addAudiButton">Create Auditorium</h4>
<h4 class="modal-title" ng-if="editAudiButton">Edit Auditorium</h4>
<h4 class="modal-title" ng-if="removeAudiButton">Do you want to delete Audi ?</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div ng-if="!removeAudiButton" class="modal-body">
<div class="form-group">
<label class="required" for="name">Name:</label>
<input type="name" class="form-control form-group" placeholder="Enter name" name="name"
ng-model="audiOject.name" autocomplete="off" required>
<div ng-if="audiModal.$submitted || audiModal.name.$touched" ng-messages="audiModal.name.$error">
<div ng-messages-include="movie-ticketing/commons/messages.html"></div>
</div>
</div>
<div class="form-group">
<label class="required" for="name">Seats:</label>
<input type="number" class="form-control form-group" placeholder="Enter seats" name="seats"
ng-model="audiOject.seats" autocomplete="off" required>
<div ng-if="audiModal.$submitted || audiModal.seats.$touched" ng-messages="audiModal.seats.$error">
<div ng-messages-include="movie-ticketing/commons/messages.html"></div>
</div>
</div>
<div class="form-group">
<label for="name">Opening Time:</label>
<input type="number" class="form-control form-group" placeholder="Enter opening time" name="openingTime"
max="24" ng-model="audiOject.opening_time" ng-value=9 autocomplete="off">
<div ng-if="audiModal.$submitted || audiModal.openingTime.$touched"
ng-messages="audiModal.openingTime.$error">
<div ng-messages-include="movie-ticketing/commons/messages.html"></div>
</div>
</div>
<div class="form-group">
<label for="name">Closing Time:</label>
<input type="number" class="form-control form-group" placeholder="Enter closing time" name="closingTime"
max="24" value="21" ng-model="audiOject.closing_time" autocomplete="off">
<div ng-if="audiModal.$submitted || audiModal.closingTime.$touched"
ng-messages="audiModal.closingTime.$error">
<div ng-messages-include="movie-ticketing/commons/messages.html"></div>
</div>
</div>
<p class="container width span-error">{{non_field_errors}}</p>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger" ng-click=closeModal() data-dismiss="modal">Close</button>
<button type="submit" ng-if="addAudiButton" class="btn btn-success" ng-click=createAudi()>Create</button>
<button type="submit" ng-if="editAudiButton" class="btn btn-primary" ng-click=editAudi()>Edit</button>
<button type="button" ng-if="removeAudiButton" class="btn btn-danger" data-dismiss="modal"
ng-click=removeAudi()>Delete</button>
</div>
</div>
</div>
</form>
</div>
</div>
|
import {gql, useMutation} from '@apollo/client'
import { useRouter } from 'next/router'
const 나의그래프큐엘셋팅 = gql`
mutation createBoard($writer: String, $title: String, $contents: String){ # 변수의 타입 적는 곳
createBoard(writer: $writer, title: $title, contents: $contents){ # 실제 우리가 전달할 변수 적는 곳
_id
number
message
}
}
`
export default function GraphqlMutationPage(){
const router = useRouter()
const [나의함수] = useMutation(나의그래프큐엘셋팅)
const onClickSubmit = async () => {
try {
// try에 있는 내용을 시도하다가 실패하면, 다음에 있는 모든 줄들을 모두 무시!!! 하고, catch에 있는 내용이 실행됨!
const result = await 나의함수({
variables: { // variables 이게 $ 역할을 함
writer: "훈이1231231213",
title: "안녕하세요!!123123123",
contents: "반갑습니다123123123"
}
})
console.log(result)
console.log(result.data.createBoard.number)
// router.push("/05-10-dynamic-routed-board-mutation/" + result.data.createBoard.number) // 더하기 표시가 많아지면 거슬림
router.push(`/05-10-dynamic-routed-board-mutation/${result.data.createBoard.number}`) // 더하기 생략하는 방식(=템플릿 리터럴)
} catch(error){
console.log(error.message)
alert(error.message)
}
}
return (
<button onClick={onClickSubmit}>GRAPHQL-API(동기) 요청하기</button>
)
}
|
#!/usr/bin/python
# Authors: Simo Sorce <ssorce@redhat.com>
#
# Copyright (C) 2008-2010 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import sys
try:
import os
from ipaserver.install import service, installutils
from ipapython import services as ipaservices
from ipaserver.install.dsinstance import config_dirname, realm_to_serverid
from ipaserver.install.installutils import is_ipa_configured, ScriptError
from ipapython.ipautil import wait_for_open_ports, wait_for_open_socket
from ipalib import api, errors
from ipapython import sysrestore
from ipapython import config
from ipapython.dn import DN
import ldap
import ldap.sasl
import ldapurl
import socket
except ImportError:
print >> sys.stderr, """\
There was a problem importing one of the required Python modules. The
error was:
%s
""" % sys.exc_value
sys.exit(1)
SASL_EXTERNAL = ldap.sasl.sasl({}, 'EXTERNAL')
class IpactlError(ScriptError):
pass
def check_IPA_configuration():
if not is_ipa_configured():
# LSB status code 6: program is not configured
raise IpactlError("IPA is not configured " +
"(see man pages of ipa-server-install for help)", 6)
def is_dirsrv_debugging_enabled():
"""
Check the IPA and PKI-CA 389-ds instances to see if debugging is
enabled. If so we suppress that in our output.
returns True or False
"""
debugging = False
serverid = realm_to_serverid(api.env.realm)
for dse in ['/etc/dirsrv/slapd-PKI-IPA/', config_dirname(serverid)]:
try:
fd = open(dse + 'dse.ldif', 'r')
except IOError:
continue
lines = fd.readlines()
fd.close()
for line in lines:
if line.lower().startswith('nsslapd-errorlog-level'):
(option, value) = line.split(':')
if int(value) > 0:
debugging = True
return debugging
def get_capture_output(service, debug):
"""
We want to display any output of a start/stop command with the
exception of 389-ds when debugging is enabled because it outputs
tons and tons of information.
"""
if service == 'dirsrv' and not debug and is_dirsrv_debugging_enabled():
print ' debugging enabled, suppressing output.'
return True
else:
return False
def parse_options():
usage = "%prog start|stop|restart|status\n"
parser = config.IPAOptionParser(usage=usage,
formatter=config.IPAFormatter())
parser.add_option("-d", "--debug", action="store_true", dest="debug",
help="Display debugging information")
options, args = parser.parse_args()
safe_options = parser.get_safe_opts(options)
return safe_options, options, args
def emit_err(err):
sys.stderr.write(err + '\n')
def get_config(dirsrv):
base = DN(('cn', api.env.host), ('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
srcfilter = '(ipaConfigString=enabledService)'
attrs = ['cn', 'ipaConfigString']
if not dirsrv.is_running():
raise IpactlError("Failed to get list of services to probe status:\n" +
"Directory Server is stopped", 3)
try:
# The start/restart functions already wait for the server to be
# started. What we are doing with this wait is really checking to see
# if the server is listening at all.
lurl = ldapurl.LDAPUrl(api.env.ldap_uri)
if lurl.urlscheme == 'ldapi':
wait_for_open_socket(lurl.hostport, timeout=api.env.startup_timeout)
else:
(host,port) = lurl.hostport.split(':')
wait_for_open_ports(host, [int(port)], timeout=api.env.startup_timeout)
con = ldap.initialize(api.env.ldap_uri)
con.sasl_interactive_bind_s('', SASL_EXTERNAL)
res = con.search_st(str(base),
ldap.SCOPE_SUBTREE,
filterstr=srcfilter,
attrlist=attrs,
timeout=10)
except ldap.SERVER_DOWN, e:
# LSB status code 3: program is not running
raise IpactlError("Failed to get list of services to probe status:\n" +
"Directory Server is stopped", 3)
except ldap.NO_SUCH_OBJECT:
masters_list = []
dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
attrs = ['cn']
try:
entries = con.search_s(str(dn), ldap.SCOPE_ONELEVEL, attrlist=attrs)
except Exception, e:
masters_list.append("No master found because of error: %s" % str(e))
else:
for dn,master_entry in entries:
masters_list.append(master_entry.get('cn', [None])[0])
masters = "\n".join(masters_list)
raise IpactlError("Failed to get list of services to probe status!\n"
"Configured hostname '%s' does not match any master server in LDAP:\n%s"
% (api.env.host, masters))
except Exception, e:
raise IpactlError("Unknown error when retrieving list of services from LDAP: " + str(e))
svc_list = []
for entry in res:
name = entry[1]['cn'][0]
for p in entry[1]['ipaConfigString']:
if p.startswith('startOrder '):
order = p.split()[1]
svc_list.append((order, name))
return svc_list
def ipa_start(options):
dirsrv = ipaservices.knownservices.dirsrv
try:
print "Starting Directory Service"
dirsrv.start(capture_output=get_capture_output('dirsrv', options.debug))
except Exception, e:
raise IpactlError("Failed to start Directory Service: " + str(e))
svc_list = []
try:
svc_list = get_config(dirsrv)
except Exception, e:
emit_err("Failed to read data from Directory Service: " + str(e))
emit_err("Shutting down")
try:
dirsrv.stop(capture_output=False)
except:
pass
if isinstance(e, IpactlError):
# do not display any other error message
raise IpactlError(rval=e.rval)
else:
raise IpactlError()
if len(svc_list) == 0:
# no service to stop
return
for (order, svc) in sorted(svc_list):
svc_name = service.SERVICE_LIST[svc][0]
svchandle = ipaservices.service(svc_name)
try:
print "Starting %s Service" % svc
svchandle.start(capture_output=get_capture_output(svc_name, options.debug))
except:
emit_err("Failed to start %s Service" % svc)
emit_err("Shutting down")
for (order, svc) in sorted(svc_list):
svc_name = service.SERVICE_LIST[svc][0]
svc_off = ipaservices.service(svc_name)
try:
svc_off.stop(capture_output=False)
except:
pass
try:
dirsrv.stop(capture_output=False)
except:
pass
raise IpactlError("Aborting ipactl")
def ipa_stop(options):
dirsrv = ipaservices.knownservices.dirsrv
svc_list = []
try:
svc_list = get_config(dirsrv)
except Exception, e:
# ok if dirsrv died this may fail, so let's try to quickly restart it
# and see if we can get anything. If not throw our hands up and just
# exit
try:
dirsrv.start(capture_output=False)
svc_list = get_config(dirsrv)
except Exception, e:
emit_err("Failed to read data from Directory Service: " + str(e))
emit_err("Shutting down")
try:
# just try to stop it, do not read a result
dirsrv.stop()
finally:
raise IpactlError()
if len(svc_list) == 0:
# no service to stop
return
for (order, svc) in sorted(svc_list, reverse=True):
svc_name = service.SERVICE_LIST[svc][0]
svchandle = ipaservices.service(svc_name)
try:
print "Stopping %s Service" % svc
svchandle.stop(capture_output=False)
except:
emit_err("Failed to stop %s Service" % svc)
try:
print "Stopping Directory Service"
dirsrv.stop(capture_output=False)
except:
raise IpactlError("Failed to stop Directory Service")
def ipa_restart(options):
dirsrv = ipaservices.knownservices.dirsrv
try:
print "Restarting Directory Service"
dirsrv.restart(capture_output=get_capture_output('dirsrv', options.debug))
except Exception, e:
raise IpactlError("Failed to restart Directory Service: " + str(e))
svc_list = []
try:
svc_list = get_config(dirsrv)
except Exception, e:
emit_err("Failed to read data from Directory Service: " + str(e))
emit_err("Shutting down")
try:
dirsrv.stop(capture_output=False)
except:
pass
if isinstance(e, IpactlError):
# do not display any other error message
raise IpactlError(rval=e.rval)
else:
raise IpactlError()
if len(svc_list) == 0:
# no service to stop
return
for (order, svc) in sorted(svc_list):
svc_name = service.SERVICE_LIST[svc][0]
svchandle = ipaservices.service(svc_name)
try:
print "Restarting %s Service" % svc
svchandle.restart(capture_output=get_capture_output(svc_name, options.debug))
except:
emit_err("Failed to restart %s Service" % svc)
emit_err("Shutting down")
for (order, svc) in sorted(svc_list):
svc_name = service.SERVICE_LIST[svc][0]
svc_off = ipaservices.service(svc_name)
try:
svc_off.stop(capture_output=False)
except:
pass
try:
dirsrv.stop(capture_output=False)
except:
pass
raise IpactlError("Aborting ipactl")
def ipa_status(options):
dirsrv = ipaservices.knownservices.dirsrv
try:
if dirsrv.is_running():
print "Directory Service: RUNNING"
else:
print "Directory Service: STOPPED"
except:
raise IpactlError("Failed to get Directory Service status")
svc_list = []
try:
svc_list = get_config(dirsrv)
except IpactlError, e:
raise e
except Exception, e:
raise IpactlError("Failed to get list of services to probe status: " + str(e))
if len(svc_list) == 0:
return
for (order, svc) in sorted(svc_list):
svc_name = service.SERVICE_LIST[svc][0]
svchandle = ipaservices.service(svc_name)
try:
if svchandle.is_running():
print "%s Service: RUNNING" % svc
else:
print "%s Service: STOPPED" % svc
except:
emit_err("Failed to get %s Service status" % svc)
def main():
if not os.getegid() == 0:
# LSB status code 4: user had insufficient privilege
raise IpactlError("You must be root to run ipactl.", 4)
safe_options, options, args = parse_options()
if len(args) != 1:
# LSB status code 2: invalid or excess argument(s)
raise IpactlError("You must specify one action", 2)
elif args[0] != "start" and args[0] != "stop" and args[0] != "restart" and args[0] != "status":
raise IpactlError("Unrecognized action [" + args[0] + "]", 2)
if (args[0] in ('start', 'restart') and
os.path.exists('/proc/sys/crypto/fips_enabled')):
with open('/proc/sys/crypto/fips_enabled', 'r') as f:
if f.read().strip() != '0':
raise IpactlError("Cannot start IPA server in FIPS mode")
# check if IPA is configured at all
try:
check_IPA_configuration()
except IpactlError, e:
if args[0].lower() == "status":
# Different LSB return code for status command:
# 4 - program or service status is unknown
# This should differentiate uninstalled IPA from status
# code 3 - program is not running
e.rval = 4
raise e
else:
raise e
api.bootstrap(context='cli', debug=options.debug)
api.finalize()
if '.' not in api.env.host:
raise IpactlError("Invalid hostname '%s' in IPA configuration!\n"
"The hostname must be fully-qualified" % api.env.host)
if args[0].lower() == "start":
ipa_start(options)
elif args[0].lower() == "stop":
ipa_stop(options)
elif args[0].lower() == "restart":
ipa_restart(options)
elif args[0].lower() == "status":
ipa_status(options)
if __name__ == '__main__':
installutils.run_script(main, operation_name='ipactl')
|
// Import necessary testing utilities from NestJS
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
// Set up the testing module before each test
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController], // Provide AppController for testing
providers: [AppService], // Provide AppService for testing
}).compile();
appController = app.get<AppController>(AppController); // Retrieve the instance of AppController
});
// Test suite for the root route
describe('root', () => {
// Test to check if the getHello method returns "Hello World!"
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!'); // Assert the expected result
});
});
});
|
<template>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<InfoCard header="Connection:">
<template #icon>
<WifiIcon />
</template>
<template #content>
<InfoCardRow property="Last Seen:">
<template #value>
<DeviceLastSeenBadge :last-seen-at="lastSeenAt" :last-seen-ms="lastSeenMs" :last-seen-since="lastSeenSince" />
</template>
</InfoCardRow>
<InfoCardRow property="Status:">
<template #value>
<StatusBadge :status="device.status" />
</template>
</InfoCardRow>
<InfoCardRow property="Agent Version:" :value="device.agentVersion || 'unknown'" />
</template>
</InfoCard>
<InfoCard header="Deployment:">
<template #icon>
<TemplateIcon />
</template>
<template #content>
<InfoCardRow property="Application:">
<template #value>
<router-link v-if="device?.application" :to="{name: 'Application', params: { id: device.application.id }}">
{{ device.application?.name }}
</router-link>
<span v-else>None</span>
</template>
</InfoCardRow>
<InfoCardRow v-if="device.ownerType!=='application'" property="Instance:">
<template #value>
<router-link v-if="device?.instance" :to="{name: 'Instance', params: { id: device.instance.id }}">
{{ device.instance?.name }}
</router-link>
<span v-else>None</span>
</template>
</InfoCardRow>
<InfoCardRow property="Active Snapshot:">
<template #value>
<span class="flex gap-2 pr-2">
<span class="flex items-center space-x-2 text-gray-500 italic">
<ExclamationIcon class="text-yellow-600 w-4" v-if="!device.activeSnapshot || !targetSnapshotDeployed" />
<CheckCircleIcon class="text-green-700 w-4" v-else />
</span>
<template v-if="device.activeSnapshot">
<div class="flex flex-col">
<span>{{ device.activeSnapshot.name }}</span>
<span class="text-xs text-gray-500">{{ device.activeSnapshot.id }}</span>
</div>
</template>
<template v-else>
No Snapshot Deployed
</template>
</span>
</template>
</InfoCardRow>
<InfoCardRow property="Target Snapshot:">
<template #value>
<span class="flex gap-2 pr-2">
<span class="flex items-center space-x-2 text-gray-500 italic">
<ExclamationIcon class="text-yellow-600 w-4" v-if="!device.targetSnapshot" />
<CheckCircleIcon class="text-green-700 w-4" v-else />
</span>
<template v-if="device.targetSnapshot">
<div class="flex flex-col">
<span>{{ device.targetSnapshot.name }}</span>
<span class="text-xs text-gray-500">{{ device.targetSnapshot.id }}</span>
</div>
</template>
<template v-else>
No Target Snapshot Set
</template>
</span>
</template>
</InfoCardRow>
<InfoCardRow property="Device Mode">
<template #value>
<span v-if="device.mode === 'developer'" class="flex space-x-2 pr-2 items-center">
<BeakerIcon class="text-purple-600 w-4" />
<span> Developer Mode</span>
</span>
<span v-else>
<span> Default</span>
</span>
</template>
</InfoCardRow>
</template>
</InfoCard>
</div>
</template>
<script>
// utilities
import { BeakerIcon, CheckCircleIcon, ExclamationIcon, TemplateIcon, WifiIcon } from '@heroicons/vue/outline'
// api
import { mapState } from 'vuex'
// components
import InfoCard from '../../components/InfoCard.vue'
import InfoCardRow from '../../components/InfoCardRow.vue'
import StatusBadge from '../../components/StatusBadge.vue'
import DeviceLastSeenBadge from './components/DeviceLastSeenBadge.vue'
export default {
name: 'DeviceOverview',
emits: ['device-updated', 'device-refresh'],
props: ['device'],
components: {
BeakerIcon,
CheckCircleIcon,
ExclamationIcon,
WifiIcon,
InfoCard,
InfoCardRow,
TemplateIcon,
DeviceLastSeenBadge,
StatusBadge
},
computed: {
...mapState('account', ['settings', 'features']),
targetSnapshotDeployed: function () {
return this.device.activeSnapshot?.id === this.device.targetSnapshot?.id
},
lastSeenAt: function () {
return this.device?.lastSeenAt || ''
},
lastSeenMs: function () {
return this.device?.lastSeenMs || 0
},
lastSeenSince: function () {
return this.device?.lastSeenSince || ''
},
deviceOwnerType: function () {
return this.device?.ownerType || ''
}
},
mounted () {
this.refreshDevice()
},
methods: {
// pollTimer method is called by VueTimersMixin. See the timers property above.
pollTimer: async function () {
this.refreshDevice()
},
refreshDevice: function () {
this.$emit('device-refresh') // cause parent to refresh device
}
}
}
</script>
|
"use client";
import { NextPage } from "next";
import React, { useEffect, useRef, useState } from "react";
import { CreateModalProps } from "../../types/components";
import Overlay from "../Overlay";
import Input from "../Input";
import { toast } from "sonner";
import { addDoc, collection, doc, serverTimestamp } from "firebase/firestore";
import { auth, db } from "@/app/firebase";
import { useAuthState } from "react-firebase-hooks/auth";
import { useAppContext } from "@/app/context/AppContext";
import useModalAnimation from "./useModalAnimation";
export interface formData {
title: string;
}
const CreateNoteModal: NextPage<CreateModalProps> = ({
show,
setShow,
content,
buttonContent,
addNewNote,
}) => {
const modalRef = useRef<HTMLDivElement>(null);
const [inputData, setInputData] = useState<formData>({ title: "" });
const [user] = useAuthState(auth);
const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.preventDefault();
setInputData({ title: event.target.value });
};
useModalAnimation(modalRef);
const formValidation = () => {
const words = inputData.title.trim().split(/\s+/);
if (inputData.title.trim() === "") {
toast.error("Please enter a title.");
return false;
}
if (words.length > 3) {
toast.error("Please enter less than three words!");
return false;
}
return true;
};
const handleCreateNoteey = async () => {
if (!formValidation() || !user) {
return;
}
if (user) {
const userDocRef = doc(db, "user", user?.uid); // Reference to the user document
const noteCollectionRef = collection(userDocRef, "note"); // Reference to the "note" subcollection
try {
const newNoteData = {
title: inputData.title,
timestamp: serverTimestamp(),
};
const newNoteDocRef = await addDoc(noteCollectionRef, newNoteData);
const newNote = { id: newNoteDocRef.id, ...newNoteData };
addNewNote(newNote);
setShow(false);
} catch (error) {
toast.error("Error adding note to user document");
}
}
};
const cancelModal = () => {
setShow(false);
};
const { color } = useAppContext();
const background = color || "#e85444";
const backgroundStyle = { backgroundColor: background };
return (
<Overlay show={show} setShow={setShow} modalRef={modalRef}>
{show && (
<div
ref={modalRef}
id="createModal"
className="m-10 max-w-[405px] p-6 flex h-fit w-full flex-col items-center rounded-[10px] bg-white dark:bg-[#232323] gap-3"
>
<p className="text-center text-lg text-text dark:text-[#FFFFFF]">
{content}
</p>
<form action="" className="w-full">
<Input
name="createNote"
id="createNote"
value={inputData.title}
autoComplete="off"
required
onChange={handleInputChange}
type="text"
additionalClasses="border w-full outline-none focus-none bg-transparent dark:border-[#3D3D3D] border-[#C2C2C2] dark:text-[#FFFFFF] p-2 rounded text-black text-sm dark:placeholder-[#777777]"
placeholder="Enter note title"
/>
</form>
{buttonContent && (
<div className="flex w-full py-2 gap-4">
<button
className="w-full py-2 rounded-lg transition-all duration-300 hover:bg-[#eee] dark:hover:bg-[#1d1d1d] hover:text-black border dark:border-[#3D3D3D] border-[#C2C2C2] dark:text-[#CCCCCC]"
onClick={cancelModal}
>
Cancel
</button>
<button
className="w-full rounded-lg hover:opacity-90 transition-all duration-300 px-4 py-2 text-sm text-text"
style={backgroundStyle}
onClick={handleCreateNoteey}
>
{buttonContent}
</button>
</div>
)}
</div>
)}
</Overlay>
);
};
export default CreateNoteModal;
|
package com.dereferencemypointer.itemgenmod;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.entity.EquipmentSlot;
import net.minecraft.world.item.ArmorMaterial;
import net.minecraft.world.item.crafting.Ingredient;
import java.util.function.Supplier;
public class ArmorMaterialBase implements ArmorMaterial {
private final int enchantability;
private final int[] durability, damageReduction;
private final float knockbackResistance, toughness;
private final String name;
private final SoundEvent equipSound;
private final Supplier<Ingredient> repairMaterial;
public ArmorMaterialBase(int enchantability, int[] durability, int[] damageReduction, float knockbackResistance, float toughness, String name, SoundEvent equipSound, Supplier<Ingredient> repairMaterial) {
this.enchantability = enchantability;
this.durability = durability;
this.damageReduction = damageReduction;
this.knockbackResistance = knockbackResistance;
this.toughness = toughness;
this.name = name;
this.equipSound = equipSound;
this.repairMaterial = repairMaterial;
}
@Override
public int getDurabilityForSlot(EquipmentSlot pSlot) {
return durability[pSlot.getIndex()];
}
@Override
public int getDefenseForSlot(EquipmentSlot pSlot) {
return damageReduction[pSlot.getIndex()];
}
@Override
public int getEnchantmentValue() {
return enchantability;
}
@Override
public SoundEvent getEquipSound() {
return equipSound;
}
@Override
public Ingredient getRepairIngredient() {
return repairMaterial.get();
}
@Override
public String getName() {
return name;
}
@Override
public float getToughness() {
return toughness;
}
@Override
public float getKnockbackResistance() {
return knockbackResistance;
}
}
|
package TCP_recup;
import java.io.*;
import java.net.*;
import java.util.*;
public class Usuario {
private String nombre;
private String direccionIP;
private Socket socket;
private ObjectOutputStream outputStream;
private ObjectInputStream inputStream;
private static List<Usuario> Usuarios = new ArrayList<>();
private static List<Usuario> vecinos = new ArrayList<>();
private static List<Usuario> conectados = new ArrayList<>();
public Usuario(String nombre, String direccionIP) {
this.nombre = nombre;
this.direccionIP = direccionIP;
}
public String getNombre() {
return nombre;
}
public String getDireccionIP() {
return direccionIP;
}
public void conectar(Mensaje M) {
try {
socket = new Socket(encontrarVecinoMasCercano(M.getDestinatario()).direccionIP, 12345);
outputStream = new ObjectOutputStream(socket.getOutputStream());
System.out.println(nombre + " se ha conectado.");
} catch (ConnectException e) {
System.out.println("Error al conectar: La conexión fue rechazada. Asegúrate de que el destinatario esté ejecutando el programa y escuchando en el puerto correcto.");
} catch (IOException e) {
System.out.println("Error al conectar: " + e.getMessage());
}
}
public void desconectar() {
try {
if (socket != null && !socket.isClosed()) {
socket.close();
System.out.println(nombre + " se ha desconectado.");
}
} catch (IOException e) {
}
}
public void enviarMensaje(Mensaje mensaje) {
if (!nombre.equals(mensaje.getDestinatario())) {
try {
conectar(mensaje);
if (socket != null && socket.isConnected()) {
outputStream.writeObject(mensaje);
System.out.println(nombre + " ha enviado un mensaje a " + mensaje.getDestinatario() + ": " + mensaje.getTexto());
desconectar(); // Desconectar después de enviar el mensaje
} else {
System.out.println("No se pudo establecer la conexión. El socket no está disponible o no está conectado.");
}
} catch (IOException e) {
System.out.println("Error al enviar el mensaje: " + e.getMessage());
}
} else {
System.out.println("No es necesario conectarse para enviar un mensaje a uno mismo.");
}
}
private Usuario encontrarVecinoMasCercano(String destino) {
Usuario vecinoMasCercano = null;
int distanciaMasCercana = Integer.MAX_VALUE;
Usuario temp = null;
for (Usuario i: Usuarios) {
if (i.nombre.equals(destino)){
temp = i;
}
}
for (Usuario vecino : vecinos) {
if (!vecino.getNombre().equals(nombre)) {
int distancia = Math.abs(Usuarios.indexOf(vecino) - Usuarios.indexOf(temp));
if (distancia < distanciaMasCercana) {
distanciaMasCercana = distancia;
vecinoMasCercano = vecino;
}
}
}
return vecinoMasCercano;
}
public void recibirMensaje(Mensaje mensaje) {
if (nombre.equals(mensaje.getDestinatario())) {
System.out.println("Mensaje recibido: " + mensaje.getTexto());
} else {
Usuario vecinoMasCercano = encontrarVecinoMasCercano(mensaje.getDestinatario());
if (vecinoMasCercano != null) {
System.out.println(nombre + " reenviando mensaje a " + vecinoMasCercano.getNombre());
this.enviarMensaje(mensaje);
} else {
System.out.println("No se encontró un vecino para reenviar el mensaje.");
}
}
}
private static String obtenerIPInterfaz() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface current = interfaces.nextElement();
if (current.getName().equals("eno2") && current.isUp() && !current.isLoopback() && !current.isVirtual()) {
Enumeration<InetAddress> addresses = current.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress currentAddr = addresses.nextElement();
if (currentAddr instanceof Inet4Address) {
return currentAddr.getHostAddress();
}
}
}
}
return null;
} catch (Exception e) {
return null;
}
}
private static List<Usuario> leerUsuariosDesdeArchivo(String rutaArchivo) {
List<Usuario> vecinos = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(rutaArchivo))) {
String linea;
while ((linea = br.readLine()) != null) {
String[] partes = linea.split(":");
if (partes.length == 2) {
String nombre = partes[0].trim().replace("\"", "");
String direccionIP = partes[1].trim().replace("\"", "");
vecinos.add(new Usuario(nombre, direccionIP));
}
}
} catch (IOException e) {
}
return vecinos;
}
public static void main(String[] args) {
String ipPublica = obtenerIPInterfaz();
if (ipPublica != null) {
System.out.println("La dirección IP de la interfaz es: " + ipPublica);
} else {
System.out.println("No se pudo obtener la dirección IP de la interfaz.");
return;
}
Usuarios = leerUsuariosDesdeArchivo("/home/dimeglio/Escritorio/Socketes/SocketsTCP/src/Extra_Dimeglio/topologia"); // Ruta real del archivo de usuarios
int posicion = -1;
for (int i = 0; i < Usuarios.size(); i++) {
if (Usuarios.get(i).getDireccionIP().equals(ipPublica)) {
posicion = i + 1;
break;
}
}
if (posicion != -1) {
System.out.println("Hola, soy " + Usuarios.get(posicion - 1).getNombre() +
" y estoy en la posición " + posicion + " en la topografía.");
} else {
System.out.println("No se encontró la posición en la topografía.");
return;
}
// Después de que se conectan al menos dos usuarios, se muestra la topografía
for (int i = 0; i< Usuarios.size(); i++)
if(i+1 != Usuarios.size() && Usuarios.get(i+1).direccionIP.equals(ipPublica) || i != 0 && Usuarios.get(i-1).direccionIP.equals(ipPublica)){
vecinos.add(Usuarios.get(i));
}
System.out.println("Topografía de la red:");
for (Usuario usuario : Usuarios) {
System.out.println(usuario.getNombre() + " - " + usuario.getDireccionIP());
}
System.out.println("vecinos: ");
for (Usuario usuario : vecinos) {
System.out.println(usuario.getNombre() + " - " + usuario.getDireccionIP());
}
// Inicia un thread para la escucha continua del servidor
new Thread(() -> {
try {
ServerSocket serverSocket = new ServerSocket(12346);
System.out.println("Esperando a que se conecten otros usuarios...");
while (true) {
Socket clienteSocket = serverSocket.accept();
System.out.println("¡Usuario conectado!");
ObjectInputStream inputStream = new ObjectInputStream(clienteSocket.getInputStream());
// Manejar la comunicación con el usuario conectado en otro thread
new Thread(() -> {
try {
while (true) {
Mensaje mensajeRecibido = (Mensaje) inputStream.readObject();
for (Usuario i: Usuarios
) {
if (i.direccionIP.equals(ipPublica)){
i.recibirMensaje(mensajeRecibido);
}
}
}
} catch (IOException | ClassNotFoundException e) {
}
}).start();
}
} catch (IOException e) {
}
}).start();
// El usuario principal puede enviar mensajes a otros usuarios
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Escribe el mensaje (destinatario-mensaje):");
String entrada = scanner.nextLine();
String[] partes = entrada.split("-");
if (partes.length == 2) {
String destinatario = partes[0].trim();
String textoMensaje = partes[1].trim();
Mensaje mensaje = new Mensaje(textoMensaje, destinatario);
for (Usuario i: Usuarios
) {
if (Objects.equals(i.direccionIP, ipPublica)) {
i.enviarMensaje(mensaje);
}
}
} else {
System.out.println("Formato incorrecto. Debe ser 'destinatario-mensaje'.");
}
}
}
}
class Mensaje implements Serializable {
private String texto;
private String destinatario;
public Mensaje(String texto, String destinatario) {
this.texto = texto;
this.destinatario = destinatario;
}
public String getTexto() {
return texto;
}
public String getDestinatario() {
return destinatario;
}
}
|
import Perks from "../Perks";
import PhotosUploader from "../PhotosUploader";
import { useState, Fragment, useEffect } from "react";
import axios from "axios";
import AccountNav from "../AccountNav";
import { Navigate, useParams } from "react-router-dom";
const PlacesFormPage = () => {
const { id } = useParams();
const [title, setTitle] = useState("");
const [address, setAddress] = useState("");
const [addedPhotos, setAddedPhotos] = useState([]);
const [description, setDescription] = useState("");
const [perks, setPerks] = useState([]);
const [extraInfo, setExtraInfo] = useState("");
const [checkIn, setCheckIn] = useState("");
const [checkOut, setCheckOut] = useState("");
const [maxGuests, setMaxGuests] = useState("");
const [price, setPrice] = useState(100);
const [redirect, setRedirect] = useState(false);
console.log(price);
useEffect(() => {
if (!id) return;
axios.get("/places/" + id).then(({ data }) => {
setTitle(data.title);
setAddress(data.address);
setAddedPhotos(data.photos);
setDescription(data.description);
setPerks(data.perks);
setExtraInfo(data.extraInfo);
setCheckIn(data.checkIn);
setCheckOut(data.checkOut);
setMaxGuests(data.maxGuests);
setPrice(data.price);
});
}, [id]);
const inputHeader = (text) => {
return <h2 className="text-2xl mt-4">{text}</h2>;
};
const inputDescription = (text) => {
return <p className="text-gray-500 text-sm">{text}</p>;
};
const preInput = (header, description) => {
return (
<Fragment>
{inputHeader(header)}
{inputDescription(description)}
</Fragment>
);
};
const savePlace = async (ev) => {
ev.preventDefault();
const placeData = {
title,
address,
description,
addedPhotos,
perks,
extraInfo,
price,
checkIn,
checkOut,
maxGuests,
};
if (id) {
await axios.put("/places/", { id, ...placeData });
} else {
await axios.post("/places", placeData);
}
setRedirect(true);
};
if (redirect) return <Navigate to="/account/places" />;
return (
<div>
<AccountNav />
<form onSubmit={savePlace}>
{preInput(
"Title",
"title for your place, should be short and catchy as advertisement"
)}
<input
type="text"
onChange={(ev) => setTitle(ev.target.value)}
value={title}
placeholder="title, for example: My lovely appartment"
/>
{preInput("Address", "Address to this place")}
<input
type="text"
value={address}
onChange={(ev) => setAddress(ev.target.value)}
placeholder="address"
/>
{preInput("Photos", "more = better")}
<PhotosUploader
setAddedPhotos={setAddedPhotos}
addedPhotos={addedPhotos}
/>
{preInput("Description", "description of the place")}
<textarea
value={description}
onChange={(ev) => setDescription(ev.target.value)}
/>
{preInput("Perks", "select all the perks of your place")}
<div className="grid grid-cols-2 gap-2 mt-2 md:grid-cols-3 lg:grid-cols-6">
<Perks selected={perks} onChange={setPerks} />
</div>
{preInput("Extra info", "house rules, etc")}
<textarea
value={extraInfo}
onChange={(ev) => setExtraInfo(ev.target.value)}
/>
{preInput(
"Check in & out times, max guests",
"add check in and out times, remember to have some time window for clening the room between guests"
)}
<div className="grid gap-2 grid-cols-2 md:grid-cols-4">
<div>
<h3 className="mt-2 -mb-1">Check in time</h3>
<input
type="text"
value={checkIn}
onChange={(ev) => setCheckIn(ev.target.value)}
placeholder="14"
/>
</div>
<div>
<h3 className="mt-2 -mb-1">Check out time</h3>
<input
type="text"
placeholder="11"
value={checkOut}
onChange={(ev) => setCheckOut(ev.target.value)}
/>
</div>
<div>
<h3 className="mt-2 -mb-1">Max number of guests</h3>
<input
type="number"
value={maxGuests}
onChange={(ev) => setMaxGuests(ev.target.value)}
/>
</div>
<div>
<h3 className="mt-2 -mb-1">Price per night</h3>
<input
type="number"
value={price}
onChange={(ev) => setPrice(ev.target.value)}
/>
</div>
</div>
<button className="primary my-4">Save</button>
</form>
</div>
);
};
export default PlacesFormPage;
|
import { Action } from '@ngrx/store';
import { chapter, article } from '../model';
/**
* For each action type in an action group, make a simple
* enum object for all of this group's action types.
*/
export enum ActionTypes {
chapters = 'get/chapters',
articles = 'get/articles',
};
/**
* Every action is comprised of at least a type and an optional
* payload. Expressing actions as classes enables powerful
* type checking in reducer functions.
*/
export class chapters implements Action {
readonly type = ActionTypes.chapters;
constructor(public payload: chapter[]) { }
}
export class articles implements Action {
readonly type = ActionTypes.articles;
constructor(public payload: article) { }
}
/**
* Export a type alias of all actions in this action group
* so that reducers can easily compose action types
*/
export type Actions = chapters | articles;
|
import Container from 'react-bootstrap/Container'
import Spinner from 'react-bootstrap/Spinner';
import Alert from 'react-bootstrap/Alert';
import Button from 'react-bootstrap/Button';
import React, { useState } from 'react';
import Row from 'react-bootstrap/Row'
import { NavLink, useHistory } from 'react-router-dom';
// import useAuth from './../../../hooks/useAuth';
import useAuth from '../../../hooks/useAuth';
import { Form } from 'react-bootstrap';
import Header from '../../Shared/Navigation/Header';
import Footer from '../../Shared/Footer/Footer';
const Register = () => {
const [loginData, setLoginData] = useState({});
const history = useHistory();
const { user, registerUser, isLoading, authError } = useAuth();
const handleOnBlur = e => {
const field = e.target.name;
const value = e.target.value;
const newLoginData = { ...loginData };
newLoginData[field] = value;
setLoginData(newLoginData);
}
const handleLoginSubmit = e => {
if (loginData.password !== loginData.password2) {
alert('Your password did not match');
return
}
registerUser(loginData.email, loginData.password, loginData.name, history);
e.preventDefault();
}
return (
<>
<Header></Header>
<Container className="py-5 w-50">
<Row>
<h1>Please Register</h1>
{!isLoading && <Form onSubmit={handleLoginSubmit}>
<Form.Group
className="mb-3" controlId="formBasicEmail">
<Form.Label>Enter Your Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter Name"
name="name"
onBlur={handleOnBlur}
/>
</Form.Group>
<Form.Group
className="mb-3" controlId="formBasicEmail">
<Form.Label>Enter Your Email</Form.Label>
<Form.Control
placeholder="Enter email"
name="email"
type="email"
onBlur={handleOnBlur}
/>
</Form.Group>
<Form.Group
className="mb-3" controlId="formBasicEmail">
<Form.Label>Enter Your Password</Form.Label>
<Form.Control
placeholder="Enter password"
type="password"
name="password"
onBlur={handleOnBlur}
/>
</Form.Group>
<Form.Group
className="mb-3" controlId="formBasicEmail">
<Form.Label>Retype Password</Form.Label>
<Form.Control
placeholder="Retype Password"
type="password"
name="password2"
onBlur={handleOnBlur}
/>
</Form.Group>
<Button type="submit" variant="success">Register</Button>
<p><NavLink
style={{ textDecoration: 'none' }}
to="/login">
<Button variant="text" className='text-primary fw-bold'>Already Registered? Please Login</Button>
</NavLink></p>
</Form>}
{isLoading && <Spinner animation="border" />}
{user?.email && <Alert variant="success">User Created successfully!</Alert>}
{authError && <Alert variant="danger">{authError}</Alert>}
</Row>
</Container>
<Footer></Footer>
</>
);
};
export default Register;
|
//
// OnBoardingScreen.swift
// IntelectualPath
//
// Created by Альпеша on 03.01.2024.
//
import SwiftUI
struct OnBoardingScreen: View {
@State var onBoardingItems: [OnBoardingItem] = [
.init(title: "Study",
subtitle: "Learn any programming languages and confirm the completed material with a quiz.",
lottieView: .init(name: "Study", bundle: .main)),
.init(title: "Share",
subtitle: "Share your knowledge with others. Get feedback from other users.",
lottieView: .init(name: "Share", bundle: .main)),
.init(title: "Create",
subtitle: "Create discussions and solve the problem together with other users.",
lottieView: .init(name: "Create", bundle: .main))
]
@State var currentIndex: Int = 0
@State private var isMainViewActive = false
var body: some View {
GeometryReader{
let size = $0.size
HStack(spacing: 0) {
ForEach($onBoardingItems){ $item in
let isLastSlide = (currentIndex == onBoardingItems.count - 1)
VStack{
HStack{
Button("Back") {
if currentIndex > 0 {
currentIndex -= 1
playAnimation()
}
}
.opacity(currentIndex > 0 ? 1 : 0)
Spacer(minLength: 0)
Button("Skip") {
currentIndex = onBoardingItems.count - 1
playAnimation()
}
.opacity(isLastSlide ? 0 : 1)
}
.tint(.blue)
.fontWeight(.bold)
VStack(spacing: 15){
let offset = -CGFloat(currentIndex) * size.width
ResizableLottie(onboardingItem: $item)
.frame(height: size.width)
.onAppear {
if currentIndex == indexOf(item) {
item.lottieView.play()
}
}
.offset(x: offset)
.animation(.easeInOut(duration: 0.5), value: currentIndex)
Text(item.title)
.font(.title.bold())
.foregroundColor(.black)
.offset(x: offset)
.animation(.easeInOut(duration: 0.5).delay(0.1), value: currentIndex)
Text(item.subtitle)
.font(.system(size: 14))
.multilineTextAlignment(.center)
.padding(.horizontal, 15)
.foregroundColor(.gray)
.offset(x: offset)
.animation(.easeInOut(duration: 0.5).delay(0.2), value: currentIndex)
}
Spacer(minLength: 0)
VStack(spacing: 15){
Text(isLastSlide ? "Start" : "Next")
.fontWeight(.bold)
.foregroundColor(.white)
.padding(.vertical, isLastSlide ? 13 : 12)
.frame(maxWidth: .infinity)
.background(
Capsule()
.fill(.blue)
)
.padding(.horizontal, isLastSlide ? 30 : 100)
.onTapGesture {
if isLastSlide {
isMainViewActive = true
} else {
let currentProgress = onBoardingItems[currentIndex].lottieView.currentProgress
if currentIndex < onBoardingItems.count - 1 {
onBoardingItems[currentIndex].lottieView.currentProgress = (currentProgress == 0 ? 0.7 : currentProgress)
currentIndex += 1
playAnimation()
}
}
}
HStack {
Text("Terms of Service")
Text("Privacy Policy")
}
.font(.caption2)
.underline(true, color: .primary)
.offset(y: 5)
}
}
.animation(.easeInOut, value: isLastSlide)
.padding(15)
.frame(width: size.width, height: size.height)
}
}
.background(.white)
.frame(width: size.width * CGFloat(onBoardingItems.count), alignment: .leading)
if isMainViewActive {
withAnimation(.easeInOut) {
MainAuthView()
.transition(.move(edge: .bottom))
}
}
}
}
func playAnimation() {
onBoardingItems[currentIndex].lottieView.currentProgress = 0
onBoardingItems[currentIndex].lottieView.play(toProgress: 0.7)
}
func indexOf(_ item: OnBoardingItem) -> Int {
if let index = onBoardingItems.firstIndex(of: item) {
return index
}
return 0
}
}
|
from django.shortcuts import render, HttpResponseRedirect, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from .models import Add
import re
def dashboard(request):
return render(request,"dashboard.html")
@login_required
def add_book(request):
if request.method=='POST':
name=request.POST.get("name")
price=request.POST.get("price")
quantity=request.POST.get("quantity")
author=request.POST.get("author")
description=request.POST.get("description")
image = request.FILES.get("image")
AddBooks=Add(name=name, price=price, quantity=quantity, author=author, description=description, image=image)
AddBooks.save()
return HttpResponseRedirect('/')
return render(request,'add_book.html')
def book_details(request):
if request.method == 'POST':
if 'remove' in request.POST:
book_name = request.POST.get('remove')
book =Add.book_detail(book_name)
book.delete()
return redirect('home')
elif "name" in request.POST:
name1=request.POST.get('name')
price1=request.POST.get('price')
author1=request.POST.get('author')
description1=request.POST.get('description')
image1=request.FILES.get('image')
book=request.POST.get("book")
if not image1:
new_image=Add.book_detail(book)
image1=new_image.image
change=Add.book_detail(book)
change.name=name1
change.price=price1
change.author=author1
change.description=description1
change.image=image1
change.save()
return redirect('home')
return render(request, 'home.html')
@login_required
def home(request):
if request.method=="POST":
if "search" in request.POST:
search_book = request.POST.get("search")
books = []
all_books = Add.showbook()
if not search_book:
return redirect('home')
for book in all_books:
iname = book.name.upper()
search_book = search_book.upper()
if re.search(search_book, iname):
books.append(book)
context={}
context["book"]=books
if books:
message = f"Search Results.."
context["message"] = message
return render(request, 'home.html',context)
else:
error = f"The Book with the name containing '{search_book.lower().capitalize()}' is not available"
context["book"] = all_books
context['error'] = error
return render(request, 'home.html',context)
id=request.POST.get('id')
book_details=Add.book_detail(id)
context={}
context["context"]=book_details
return render(request,"book_details.html",context)
else:
books=Add.showbook()
context={}
context["book"]=books
return render(request, 'home.html',context)
def user_logout(request):
logout(request)
return HttpResponseRedirect('/')
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('/')
else:
error_message = "Invalid username or password"
return render(request, 'login.html', {'error_message': error_message})
return render(request, 'login.html')
def user_signup(request):
if request.method == 'POST':
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
repeatPassword = request.POST['repeatPassword']
if password == repeatPassword:
try:
user = User.objects.create_user(username, email, password)
user.save()
login(request, user)
return redirect('/login')
except:
error_mesage = 'Error creating account'
return render(request, 'register.html', {'error_message' : error_mesage})
else:
error_mesage = 'Password do not match'
return render(request, 'blog_generator/signup.html', {'error_message' : error_mesage})
return render(request, 'register.html')
|
import React from 'react'
import { Route } from 'react-router-dom'
/**
* https://ja.reactjs.org/docs/concurrent-mode-suspense.html
*/
type SuspenseRouteProps = React.ComponentProps<typeof Route> &
React.SuspenseProps
export const SuspenseRoute: React.FC<SuspenseRouteProps> = ({
children,
fallback,
...routeProps
}) => {
const suspenseProps: React.SuspenseProps = { children, fallback }
return (
<Route {...routeProps}>
<React.Suspense {...suspenseProps} />
</Route>
)
}
|
import { IAsset } from "./IAsset";
import { Loader } from "./Loader";
class ImageLoader extends Loader {
validExt: string[] = ["png", "jpg", "jpeg", "gif"];
fileType = "image";
async loadAssset(asset: IAsset) {
const url = asset.url;
const image = new Image();
image.src = url;
await new Promise((res) => {
image.onload = () => {
AssetLoader.addLoadedAsset(this, { ...asset, data: image });
res(image);
};
});
}
}
export class AssetLoader {
static loadedAssets: Record<string, IAsset> = {};
static assets: Record<string, IAsset> = {};
static loaders: Loader[] = [new ImageLoader()];
static addAsset(asset: IAsset) {
const loader = AssetLoader.getLoaderByUrl(asset.url);
this.assets[loader.fileType + ":" + asset.name] = asset;
}
static getLoaderByUrl(url: string) {
return AssetLoader.loaders.filter(
(loader) => loader.validExt.indexOf(url.split(".").pop()) > -1
)[0];
}
static registerLoader(loader: Loader) {
AssetLoader.loaders.push(loader);
}
static addLoadedAsset(loader: Loader, asset: IAsset) {
this.loadedAssets[loader.fileType + ":" + asset.name] = asset;
}
static async loadAssets() {
const promises = Object.keys(AssetLoader.assets).map((key) => {
if (AssetLoader.loadedAssets[key] !== undefined) return;
const asset = AssetLoader.assets[key];
const loader = AssetLoader.getLoaderByUrl(asset.url);
return loader.loadAssset(asset);
});
await Promise.all(promises);
}
static getLoadedAsset(name: string) {
return AssetLoader.loadedAssets[name];
}
}
|
import { Route } from "react-router-dom";
import SignUp from "./components/SignUp";
import { Layout } from "antd";
import Login from "./components/Login";
import PrivateRoute from "./components/PrivateRoute";
import Categories from "./components/Categories";
import Records from "./components/Records";
import Headers from "./components/Headers";
import Logout from "./components/Logout";
function App() {
const { Content, Footer } = Layout;
return (
<>
<Layout>
<Headers />
<Content
className="site-layout"
style={{ padding: "50px", marginTop: 64 }}
>
<Route path="/register" component={SignUp} />
<Route path="/login" component={Login} />
<Route path="/logout" component={Logout} />
<PrivateRoute path="/categories" component={Categories} />
<PrivateRoute path="/records" component={Records} />
</Content>
<Footer style={{ textAlign: "center" }}>Expense Tracker</Footer>
</Layout>
</>
);
}
export default App;
|
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
const useSceneInitializer = (containerRef, scene, camera, rendererRef) => {
camera.position.set(4, 3, 5);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
if (containerRef.current) {
containerRef.current.appendChild(renderer.domElement);
}
rendererRef.current = renderer; // Store the renderer in the ref
const controls = new OrbitControls(camera, renderer.domElement);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(0, 1, 0);
scene.add(directionalLight);
// Create a simple cube and add it to the scene
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
};
export default useSceneInitializer;
|
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>웹디자인기능사 메뉴 A-3유형</title>
<link rel="stylesheet" href="./A-3.css" />
</head>
<body>
<div id="wrap">
<header id="header">
<h1 class="logo">
<span class="text">로고</span>
</h1>
<nav class="nav">
<ul class="menu">
<li>
<a href="#">메뉴1</a>
<ul class="submenu">
<li>
<a href="#">서브메뉴1-1</a>
</li>
<li>
<a href="#">서브메뉴1-2</a>
</li>
<li>
<a href="#">서브메뉴1-3</a>
</li>
<li>
<a href="#">서브메뉴1-4</a>
</li>
</ul>
</li>
<li>
<a href="#">메뉴2</a>
<ul class="submenu">
<li>
<a href="#">서브메뉴2-1</a>
</li>
<li>
<a href="#">서브메뉴2-2</a>
</li>
<li>
<a href="#">서브메뉴2-3</a>
</li>
<li>
<a href="#">서브메뉴2-4</a>
</li>
</ul>
</li>
<li>
<a href="#">메뉴3</a>
<ul class="submenu">
<li>
<a href="#">서브메뉴3-1</a>
</li>
<li>
<a href="#">서브메뉴3-2</a>
</li>
<li>
<a href="#">서브메뉴3-3</a>
</li>
<li>
<a href="#">서브메뉴3-4</a>
</li>
</ul>
</li>
<li>
<a href="#">메뉴4</a>
<ul class="submenu">
<li>
<a href="#">서브메뉴4-1</a>
</li>
<li>
<a href="#">서브메뉴4-2</a>
</li>
<li>
<a href="#">서브메뉴4-3</a>
</li>
<li>
<a href="#">서브메뉴4-4</a>
</li>
</ul>
</li>
</ul>
</nav>
</header>
<!-- // header -->
<article id="slider">
<span class="text">이미지 슬라이드</span>
</article>
<!-- // slider -->
<main id="contents">
<section class="content1">
<span class="text">공지사항(C.1) / 갤러리(C.2)</span>
</section>
<section class="content2">
<span class="text">배너(C.3)</span>
</section>
<section class="content3">
<span class="text">바로가기(C.4)</span>
</section>
</main>
<!-- // contents -->
<footer id="footer">
<div class="footer1">
<span class="text">로고</span>
</div>
<div class="footer2">
<div class="footer2-1">
<span class="text">하단 메뉴</span>
</div>
<div class="footer2-2">
<span class="text">Copyright</span>
</div>
</div>
</footer>
<!-- // footer -->
</div>
<!-- // wrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
// .nav .menu > li mouseover시 전체메뉴(#header::after, .submenu)가 보이도록
// 1. jquery
// $(function(){
// $('.nav .menu > li').mouseover(function(){
// $('.submenu').stop().slideDown(300);
// $('#header').addClass('is-on');
// });
// $('.nav .menu > li').mouseout(function(){
// $('.submenu').stop().slideUp(300);
// $('#header').removeClass('is-on');
// });
// });
// 2. javascript
window.onload = function(){
let navList = document.querySelectorAll('.nav .menu > li');
let navBg = document.querySelector('#header');
let subMenu = document.querySelectorAll('.nav .submenu');
navList.forEach((navItem) => {
navItem.addEventListener('mouseover', function(){
subMenu.forEach((sub) => {
sub.style.height = '166.4px';
});
navBg.classList.add('is-on');
});
navItem.addEventListener('mouseout', function(){
subMenu.forEach((sub) => {
sub.style.height = '0px';
});
navBg.classList.remove('is-on');
});
});
};
</script>
</body>
</html>
|
const express = require("express");
const https = require("https");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get("/", function(req, res){
res.sendFile(__dirname + "/index.html");
//res.send("Server is up and running.")
});
app.post("/", function(req, res){
console.log(req.body.cityName);
const query = req.body.cityName;
const apikey = "494e541d8491f73b716cc6260a480714";
const unit = "metric";
const url = "https://api.openweathermap.org/data/2.5/weather?q=" + query + "&appid=" + apikey + "&units=" + unit;
https.get(url, function(response){
console.log(response.statusCode);
response.on("data", function(data){
//console.log(data);
const weatherData = JSON.parse(data);
const temp = weatherData.main.temp;
console.log(temp);
const weatherDescription = weatherData.weather[0].description;
console.log(weatherDescription);
const icon = weatherData.weather[0].icon;
const imageURL = "http://openweathermap.org/img/wn/" + icon + "@2x.png";
// const object = {
// name: "Angela",
// facouriteFood: "Ramen"
// }
// console.log(JSON.stringify(object));
res.write("<p>The weather is currently " + weatherDescription + ".</p>");
res.write("<h1>The temperature in " + query + " is " + temp + " degrees celcius.</h1>");
res.write("<img src=" + imageURL + ">");
res.send();
});
});
})
app.listen(3000, function(){
console.log("Server is running on port 3000.");
});
|
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { OperationsService } from '../../../services/operations.service';
import { PjManagementService } from '../../../services/pj-management.service';
import { ActionEvents } from '../../../shared/enums/action-events';
import { CreateUpdateIssueComponent } from '../../dialogs/create-update-issue/create-update-issue.component';
import { CreateUpdateOperationComponent } from '../../dialogs/create-update-operation/create-update-operation.component';
import { CreateUpdateProjectComponent } from '../../dialogs/create-update-project/create-update-project.component';
import { ListingTableComponent } from '../listing-table/listing-table.component';
import * as _moment from 'moment';
const moment = _moment;
@Component({
selector: 'app-operation-management',
templateUrl: './operation-management.component.html',
styleUrls: ['./operation-management.component.scss']
})
export class OperationManagementComponent implements OnInit {
operationsData: any[]=[];
colsOpions = {
cols: [
{
header: 'title',
key: 'title'
},
{
header: 'type',
key: 'type',
},
{
header: 'estimated_start_date',
key: 'estimated_start_date',
},
{
header: 'estimated_end_date',
key: 'estimated_end_date',
},
{
header: 'completion',
key: 'completion',
},{
header: 'comments',
key: 'comments',
},{
header: 'Status',
key: 'status',
},
{
header: 'actual_start_date',
key: 'actual_start_date',
},
{
header: 'actual_end_date',
key: 'actual_end_date',
},
{
header: 'actions',
key: 'actions',
}
],
};
actionEvents = ActionEvents;
menuActions= [
{
name: 'Edit',
event: this.actionEvents.EDIT
},
{
name: 'Print',
event: this.actionEvents.PRINT
}
,{
name: 'Delete',
event: this.actionEvents.DELETE
}
];
@ViewChild(ListingTableComponent) tableData: ListingTableComponent;
constructor(private pjService: PjManagementService,
private _operationService: OperationsService,
private _route: ActivatedRoute,
private dialog: MatDialog,
private _router: Router) { }
ngOnInit(): void {
this.operationsData = this._operationService.getOperatinsData().map((item: any)=>{
item.estimated_start_date = moment(item.estimated_start_date).format('d/MM/yyyy');
item.estimated_end_date = moment(item.estimated_end_date).format('d/MM/yyyy');
item.actual_start_date = moment(item.actual_start_date).format('d/MM/yyyy');
item.actual_end_date = moment(item.actual_end_date).format('d/MM/yyyy');
return item;
});
}
newOperation(event: any): void{
if(event?.toCreateItem){
const dialogRef = this.dialog.open(CreateUpdateOperationComponent, {
width: '700px',
height: '700px',
data: null
});
dialogRef.afterClosed().subscribe((result: any) => {
if(result)
{
const newRow: any = {
id: this.operationsData.length + 1,
...result
};
console.log({newRow});
this._operationService.operationsData.push(newRow);
this.operationsData = this._operationService.getOperatinsData();
console.log('operationsData=> ', this.operationsData);
this.reloadComponent();
}
});
}
}
reloadComponent() {
let currentUrl = this._router.url;
this._router.routeReuseStrategy.shouldReuseRoute = () => false;
this._router.onSameUrlNavigation = 'reload';
this._router.navigate([currentUrl]);
}
handleAction(event: any): void{
if(event.actionName === this.actionEvents.EDIT){
this.editOperation(event);
}
else if(event.actionName === this.actionEvents.DELETE){
this.deleteOperation(event);
}
}
editOperation(item: any): void{
let itemToUpdate = this._operationService.getOperatinByID(item.id);
// itemToUpdate.resolution_date =moment(item.resolution_date).toISOString();
// itemToUpdate.date =moment( item.date).toISOString();
const dialogRef = this.dialog.open(CreateUpdateOperationComponent, {
width: '700px',
height: '700px',
data: itemToUpdate
});
dialogRef.afterClosed().subscribe((result) => {
if(result)
{
}
});
}
deleteOperation(item: any): void{
this.operationsData = this.operationsData.filter((x)=> x.id !== item.id);
this.tableData.data = this.operationsData;
this.tableData.ngAfterViewInit();
}
}
|
import React, { useRef } from "react";
import { useReactToPrint } from "react-to-print";
import { v4 as uuidv4 } from "uuid";
import Button from "@/components/Button/Button";
import { Property } from "~/contracts";
import { PrinterIcon } from "~/icons/Icons";
import { hasValue, timestampToDate } from "~/utils";
import "./PrintPropertyMultiple.scss";
const PrintPropertyMultiple = ({
properties,
usePrinterIcon,
children,
}: {
properties: Property[];
usePrinterIcon?: boolean;
children: any;
}) => {
const componentRef = useRef(null);
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
const getPageMargins = () => {
return `@page {
margin: 23px 20px 30px 20px !important;
}`;
};
return (
<>
{usePrinterIcon ? (
<span onClick={handlePrint}>
<PrinterIcon />
</span>
) : (
<Button type="button" isDisabled={false} onClick={handlePrint}>
{children}
</Button>
)}
<div className="multiple-property-label-container ">
<style>{getPageMargins()}</style>
<div ref={componentRef} style={{ display: "flex", flexWrap: "wrap" }}>
{properties.map((property) => {
const {
p_type,
p_comp_ref,
p_unit,
p_condo,
p_book_1,
p_book_2,
p_page_1,
p_page_2,
p_cert_1,
seller_1,
seller_2,
seller_3,
seller_4,
buyer_1,
buyer_2,
p_instructions,
c_name,
p_requester,
c_file,
p_request_date,
p_input_date,
} = property;
const formatp_request_date = `${
hasValue(p_request_date)
? timestampToDate(p_request_date, "mmDDyyyy").date
: ""
}`;
const formatp_input_date = `${
hasValue(p_input_date)
? timestampToDate(p_input_date, "mmDDyyyy").date
: ""
}`;
const formatp_unit = p_unit ? `unit ${p_unit}` : "";
return (
<div
key={uuidv4()}
style={{
fontSize: "16px",
height: "200px",
display: "flex",
flexDirection: "column",
justifyContent: "center",
fontFamily: `'Times New Roman','Courier New', Courier, monospace`,
width: "50%",
paddingLeft: "10px",
}}
>
<p>
{" "}
{formatp_request_date} {"("}
<b>{p_type}</b>
{") "}
<span style={{ fontSize: "14px" }}>
{"(Input "}
{formatp_input_date}
{") "}
</span>
{"CR#"}
{p_comp_ref || ""}
</p>
<p> {`${formatp_unit} ${p_condo || ""}`} </p>
<p>
{" "}
{`B:${p_book_1 || ""} P:${p_page_1 || ""} B:${
p_book_2 || ""
} P:${p_page_2 || ""} C:${p_cert_1 || ""}`}{" "}
</p>
<p> {`S:${seller_1 || ""} S:${seller_2 || ""}`} </p>
<p> {`S:${seller_3 || ""} S:${seller_4 || ""}`} </p>
<p> {`B:${buyer_1 || ""} B:${buyer_2 || ""}`} </p>
<p> {`*${p_instructions || ""}`} </p>
<p> {`${c_name || ""}, ${p_requester || ""}`} </p>
<p> {`${c_file || ""}`} </p>
</div>
);
})}
</div>
</div>
</>
);
};
export default PrintPropertyMultiple;
|
package ir.mahdi.gharooni.gallerykt.data.local.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
import ir.mahdi.gharooni.gallerykt.domain.model.Image
import ir.mahdi.gharooni.gallerykt.domain.model.Url
import ir.mahdi.gharooni.gallerykt.domain.model.User
import ir.mahdi.gharooni.gallerykt.utils.TABLE_NAME_FAVORITE_IMAGES
@Entity(tableName = TABLE_NAME_FAVORITE_IMAGES)
data class FavoriteImageEntity(
@PrimaryKey(autoGenerate = false)
val id: String,
val description: String?,
val likes: Int,
val user: User,
val url: Url,
)
fun FavoriteImageEntity.toImage(): Image {
return Image(
id = id,
description = description,
likes = likes,
user = user,
url = url,
)
}
|
input_data = input()
row = int(input_data[1]) # 문자열도 슬라이싱이 가능하니까 열과 행을 따로 받기
column = int(ord(input_data[0])) - int(ord('a')) + 1 # ord 함수는 문자의 유니코드 값을 돌려주는 함수 / a는 97이므로 받은 문자 유니코드 - a의 유니코드 +1
steps = [(-2, -1), (-1, -2), (1, -2), (2, -1), (2, 1), (1, 2), (-1, 2), (-2, 1)] # 나이트가 이동할 수 있는 8가지 방향 정의
result = 0
for step in steps: # 방향 1가지를 빼서
next_row = row + step[0] # row에 더하고
next_column = column + step[1] # column에도 더하기
if next_row >= 1 and next_row <= 8 and next_column >= 1 and next_column <= 8: # 그 결과가 8 X 8 좌표 평면을 벗어나지 않는 경우, +1
result += 1
print(result)
|
import requests
import lxml
from bs4 import BeautifulSoup
from aiogram import Bot, Dispatcher, executor, types
import markups as nav
import random
from decouple import config
TOKEN = config('TOKEN')
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
async def command_start(message: types.Message):
await bot.send_message(message.from_user.id, 'Hello, {0.first_name}'.format(message.from_user), reply_markup=nav.mainMenu)
@dp.message_handler()
async def bot_message(message: types.Message):
if message.text == '🎲 Рандомное число игральной кости':
await bot.send_message(message.from_user.id, 'Ваше число: ' + str(random.randint(1,6)))
elif message.text == '🎦 как искать КИНО':
await bot.send_message(message.from_user.id, 'Просто введи название фильма и я попытаюсь найти их для тебя C:')
elif message.text == '💲 Курс валют':
valutes_true = {}
def get_html(url):
r = requests.get(url)
return r.text
def get_valutes(safari):
soup = BeautifulSoup(safari, 'lxml')
money = soup.find('div', class_='nbkr_tabs_wrapper').find_all('h2')
flags = ['🇺🇲','🇪🇺','🇷🇺','🇰🇿']
valutes1 = []
for i in money:
valutes1.append(i.text)
for x,y in zip(flags,valutes1):
valutes_true.setdefault(x,[]).append(y)
return valutes_true
def safari():
url = f'https://www.akchabar.kg/ru/exchange-rates/'
ready = get_valutes(get_html(url))
return ready
safari()
for key, value in valutes_true.items():
string = str(value).replace('[','').replace(']','').replace("'",'')
await bot.send_message(message.from_user.id,f'{key}:{string}')
else:
# --- Реализован парсиг и поиск по двум онлайн-кинотеатрам hdrezka.re && megogo.net --- #
def get_html(url):
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.1 Safari/605.1.15'}
r = requests.get(url, headers=headers)
return r.text
def get_links(safari):
soup = BeautifulSoup(safari, 'lxml')
try:
media = soup.find('div', class_='b-content__inline_item-cover')
response_true = media.find('a').get('href')
return response_true
except:
pass
def get_links_megogo(safari):
soup = BeautifulSoup(safari, 'lxml')
try:
media = soup.find('a', class_='overlay').get('href')
return media
except:
return 'К сожалению, увы и ах :C'
def safari(text):
corrected_link = text.replace(' ','+')
corrected_link2 = text.replace(' ','%20')
hdrezka = f'https://hdrezka.re/search/{corrected_link.lower()}/'
megogo = f'https://megogo.net/ru/search-extended?q={corrected_link2.lower()}/'
hdrezka_result = get_links(get_html(hdrezka))
megogo_result = get_links_megogo(get_html(megogo))
return hdrezka_result, megogo_result
text = message.text
link = safari(text)
await bot.send_message(message.from_user.id, 'HDREZKA: ' + str(link[0]))
await bot.send_message(message.from_user.id, 'MEGOGO: ' + str(link[1]))
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
|
# Singleton
class Singleton:
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Singleton, cls).__new__(cls) # cls - екземпляр класу
return cls.instance
def __init__(self, value):
self.value = value
foo = Singleton(10)
baz = Singleton(20)
bar = Singleton(30)
print(foo.value, baz.value, bar.value)
print(foo, baz, bar)
# 0x7fe6002c8f10
# 0x7fe6002c8f10
# 0x7fe6002c8f10
|
using System;
using System.Collections.Generic;
namespace T03.ShoppingSpree
{
public class Person
{
private string name;
private decimal money;
private readonly List<Product> bagOfProducts;
public Person()
{
this.BagOfProducts = new List<Product>();
}
public Person(string name, decimal money) : this()
{
this.Name = name;
this.Money = money;
}
public string Name
{
get
{
return this.name;
}
set
{
if (string.IsNullOrWhiteSpace(value))
{
throw new ArgumentException("Name cannot be empty");
}
this.name = value;
}
}
public decimal Money
{
get
{
return this.money;
}
set
{
if (value<0)
{
throw new ArgumentException("Money cannot be negative");
}
this.money = value;
}
}
public ICollection<Product> BagOfProducts { get; set; }
}
}
|
# Governance in 💫Grewety Creative Space
This document outlines the governance model for **💫Grewety**. This includes detailed descriptions of different roles,
nomination processes, code review processes, and [Code of Conduct][coc] enforcement.
> 👉 **All community members must follow the [Code of Conduct (CoC)][coc].**
> Consequences for CoC violations are detailed in [Moderation](#moderation).
> 👉 **Want to trigger a vote, nomination, or perform some other action?**
> Scroll down to [Playbook](#governance-playbook).
## Get Involved
**Anything that supports the 💫Grewety community is a valuable contribution!**
All types of contribution are meaningful. This can include code changes, type fixes, [Discord][discord] activity, and
even posting about **💫Grewety** to your personal blog. No contribution is too small!
Anyone can become a **💫Grewety** contributor (yes, even you🖐️). Engineering ability is not required. Our goal is to
recognize all contributors to the project regardless of skill, experience or background.
## Community Roles
We recognize different types of contribution as five different **Community Roles**. Because each Community Role comes
with a new set of privileges and responsibilities, you may also see these roles as gratitude.
> ✨ **More on this topic**: [Generating a culture of recognition and gratitude in teams][kudo]
Community Roles are available to **all members** of the **💫Grewety** community, regardless of coding skill or
experience.
Two important things that we look for in a contributor are:
- **Being here**: Everyone's time is valuable, and the fact that you're here and contributing to **💫Grewety** is
amazing! Thank
you for being a part of this project with us.
- **Being a positive member of our community**: Go above and beyond our [Code of Conduct][coc] and commit to healthy
communication across pull requests, issue discussions, [Discord][discord] conversations, and any interactions outside
our community (e.g. no Twitter bullies allowed 😑)
All Community Roles are granted for as long as the individual wishes to engage with **💫Grewety**.
Contributors can voluntarily leave the project at any time. See [🦖Alumni](#alumni) below for
more information.
In extreme cases ‒ such as a [Code of Conduct][coc] violation ‒ a role may be revoked by a 👮Project Steward at their
discretion.
Each new contributor involvement unlocks new privileges and responsibilities both on [Discord][discord] and on GitHub.
Below is a summary of each role.
### Overview about Community Roles
| Community Roles | Optional Roles | Privileges | Nomination |
|:------------------:|:-------------------------------------:|:-----------------:|:---------------------------------------------------------------:|
| 🥉Contributor | _none_ | _none_ | Autonomous application by a Community Member himself |
| 🥈Maintainer | [🚩Moderator Role](#moderator-role) | [Voting](#voting) | Nomination and voting by other 🥈Maintainers |
| 🥇Core Member | [👮Project Steward](#project-steward) | [Voting](#voting) | Nomination and voting by other 🥇Core Members |
| 🪅Committed Member | [🚩Moderator Role](#moderator-role) | _none_ | Hired or brought in to work for the Community by 🥇Core Members |
| 🦖Alumni | _none_ | _none_ | Autonomous application as 🥈Maintainer or 🥇Core Member himself |
### 🥉Contributor
Have you done something (big or small) to contribute to the health, success, or growth of **💫Grewety**? **👏
Congratulations, you're officially recognized as a contributor to the project!**
#### Recognized Contributions (Examples)
- **GitHub**: Submitting a merged pull request.
- **GitHub**: Filing a detailed bug report or RFC.
- **GitHub**: Updating documentation or fixing a typo.
- Helping people on GitHub, [Discord][discord], etc.
- Answering questions on Stack Overflow, Twitter, etc.
- Blogging, Vlogging, Podcasting, and Livestreaming about **💫Grewety**.
_This list is incomplete. Similar contributions are also recognized._
#### Privileges
- New role on [Discord][discord]: `@contributor`
- New color on [Discord][discord]: **🥉bronze**
- Invitations to contributor-only events, sticker drops, and the occasional swag drop.
#### Responsibilities
This role does not require any extra responsibilities nor time commitment. We hope you stick around and keep
participating in our community.
If you're interested in becoming a **🥈Maintainer**, you can explore some of those responsibilities in
the [next section](#maintainer).
#### Nomination Process to Contributor
- You may self-nominate by sending the message `!contribute` in any [Discord][discord] channel. If you do this, please
share a second message with a link or description of your contribution so that people can recognize you for the
contribution.
- You may also be granted this role automatically if you are active and helpful on [Discord][discord].
- The nomination is limited for one (1) year before a self-renomination have to take place.
### 🥈Maintainer
The **🥈Maintainer** role is available to contributors who want to join the team and take part in the long-term
maintenance and growth of **💫Grewety**.
The 🥈Maintainer role is critical to the long-term health of **💫Grewety**. 🥈Maintainers act as the first line of defense
when it comes to new issues and user requests, pull requests (PR) and [Discord][discord] activity. 🥈Maintainers are
most likely the first people that a user will interact with on [Discord][discord] or GitHub.
**🥈Maintainers are not required to write code!** Some 🥈Maintainers spend most of their time inside
of [Discord][discord], maintaining a healthy community there. Others work on technical documentation, support, or
design.
**A 🥈Maintainer has the opportunity for optional [🚩Moderator Role](#moderator-role).** All maintainers are trusted
with the ability to help moderate our [Discord][discord] and GitHub communities when a community member reaches out
for moderation help.
**A 🥈Maintainer has the opportunity for participation in the
[🤩User Satisfaction Committee Working Group](#user-satisfaction-committee-usc)**. Due to this involvement in the
community and the project insigts about the users needs are valuable for the future and prosperity of **💫Grewety**.
#### Recognized Contributions (Examples)
There is no strict minimum number of contributions needed to reach this Kudo, as long as you can show **sustained**
involvement over some amount of time (at least a few months).
- **GitHub**: Submitting multiple non-trivial pull requests and RFCs.
- **GitHub**: Reviewing multiple non-trivial pull requests and RFCs.
- **Discord**: Supporting users in [Discord][discord], especially in the `#support` channel.
- **Discord**: Active participation in RFC meetings and other events.
- **GitHub + Discord**: Triaging and confirming user issues and requests.
_This list is incomplete. Similar contributions are also recognized._
#### Privileges
- All privileges of the [🥉Contributor Role](#contributor), plus...
- Invitation to the `@maintainer` role on [Discord][discord].
- Invitation to the private `#maintainers` channel on [Discord][discord].
- Invitation to the `grewety` organization on GitHub.
- Invitation to the `maintainers` team on GitHub.
- New color on [Discord][discord]: **🥈silver**
- Be nominated to join the [🚩Moderator Role](#moderator-role) on [Discord][discord].
- Be nominated to join the [🤩User Satisfaction Committee Working Group](#user-satisfaction-committee-usc).
- Ability to push branches directly to the `grewety` GitHub organization (personal forks no longer needed).
- Ability to review GitHub pull request (PRs).
- Ability to merge _some_ GitHub pull requests (PRs).
- Ability to vote on _some_ initiatives (see [Voting](#voting) below).
#### Responsibilities
- Participate in the project as a team player.
- Bring a friendly, welcoming voice to the **💫Grewety** community.
- Be active on [Discord][discord], especially in the #support channel.
- Triage new issues.
- Review pull requests.
- Merge some, non-trivial community pull requests.
- Merge your own pull requests (once reviewed and approved).
#### Nomination Process to Maintainer
- To be nominated, a nominee is expected to already be performing some of the responsibilities of a 🥈Maintainer.
- You can be nominated by any existing 🥈Maintainer.
- A nomination thread will be created in [Discord][discord] `#maintainers` channel (the private channel for all
🥈Maintainers) with your nomination ‒ with or without your awareness.
- Once nominated, [voting for a new 🥈Maintainer](#voting-new-maintainer) is initiated.
- The nomination is limited for two (2) years before a renomination have to take place.
### 🥇Core Member
The **🥇Core Member** role is available to community members who have a larger-than-usual impact on the **💫Grewety**
project and community. They are seen as leaders in the project and are listened to by the wider **💫Grewety**
community, often before they have even reached this reputation. A Member is recognized for contributing a significant
amount of time and energy to the project through solving issues, pull requests and RFCs, bug fixes, implementing
advanced enhancements/features, gathering user feedback, creating documentation and tutorials and/or actively
posting on [Discord][discord].
Not every 🥉Contributor Role will graduate to this role, and that's okay! 🥈Maintainers still have significant
responsibility and privileges within our community, e.g. participation in the
[🤩User Satisfaction Committee Working Group](#user-satisfaction-committee-usc) and influencing the roadmap of the
**💫Grewety** project.
#### Privileges
- All privileges of the [🥈Maintainer Role](#maintainer), plus...
- Invitation to the new `@coremember` role on [Discord][discord].
- New color on [Discord][discord]: **🥇gold**
- Invitation to the private `#coremembers` channel on [Discord][discord].
- Invitation to the `+coremembers` team on GitHub.
- Ability to vote on most initiatives (see [Voting](#voting) below).
#### Responsibilities
- All the responsibilities of [🥈Maintainer Role](#maintainer), including...
- Ownership over specific part(s) of the project.
- Ownership over the long-term health and success of **💫Grewety**.
- Leadership as a role-model to other maintainers and community members.
#### Nomination Process to Core Member
- To be nominated, a nominee is expected to already be performing some of the responsibilities of a 🥇Core Member.
- You can be nominated by any existing 🥇Core Member.
- A nomination thread will be created in [Discord][discord] `#coremembers` channel (the private channel for all
🥇Core Member) with your nomination ‒ with or without your awareness.
- Once nominated, [voting for a new 🥇Core Member](#voting-new-core-member) is initiated.
- The nomination is limited for three (3) years before a renomination have to take place.
### 🪅Committed Member
**🪅Committed Member** is by default a time-limited special designation for anyone who has been brought in to work on or
contribute to the **💫Grewety** project on behalf of 🥇Core Members without rising through our normal contributor stages.
For example: a **💫Grewety** designer or developer advocate hired to assist the community could be nominated for a
🪅Committed Member role without having a previously earned 🥉Bronze Contributor Kudo.
#### Privileges
- `@committed` role on [Discord][discord].
- New name color on Discord: **🪅yellow**
- Invitation to `#coremembers` channel on [Discord][discord], at the discretion of the 👮Project Steward.
- Invitation to the `committed` team on GitHub.
A 🪅Committed Member is still eligible for other roles in the community and may still vote as defined by their
other roles.
#### Limitations
🪅Committed Members does not grant any abilities when it comes to voting and project governance.
- No voting abilities.
- No nomination abilities.
- Can be revoked at any time by the 👮Project Steward or a vote by the 🥇Core Members with an overwhelming majority
(70%+).
- Limited for six (6) months, unless otherwise specified in the nomination. After this period, a new nomination must be
made.
#### Nomination Process to Committed Member
A 🪅Committed Member nomination must still be approved through the normal 🥇Core Member nomination and voting process.
During the nomination, the 👮Project Steward will state that the nomination is for the 🪅Committed Member designation.
The 👮Project Steward is the only one who can officially make this designation during the nomination process.
A 🪅Committed Member can become a full 🥇Core Member (with all limitations removed) through the normal 🥇Core Member
nomination and voting procedure.
If a 🪅Committed Member has their membership revoked, the 👮Project Steward may choose to impose a waiting period of
some number of days, during which the member can not be re-nominated to become a 🥇Core Member.
### 🦖Alumni
**🦖Alumni** is a special designation for at least a 🥈Maintainers who have stepped away from the project and no longer
contribute regularly.
Community Roles are granted for as long as the person wishes to engage with the project. However, over time an active
community member may choose to step away from the **💫Grewety** project to work on other things. Moving on from a project
is a natural and well-understood part of any open source community, and we celebrate it!
As a 🥈Maintainer you can retire your role at any time by pinging the 👮Project Steward and requesting 🦖Alumni
status. You can initiate this action yourself if you know ahead-of-time that you need to step away from the project. Or,
if you have gone several months without interacting with the **💫Grewety** community, the 👮Project Steward may actively
reach out to you to discuss retiring as a way to make room for new contributors.
#### Privileges
By retiring and joining 🦖Alumni you trade in your current set of roles, privileges, and responsibilities for a new,
special 🦖Alumni role, which comes with its own set of privileges:
- `@alumni` role on [Discord][discord].
- New name color on Discord: **🦖light green**.
- Invitation to the private `#alumni` channel on [Discord][discord].
#### Rejoining
As an 🦖Alumni member, you are still a part of the **💫Grewety** community and can continue to be a part of
our [Discord][discord], GitHub, and anywhere else. You may also request to have your old roles reinstated at any
time through the normal nomination & voting process for that role.
Rejoining the project as a 🥉Contributor will automatically remove you from the 🦖Alumni role.
### Additional Roles
Few Community Roles can have additional roles with additional responsibilities and delegated duties as described next.
#### 🚩Moderator Role
**Moderator** is a special role available to [🥈Maintainer Role](#maintainer). While all maintainers are
granted permissions to moderate for bad behavior across our community, a Moderator actively takes on this the
responsibility. For example, a community member may ping moderators (via the `@moderator` role) to resolve spam posts or
[Code of Conduct][coc] violations.
Trivial tasks (like removing spam) can be acted on unilaterally by a Moderator. Other non-trivial tasks (like assisting
with or resolving a [Code of Conduct][coc] violation) should involve the entire Moderator team (and in some cases, the
👮Project Steward).
##### Privileges
- `@mods` role on [Discord][discord].
- Invitation to the private `#mods` channel on [Discord][discord].
- Invitation to the `mods` team on GitHub.
##### Nomination
Any at least [🥈Maintainer](#maintainer) can self-nominate by messaging the 👮Project Steward
(`@steward`) on [Discord][discord].
#### 👮Project Steward
The **👮Project Steward** is an additional role bestowed to 1 (or more) 🥇Core Member of the project.
The role of 👮️Project Steward is mainly an administrative one. 👮Project Stewards control and maintain sensitive
project assets, assist in resolving conflicts, and act as tiebreakers in the event of disagreements.
In extremely rare cases, a 👮Project Steward can act unilaterally when they believe it is in the project's best
interest and can prove that the issue cannot be resolved through normal governance procedure. The 👮Project Steward
must publicly state their reason for unilateral action before taking it.
##### Responsibilities
- Invitation to the new `@steward` role on [Discord][discord].
- Establish [Code of Conduct][coc].
- Bears the 💰costs of the **💫Grewety** services.
- Ensuring and maintaining the availability of the **💫Grewety** services.
- Leadership and sincere interest in the welfare of **💫Grewety** community.
- Ability to initiate a [vote](#voting).
- Ability to veto [votes](#voting) and resolve voting deadlocks.
- Define project direction and planning, preferably by RFC.
- Ability to decide on [moderation](#moderation) decisions.
- Administration privileges on the [Grewety GitHub.org][github].
- Administration privileges on the [Grewety Discord server][discord].
- Publish access to the [Grewety npmjs account][npmjs].
- Domain registrar and DNS access to https://grewety.com, and all other subdomains.
- Access to the `*@grewety.com` email address.
##### Nomination Process for a Project Steward
- 👮Project Steward cannot nominate themselves, except for the founder [**Raphael Bossek**][rbo] aka _@hephaistos_DE_.
- Only 🥇Core Members are eligible.
- New 👮Project Steward will be added based on a unanimous vote by the existing 👮Project Steward(s).
- In the event that someone is unreachable then the decision will be deferred.
## Working Groups
Besides our Community Roles described above, there are **Working Groups** available that community members
are welcome to join. Working Groups are a great way to organize around different projects and initiatives in our
community. For example:
- 📒Editor Working Group runs the `#docs` [Discord][discord] channel and organizes the growth and development of
**💫Grewety** documentation and tutorials.
- 🎓Supporter Working Group runs the `#support` [Discord][discord] channel and helps anyone who needs help using
**💫Grewety**.
- 🌏Translator Working Group runs the `#i18n` [Discord][discord] channel and organizes translations in several languages.
Many of these Working Groups can be joined by the first contribution in the corresponding channel on
[Discord][discord]. Getting involved with a Working Group is a great way to start contributing to **💫Grewety**.
### 🤩User Satisfaction Committee (USC)
The **🤩USC** is a special Working Group available to 🥈Maintainers and 🥇Core Members. Their duty is to ensure that the
needs of **💫Grewety** users are taken into account and that future necessary changes are identified at an early
stage and recorded in the form of RFCs. Satisfied users is the goal.
A 🤩USC Working Group member takes care of the needs of the users and is convinced that the continuity of the
**💫Grewety** project can only be ensured if the needs of the users can be satisfied. He draws his knowledge from
handling `#support` questions, creating guidance on relevant use cases, getting feedback from users in
[Discord][discord] and elsewhere. Any form of interaction within and especially outside the community are important
and valuable sources of inspiration. This make the participation in the `#support` and `#docs` Working Groups so
relevant and valuable.
#### Privileges
- `@usc` role on [Discord][discord].
- Invitation to the private `#usc` channel on [Discord][discord].
- Invitation to the `usc` team on GitHub.
- Ability to vote on RFCs (see [vote rules & requirements](#voting) below).
#### Responsibilities
- Participating in RFC discussions and user conversations on [Discord][discord], especially in `#support` channel.
- Gathering information about user needs and create meaningfully RFCs.
- Creating und publishing of helpful tutorials for new users and **💫Grewety** veterans based on needs and trends.
#### Nomination
- To be nominated, a nominee is expected to already be active in strategical roadmap discussions and performing some
of the responsibilities of a 🤩USC member.
- You can be nominated by any existing 🥈Maintainers and 🥇Core Members. Note: This includes all existing 🤩USC members
as well.
- Once nominated, there will be a vote by existing 🥈Maintainers and 🥇Core Members.
- See [vote rules & requirements](#voting) for info on how this vote works.
### 💎Technical Excellence Committee (TEC)
The **💎TEC** is a special role available to 🥇Core Members. 💎TEC members are responsible for the technical excellence
and reliability of the **💫Grewety** projects.
💎TEC members are technical guardians over the **💫Grewety** projects. Their duty is to ensure code maintainability,
technical documentation, correctness and security.
💎TEC members are ultimately responsible for technical decision-making when it comes to any compatibility breaking
changes to the **💫Grewety** projects.
A 💎TEC member has significant sway in software design decisions. For this reason, coding experience is critical for this
role. 💎TEC membership is one of the few roles that requires a significant contribution history of code to the
**💫Grewety** project on GitHub.
#### Privileges
- `@tec` role on [Discord][discord].
- Invitation to the private `#tec` channel on [Discord][discord].
- Invitation to the `tec` team on GitHub.
- Ability to merge all GitHub pull requests (PRs).
- Ability to vote on RFCs and technical initiatives (see [vote rules & requirements](#voting) below).
#### Responsibilities
- Participating in RFC discussions and technical meetings.
- Assisting with design and implementation of non-trivial GitHub pull requests (PRs).
- Reviewing and merging larger, non-trivial pull requests (PRs).
- Maintaining and improving overall codebase architecture.
- Tracking and ensuring progress of open pull requests.
- Mentoring and guiding other community contributors.
#### Nomination
- To be nominated, a nominee is expected to already be active in technical discussions and performing some of the
responsibilities of a 💎TEC member.
- You can be nominated by any existing 🥇Core Members. Note: This includes all existing 💎TEC members as well.
- Once nominated, there will be a vote by existing 🥇Core Members.
- See [vote rules & requirements](#voting) for info on how this vote works.
# Governance Playbook
## Decision-Making Process
Changes for **💫Grewety** projects are discussed using a model called [Consensus-seeking decision-making]
[consensus-seeking]. This model attempts to achieve consensus on all changes to **💫Grewety**, but has a fallback voting
procedure in place if consensus appears unattainable.
> ✨ **More on this topic**: Read more
> about [Consensus Decision-Making](https://thedecider.app/consensus-decision-making)
> approach and the process itself, its pros and cons and how to avoid common pitfalls. There is a more detailed
> guide to [Consent Decision-Making](https://patterns.sociocracy30.org/consent-decision-making.html) for 👮Project
> Steward, the facilitators of the decision-making process.
**If consensus still cannot be reached**, the 👮Project Steward may change
the [decision-making model][decision-making-models] even continue with [rough consensus][rough-consensus] to resolve
a deadlock in the process that has not achieved absolute consensus, as described below (borrowed from the
[IETF][rfc2418]):
> Working groups make decisions through a "rough consensus" process. **💫Grewety** consensus does not require
> that all participants agree although this is, of course, preferred. In general, the dominant view of the working
> group, e.g. 🤩USC and 💎TEC for RFCs, shall prevail. (However, "dominance" is not to be determined on the basis of
> volume or persistence, but rather a more general sense of agreement). Consensus can be determined by a show of hands,
> humming, or any other means on which the working group agrees (by rough consensus, of course). Note that working
> group of the TSC does not qualify as "rough consensus" and 99% is better than rough. It is up to the 👮Project Steward
> to determine if rough consensus has been reached.
## Voting
Certain project decisions (like governance changes and membership nominations) require a vote. Below are the changes
that require a vote, and the rules that govern that vote.
The 👮Project Steward may initiate a vote for any unlisted project decision.
[General Voting Rules](#general-voting-rules) will apply, along with any addition rules provided at the 👮Project
Steward's discretion. If this unlisted project decision is expected to be repeated in the future, voting rules
should be agreed on and then added to this document.
### General Voting Rules
- Members may abstain from any vote.
- Members who do not vote within 3 days will automatically abstain.
- 👮Project Stewards may reduce the 3 days automatic abstain for urgent decisions.
- 👮Project Stewards reserve the right to veto approval with a publicly disclosed reason.
### Voting: New 🥈Maintainer
> 💡 **Note**: This process kicks off once a valid nomination has been made.
> See [Nomination Process to a Maintainer](#nomination-process-to-maintainer) above for more
> details on nomination.
> ⚖️ **Who can vote:** Any 🥈Maintainer, 🥇Core Member can participate in the vote thread after a valid nomination has
> been made.
1. Once a vote thread is created, existing 🥈Maintainers, 🥇Core Member and 👮Project Stewards can discuss the nomination
in private.
2. The normal 3 day voting & discussion window begins with the thread creation.
3. Voting can be done in the thread (visible to other voters) or in a private DM to the 👮Project Stewards.
4. Once the vote is complete, the thread is deleted.
5. The vote must receive an overwhelming majority (70%+) to pass.
6. **If the vote passes**: the nominee will be made a 🥈Maintainer and all privileges will be made available to them.
7. **If the vote fails**: the 👮Project Steward is responsible for informing the nominee with constructive, actionable
feedback.
> 💡 **Note**: This is not required if the nominee was not made aware of their nomination.
### Voting: New 🥇Core Member
> 💡 **Note**: This process kicks off once a valid nomination has been made.
> See [Nomination Process to a Core Member](#nomination-process-to-core-member) above for more details on
> nomination.
> ⚖️ **Who can vote:** Any 🥇Core Member can participate in the vote thread after a valid nomination has been made.
1. Once a vote thread is created, existing 🥇Core Members can discuss the nomination in private.
2. The normal 3 day voting & discussion window begins with the thread creation.
3. Voting can be done in the thread (visible to other voters) or in a private DM to the 👮Project Stewards.
4. Once the vote is complete, the thread is deleted.
5. The vote must receive an overwhelming majority (70%+) to pass.
6. **If the vote passes**: the nominee will be made a 🥇Core Member and all privileges will be made available to them.
7. **If the vote fails**: the 👮Project Stewards is responsible for informing the nominee with constructive, actionable
feedback.
> 💡 **Note**: This is not required if the nominee was not made aware of their nomination.
### Voting: Governance Change
A vote is initiated once a pull request (PR) to the `GOVERNANCE.md` file is submitted by a 🥇Core Member.
If the pull request (PR) submitter is not a 🥇Core Member, the pull request (PR) can be closed by any 🥈Maintainer
without a vote. However, any 🥇Core Member may request a vote on that pull request (PR), in which case a vote is
initiated.
> ⚖️ **Who can vote:** Any 🥇Core Member.
> 💡 **Note**: All 🥈Maintainers are encouraged to discuss and voice their opinion in the
> pull request (PR) discussion. 🥇Core Members should take the opinions of 🥈Maintainers into consideration when voting.
1. The pull request discussion thread is used to discuss the Governance Change.
2. The normal 3 day voting & discussion window begins with either the pull request (PR) creation or the removal of
`WIP:` from the pull request (PR) title if the pull request (PR) was created as a draft.
3. Voting can be done in the pull request via a review of either **Approve (For)** or **Change Requested (Against)**.
4. The vote must receive a simple majority (50%+) to pass.
5. **If the vote passes**: the pull request (PR) is merged and the changes take effect immediately.
6. **If the vote fails**: the pull request (PR) is closed and no change occurs.
### Voting: Request for Change (RFC) Proposals
Introduction of new features, removal or incompatible change of existing features in **💫Grewety** are discussed using a
model called [Consensus-seeking decision-making][consensus-seeking]. This model attempts to achieve consensus on all
significant changes to **💫Grewety**, but has a fallback voting procedure in place if consensus appears unattainable.
> ⚖️ **Who can vote:** All [🤩USC](#user-satisfaction-committee-usc) and [💎TEC](#technical-excellence-committee-tec)
> members.
1. Anyone can submit an RFC to suggest changes to **💫Grewety**.
2. Scope of change: trivial changes and obvious improvements
- A _trivial_ technical change can be discussed and approved entirely within the RFC GitHub issue, as long as
there are no objections from 💎TEC members. This is not considered a formal vote.
- An _obvious_ improvement of the user satisfaction can be discussed and approved entirely with the RFC GitHub, as
long as there are objections from 🤩USC members.
3. A non-trivial, significant change should be discussed within the RFC and **approved during an RFC meeting call**. In
some cases, an RFC may be approved outside an RFC meeting using pull request (PR) reviews as a proxy for votes.
4. During an RFC meeting, the person leading the call will attempt to achieve a [decision](#decision-making-process)
on the RFC proposal.
5. **If consensus is reached**: the RFC is approved.
6. **If consensus is not reached**: The RFC author, the 🤩USC and 💎TEC members must make all reasonable attempts to
resolve issues and reach a decision in GitHub or a follow-up RFC meeting. The process of reaching can take time, and
should not be rushed as long as all participants are making a reasonable effort to respond.
7. **If consensus still cannot be reached**: The 👮Project Steward may invoke [rough consensus][rough-consensus] or
choose any [other decision-making model](#decision-making-process) to resolve an RFC that has not achieved absolute
consensus.
## Moderation
Outlined below is the process for [Code of Conduct][coc] violation reviews.
### Reporting
Anyone may report a [Code of Conduct][coc] violation. Violations can be reported in the following ways:
- In private, via email to one or more 👮Project Stewards.
- In private, via direct message to a 👮Project Steward on [Discord][discord].
- In public, via a GitHub comment (mentioning `grewety/@maintainers`).
- In public, via the project [Discord][discord] server (mentioning `@steward`).
### Who gets involved?
Each report will be assigned reviewers. These will initially be all project 👮Project Stewards.
In the event of any conflict of interest - in example if 👮Project Stewards who are personally connected to a
situation, they must immediately recuse themselves.
At request of the reporter and if deemed appropriate by the reviewers, another neutral third-party may be involved in
the review and decision process.
### Review
If a report doesn't contain enough information, the reviewers will strive to obtain all relevant data before acting.
The reviewers will then review the incident and determine, to the best of their ability:
- What happened.
- Whether this event constitutes a [Code of Conduct][coc] violation.
- Who, if anyone, was involved in the violation.
- Whether this is an ongoing situation.
The reviewers should aim to have a resolution agreed very rapidly; if not agreed within a week, they will inform the
parties of the planned date.
### Resolution
Responses will be determined by the reviewers on the basis of the information gathered and of the potential
consequences. It may include:
- Taking no further action.
- Issuing a reprimand (private or public).
- Asking for an apology (private or public).
- Permanent ban from the GitHub org and [Discord][discord] server.
- Revoked contributor status.
---
👏 Inspired by https://github.com/withastro/.github/blob/main/GOVERNANCE.md.
[coc]: CODE_OF_CONDUCT.md
[github]: https://github.com/grewety
[npmjs]: (https://www.npmjs.com/package/grewety)
[discord]: https://discord.gg/yCzTBrbb6Y
[rbo]: https://github.com/RaphaelBossek
[kudo]: https://medium.com/@milecard195/kudo-cards-generating-a-culture-of-recognition-and-gratitude-in-teams-f123cdd9934b
[rfc2418]: https://www.rfc-editor.org/rfc/inline-errata/rfc2418.html
[consensus-seeking]: https://en.wikipedia.org/wiki/Consensus-seeking_decision-making
[rough-consensus]: https://en.wikipedia.org/wiki/Rough_consensus
[decision-making-models]: https://thedecider.app/side-by-side-comparison
|
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:firebase_project_2/prototype_1_lib/lib/screens/detailed_screen/tabs/basic_info_screen/update_soldier_details_screen.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:firebase_project_2/prototype_1_lib/lib/user_models/user_details.dart';
import 'package:firebase_project_2/prototype_1_lib/lib/screens/detailed_screen/util/soldier_detailed_screen_info_template.dart';
// ignore: must_be_immutable
class BasicInfoTab extends StatefulWidget {
BasicInfoTab(
{super.key,
required this.docID,
required this.callback,
required this.isToggled});
final String docID;
late Function callback;
final bool isToggled;
@override
State<BasicInfoTab> createState() => _BasicInfoTabState();
}
class _BasicInfoTabState extends State<BasicInfoTab> {
Future deleteUserAccount() async {
deleteAttendance();
deleteStatuses();
deleteCurrentUser();
Navigator.pop(context);
}
Future deleteStatuses() async {
var collection = FirebaseFirestore.instance
.collection("Users")
.doc(widget.docID)
.collection('Statuses');
var snapshots = await collection.get();
for (var doc in snapshots.docs) {
await doc.reference.delete();
}
}
Future deleteAttendance() async {
var collection = FirebaseFirestore.instance
.collection("Users")
.doc(widget.docID)
.collection('Attendance');
var snapshots = await collection.get();
for (var doc in snapshots.docs) {
await doc.reference.delete();
}
}
Future deleteCurrentUser() async {
FirebaseFirestore.instance.collection("Users").doc(widget.docID).delete();
}
@override
Widget build(BuildContext context) {
final userDetailsModel = Provider.of<UserData>(context);
return SingleChildScrollView(
child: SizedBox(
height: 750.h,
child: StreamBuilder(
stream: userDetailsModel.userData_data(widget.docID),
builder: (context, snapshot) {
if (snapshot.hasData) {
//We are trying to map the key and values pairs
//to a variable called "data" of Type Map
Map<String, dynamic> data =
snapshot.data!.data() as Map<String, dynamic>;
return Column(
children: [
SoldierDetailedInfoTemplate(
title: "Date Of Birth",
content: data['dob'].toString().toUpperCase(),
icon: Icons.cake_rounded,
isToggled: widget.isToggled,
),
SoldierDetailedInfoTemplate(
title: "Ration Type:",
content: data['rationType'].toUpperCase(),
icon: Icons.food_bank_rounded,
isToggled: widget.isToggled,
),
SoldierDetailedInfoTemplate(
title: "Blood Type:",
content: data['bloodgroup'].toString(),
icon: Icons.bloodtype_rounded,
isToggled: widget.isToggled,
),
SoldierDetailedInfoTemplate(
title: "Enlistment Date:",
content: data['enlistment'].toString().toUpperCase(),
icon: Icons.date_range_rounded,
isToggled: widget.isToggled,
),
SoldierDetailedInfoTemplate(
title: "ORD:",
content: data['ord'].toString().toUpperCase(),
icon: Icons.military_tech_rounded,
isToggled: widget.isToggled,
),
SizedBox(
height: 30.h,
),
Center(
child: TextButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => UpdateSoldierDetailsPage(
docID: widget.docID,
name: TextEditingController(text: data['name']),
company: TextEditingController(
text: data['company']),
platoon: TextEditingController(
text: data['platoon']),
section: TextEditingController(
text: data['section']),
appointment: TextEditingController(
text: data['appointment']),
dob: data['dob'],
ord: data['ord'],
enlistment: data['enlistment'],
selectedItem: data['rationType'],
selectedRank: data['rank'],
selectedBloodType: data['bloodgroup'],
callback: widget.callback,
isToggled: widget.isToggled),
),
).then((value) => widget.callback);
},
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 40.0.w, vertical: 16.0.h),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
gradient: const LinearGradient(
colors: [
Color.fromARGB(255, 72, 30, 229),
Color.fromARGB(255, 130, 60, 229),
],
),
borderRadius: BorderRadius.circular(50.0.r)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.edit_document,
color: Colors.white,
),
SizedBox(
width: 20.w,
),
Text(
"EDIT SOLDIER DETAILS",
style: GoogleFonts.poppins(
fontSize: 18.sp,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
),
),
),
SizedBox(
height: 20.h,
),
Center(
child: TextButton(
onPressed: () async {
await deleteUserAccount();
},
child: Container(
padding: EdgeInsets.symmetric(
horizontal: 30.0.w, vertical: 16.0.h),
decoration: BoxDecoration(
shape: BoxShape.rectangle,
gradient: const LinearGradient(
colors: [
Colors.red,
Color.fromARGB(255, 237, 131, 124)
],
),
borderRadius: BorderRadius.circular(50.0.r)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.delete,
color: Colors.white,
),
SizedBox(
width: 20.w,
),
Text(
"DELETE SOLDIER DETAILS",
style: GoogleFonts.poppins(
fontSize: 18.sp,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
SizedBox(
height: 30.h,
)
],
),
),
),
),
],
);
}
return const Text('Loading......');
},
),
),
);
}
}
|
<?php
namespace App\Http\Controllers;
use Session;
use Auth;
use Illuminate\Http\Request;
class ProfilesController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('admin.users.profile')->with('user', Auth::user());
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request)
{
// Take care of the avatar image
$this->validate($request, [
'name' => 'required',
'email' => 'required|email',
'facebook' => 'required|url',
'youtube' => 'required|url'
]);
$user=Auth::user();
if($request->hasFile('avatar')){
$avatar = $request->avatar;
$avatar_new_name=time().$avatar->getClientOrignalName();
$avatar->move('uploads/avatar', $avatar_new_name);
$user->profile->avatar = 'uploads/avatar' .$avatar_new_name;
$user->profile->save();
}
// Profile details
$user->name = $request->name;
$user->email = $request->email;
$user->profile->facebook = $request->facebook;
$user->profile->youtube = $request->youtube;
$user->save();
$user->profile->save();
// Password
if($request->has('password')){
$user->password = bcrypt($request->password);
}
Session::flash('success', 'Your Profile has been successfully update!');
return redirect()->back();
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
|
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Observable, map, tap } from 'rxjs';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { TodoStore } from '../+state/todo.store';
import { Todo } from '../todo';
@Component({
selector: 'nx-crud-todo-details',
standalone: true,
imports: [CommonModule],
template: `
<p>todo-details works!</p>
ID is: {{id$ | async}}
{{todo$ | async | json}}
`,
styles: [
`
:host {
display: block;
}
`,
],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [TodoStore]
})
export class TodoDetailsComponent {
public readonly id$: Observable<string> = this.route.paramMap.pipe(
map((params: ParamMap) => params.get('id') || ''),
tap((id: string) => this.store.setActiveTodo(parseInt(id)))
);
public readonly todo$: Observable<Todo | undefined> = this.store.activeTodo$;
constructor(private readonly route: ActivatedRoute, private store: TodoStore){}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.