text
stringlengths 184
4.48M
|
|---|
import axios from "axios";
import React, { useEffect, useState } from "react";
import PrescriptionPrev from "../../../components/Models/PrescriptionPrev";
import WritePrescription from "../../../components/Models/WritePrescription";
import spinner from "../../../assets/images/spinning-dots.svg";
import toast from "react-hot-toast";
import PatientDetail from "../../../components/Models/PatientDetail";
import { useDispatch, useSelector } from "react-redux";
import { addPrescription, fetchPatients } from "../../../stor/slices/patients";
import { readDrProfile } from "../../../stor/slices/doctor";
const initialState = {
presDate: "",
prescription: "",
};
export default function DoctorPatients() {
const [patient, setPatient] = useState({});
const [state, setState] = useState(initialState);
const [patientId, setPatientId] = useState("");
const [prescriptionData, setPrescriptionData] = useState([]);
const [Loading, setLoading] = useState(false);
const doctor = useSelector((state) => state.doctor.doctor.doctor);
console.log("๐ ~ DoctorPatients ~ doctor:", doctor)
const handleChange = (e) => {
setState({ ...state, [e.target.name]: e.target.value });
};
const dispatch = useDispatch();
// 665331fabcc678c95841456f
const { patients, isLoading } = useSelector((state) => state.patients);
console.log("๐ ~ DoctorPatients ~ patients:", patients);
useEffect(() => {
dispatch(fetchPatients());
}, [dispatch]);
useEffect(() => {
dispatch(readDrProfile());
}, []);
const handleAddPrescription = async () => {
const { presDate, prescription } = state;
const drName = doctor.firstName + doctor.lastName;
const prescriptionData = { drName, presDate, prescription, patientId };
try {
setLoading(true);
dispatch(addPrescription(prescriptionData));
dispatch(fetchPatients());
setState(initialState);
setLoading(false);
} catch (error) {
setLoading(false);
}
};
const handlePrescriptionPrev = (val) => {
const prescArray = val.prescriptions;
setPrescriptionData(prescArray);
};
const handlePrev = (doc) => {
setPatient(doc);
};
return (
<>
<div className="container">
<div className="row">
<div className="col-12">
<span className="fs-2 fw-medium"> Doctors </span>
</div>
</div>
{isLoading ? (
<div className="row">
<div className="col-6 mx-auto ">
<img src={spinner} alt=".." />
</div>
</div>
) : (
<div className="row my-3 cart">
<div className="col-12">
<div className="table-responsive border">
<table className="table table-hover align-middle ">
<thead className="table-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Age</th>
<th scope="col">CNIC</th>
<th scope="col">Phone Number</th>
<th scope="col">DR</th>
<th scope="col">Details</th>
<th scope="col">prescriptions</th>
</tr>
</thead>
<tbody>
{patients.map((doc, i) => {
if(doc.drId===doctor.userId)
return (
<tr key={i}>
<th scope="row">{i + 1}</th>
<td>
{doc.firstName} {doc.lastName}
</td>
<td>{doc.age} year</td>
<td>{doc.patientCNIC}</td>
<td>{doc.phoneNumber}</td>
<td>{doc.drName}</td>
<td>
<i
class="fa-solid fa-eye fs-4 m-2"
data-bs-toggle="modal"
data-bs-target="#patientDetailModal"
onClick={() => handlePrev(doc)}
></i>
</td>
<td>
<div>
<button
type="button"
class="btn btn-sm btn-warning text-white m-2"
data-bs-toggle="modal"
data-bs-target="#prescriptionModal"
onClick={() => handlePrescriptionPrev(doc)}
>
chack Prev
</button>
<button
type="button"
class="btn btn-sm btn-primary m-2"
data-bs-toggle="modal"
data-bs-target="#writePrescriptionModal"
onClick={() => setPatientId(doc._id)}
>
write Prev
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
)}
</div>
<PrescriptionPrev prescriptionData={prescriptionData} />
<WritePrescription
drName={"abc"}
onChange={handleChange}
state={state}
isLoading={Loading}
onClick={() => handleAddPrescription()}
/>
<PatientDetail doc={patient} />
</>
);
}
|
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { rootReducerType } from "../../redux/todos/actionTypes";
import { colorChanged, statusChanged } from "../../redux/filters/actions";
const Footer = () => {
const dispatch = useDispatch();
const todos = useSelector((state: rootReducerType) => state.todos);
const filters = useSelector((state: rootReducerType) => state.filters);
const remainingTask = todos?.filter((task) => !task.completed);
const handleStatusChange = (status: string) => {
dispatch(statusChanged(status));
};
const handleColorChange = (color: string) => {
if (filters.colors?.includes(color)) {
dispatch(colorChanged(color, "removed"));
} else {
dispatch(colorChanged(color, "added"));
}
};
return (
<div className="mt-4 flex justify-between text-xs text-gray-500">
{remainingTask.length > 0 ? (
<p>{remainingTask.length} tasks left</p>
) : (
<p>No task is left</p>
)}
<ul className="flex space-x-1 items-center text-xs">
<li
className={`cursor-pointer ${
filters?.status && filters?.status === "All" && " font-bold"
}`}
onClick={() => handleStatusChange("All")}
>
All
</li>
<li>|</li>
<li
className={`cursor-pointer ${
filters?.status && filters?.status === "Incomplete" && " font-bold"
}`}
onClick={() => handleStatusChange("Incomplete")}
>
Incomplete
</li>
<li>|</li>
<li
className={`cursor-pointer ${
filters?.status && filters?.status === "Completed" && " font-bold"
}`}
onClick={() => handleStatusChange("Completed")}
>
Complete
</li>
<li></li>
<li></li>
<li
className={`h-3 w-3 border-2 border-green-500 md:hover:bg-green-500 rounded-full cursor-pointer ${
filters.colors?.includes("green") && "bg-green-500"
}`}
onClick={() => handleColorChange("green")}
></li>
<li
className={`h-3 w-3 border-2 border-red-500 md:hover:bg-red-500 rounded-full cursor-pointer ${
filters.colors?.includes("red") && "bg-red-500"
}`}
onClick={() => handleColorChange("red")}
></li>
<li
className={`h-3 w-3 border-2 border-yellow-500 md:hover:bg-yellow-500 rounded-full cursor-pointer ${
filters.colors?.includes("yellow") && "bg-yellow-500"
}`}
onClick={() => handleColorChange("yellow")}
></li>
</ul>
</div>
);
};
export default Footer;
|
import * as endopoints from './utility/endpoints';
import { ConstructorStandingsList, ConstructorStandingsRootObject } from './models/constructor-standings-models';
import { DriverStandingsList, DriverStandingsRootObject } from './models/driver-standings-models';
import { Race, SeasonRootObject } from './models/season-models';
import { RaceStandingsRootObject, Result } from './models/race-models'
import { Logger } from './utility/logger';
import { SprintRaceRootObject, SprintResult } from './models/sprint-race-models';
import { QualifyingResult, QualifyingRootObject } from './models/qualifying-models';
export class Backend {
logger = new Logger();
constructor() {}
async getSessionSchedule(): Promise<Race[]> {
//todo: cache this value becasue it will unlikely change in the time
this.logger.log('log', 'Getting session schedule');
const response = await fetch(endopoints.seasonSchedule);
const data: SeasonRootObject = await response.json();
return data.MRData.RaceTable.Races;
}
async getDriverStandings(): Promise<DriverStandingsList[]> {
this.logger.log('log', 'Getting driver standings');
const response = await fetch(endopoints.driverStandings);
const data: DriverStandingsRootObject = await response.json();
return data.MRData.StandingsTable.StandingsLists;
}
async getConstructorStandings(): Promise<ConstructorStandingsList[]> {
this.logger.log('log', 'Getting constructor standings');
const response = await fetch(endopoints.constructorStandings);
const data: ConstructorStandingsRootObject = await response.json();
return data.MRData.StandingsTable.StandingsLists;
}
async getQualiResultsByYearAndRound(year: number, round: number): Promise<QualifyingResult[]> {
this.logger.log('log', 'Getting quali results for year ' + year + ' and round ' + round);
const url = endopoints.qualifying.replace(':year', year.toString()).replace(':round', round.toString());
this.logger.log('log', url);
const response = await fetch(url);
const data: QualifyingRootObject = await response.json();
return data.MRData.RaceTable.Races[0].QualifyingResults;
}
async getRaceResultsByYearAndRound(year: number, round: number): Promise<Result[]> {
this.logger.log('log', 'Getting race results for year ' + year + ' and round ' + round);
const url = endopoints.race.replace(':year', year.toString()).replace(':round', round.toString());
this.logger.log('log', url);
const response = await fetch(url);
const data: RaceStandingsRootObject = await response.json();
return data.MRData.RaceTable.Races[0].Results;
}
async getSprintRaceResultsByYearAndRound(year: number, round: number): Promise<SprintResult[]> {
this.logger.log('log', 'Getting sprint race results for year ' + year + ' and round ' + round);
const url = endopoints.sprintRace.replace(':year', year.toString()).replace(':round', round.toString());
this.logger.log('log', url);
const response = await fetch(url);
const data: SprintRaceRootObject = await response.json();
return data.MRData.RaceTable.Races[0].SprintResults;
}
}
|
๏ปฟusing System;
using System.Diagnostics;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace DistSysACW
{
// Dependancie injection example.
/*public interface ISomeService
{
void Hello(string message);
}
public class SomeService : ISomeService
{
public void Hello(string message)
{
Debug.WriteLine(message + "from my service");
}
}*/
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Models.UserContext>();
//services.AddTransient<ISomeService, SomeService>();
// Extra control over error messages.
services.AddMvc(options => {
options.AllowEmptyInputInBodyModelBinding = true;
options.Filters.Add(new Filters.AuthFilter());})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Added API Key middleware to the pipeline.
app.UseMiddleware<Middleware.AuthMiddleware>();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseMvc();
}
}
}
|
import React from 'react';
import { connect } from 'react-redux';
import { fetchBooks, toggleBookIsRead } from '../actions/MyBooksActions';
import Navbar from './Navbar';
import BookContainer from './BookContainer'
class App extends React.Component{
componentWillMount(){
this.props.dispatchFetchBooks();
}
render() {
const { searchString, books, isFetching, initSpinner, dispatchBookIsReadClick, displayAll } = this.props;
const spinnerStyle = { display: isFetching ? 'block' : 'none' };
return(
<div>
<Navbar displayAll={displayAll} />
<div style={spinnerStyle} className={`ibm-spinner-container ${initSpinner ? 'init-spin' : 'end-spin'}`}>
<div className="ibm-spinner">
<svg width="150" height="150" viewBox="-75 -75 150 150">
<circle cx="0" cy="0" r="37.5" />
</svg>
</div>
</div>
<BookContainer books={books} searchString={searchString} onBookIsReadClick={dispatchBookIsReadClick} displayAll={displayAll} />
</div>
);
}
}
const mapStateToProps = (state) => ({
books: state.myBooks.books,
isFetching: state.myBooks.isFetching,
initSpinner: state.myBooks.initSpinner,
searchString: state.navbar.searchString,
displayAll: state.navbar.displayAll
});
const mapDispatchToProps = (dispatch) => ({
dispatchFetchBooks: () => {
dispatch(fetchBooks());
},
dispatchBookIsReadClick: (id) => {
dispatch(toggleBookIsRead(id));
}
})
export default connect(mapStateToProps, mapDispatchToProps)(App);
// Replace <BookContainer line with this to test componentWillUnmount>
// {this.state.searchString === 'testunmount' ? <div></div> : <BookContainer searchString={this.state.searchString} />}
|
#ifndef TATOOINE_BLAS_BASE_H
#define TATOOINE_BLAS_BASE_H
#include <tatooine/concepts.h>
namespace tatooine {
template <arithmetic_or_complex Real, std::size_t... N>
struct tensor;
} // namespace tatooine
namespace tatooine::blas {
/// \defgroup blas BLAS
/// <table>
/// <tr><th>Name <th>Description</tr>
/// <tr><td>BD <td>bidiagonal matrix</tr>
/// <tr><td>DI <td>diagonal matrix</tr>
/// <tr><td>GB <td>general band matrix</tr>
/// <tr><td>GE <td>general matrix (i.e., unsymmetric, in some cases
/// rectangular)</tr> <tr><td>GG <td>general matrices, generalized problem
/// (i.e., a pair of general matrices)</tr> <tr><td>GT <td>general tridiagonal
/// matrix</tr> <tr><td>HB <td>(complex) Hermitian band matrix</tr> <tr><td>HE
/// <td>(complex) Hermitian matrix</tr> <tr><td>HG <td>upper Hessenberg matrix,
/// generalized problem (i.e. a Hessenberg and a triangular matrix)</tr>
/// <tr><td>HP <td>(complex) Hermitian, packed storage matrix</tr>
/// <tr><td>HS <td>upper Hessenberg matrix</tr>
/// <tr><td>OP <td>(real) orthogonal matrix, packed storage matrix</tr>
/// <tr><td>OR <td>(real) orthogonal matrix</tr>
/// <tr><td>PB <td>symmetric matrix or Hermitian matrix positive definite
/// band</tr> <tr><td>PO <td>symmetric matrix or Hermitian matrix positive
/// definite</tr> <tr><td>PP <td>symmetric matrix or Hermitian matrix positive
/// definite, packed storage matrix</tr> <tr><td>PT <td>symmetric matrix or
/// Hermitian matrix positive definite tridiagonal matrix</tr> <tr><td>SB
/// <td>(real) symmetric band matrix</tr> <tr><td>SP <td>symmetric, packed
/// storage matrix</tr> <tr><td>ST <td>(real) symmetric matrix tridiagonal
/// matrix</tr> <tr><td>SY <td>symmetric matrix</tr> <tr><td>TB <td>triangular
/// band matrix</tr> <tr><td>TG <td>triangular matrices, generalized problem
/// (i.e., a pair of triangular matrices)</tr> <tr><td>TP <td>triangular, packed
/// storage matrix</tr> <tr><td>TR <td>triangular matrix (or in some cases
/// quasi-triangular)</tr> <tr><td>TZ <td>trapezoidal matrix</tr> <tr><td>UN
/// <td>(complex) unitary matrix</tr> <tr><td>UP <td>(complex) unitary, packed
/// storage matrix</tr>
/// </table>
enum class op : char {
no_transpose = 'N',
transpose = 'T',
conjugate_transpose = 'C'
};
enum class uplo : char { upper = 'U', lower = 'L', general = 'G' };
enum class diag : char { non_unit = 'N', unit = 'U' };
enum class side : char { left = 'L', right = 'R' };
enum class format : char { lapack = 'L', tile = 'T' };
/// \defgroup blas1 BLAS Level 1
/// \brief Vector Operations
/// \ingroup blas
/// \defgroup blas2 BLAS Level 2
/// \brief Matrix-Vector Operations
/// \ingroup blas
/// \defgroup blas3 BLAS Level 3
/// \brief Matrix-Matrix Operations
/// \ingroup blas
} // namespace tatooine::blas
#endif
|
"use client"
import Select from "react-select";
import { useEffect, useState } from "react";
import { api } from "@/data/api";
const FormInfoBox = () => {
const catOptions = [
{ value: "Banking", label: "Banking" },
{ value: "Digital & Creative", label: "Digital & Creative" },
{ value: "Retail", label: "Retail" },
{ value: "Human Resources", label: "Human Resources" },
{ value: "Managemnet", label: "Managemnet" },
{ value: "Accounting & Finance", label: "Accounting & Finance" },
{ value: "Digital", label: "Digital" },
{ value: "Creative Art", label: "Creative Art" },
];
let jw='';
let id=0;
const userString = localStorage.getItem('user');
// console.log(userString);
if (userString) {
const user = JSON.parse(userString);
id = user.user.userId;
jw = user.jwt;
} else {
console.error("User data not found");
}
const [showToast,setShowToast] = useState(false)
const [isEditMode, setIsEditMode] = useState(true);
const info = {
email: '',
phoneNumber: '',
name: '',
title: '',
currentSalary: '',
expectedSalary: '',
experience: '',
age: '',
education:'',
language: '',
categories: null,
description: ''
}
const [information, setInformation] = useState(info);
const handleClick = async (e) => {
e.preventDefault();
try {
const apiUrl = api + 'jobseeker/update/' + id;
// console.log(jw);
const name= information.name;
const jobTitle = information.title;
const currentSalary = information.currentSalary;
const expectedSalary = information.expectedSalary;
const experience = information.experience;
const age = information.age;
const educationLevel = information.education;
const languages = information.language;
const jobCategory = information.categories.value;
const description = information.description;
console.log(information);
const response = await fetch(apiUrl, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${jw}`,
},
body: JSON.stringify({ name,jobTitle, currentSalary, expectedSalary, experience, age, educationLevel,languages, jobCategory, description }),
});
if (response.ok) {
const data = await response.json();
console.log('Data saved successfully:', data);
if (typeof window !== 'undefined') {
localStorage.setItem('info', JSON.stringify(data));
}
localStorage.setItem('info', JSON.stringify(data));
setIsEditMode(false);
setShowToast(true)
} else {
console.error('Data saving failed');
}
} catch (error) {
console.error('Error:', error);
}
}
const handleEditClick = async (e) => {
e.preventDefault();
setIsEditMode(true); // Switch to edit mode
try{
const info1 = localStorage.getItem('info');
const parsedInfo = JSON.parse(info1);
// const id = parsedInfo.jsId;
const apiUrl1 = api+"jobseeker/get/" + id;
const response = await fetch(apiUrl1, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${jw}`,
},
});
if (response.ok) {
const data = await response.json();
setInformation({
name: data.name,
title: data.jobTitle,
currentSalary: data.currentSalary,
expectedSalary: data.expectedSalary,
experience: data.experience,
age: data.age,
education: data.educationLevel,
language: data.languages,
categories: data.jobCategory,
description: data.description
});
} else {
console.log("Error fetching data:")
}
}
catch(error){
console.error('Error:', error);
}
};
const handleChange = (e) => {
setInformation({
...information,
[e.target.name]: e.target.value,
})
}
const handleChange2 = (selectedOption) => {
setInformation({
...information,
categories: selectedOption || null
});
};
useEffect(() => {
const getData = async () => {
try{
const user = JSON.parse(userString);
const id = user.jsId;
const apiUrl1 = api+"jobseeker/get/" + id;
const response = await fetch(apiUrl1, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${jw}`,
},
});
if (response.ok) {
const data = await response.json();
console.log(data);
setInformation({
name: data.name,
title: data.jobTitle,
currentSalary: data.currentSalary,
expectedSalary: data.expectedSalary,
experience: data.experience,
age: data.age,
education: data.educationLevel,
language: data.languages,
categories: data.jobCategory,
description: data.description
});
} else {
console.log("Error fetching data:")
}
}
catch(error){
console.error('Error:', error);
}
}
getData();
setIsEditMode(false);
},[]);
return (
<form className="default-form">
<div className="row">
<div className="form-group col-lg-6 col-md-12">
<label>Full Name</label>
<input type="text" name="name" placeholder="Jerome"
value={information.name}
onChange={handleChange}
disabled={!isEditMode}
required />
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-6 col-md-12">
<label>Job Title</label>
<input type="text" name="title" placeholder="UI Designer"
value={information.title}
onChange={handleChange}
disabled={!isEditMode}
required />
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-6 col-md-12">
<label>Phone</label>
<input
type="text"
name="phoneNumber"
placeholder="0 123 456 7890"
value={information.phoneNumber}
onChange={handleChange}
disabled={!isEditMode}
required
/>
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-6 col-md-12">
<label>Email address</label>
<input
type="text"
name="email"
placeholder="creativelayers"
value={information.email}
onChange={handleChange}
disabled={!isEditMode}
required
/>
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-3 col-md-12">
<label>Current Salary($)</label>
<input
type="number"
name="currentSalary"
placeholder="50"
value={information.currentSalary}
onChange={handleChange}
disabled={!isEditMode}
required
/>
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-3 col-md-12">
<label>Expected Salary($)</label>
<input
type="number"
name="expectedSalary"
placeholder="60"
value={information.expectedSalary}
onChange={handleChange}
disabled={!isEditMode}
required
/>
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-6 col-md-12">
<label>Experience</label>
<input type="number" name="experience" placeholder="5"
value={information.experience}
onChange={handleChange}
disabled={!isEditMode}
required />
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-6 col-md-12">
<label>Age</label>
<input type="number" defaultValue={20} min={18} name="age" placeholder="20"
value={information.age}
onChange={handleChange}
disabled={!isEditMode}
required />
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-6 col-md-12">
<label>Education Levels</label>
<input type="text" name="education" placeholder="Certificate"
value={information.education}
onChange={handleChange}
disabled={!isEditMode}
required />
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-6 col-md-12">
<label>Languages</label>
<input
type="text"
name="language"
placeholder="English, Turkish"
value={information.language}
onChange={handleChange}
disabled={!isEditMode}
required
/>
</div>
{/* <!-- Search Select --> */}
<div className="form-group col-lg-6 col-md-12">
<label>Categories </label>
<Select
defaultValue={[catOptions[1]]}
options={catOptions}
className="basic-multi-select"
classNamePrefix="select"
value={information.categories}
onChange={handleChange2}
disabled={!isEditMode}
required
/>
</div>
{/* <!-- About Company --> */}
<div className="form-group col-lg-12 col-md-12">
<label>Description</label>
<textarea placeholder="Spent several years working on sheep on Wall Street. Had moderate success investing in Yugo's on Wall Street. Managed a small team buying and selling Pogo sticks for farmers. Spent several years licensing licorice in West Palm Beach, FL. Developed several new methods for working it banjos in the aftermarket. Spent a weekend importing banjos in West Palm Beach, FL.In this position, the Software Engineer collaborates with Evention's Development team to continuously enhance our current software solutions as well as create new solutions to eliminate the back-office operations and management challenges present"
name="description"
value={information.description}
onChange={handleChange}
disabled={!isEditMode}
></textarea>
</div>
{/* <!-- Input --> */}
<div className="form-group col-lg-6 col-md-12">
{isEditMode ? (
<button className="theme-btn btn-style-one" onClick={handleClick}>
Save
</button>
) : (
<button className="btn btn-outline-primary btn-lg" onClick={handleEditClick}>
Edit
</button>
)}
</div>
</div>
<div
className={`toast position-fixed bottom-0 end-0 m-3 ${ showToast ? 'show' : ''}`}
role="alert"
aria-live="assertive"
aria-atomic="true"
style={{ backgroundColor: '#d6e9f7' }} // Set background color to light blue
>
<div className="toast-header" style={{ backgroundColor: '#d6e9f7' }}> {/* Set header background color to a lighter shade of blue */}
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-info-circle-fill" viewBox="0 0 16 16">
<path d="M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.93-9.412-1 4.705c-.07.34.029.533.304.533.194 0 .487-.07.686-.246l-.088.416c-.287.346-.92.598-1.465.598-.703 0-1.002-.422-.808-1.319l.738-3.468c.064-.293.006-.399-.287-.47l-.451-.081.082-.381 2.29-.287zM8 5.5a1 1 0 1 1 0-2 1 1 0 0 1 0 2"/>
</svg>
<strong className="me-auto">Notification</strong>
<button
type="button"
className="btn-close"
data-bs-dismiss="toast"
aria-label="Close"
onClick={() => setShowToast(false)}
></button>
</div>
<div className="toast-body">
Data saved Successfully.
</div>
</div>
</form>
);
};
export default FormInfoBox;
|
import React from 'react';
import { createDrawerNavigator } from '@react-navigation/drawer';
import FriendList from './FriendList'; // Import your FriendList component
import XboxScreen from './XboxScreen'; // Import your XboxScreen component
import MainScreen from './MainScreen'; // Import your MainScreen component
import Login from './Login'; // Import your Login component
import Register from './Register'; // Import your Register component
import AboutMyApp from './AboutMyApp'; // Import your AboutMyApp component
import PC_Games from './PC_Games'; // Import your PC_Games component
import OnboardingScreen from './OnboardingScreen'; // Import your OnboardingScreen component
const Drawer = createDrawerNavigator();
const DrawerNavigator = () => {
return (
<Drawer.Navigator
initialRouteName="MainScreen"
drawerContent={(props) => <CustomDrawerContent {...props} />}
>
<Drawer.Screen name="FriendList" component={FriendList} />
<Drawer.Screen name="XboxScreen" component={XboxScreen} />
<Drawer.Screen name="MainScreen" component={MainScreen} />
<Drawer.Screen name="Login" component={Login} />
<Drawer.Screen name="Register" component={Register} />
<Drawer.Screen name="AboutMyApp" component={AboutMyApp} />
<Drawer.Screen name="PC_Games" component={PC_Games} />
<Drawer.Screen name="Onboarding" component={OnboardingScreen} /> {/* Added OnboardingScreen */}
{/* Add more screens as needed */}
</Drawer.Navigator>
);
};
export default DrawerNavigator;
|
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="styles/styles.css">
<title>Ejercicio 1</title>
</head>
<body>
<h1>Ejercicio 1</h1>
{% if name %}
<h2>Nombre: {{ name }}</h2>
{% endif %}
{% if age %}
<h2>Edad: {{ age }}</h2>
{% endif %}
<form action="/calculate" method="post">
<h1>Calculo de compras</h1>
<h2>Ingresa tu nombre</h2>
<input
type="text"
name="name"
placeholder="Ingrese su nombre"
>
<h2>Ingresa tu edad</h2>
<input
type="text"
name="age"
placeholder="Ingrese su edad"
>
<h2>Ingrese la cantidad de tarros de pintura a comprar</h2>
<input
type="text"
name="paint"
placeholder="Ingrese la cantidad de tarros de pintura a comprar"
>
<button>Calcular</button>
</form>
{% if name and age and paint %}
{% if age < 18 %}
<h2>Total sin descuento: ${{ 9000 * paint }}</h2>
<h2>El descuento es: $0</h2>
<h2>El total a pagar es de: ${{ 9000 * paint }}</h2>
{% endif %}
{% if age >= 18 and age <= 30 %}
<h2>Total sin descuento: ${{ 9000 * paint }}</h2>
<h2>El descuento es de: ${{ 9000 * paint * 15 / 100 }}</h2>
<h2>El total a pagar es de: ${{ 9000 * paint - 9000 * paint * 15 / 100 }}</h2>
{% endif %}
{% if age > 30 %}
<h2>Total sin descuento: ${{ 9000 * paint }}</h2>
<h2>El descuento es de: ${{ 9000 * paint * 25 / 100 }}</h2>
<h2>El total a pagar es de: ${{ 9000 * paint - 9000 * paint * 25 / 100 }}</h2>
{% endif %}
{% endif %}
</body>
</html>
|
package com.example.recipehelper;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.material.snackbar.Snackbar;
import java.util.HashMap;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final String TAG = MainActivity.class.getSimpleName();
public static final String EXTRA_NEW_RECIPE = "com.example.recipehelper.MainActivity.extra.NEW_RECIPE";
public static final String EXTRA_RECIPE = "com.example.recipehelper.MainActivity.extra.RECIPE";
public static final String EXTRA_INGREDIENTS = "com.example.recipehelper.MainActivity.extra.INGREDIENTS";
public static final String EXTRA_STEPS = "com.example.recipehelper.MainActivity.extra.STEPS";
public static final String EXTRA_TIMERS = "com.example.recipehelper.MainActivity.extra.TIMERS";
public static final String EXTRA_PREP = "com.example.recipehelper.MainActivity.extra.PREP";
public static final String EXTRA_TYPE = "com.example.recipehelper.MainActivity.extra.TYPE";
private static final int REQUEST_NOTIFICATIONS = 0;
RecipeViewModel mRecipeViewModel;
RecipeListAdapter adapter;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakeDetector;
ActivityResultLauncher<Intent> mStartEditActivityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == RESULT_OK){
Intent intent = result.getData();
if(intent == null) return;
//get edited data
boolean isNewRecipe = intent.getBooleanExtra(EXTRA_NEW_RECIPE, true);
String recipe = intent.getStringExtra(EXTRA_RECIPE);
String ingredients = intent.getStringExtra(EXTRA_INGREDIENTS);
String steps = intent.getStringExtra(EXTRA_STEPS);
String timers = intent.getStringExtra(EXTRA_TIMERS);
int prepTime = intent.getIntExtra(EXTRA_PREP, 0);
int recipeType = intent.getIntExtra(EXTRA_TYPE, Recipe.RecipeType.UNSPECIFIED);
if(isNewRecipe) {
mRecipeViewModel.insert(new Recipe(recipe, ingredients, steps, timers, prepTime, recipeType));
Toast.makeText(MainActivity.this, getResources().getString(R.string.new_recipe_toast, recipe), Toast.LENGTH_SHORT).show();
} else {
mRecipeViewModel.changeIngredients(ingredients, recipe);
mRecipeViewModel.changeSteps(steps, recipe);
mRecipeViewModel.changeTimers(timers, recipe);
mRecipeViewModel.changePrepTime(prepTime, recipe);
mRecipeViewModel.changeRecipeType(recipeType, recipe);
Toast.makeText(MainActivity.this, getResources().getString(R.string.saved_recipe_toast, recipe), Toast.LENGTH_SHORT).show();
}
}
});
ActivityResultLauncher<Intent> mStartRecipeActivityForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == RESULT_OK){
Intent intent = result.getData();
if(intent == null) return;
//get edited data
}
});
@Override
protected void onStop() {
super.onStop();
if(mAccelerometer != null) {
mSensorManager.unregisterListener(mShakeDetector);
}
}
@Override
protected void onStart() {
super.onStart();
if(mAccelerometer != null) {
mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random random = new Random();
mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
RecyclerView recyclerView = findViewById(R.id.recipe_recycleview);
adapter = new RecipeListAdapter(this);
adapter.setOnItemClickListener((view, position) -> {
Log.d(TAG, "clicked: " + position);
//click to start new recipe
Recipe recipe = adapter.getRecipeAtPosition(position);
Intent intent = new Intent(MainActivity.this, StartRecipeActivity.class);
intent.putExtra(StartRecipeActivity.EXTRA_NOTIFICATION, false);
intent.putExtra(StartRecipeActivity.EXTRA_RECIPE, recipe.getRecipe());
intent.putExtra(StartRecipeActivity.EXTRA_INGREDIENTS, recipe.getIngredients());
intent.putExtra(StartRecipeActivity.EXTRA_STEPS, recipe.getSteps());
intent.putExtra(StartRecipeActivity.EXTRA_TIMERS, recipe.getTimers());
mStartRecipeActivityForResult.launch(intent);
});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecipeViewModel.getAllRecipes().observe(this, adapter::setRecipes);
ItemTouchHelper helper = new ItemTouchHelper(
new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
@Override
public boolean onMove(@NonNull RecyclerView recyclerView,
@NonNull RecyclerView.ViewHolder viewHolder,
@NonNull RecyclerView.ViewHolder target) {
return false;
}
@Override
public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder,
int direction) {
int position = viewHolder.getAdapterPosition();
//refreshes item to reappear
adapter.notifyItemRemoved(position);
adapter.notifyItemInserted(position);
Recipe recipe = adapter.getRecipeAtPosition(position);
//item swiped opens alert dialog for editing or deleting
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle(getResources().getString(R.string.edit_or_delete_dialog, recipe.getRecipe()));
if((getResources().getConfiguration().uiMode &
Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES){
alertDialogBuilder.setIcon(R.drawable.ic_action_edit_icon_dark);
} else {
alertDialogBuilder.setIcon(R.drawable.ic_action_edit_icon);
}
alertDialogBuilder.setPositiveButton(R.string.delete, (arg0, arg1) -> {
//delete
mRecipeViewModel.deleteRecipe(recipe);
Snackbar.make(findViewById(R.id.recipe_recycleview) , getResources().getString(R.string.delete_recipe_snackbar, recipe.getRecipe()), Snackbar.LENGTH_LONG)
.setAction(R.string.undo, view ->
mRecipeViewModel.insert(recipe)).show();
});
alertDialogBuilder.setNegativeButton(R.string.edit, (dialog, which) -> {
//edit
Intent intent = new Intent(MainActivity.this, EditRecipeActivity.class);
intent.putExtra(EditRecipeActivity.EXTRA_NEW_RECIPE, false);
intent.putExtra(EditRecipeActivity.EXTRA_RECIPE, recipe.getRecipe());
intent.putExtra(EditRecipeActivity.EXTRA_INGREDIENTS, recipe.getIngredients());
intent.putExtra(EditRecipeActivity.EXTRA_STEPS, recipe.getSteps());
intent.putExtra(EditRecipeActivity.EXTRA_TIMERS, recipe.getTimers());
intent.putExtra(EditRecipeActivity.EXTRA_PREP, recipe.getPrepTime());
intent.putExtra(EditRecipeActivity.EXTRA_TYPE, recipe.getRecipeType());
mStartEditActivityForResult.launch(intent);
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
helper.attachToRecyclerView(recyclerView);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if(mSensorManager != null) {
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
mShakeDetector = new ShakeDetector();
mShakeDetector.setOnShakeListener(() -> {
//on shake, get random recipe
Recipe recipe = adapter.getRecipeAtPosition(random.nextInt(adapter.getItemCount()));
Intent intent = new Intent(MainActivity.this, StartRecipeActivity.class);
intent.putExtra(StartRecipeActivity.EXTRA_NOTIFICATION, false);
intent.putExtra(StartRecipeActivity.EXTRA_RECIPE, recipe.getRecipe());
intent.putExtra(StartRecipeActivity.EXTRA_INGREDIENTS, recipe.getIngredients());
intent.putExtra(StartRecipeActivity.EXTRA_STEPS, recipe.getSteps());
intent.putExtra(StartRecipeActivity.EXTRA_TIMERS, recipe.getTimers());
mStartRecipeActivityForResult.launch(intent);
});
if(savedInstanceState == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.POST_NOTIFICATIONS)
== PackageManager.PERMISSION_DENIED) {
if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.POST_NOTIFICATIONS)){
Snackbar.make(findViewById(R.id.recipe_recycleview), R.string.notifs_on_request, Snackbar.LENGTH_LONG)
.setAction(R.string.ok, (view) -> {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, REQUEST_NOTIFICATIONS);
}).show();
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.POST_NOTIFICATIONS}, REQUEST_NOTIFICATIONS);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_add) {
createNewRecipePopup();
return true;
} else if (id == R.id.action_delete_all){
//delete all
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setTitle(R.string.delete_all_recipes_title);
if((getResources().getConfiguration().uiMode &
Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES){
alertDialogBuilder.setIcon(R.drawable.ic_action_warning_dark);
} else {
alertDialogBuilder.setIcon(R.drawable.ic_action_warning);
}
alertDialogBuilder.setMessage(R.string.delete_all_recipes_subtitle);
alertDialogBuilder.setPositiveButton(R.string.delete, (arg0, arg1) -> {
//delete
mRecipeViewModel.deleteAll();
Toast.makeText(MainActivity.this, R.string.all_recipes_deleted, Toast.LENGTH_SHORT).show();
});
alertDialogBuilder.setNegativeButton(R.string.cancel, (dialog, which) -> {});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
public void createNewRecipePopup() {
AlertDialog.Builder popupBuilder = new AlertDialog.Builder(MainActivity.this);
popupBuilder.setTitle(R.string.new_recipe_dialog_title);
View popupView = getLayoutInflater().inflate(R.layout.new_recipe_popup_layout, null);
EditText recipeEditText = popupView.findViewById(R.id.edit_text_recipe);
Button addRecipe = popupView.findViewById(R.id.apply_new_recipe_button);
Button cancel = popupView.findViewById(R.id.recipe_cancel_button);
popupBuilder.setView(popupView);
AlertDialog alertDialog = popupBuilder.create();
alertDialog.show();
addRecipe.setOnClickListener((view) -> {
if (!(recipeEditText.getText().toString().trim().equals(""))) {
Intent intent = new Intent(MainActivity.this, EditRecipeActivity.class);
intent.putExtra(EditRecipeActivity.EXTRA_NEW_RECIPE, true);
intent.putExtra(EditRecipeActivity.EXTRA_RECIPE, recipeEditText.getText().toString().trim());
mStartEditActivityForResult.launch(intent);
alertDialog.dismiss();
}
});
cancel.setOnClickListener((view) -> alertDialog.dismiss());
}
@RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
HashMap<String, Integer> perms = new HashMap<>();
switch(requestCode){
case REQUEST_NOTIFICATIONS:
perms.put(android.Manifest.permission.POST_NOTIFICATIONS, PackageManager.PERMISSION_GRANTED);
if(grantResults.length > 0){
for(int i = 0; i < permissions.length; i++){
perms.put(permissions[i], grantResults[i]);
}
if(perms.get(android.Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, R.string.notifications_enabled, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.notifications_disabled, Toast.LENGTH_SHORT).show();
}
}
break;
default:
break;
}
}
}
|
/*
@title: Demo of how test can be implemented
@authors: RhonyP, ManuelMG, DavidM
@date: 25-feb-12
@description: This is a demo for define how can be the test structure in JS using QUnit
*/
/// required because when bizagi is loaded also is loaded required libraries (jquery...)
bizagi.loader.then( function() {
/// This is the name of the set of tests. Should be the name of the class to test?
module("First Test");
/// a specific test, this can have many assertions in it,
/// first parameter is the descriptive name of the requirement
test("check", function() {
/// why use !! if this get the same result without that?
ok(!!bizagi.rendering.render, "bizagi loaded");
ok(!!$.ajax, "Jquery loaded");
});
test("load stub file base" , function(){
// Ajax load
expect(1);
/// stop current execution thread dont forget start at the end
stop();
/// Load file
$.ajax({
url : "jquery/editor/base/mocks/stub.renders.json.txt",
dataType : "text"
/// option 1 use then with callback for done and fail
}).then(function() {
//console.debug("THEN DONE");
}, function() {
//console.debug("THEN FAIL");
/// Option two use done and fail directly, this is better!
}).done(function(json) {
ok(true, "DONE Loaded stub.renders.json.txt");
start();
}).fail(function() {
start();
});
/// Required if the ajax doesn't load the file.
/// set to 1000ms for avoid false negatives, the load take about 20ms
setTimeout(function() {
start();
}, 1000);
});
/// A more realistic test
test("load stub file base" , function(){
// Ajax load
/// Expected assertions in the test
expect(3);
stop();
$.ajax({
url : "jquery/editor/base/mocks/stub.renders.json.txt",
dataType : "text"
}).done(function(json) {
ok(!!json, "File loaded successfuly");
json = JSON.parse(json);
start();
ok(json.renders !== undefined, "renders exists");
ok(json.renders.length == 29, "renders' length is 29");
});
setTimeout(function() {
start();
}, 1000);
});
});
|
import usePlacesAutocomplete, {
getGeocode,
getLatLng,
} from "use-places-autocomplete";
import { Col, Input, Row, Popover } from "antd";
import "./Map.scss";
import { useEffect } from "react";
const PlacesAutocomplete = ({
setPosition = () => {},
isShowDetail = true,
setAddress = () => {},
addressInitial = "",
}) => {
const {
ready,
value,
suggestions: { status, data },
setValue,
clearSuggestions,
} = usePlacesAutocomplete();
useEffect(() => {
if (addressInitial) {
setValue(addressInitial, false);
clearSuggestions();
}
}, [addressInitial]);
const handleSelect = async (address) => {
setValue(address, false);
setAddress(address);
clearSuggestions();
const results = await getGeocode({ address });
const { lat, lng } = getLatLng(results[0]);
setPosition({ lat, lng });
};
return (
<Col span={24}>
<Row>
<Popover
style={{ width: "100%" }}
content={
status === "OK" && (
<Col>
{data.map(({ place_id, description }) => {
return (
<Row
className="address-suggestion"
key={place_id}
onClick={() => handleSelect(description)}
>
{description}
</Row>
);
})}
</Col>
)
}
title="Title"
trigger="click"
open={status === "OK"}
placement="bottomLeft"
arrow={false}
>
<Input
style={{ width: "100%" }}
placeholder="Tรฌm kiแบฟm ฤแปa ฤiแปm mong muแปn tแบกi ฤรขy"
value={value}
disabled={!ready}
allowClear={true}
onChange={(e) => {
setValue(e?.target?.value);
if (!e.target.value || e.target.value.length === 0) {
setAddress("");
}
}}
/>
</Popover>
</Row>
{value && isShowDetail && (
<>
<Row style={{ paddingTop: 10, fontWeight: "bold" }}>
Thรดng tin chi tiแบฟt
</Row>
<Row>
<Col style={{ width: 120 }}>ฤแปa chแป:</Col>
<Col>{value}</Col>
</Row>
</>
)}
</Col>
);
};
export default PlacesAutocomplete;
|
# Main Command: Go 7
# Cubes by Guy Walker
# www.cr31.co.uk/logoarts
To New
# set default screen, pen and turtle values
ResetAll SetScreenSize [400 400] HideTurtle
SetSC Black SetPC Green SetPS 1 PenUp
End
To Init :Order
# global values
Make "Width 384
GlobalMake "Depth :Order # Cube depth
GlobalMake "Side :Width/(:Order+:Depth*0.4)
GlobalMake "OffsetX :Side+(:Side*((:Depth-1)*0.4))-(:Width/2)
GlobalMake "OffsetY :Side+(:Side*((:Depth-1)*0.35))-(:Width/2)
End
To Gridd :M :N
# return X Y screen position
Make "X (:M*:Side) + :OffSetX
Make "Y (:N*:Side) + :OffSetY
Output List :X :Y
End
To DrawGrid :Order :Depth
# draw M x N array of cubes
For (List "M 0 :Order-1) [
For (List "N 0 :Order-1) [
If 0 = Random :Order [
SetPos Gridd :M :N Cube :Side Wait 6] ] ]
End
To Cube :Side
# cube drawn from upper right front corner
Make "Col (List 63+Random 127 63+Random 127 63+Random 127)
SetPC White PenDown Left 90
Repeat 4 [Forward :Side Left 90]
FillPoly :Col Right 144
Repeat 2 [Forward :Side/2 Left 144 Forward :Side Left 36]
FillPoly Light :Col Right 126
Repeat 2 [Forward :Side Left 126 Forward :Side/2 Left 54]
FillPoly Dark :Col Right 180 PenUp
End
To FillPoly :Col
PenUp Left 45 Forward 4 FillZone SetPC :Col Fill
Back 4 Right 45 SetPC White PenDown
End
To Light :Hue
# output rgb list midway between :hue and white
Repeat 3 [
Make "Hue ButFirst LPut Int (255+(First :Hue))/2 :Hue]
Output :Hue
End
To Dark :Hue
# output rgb list midway between :hue and black
Repeat 3 [
Make "Hue ButFirst LPut Int (First :Hue)/2 :Hue]
Output :Hue
End
To Go :Order
New Init :Order
Repeat :Depth [
DrawGrid :Order RepCount
Make "OffsetX :OffsetX - (Cos 36) * :Side/2
Make "OffsetY :OffsetY - (Sin 36) * :Side/2 ]
End
|
const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const { Server } = require("socket.io");
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
io.on("connection", (socket) => {
console.log("connnected:", socket.id);
socket.on("send_message", (data) => {
socket.to(data.room).emit("receive_message", data);
});
socket.on("join_room", (roomID) => {
socket.join(roomID);
console.log(
`USER WITH ROOM ID: ${socket.id} IS JOINED THE ROOM: ${roomID}`
);
});
socket.on("disconnect", () => {
console.log("disconnected", socket.id);
});
});
server.listen(3001, () => {
console.log("SERVER IS RUNNING");
});
|
package com.example.stay_mate.service.partner;
import com.example.stay_mate.model.partner.Partner;
import com.example.stay_mate.repository.partner.PartnerRepository;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
public class PartnerService implements UserDetailsService {
private final PartnerRepository partnerRepository;
public PartnerService(PartnerRepository partnerRepository) {
this.partnerRepository = partnerRepository;
}
// @PreAuthorize("hasRole('ROLE_PARTNER')")
public void savePartner(Partner partner) {
partnerRepository.save(partner);
}
public List<Partner> findAllPartner() {
return partnerRepository.findAll();
}
public Partner getPartnerById(Integer id) {
return partnerRepository.findPartnerById(id);
}
public Partner getPartnerByEmail(String email) {
return partnerRepository.getPartnerByEmail(email);
}
public boolean isEmailAlreadyTaken(String email) {
return partnerRepository.existsByEmail(email);
}
@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return partnerRepository.findByEmail(email)
.orElseThrow(
() -> new UsernameNotFoundException(
String.format("User not found:" + email)
)
);
}
@Transactional
public void deletePartnerById(Integer id) {
partnerRepository.deletePartnerById(id);
}
public Partner findByEmail(String email) {
return partnerRepository.findByEmail(email).orElse(null);
}
}
|
//
// swift-algorithm
//
// Created by Misaka on 2023/8/17.
//
// ๆผ่ฝฆ
import Foundation
extension Solution {
/*
่ฝฆไธๆๅๆ capacity ไธช็ฉบๅบงไฝใ่ฝฆ ๅช่ฝ ๅไธไธชๆนๅ่ก้ฉถ๏ผไนๅฐฑๆฏ่ฏด๏ผไธๅ
่ฎธๆๅคดๆๆนๅๆนๅ๏ผ
็ปๅฎๆดๆฐ capacity ๅไธไธชๆฐ็ป trips , trip[i] = [numPassengersi, fromi, toi] ่กจ็คบ็ฌฌ i ๆฌกๆ
่กๆ numPassengersi ไนๅฎข๏ผๆฅไปไปฌๅๆพไปไปฌ็ไฝ็ฝฎๅๅซๆฏ fromi ๅ toi ใ่ฟไบไฝ็ฝฎๆฏไปๆฑฝ่ฝฆ็ๅๅงไฝ็ฝฎๅไธ็ๅ
ฌ้ๆฐใ
ๅฝไธไป
ๅฝไฝ ๅฏไปฅๅจๆๆ็ปๅฎ็่ก็จไธญๆฅ้ๆๆไนๅฎขๆถ๏ผ่ฟๅ true๏ผๅฆๅ่ฏท่ฟๅ falseใ
*/
func carPooling(_ trips: [[Int]], _ capacity: Int) -> Bool {
var stations = 0
for trip in trips {
let toStation = trip[2]
if toStation + 1 > stations {
stations = toStation + 1
}
}
var diff: [Int] = Array(repeating: 0, count: stations)
for trip in trips {
let val = trip[0] // ไนๅฎขๆฐ้
let i = trip[1] // ็ฌฌ trip[1] ็ซไนๅฎขไธ่ฝฆ
let j = trip[2] - 1 // ็ฌฌ trip[2] ็ซไนๅฎขๅทฒ็ปไธ่ฝฆ๏ผๅณไนๅฎขๅจ่ฝฆไธ็ๅบ้ดๆฏ [trip[1], trip[2] - 1]
diff[i] += val
if j + 1 < diff.count {
diff[j + 1] -= val
}
}
var curCapacity = 0
for i in 0 ..< diff.count {
curCapacity += diff[i]
if curCapacity > capacity {
return false
}
}
return true
}
}
|
import { Heading, Text, VStack } from "native-base";
import { api } from "../lib/axios";
import { Header } from "../components/Header";
import { Input } from "../components/Input";
import { Button } from "../components/Button";
import Logo from '../assets/logo.svg';
import { useState } from "react";
import { toast } from "../lib/toast";
export function New() {
const [title, setTitle] = useState('');
const [isLoading, setIsLoading] = useState(false);
async function handlePollCreate() {
if (!title.trim()) {
return toast.error('Informe um nome para o seu bolรฃo')
}
try {
setIsLoading(true);
await api.post('/polls', { title })
toast.success('Bolรฃo criado com sucesso!')
setTitle('');
} catch (error) {
console.log(error)
toast.error('Nรฃo foi possรญvel criar o bolรฃo')
} finally {
setIsLoading(false);
}
}
return (
<VStack flex="1" bgColor="gray.900">
<Header title="Criar novo bolรฃo" />
<VStack mt="8" mx="5" alignItems="center">
<Logo />
<Heading
fontFamily="heading"
color="white"
fontSize="xl"
my="8"
textAlign="center"
>
Crie seu prรณprio bolรฃo da copa{'\n'}e compartilhe entre amigos!
</Heading>
<Input
placeholder="Qual o nome do seu bolรฃo?"
mb="2"
onChangeText={setTitle}
value={title}
/>
<Button
title="CRIAR MEU BOLรO"
onPress={handlePollCreate}
isLoading={isLoading}
/>
<Text color="gray.200" fontSize="sm" textAlign="center" px="10" mt="4">
Apรณs criar seu bolรฃo, vocรช receberรก um cรณdigo รบnico
que poderรก usar para convidar outras pessoas.
</Text>
</VStack>
</VStack>
)
}
|
open! Core
open Hardcaml
open Hardcaml_risc_v
open Hardcaml_risc_v_hart
open Hardcaml_uart_controller
open Hardcaml_waveterm
open Opcode_helper
open! Bits
let debug = false
module Make (M : sig
type sim
val create_sim : string -> sim
val finalize_sim : sim -> unit
val test_and_registers : instructions:Bits.t list -> sim -> int * int list
val test : instructions:Bits.t list -> sim -> unit
end) =
struct
let create_sim = M.create_sim
let finalize_sim = M.finalize_sim
let test = M.test
let%expect_test "addi" =
(* TODO: Add qcheck tests for every opcode *)
let open Quickcheck.Generator in
let sim = create_sim "addi_qcheck" in
Quickcheck.test
~trials:100
(tuple4
(Int.gen_incl 1 31)
(Int.gen_incl 1 31)
(Int.gen_incl 1 2047)
(Int.gen_incl 1 2047))
~f:(fun (rd, rs1, rs1_initial, imm) ->
let _pc, registers =
M.test_and_registers
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:rs1 ~immediate:rs1_initial
; op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1 ~rd ~immediate:imm
]
sim
in
let result = List.nth_exn registers rd in
let expectation = rs1_initial + imm in
if result <> expectation
then
raise_s
[%message
"Failed"
(rd : int)
(rs1 : int)
(rs1_initial : int)
(imm : int)
(registers : int list)];
())
;;
let%expect_test "op_imm" =
let sim = create_sim "test_op_imm" in
test
~instructions:[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:550 ]
sim;
[%expect
{|
(4 (0 550 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
22600093 00 00 00 00 00 00 00 |}];
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Xor ~rs1:0 ~rd:1 ~immediate:0b0101
; op_imm ~funct3:Funct3.Op.Xor ~rs1:1 ~rd:1 ~immediate:0b1010
]
sim;
[%expect
{|
(8 (0 15 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
504093 a0c093 00 00 00 00 00 00 |}];
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:0b1111
; op_imm ~funct3:Funct3.Op.And ~rs1:1 ~rd:1 ~immediate:0b11
]
sim;
[%expect
{|
(8 (0 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
f00093 30f093 00 00 00 00 00 00 |}];
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:0b101010
; op_imm ~funct3:Funct3.Op.Or ~rs1:1 ~rd:1 ~immediate:0b010101
]
sim;
[%expect
{|
(8 (0 63 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
2a00093 150e093 00 00 00 00 00 00 |}];
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:0b1
; op_imm ~funct3:Funct3.Op.Sll ~rs1:1 ~rd:1 ~immediate:4
]
sim;
[%expect
{|
(8 (0 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
100093 409093 00 00 00 00 00 00 |}];
(* TODO: Test the negative cases *)
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:10
; op_imm ~funct3:Funct3.Op.Slt ~rs1:1 ~rd:2 ~immediate:5
; op_imm ~funct3:Funct3.Op.Slt ~rs1:1 ~rd:3 ~immediate:15
]
sim;
[%expect
{|
(12 (0 10 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
a00093 50a113 f0a193 00 00 00 00 00 |}];
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:10
; op_imm ~funct3:Funct3.Op.Sltu ~rs1:1 ~rd:2 ~immediate:5
; op_imm ~funct3:Funct3.Op.Sltu ~rs1:1 ~rd:3 ~immediate:15
]
sim;
[%expect
{|
(12 (0 10 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
a00093 50b113 f0b193 00 00 00 00 00 |}];
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:16
; op_imm ~funct3:Funct3.Op.Srl_or_sra ~rs1:1 ~rd:2 ~immediate:4
; op_imm ~funct3:Funct3.Op.Srl_or_sra ~rs1:1 ~rd:3 ~immediate:3
]
sim;
[%expect
{|
(12 (0 16 1 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
1000093 40d113 30d193 00 00 00 00 00 |}];
(* Test x0 is hardwired to zero. *)
test
~instructions:[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rd:0 ~rs1:0 ~immediate:0x500 ]
sim;
[%expect
{|
(4 (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
50000013 00 00 00 00 00 00 00 |}];
M.finalize_sim sim;
[%expect {| |}]
;;
let%expect_test "op_imm" =
let sim = create_sim "op" in
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:500
; op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:2 ~immediate:300
; op ~funct3:Funct3.Op.Add_or_sub ~rs1:1 ~rs2:2 ~rd:3 (* WRONG *) ~funct7:0
]
sim;
[%expect
{|
(12 (0 500 300 200 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
1f400093 12c00113 2081b3 00 00 00 00 00 |}];
M.finalize_sim sim;
[%expect {| |}]
;;
let%expect_test "branch" =
let sim = create_sim "branch" in
test
~instructions:
[ branch ~funct3:Funct3.Branch.Bne ~rs1:0 ~rs2:0 ~offset:200
; branch ~funct3:Funct3.Branch.Beq ~rs1:0 ~rs2:0 ~offset:500
]
sim;
[%expect
{|
(504 (0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
c001463 1e000a63 00 00 00 00 00 00 |}];
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:550
; branch ~funct3:Funct3.Branch.Beq ~rs1:0 ~rs2:1 ~offset:500
]
sim;
[%expect
{|
(8 (0 550 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
22600093 1e100a63 00 00 00 00 00 00 |}];
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:550
; branch ~funct3:Funct3.Branch.Bne ~rs1:0 ~rs2:1 ~offset:500
]
sim;
[%expect
{|
(504 (0 550 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
22600093 1e101a63 00 00 00 00 00 00 |}];
(* Expect the second branch to be taken *)
test
~instructions:
[ branch ~funct3:Funct3.Branch.Blt ~rs1:0 ~rs2:1 ~offset:50
; op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:100
; branch ~funct3:Funct3.Branch.Blt ~rs1:0 ~rs2:1 ~offset:250
]
sim;
[%expect
{|
(258 (0 100 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
2104963 6400093 e104d63 00 00 00 00 00 |}];
(* Expect the second branch to be taken *)
test
~instructions:
[ op_imm ~funct3:Funct3.Op.Add_or_sub ~rs1:0 ~rd:1 ~immediate:100
; branch ~funct3:Funct3.Branch.Bge ~rs1:0 ~rs2:1 ~offset:50
; branch ~funct3:Funct3.Branch.Bge ~rs1:1 ~rs2:0 ~offset:250
]
sim;
[%expect
{|
(258 (0 100 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
6400093 2105963 e00dd63 00 00 00 00 00 |}];
(* TODO: Test unsigned variants and negative numbers. *)
M.finalize_sim sim;
[%expect {| |}]
;;
end
module Cpu_with_no_io_controller =
Cpu.Make
(struct
let register_width = Register_width.B32
let num_registers = 32
end)
(struct
let num_bytes = 32
end)
(struct
let num_harts = 1
let include_io_controller = Io_controller_config.No_io_controller
end)
module With_manually_programmed_ram = Make (struct
type sim =
( Bits.t ref Cpu_with_no_io_controller.I.t
, Bits.t ref Cpu_with_no_io_controller.O.t )
Cyclesim.t
* Waveform.t
* string
let create_sim name : sim =
let module Sim =
Cyclesim.With_interface
(Cpu_with_no_io_controller.I)
(Cpu_with_no_io_controller.O)
in
let sim =
Sim.create
~config:Cyclesim.Config.trace_all
(Cpu_with_no_io_controller.create
(Scope.create ~auto_label_hierarchical_ports:true ~flatten_design:true ()))
in
let waveform, sim = Waveform.create sim in
sim, waveform, name
;;
let finalize_sim sim =
if debug
then (
let _, waveform, name = sim in
Waveform.Serialize.marshall waveform ("/tmp/" ^ name))
else ()
;;
let print_ram sim =
let ram = Cyclesim.lookup_mem sim "main_memory_bram" |> Option.value_exn in
Array.map ~f:(fun mut -> Bits.Mutable.to_bits mut |> Bits.to_int) ram
|> Array.iter ~f:(fun v -> printf "%02x " v);
printf "\n"
;;
let clear_registers ~(inputs : Bits.t ref Cpu_with_no_io_controller.I.t) sim =
inputs.clear := Bits.one 1;
Cyclesim.cycle sim;
Cyclesim.cycle sim;
inputs.clear := Bits.zero 1
;;
let test_and_registers ~instructions sim =
let sim, _, _ = sim in
(* Initialize the main memory to some known values for testing. *)
let initial_ram = Cyclesim.lookup_mem sim "main_memory_bram" |> Option.value_exn in
Array.iter
~f:(fun tgt -> Bits.Mutable.copy_bits ~src:(Bits.of_int ~width:8 0) ~dst:tgt)
initial_ram;
Array.iteri
~f:(fun index tgt ->
match List.nth instructions index with
| Some instruction -> Bits.Mutable.copy_bits ~src:instruction ~dst:tgt
| None -> ())
initial_ram;
let inputs : _ Cpu_with_no_io_controller.I.t = Cyclesim.inputs sim in
let _outputs_before : _ Cpu_with_no_io_controller.O.t =
Cyclesim.outputs ~clock_edge:Side.Before sim
in
let outputs : _ Cpu_with_no_io_controller.O.t = Cyclesim.outputs sim in
clear_registers ~inputs sim;
let rec loop_for cycles =
if cycles = 0
then ()
else (
Cyclesim.cycle sim;
loop_for (cycles - 1))
in
loop_for 50;
match outputs.registers with
| [ outputs ] ->
let outputs =
Cpu_with_no_io_controller.Registers.map ~f:(fun t -> Bits.to_int !t) outputs
in
outputs.pc, outputs.general
| _ -> raise_s [%message "BUG: Unexpected number of harts"]
;;
let test ~instructions sim =
let pc, registers = test_and_registers ~instructions sim in
print_s [%message "" ~_:(pc : int) ~_:(registers : int list)];
print_ram (fst3 sim)
;;
end)
let uart_config =
{ Hardcaml_uart_controller.Config.clock_frequency = 200
; baud_rate = 200
; include_parity_bit = true
; stop_bits = 1
}
;;
module Uart_tx = Uart_tx.Make (struct
let config = uart_config
end)
module Cpu_with_dma_memory =
Cpu.Make
(struct
let register_width = Register_width.B32
let num_registers = 32
end)
(struct
let num_bytes = 32
end)
(struct
let num_harts = 1
let include_io_controller = Io_controller_config.Uart_controller uart_config
end)
module With_transmitter = struct
module I = struct
type 'a t =
{ clock : 'a
; clear : 'a
; data_in_valid : 'a
; data_in : 'a [@bits 8]
}
[@@deriving sexp_of, hardcaml]
end
module O = struct
type 'a t = { registers : 'a Cpu_with_dma_memory.Registers.t list [@length 1] }
[@@deriving sexp_of, hardcaml]
end
let create scope { I.clock; clear; data_in_valid; data_in } =
let { Uart_tx.O.uart_tx; _ } =
Uart_tx.hierarchical
~instance:"tx"
scope
{ Uart_tx.I.clock; clear; data_in_valid; data_in }
in
let { Cpu_with_dma_memory.O.registers; _ } =
Cpu_with_dma_memory.hierarchical
~instance:"cpu"
scope
{ clock; clear; uart_rx = uart_tx }
in
{ O.registers }
;;
end
module With_dma_ram = Make (struct
type sim =
(Bits.t ref With_transmitter.I.t, Bits.t ref With_transmitter.O.t) Cyclesim.t
* Waveform.t
* string
let create_sim name : sim =
let module Sim = Cyclesim.With_interface (With_transmitter.I) (With_transmitter.O)
in
let sim =
Sim.create
~config:Cyclesim.Config.trace_all
(With_transmitter.create
(Scope.create ~auto_label_hierarchical_ports:true ~flatten_design:true ()))
in
let waveform, sim = Waveform.create sim in
sim, waveform, name
;;
let finalize_sim sim =
if debug
then (
let _, waveform, name = sim in
Waveform.Serialize.marshall waveform ("/tmp/dma_" ^ name))
else ()
;;
let print_ram sim =
let ram = Cyclesim.lookup_mem sim "main_memory_bram" |> Option.value_exn in
Array.map ~f:(fun mut -> Bits.Mutable.to_bits mut |> Bits.to_int) ram
|> Array.iter ~f:(fun v -> printf "%02x " v);
printf "\n"
;;
let clear_registers ~(inputs : Bits.t ref With_transmitter.I.t) sim =
inputs.clear := Bits.one 1;
Cyclesim.cycle sim;
inputs.clear := Bits.zero 1
;;
let send_bits sim whole_packet =
(* Send the message through byte by byte. Uart_tx will transmit a
* byte once every ~10 cycles (this is dependent on the number of stop
* bits and the parity bit. *)
let inputs : _ With_transmitter.I.t = Cyclesim.inputs sim in
let rec loop_for n =
if n = 0
then ()
else (
Cyclesim.cycle sim;
loop_for (n - 1))
in
List.iter
~f:(fun input ->
inputs.data_in_valid := vdd;
inputs.data_in := of_int ~width:8 input;
Cyclesim.cycle sim;
inputs.data_in_valid := of_int ~width:1 0;
(* TODO: Tighter loop *)
loop_for 20)
whole_packet
;;
let send_dma_message ~address ~packet sim =
(* TODO: Move this to a util section *)
let whole_packet = dma_packet ~address packet in
send_bits sim whole_packet
;;
let test_and_registers ~instructions sim =
let sim, _, _ = sim in
let inputs : _ With_transmitter.I.t = Cyclesim.inputs sim in
(* Initialize the main memory to some known values for testing. *)
let initial_ram = Cyclesim.lookup_mem sim "main_memory_bram" |> Option.value_exn in
Array.iter
~f:(fun tgt -> Bits.Mutable.copy_bits ~src:(Bits.of_int ~width:8 0) ~dst:tgt)
initial_ram;
(* Send a clear signal to initialize any CPU IO controller state back to
* default so we're ready to receive. *)
clear_registers ~inputs sim;
send_dma_message
~address:0
~packet:
(Bits.concat_lsb instructions
|> Bits.split_lsb ~part_width:8
|> List.map ~f:Bits.to_char
|> String.of_char_list)
sim;
send_bits sim clear_packet;
(* We need to wait for 256 cycles because that is how long the design
* holds the clear signal for. *)
Sequence.range 0 512 |> Sequence.iter ~f:(fun _ -> Cyclesim.cycle sim);
let _outputs_before : _ With_transmitter.O.t =
Cyclesim.outputs ~clock_edge:Side.Before sim
in
let outputs : _ With_transmitter.O.t = Cyclesim.outputs sim in
let rec loop_for cycles =
if cycles = 0
then ()
else (
Cyclesim.cycle sim;
loop_for (cycles - 1))
in
loop_for 50;
match outputs.registers with
| [ outputs ] ->
let outputs =
Cpu_with_dma_memory.Registers.map ~f:(fun t -> Bits.to_int !t) outputs
in
outputs.pc, outputs.general
| _ -> raise_s [%message "BUG: Unexpected number of harts"]
;;
let test ~instructions sim =
let pc, registers = test_and_registers ~instructions sim in
print_s [%message "" ~_:(pc : int) ~_:(registers : int list)];
print_ram (fst3 sim)
;;
end)
|
package storages
import (
"errors"
"sync"
log "github.com/sirupsen/logrus"
)
// MetricType ะพะฟัะตะดะตะปัะตั ัะธะฟ ะผะตััะธะบะธ: gauge ะธะปะธ counter
type MetricType string
const (
Gauge MetricType = "gauge"
Counter MetricType = "counter"
)
// MetricValue ั
ัะฐะฝะธั ะทะฝะฐัะตะฝะธะต ะผะตััะธะบะธ, ะบะพัะพัะพะต ะผะพะถะตั ะฑััั ะฟัะตะดััะฐะฒะปะตะฝะพ ะบะฐะบ float64 ะธะปะธ uint64
type MetricValue struct {
GaugeValue float64
CounterValue uint64
}
// MemStorage ััััะบัััะฐ ะดะปั ั
ัะฐะฝะตะฝะธั ะผะตััะธะบ
type MemStorage struct {
mu sync.RWMutex
metrics map[string]MetricValue
}
type Value interface {
GetValue() interface{}
}
type FloatValue float64
type UintValue uint64
func (f FloatValue) GetValue() interface{} {
return float64(f)
}
func (u UintValue) GetValue() interface{} {
return uint64(u)
}
// NewMemStorage ัะพะทะดะฐะตั ะฝะพะฒัะน ัะบะทะตะผะฟะปัั MemStorage
func NewMemStorage() *MemStorage {
return &MemStorage{
metrics: make(map[string]MetricValue),
}
}
// UpdateMetric ะพะฑะฝะพะฒะปัะตั ะผะตััะธะบั ะฒ ั
ัะฐะฝะธะปะธัะต
func (s *MemStorage) UpdateMetric(name string, mType MetricType, value MetricValue) error {
s.mu.Lock()
defer s.mu.Unlock()
switch mType {
case Gauge:
s.metrics[name] = value
case Counter:
if existing, ok := s.metrics[name]; ok {
value.CounterValue += existing.CounterValue
}
s.metrics[name] = value
default:
return errors.New("unknown metric type")
}
//log.Infof("Key: %s, value: %v\n", name, value)
return nil
}
// GetMetric ะฒะพะทะฒัะฐัะฐะตั ะผะตััะธะบั ะธะท ั
ัะฐะฝะธะปะธัะฐ
func (s *MemStorage) GetMetric(name string) (Value, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
metricValue, ok := s.metrics[name]
if metricValue.GaugeValue != 0 {
//log.Info(FloatValue(metricValue.GaugeValue))
return FloatValue(metricValue.GaugeValue), ok
} else if metricValue.CounterValue != 0 {
//log.Info(UintValue(metricValue.CounterValue))
return UintValue(metricValue.CounterValue), ok
} else {
log.Errorf("Key: %s, value: %v\n", name, metricValue)
return UintValue(0), false
}
}
// GetAllMetrics ะฒะพะทะฒัะฐัะฐะตั ัะฟะธัะพะบ ะฒัะตั
ะผะตััะธะบ ะธ ะทะฝะฐัะตะฝะธะน ะธะท ั
ัะฐะฝะธะปะธัะฐ
func (s *MemStorage) GetAllMetrics() (map[string]MetricValue, error) {
s.mu.RLock()
defer s.mu.RUnlock()
// ะกะพะทะดะฐะตะผ ะฝะพะฒัั ะผะฐะฟั ะดะปั ะฒะพะทะฒัะฐัะฐ ะทะฝะฐัะตะฝะธะน
metricsCopy := make(map[string]MetricValue, len(s.metrics))
for key, value := range s.metrics {
metricsCopy[key] = value
}
return metricsCopy, nil
}
|
// Copyright 2023 TikTok Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memory>
#include <vector>
#include "dpca-psi/dp_cardinality_psi.h"
#include "dpca-psi/network/io_base.h"
#include "ppam/mpc/aby/aby_protocol.h"
namespace privacy_go {
namespace ppam {
using json = nlohmann::json;
using IOBase = dpca_psi::IOBase;
class PrivacyMeasurement {
public:
PrivacyMeasurement() {
dpcpsi_op_ = std::make_shared<dpca_psi::DPCardinalityPSI>();
aby_op_ = std::make_shared<ppam::AbyProtocol>();
}
PrivacyMeasurement(const PrivacyMeasurement& other) = delete;
PrivacyMeasurement& operator=(const PrivacyMeasurement& other) = delete;
~PrivacyMeasurement() = default;
/**
* @brief initialize psi and mpc protocol
* @param params: parameter configuration for psi and mpc
* @param net: net io channel
* @return none
*/
void initialize(const json& params, const std::shared_ptr<IOBase>& net);
/**
* @brief privacy ad measurement
* @param tf: threshold value for measurement
* @param keys: ID, such as phone number or email
* @param features: feature, such as age, time or personal consumption
* @return measurement result
*/
double measurement(const double& tf, const std::vector<std::vector<std::string>>& keys,
const std::vector<std::vector<double>>& features);
/**
* @brief plain ad measurement, used for correctness verification
* @param tf: threshold value for measurement
* @param keys: ID, such as phone number or email
* @param features: feature, such as age, time or personal consumption
* @return measurement result
*/
double plain_measurement(const double& tf, const std::vector<std::vector<std::string>>& keys,
const std::vector<std::vector<double>>& features);
private:
std::shared_ptr<dpca_psi::DPCardinalityPSI> dpcpsi_op_ = nullptr;
std::shared_ptr<ppam::AbyProtocol> aby_op_ = nullptr;
};
} // namespace ppam
} // namespace privacy_go
|
package er1;
// classDataArray.java
// data items as class objects
// to run this program: C>java ClassDataApp
public class Estrutura
{
private Jogador[] a; // criando um atributo privado do tipo Jogador
private int nElems; /// criando um atributo privato para controlar a quantidade de elementos
public Estrutura(int max) // construtor da classe Estrutura
{
a = new Jogador[max]; // instanciando o objeto do tipo Jogador
nElems = 0; // atribuindo 0 a quantidade de elementos
}
//--------------------------------------------------------------
public boolean findAge(int searchAge)
{ // mรฉtodo para encontrar um jogador no array pela idade utilizando busca binรกria
int lowerBound = 0; //limite inferior
int upperBound = nElems-1; //limite superior (quantidade de elementos no vetor -1)
int curIn; //posiรงรฃo atual de busca
while(true)
{
curIn = (lowerBound + upperBound ) / 2; //define o "universo" da busca
if(a[curIn].getAge()==searchAge){ //verifica se o nome nesta posiรงรฃo comeรงa com a letra informada pelo usuรกrio
for (int i =curIn; a[i].getAge()==searchAge;i++){ //verifica a posiรงรฃo atual e as sucessoras enquanto comeรงar com a mesma letra
a[i].displayJogador(); //chama o mรฉtodo displayJogador para exibir as informaรงรตes da pessoa encontrada
if (i+1==nElems){ //verifica se estรก na รบtlima posiรงรฃo do array
break;} //caso esteja, sai da repetiรงรฃo, para evitar erro de Array out of Bounds (fora de alcanรงe)
}
if (curIn!=0){ //verifica se todas as posiรงรตes jรก foram varridas, pois se curIn for 0 ao decrementar 1 neste for vai dar erro
for (int i =curIn-1; a[i].getAge()==searchAge;i--){ //verifica a posiรงรฃo anterior e as antecessoras enquanto comeรงar com a mesma letra
a[i].displayJogador(); //chama o mรฉtodo displayPessoa para exibir as informaรงรตes da pessoa encontrada
if (i==0){ //verifica se estรก na primeira posiรงรฃo do array
break;}//caso esteja, sai da repetiรงรฃo, para evitar erro de Array out of Bounds (fora de alcanรงe)
}
}
return true;
}
else if(lowerBound > upperBound)
return false; // nรฃo pude encontra-lo
else // divide o range
{
if(a[curIn].getAge() < searchAge)
lowerBound = curIn + 1; // esta na metade de cima
else
upperBound = curIn - 1; // esta na metade de baixo
} // fim do else de divisรฃo de range
} // fim do while
} // fim do mรฉtodo de pesquisa binรกria()
//--------------------------------------------------------------
//--------------------------------------------------------------
public boolean findName(String searchName) // mรฉtodo para encontrar um jogador no array pelo nome utilizando busca linear
{
boolean encontrou=false;
for(int i=0; i<nElems;i++){
if(a[i].getName().equals(searchName)){ //verifica se o nome nesta posiรงรฃo รฉ igual ao parรขmetro passado
a[i].displayJogador(); //chama o mรฉtodo displayJogador para exibir as informaรงรตes da pessoa encontrada
encontrou=true;
}
}
return encontrou;
}
// fim do mรฉtodo de pesquisa linear ()
//--------------------------------------------------------------
public void insert(String nome, double altura, int idade) // mรฉtodo de inserรงรฃo ordenada!
{
int j;
for(j=0; j<nElems; j++) // localiza onde esse elemento se encaixa
if(a[j].getAge()> idade) // OBS: Usando aqui busca linear!!! Poderia ser binรกria!
break;
for(int k=nElems; k>j; k--) // move os elementos maiores uma posiรงรฃo p/ frente
a[k] = a[k-1];
a[j] = new Jogador(nome, altura, idade); // insere o elemento na posiรงรฃo necessรกria
nElems++; // incrementa a variavel de controle de tamanho
} // finaliza o mรฉtodo de inserรงรฃo
//--------------------------------------------------------------
public boolean delete(int searchAge) //esse metodo de exclusรฃo nรฃo era necessรกrio, porรฉm implementei.
{ //contem uma falha, por exempelo, se houver 2 ou mais jogadores com a mesma idade,
int lowerBound = 0; //ele deleta apenas o primeiro que for encontrado
int upperBound = nElems-1;
int curIn;
while(true)
{
curIn = (lowerBound + upperBound) / 2;
if(a[curIn].getAge()==searchAge){
if (curIn==nElems-1){ //verifica se esse elemento nรฃo รฉ o รบltimo do array
nElems--; //caso seja, apenas descondiera o รบltimo elemento, nรฃo traz os mais altos para "frente"
}
else{
for(int k=curIn; k<nElems; k++) // move os elementos uma posiรงรฃo pra tras
a[k] = a[k+1];
nElems--; // decrementa o tamanho
}
return true;
}
else if(lowerBound > upperBound)
return false; // nรฃo pude encontra-lo
else // divide o range
{
if(a[curIn].getAge() < searchAge)
lowerBound = curIn + 1; // esta na metade de cima
else
upperBound = curIn - 1; // esta na metade de baixo
} // fim do else de divisรฃo de range
} // fim do while
} // fim do mรฉtodo de remoรงรฃo utilizando busca binรกria()
//--------------------------------------------------------------
public void displayA() // mรฉtodo que exibe todo o conteรบdo do array
{
for(int j=0; j<nElems; j++)
a[j].displayJogador();
}
//--------------------------------------------------------------
} // end class Estrutura
|
import { environment } from './environments/environment';
import * as dayjs from 'dayjs';
const createHeading = (text: string) => {
const h2Tag = document.createElement('h2');
h2Tag.textContent = text;
return h2Tag;
};
const createStatsTable = (
redirects: Array<{ accessed: string; location: string }>
) => {
const tableElement = document.createElement('table');
const tableHeadingRow = document.createElement('tr');
tableHeadingRow.innerHTML = '<th>Accessed On</th><th>Location</th>';
tableElement.appendChild(tableHeadingRow);
redirects.forEach((redirect) => {
tableElement.appendChild(createStatsTableRow(redirect));
});
return tableElement;
};
const createStatsTableRow = (redirect: {
accessed: string;
location: string;
}) => {
const trElement = document.createElement('tr');
trElement.innerHTML = `<td>${dayjs(redirect.accessed).format(
'HH:mm:ss DD/MM/YYYY'
)}</td><td>${redirect.location}<td>`;
return trElement;
};
window.onload = () => {
const straplineElement = document.querySelector('.strapline');
const id = window.location.pathname.split('/')[2];
const shortUrlBtn = document.getElementById('shortUrlBtn');
const shortUrlId = document.getElementById('shortUrlId') as HTMLInputElement;
const menuBtn = document.querySelector('#menu:before');
const menuUl = document.getElementById('menu');
shortUrlBtn.addEventListener('click', () => {
const shortUrlValue = shortUrlId.value.trim();
window.location.href = `/stats/${shortUrlValue}`;
});
menuBtn.addEventListener('click', () => {
console.log('Menu');
});
fetch(`${environment.apiUrl}/${id}/stats`)
.then((response) => response.json())
.then((result) => {
console.log(result);
if (result.status === 'ok') {
straplineElement.appendChild(
createHeading(`Viewing stats for URL: ${id}`)
);
straplineElement.appendChild(createStatsTable(result.data.redirects));
} else {
straplineElement.appendChild(createHeading(result.message));
}
});
};
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.12;
// import "hardhat/console.sol";
import "../libraries/WriteOnce.sol";
contract ImmutableStorage {
/**
* @return The address the data is written to
*/
function storageLocation() internal view returns (address) {
// calculates the address of the contract created through the first create() call made by this contract
// see: https://ethereum.stackexchange.com/a/761
return
address(
uint160(
uint256(
keccak256(
abi.encodePacked(
bytes1(0xd6),
bytes1(0x94),
address(this),
bytes1(0x01) // contracts start with nonce 1 (EIP-161)
)
)
)
)
);
}
/**
* Stores `data` and validates that it's written to the expected storage location
* @param data to be written
*/
function writeImmutable(bytes memory data) internal {
bytes memory initCode = WriteOnce.creationCodeFor(data);
address createdAt;
// Deploy contract using create
assembly {
createdAt := create(0, add(initCode, 32), mload(initCode))
}
require(createdAt == storageLocation(), "Write failed");
}
/**
* Reads the code at the storage location as data
* @return data stored at the storage location
*/
function readImmutable() internal view returns (bytes memory) {
return WriteOnce.valueStoredAt(storageLocation());
}
}
|
import { Breadcrumb, SimpleCard } from 'components'
import { useDispatch, useSelector } from 'react-redux'
import { useNavigate, useParams } from 'react-router-dom'
import { editStudent } from './store/Student.action'
import { Button, Icon, Grid, MenuItem } from '@mui/material'
import { styled } from '@mui/system'
import { Span } from 'components/Typography'
import React, { useState } from 'react'
import { ValidatorForm, TextValidator } from 'react-material-ui-form-validator'
const TextField = styled(TextValidator)(() => ({
width: '100%',
marginBottom: '16px',
}))
const Container = styled('div')(({ theme }) => ({
margin: '30px',
[theme.breakpoints.down('sm')]: {
margin: '16px',
},
'& .breadcrumb': {
marginBottom: '30px',
[theme.breakpoints.down('sm')]: {
marginBottom: '16px',
},
},
}))
const EditStudent = () => {
const { id: StudentId } = useParams()
const Student = useSelector((state) =>
state.Student.entities.find(
(Student) => Student.id.toString() === StudentId.toString()
)
)
const dispatch = useDispatch()
const navigate = useNavigate()
const [fname, setFname] = useState(Student.fname)
const [lname, setLname] = useState(Student.lname)
const handleFname = (e) => setFname(e.target.value)
const handleLname = (e) => setLname(e.target.value)
const handleClick = (e) => {
e.preventDefault()
dispatch(
editStudent({
id: StudentId,
fname,
lname,
})
)
navigate('/Student')
}
return (
<Container>
<div className="breadcrumb">
<Breadcrumb
routeSegments={[
{ name: 'EditStudent', path: '/Student' },
{ name: 'Form' },
]}
/>
</div>
<SimpleCard title="Edit Form">
<ValidatorForm onSubmit={handleClick} onError={() => null}>
<Grid container spacing={6}>
<Grid item lg={6} md={6} sm={12} xs={12} sx={{ mt: 2 }}>
<TextField
type="text"
name="fname"
id="fnameInput"
onChange={handleFname}
value={fname}
validators={['required']}
label="Fname"
errorMessages={['this field is required']}
/>
<TextField
type="text"
name="lname"
id="lnameInput"
onChange={handleLname}
value={lname}
validators={['required']}
label="Lname"
errorMessages={['this field is required']}
/>
</Grid>
</Grid>
<Button type="submit" color="primary" variant="contained">
<Icon>send</Icon>
<Span sx={{ pl: 1, textTransform: 'capitalize' }}>
Save
</Span>
</Button>
</ValidatorForm>
</SimpleCard>
</Container>
)
}
export default EditStudent
|
## VBAๅบ็ก๏ผๅทฅไฝ่กจ๏ผWorksheet๏ผๆไฝ
**1. ๅๅปบๆฐๅทฅไฝ่กจ๏ผ**
```vba
Sub CreateNewWorksheet()
' ๅจๆดปๅจๅทฅไฝ็ฐฟไธญๅๅปบไธไธชๆฐๅทฅไฝ่กจ
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets.Add
ws.Name = "ๆฐๅทฅไฝ่กจ"
End Sub
```
่ฟไธช็คบไพไปฃ็ ๅจๆดปๅจๅทฅไฝ็ฐฟไธญๅๅปบไธไธชๆฐๅทฅไฝ่กจ๏ผๅนถๅฐๅ
ถๅฝๅไธบ "ๆฐๅทฅไฝ่กจ"ใ
**2. ้ๆฉๅทฅไฝ่กจ๏ผ**
```vba
Sub SelectWorksheet()
' ้ๆฉๆๅฎๅ็งฐ็ๅทฅไฝ่กจ
ThisWorkbook.Sheets("ๅทฅไฝ่กจ1").Select
End Sub
```
่ฟไธช็คบไพไปฃ็ ้ๆฉๆๅฎๅ็งฐ็ๅทฅไฝ่กจใ
**3. ๅคๅถๅทฅไฝ่กจ๏ผ**
```vba
Sub CopyWorksheet()
' ๅคๅถๆๅฎๅ็งฐ็ๅทฅไฝ่กจๅนถๅฐๅ
ถๆๅ
ฅๅฐๆซๅฐพ
ThisWorkbook.Sheets("ๅทฅไฝ่กจ1").Copy After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)
End Sub
```
่ฟไธช็คบไพไปฃ็ ๅคๅถๆๅฎๅ็งฐ็ๅทฅไฝ่กจๅนถๅฐๅ
ถๆๅ
ฅๅฐๆซๅฐพใ
**4. ๅ ้คๅทฅไฝ่กจ๏ผ**
```vba
Sub DeleteWorksheet()
' ๅ ้คๆๅฎๅ็งฐ็ๅทฅไฝ่กจ
Application.DisplayAlerts = False ' ็ฆ็จ่ญฆๅ
ThisWorkbook.Sheets("ๅทฅไฝ่กจ1").Delete
Application.DisplayAlerts = True ' ๅฏ็จ่ญฆๅ
End Sub
```
่ฟไธช็คบไพไปฃ็ ๅ ้คๆๅฎๅ็งฐ็ๅทฅไฝ่กจใๆณจๆ๏ผๆไปฌๅจๅ ้คๅทฅไฝ่กจไนๅ็ฆ็จไบ่ญฆๅใ
**5. ้ๅฝๅๅทฅไฝ่กจ๏ผ**
```vba
Sub RenameWorksheet()
' ้ๅฝๅๆๅฎๅ็งฐ็ๅทฅไฝ่กจ
ThisWorkbook.Sheets("ๅทฅไฝ่กจ1").Name = "ๆฐๅ็งฐ"
End Sub
```
่ฟไธช็คบไพไปฃ็ ้ๅฝๅๆๅฎๅ็งฐ็ๅทฅไฝ่กจใ
**6. ้่ๅๆพ็คบๅทฅไฝ่กจ๏ผ**
```vba
Sub HideAndUnhideWorksheet()
' ้่ๆๅฎๅ็งฐ็ๅทฅไฝ่กจ
ThisWorkbook.Sheets("ๅทฅไฝ่กจ1").Visible = xlSheetHidden
' ๆพ็คบๆๅฎๅ็งฐ็ๅทฅไฝ่กจ
ThisWorkbook.Sheets("ๅทฅไฝ่กจ1").Visible = xlSheetVisible
End Sub
```
่ฟไธช็คบไพไปฃ็ ๆผ็คบๅฆไฝ้่ๅๆพ็คบๆๅฎๅ็งฐ็ๅทฅไฝ่กจใ
**7. ๅพช็ฏ้ๅๅทฅไฝ่กจ๏ผ**
```vba
Sub LoopThroughWorksheets()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Sheets
' ๅจ่ฟ้ๅฏนๆฏไธชๅทฅไฝ่กจๆง่กๆไฝ
MsgBox "ๅทฅไฝ่กจๅ็งฐ๏ผ" & ws.Name
Next ws
End Sub
```
่ฟไธช็คบไพไปฃ็ ๅพช็ฏ้ๅๅทฅไฝ็ฐฟไธญ็ๆๆๅทฅไฝ่กจ๏ผๅนถๅฏนๆฏไธชๅทฅไฝ่กจๆง่กๆไฝใ
**8. ็งปๅจๅทฅไฝ่กจ๏ผ**
```
Sub MoveWorksheet()
' ๅฐๅฝๅๅทฅไฝ่กจ็งปๅฐๅทฅไฝ็ฐฟ็ๆซๅฐพ
Sheets("Sheet1").Move After:=Sheets(Sheets.Count)
End Sub
```
**9. ๅๅปบๆฐๅทฅไฝ็ฐฟๅนถๅคๅถๅทฅไฝ่กจ๏ผ**
```
Sub CreateAndCopyWorksheet()
' ๅๅปบไธไธชๆฐ็ๅทฅไฝ็ฐฟ
Dim NewWb As Workbook
Set NewWb = Workbooks.Add
' ๅคๅถๅฝๅๅทฅไฝ่กจๅฐๆฐๅทฅไฝ็ฐฟ
ThisWorkbook.Sheets("Sheet1").Copy Before:=NewWb.Sheets(1)
End Sub
```
่ฟไบ็คบไพไปฃ็ ๆผ็คบไบExcel VBAไธญๅธธ่ง็ๅทฅไฝ่กจๆไฝ๏ผๅ
ๆฌๅๅปบใ้ๆฉใๅคๅถใๅ ้คใ้ๅฝๅใ้่ๅๆพ็คบๅทฅไฝ่กจ๏ผไปฅๅๅพช็ฏ้ๅๅทฅไฝ่กจใๆจๅฏไปฅๆ นๆฎ้่ฆ่ชๅฎไน่ฟไบ็คบไพไปฃ็ ๏ผๅนถๅฐๅฎไปฌๅบ็จไบๆจ็Excel VBA้กน็ฎไธญใ
|
import { useState } from "react";
import { Col, Container, Row } from "react-bootstrap";
import {
XCircle,
DashCircle,
DashCircleFill,
PlusCircle,
PlusCircleFill,
} from "react-bootstrap-icons";
import Image from "react-bootstrap/Image";
import { CartService } from "../../../services/basketService";
import { Link } from "react-router-dom";
import ItemCardProps from "../../../interfaces/ItemCardProps";
import useHoverStates from "./AmountChangeHooks";
import ConfirmRemoveFromBasketModal from "../../common/ConfirmRemoveFromBasketModal";
import "../../../styles/components/basket.css";
import "../../../styles/components/adaptivity/basket-adaptivity.css";
const ItemCard = ({ item, onItemRemoved, onAmountChanged }: ItemCardProps) => {
const [amount, setAmount] = useState(item.amount);
const {
isMinusHovered,
isPlusHovered,
handleMinusMouseEnter,
handleMinusMouseLeave,
handlePlusMouseEnter,
handlePlusMouseLeave,
} = useHoverStates();
const [modalShow, setModalShow] = useState(false);
const amountChange = (operation: string) => {
if (operation === "+") {
const newAmount = amount + 1;
setAmount(newAmount);
CartService.updateCartItem(item.id, { amount: newAmount });
onAmountChanged(CartService.getTotalPrice());
} else if (operation === "-") {
const newAmount = amount - 1;
if (newAmount >= 1) {
setAmount(newAmount);
CartService.updateCartItem(item.id, { amount: newAmount });
onAmountChanged(CartService.getTotalPrice());
} else {
setModalShow(true);
}
}
};
const handleRemoveItem = () => {
onItemRemoved(item.id);
};
return (
<>
<ConfirmRemoveFromBasketModal
show={modalShow}
onHide={() => setModalShow(false)}
onRemove={() => onItemRemoved(item.id)}
/>
<Row className="text-center align-items-center" id="basket-row">
<Col
xs={5}
id="basket-item-name"
className="d-flex justify-content-start"
>
<Link
to={`/catalog/${item.id}`}
className="text-decoration-none text-black d-flex align-items-center"
onClick={() => window.scroll(0, 0)}
>
<Image
src={item.picture[0]}
alt={item.name}
className="basket-product-image"
/>
<span className="ms-4">{item.name}</span>
</Link>
</Col>
<Col
xs={1}
className="white_theme d-flex justify-content-center"
>
<div className="basket-storage">1</div>
</Col>
<Col xs={3} className="d-flex justify-content-center">
<span hidden id="basket-hidden-adaptivity">
ะัะปัะบัััั:
</span>
<Container
className="d-flex justify-content-between p-2 border rounded-pill align-items-center"
style={{ minWidth: "80px", width: "7rem" }}
>
{isMinusHovered ? (
<DashCircleFill
className="basket-btn-quantity"
onMouseLeave={handleMinusMouseLeave}
onClick={() => amountChange("-")}
/>
) : (
<DashCircle
className="basket-btn-quantity"
onMouseEnter={handleMinusMouseEnter}
/>
)}
<span>{amount}</span>
{isPlusHovered ? (
<PlusCircleFill
className="basket-btn-quantity"
onMouseLeave={handlePlusMouseLeave}
onClick={() => amountChange("+")}
/>
) : (
<PlusCircle
className="basket-btn-quantity"
onMouseEnter={handlePlusMouseEnter}
/>
)}
</Container>
</Col>
<div
hidden
id="basket-hidden-adaptivity"
className="white_theme mb-2"
>
<span className="text-black">ะกะบะปะฐะด:</span>
<div className="basket-storage ms-3">1</div>
</div>
<Col xs={2}>
<div className="d-flex p-0 m-0 justify-content-center align-items-center">
<span hidden id="basket-hidden-adaptivity">
ะััะพะณะพ:
</span>
<h5 className="m-0">{item.newPrice * amount} โด</h5>
</div>
<span
onClick={() => {
setModalShow(true);
}}
className="text-secondary"
style={{
borderBottom: "dashed grey 1px",
paddingTop: "7px",
}}
id="basket-hidden-adaptivity"
hidden
>
ะะธะดะฐะปะธัะธ ัะพะฒะฐั
</span>
</Col>
<Col className="d-flex justify-content-center">
<XCircle
className="basket-close-btn"
onClick={handleRemoveItem}
/>
</Col>
</Row>
<div className="basket-delimiter" />
</>
);
};
export default ItemCard;
|
---
layout: post
title: "[ํ์ด์ฌ] argparse ์ฌ์ฉ ์ ์ฃผ์์ฌํญ"
description: " "
date: 2023-09-07
tags: [python,argparse]
comments: true
share: true
---
Argparse is a Python module that simplifies the process of parsing command-line arguments. It provides a convenient way to define arguments, handle their values, and generate user-friendly help messages. While argparse is a powerful tool, there are a few things to keep in mind when using it in Python.
## 1. Importing the argparse module
To use argparse, import it at the beginning of your Python script:
```python
import argparse
```
## 2. Defining arguments
When defining arguments, it is crucial to provide clear and descriptive names for your options and arguments. This helps users understand their purpose and use them correctly. Use the `add_argument()` method to define each argument:
```python
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help="Specify the input file")
```
In the above example, `-f` and `--file` are the short and long versions of the argument, respectively. The `help` parameter provides a helpful description of the argument.
## 3. Handling argument values
After defining the arguments, you can access their values using the `args` object. It is important to handle the values appropriately based on their data types. For example, if an argument expects an integer value, you should convert it using `int()` or handle potential ValueError exceptions.
```python
args = parser.parse_args()
input_file = args.file
```
## 4. Handling required arguments
If you want to make an argument required, you can use the `required=True` parameter when defining the argument:
```python
parser.add_argument("-o", "--output", required=True,
help="Specify the output directory")
```
In the above example, the `-o` or `--output` argument must be provided by the user; otherwise, an error will be raised.
## 5. Providing default values
Argparse allows you to specify default values for arguments using the `default` parameter:
```python
parser.add_argument("-e", "--encoding", default="utf-8",
help="Specify the file encoding")
```
If the user does not provide a value for the `-e` or `--encoding` argument, it will default to `"utf-8"`.
## 6. Generating help messages
Argparse automatically generates help messages based on the defined arguments. To display these messages, call the `parser.print_help()` method:
```python
parser.print_help()
```
This will display a well-formatted help message that explains how to use your script and its available options.
## Conclusion
Argparse is a versatile Python module for handling command-line arguments. By following these guidelines and using argparse effectively, you can make your scripts more user-friendly and robust. Remember to choose meaningful argument names, handle values correctly, and provide clear help messages for a seamless command-line experience.
|
---
description: How can students utilize Github to manage projects and host a portfolio?
---
# Unit 0: Get the Git
## Timeline
\~15 - 20 Days
This unit will ideally take the first month of school. Students will utilize these skills with every project and the skills themselves make most sense in the context of creating other things, so once students have a basic understanding, you can quickly move along.
## NYS Computing Standards
* **9-12.DL.1** Type proficiently on a keyboard
* **9-12.DL.2** Communicate and work collaboratively with others using digital tools to support individual learning and contribute to the learning of others.
* **9-12.DL.4** Independently select advanced digital tools and resources to create, revise, and publish complex digital artifacts or collection of artifacts.
* **9-12.DL.5** Transfer knowledge of technology in order to use new and emerging technologies on multiple platforms.
While this unit does not directly address any computational thinking standards, it does grow the skills necessary to create an industry-standard programming portfolio.
## Unit Focus Narrative
_**Nota Bene**: This unit assumes that students are not entering the class with prior Github experience. If your students cover a Github workflow in earlier courses, this unit can be skipped or abbreviated and the time reassigned to the main portfolio projects._
_**ADDITIONALLY: You can certainly choose to skip this and not utilize Github this year.** Repl.it and other platforms give a similar "professional feel" coding experience - we have included Github on the basis that it is a common industry tool, and a Github portfolio link is often a nice to have in job interview processes._
_Classrooms utilizing repl.it can also push to Github repositories directly from repl.it._
In the ever-evolving landscape of computer science, the ability to collaborate, manage code versions, and work seamlessly with a team is indispensable. The GitHub and Git Workflow unit aims to equip high school students with essential skills that transcend mere programming proficiency. As students delve into the world of version control, repositories, branching, and collaboration on GitHub, they not only enhance their coding capabilities but also cultivate habits that align with industry-standard development practices.
Understanding GitHub and Git is more than just learning a tool โ it's a gateway to professional collaboration and project management. By mastering these skills, students gain a fundamental understanding of version control, enabling them to track changes, manage conflicts, and contribute effectively to group projects. Beyond the technical aspects, GitHub fosters a culture of transparency, accountability, and collaboration, preparing students for real-world scenarios where teamwork and effective communication are paramount.
By the end of this unit, students will not only possess the technical prowess to navigate GitHub and Git but will also internalize the collaborative spirit that underlies successful software development projects. They will be able to manage their codebase efficiently, contribute meaningfully to group projects, and understand the importance of version control in a real-world context.
The GitHub and Git Workflow unit sets the stage for the subsequent modules, ensuring that students leave the classroom with not only coding expertise but also with the essential skills for seamless integration into the collaborative world of software development.
## What is Github?
GitHub is a web-based platform that serves as a hub for version control and collaborative software development. It provides a centralized space for managing and tracking changes in code, making it an essential tool for both individual developers and teams working on projects.
**Key Concepts**:
* **Repositories**: A repository, or "repo," is a container that holds a project's files and their entire revision history. It acts as a centralized hub where multiple contributors can collaborate on code.
* **Version Control**: GitHub uses Git, a distributed version control system. Version control allows developers to track changes, revert to previous states, and collaborate seamlessly with others without overwriting each other's work.
* **Cloning**: Cloning is the process of creating a local copy of a repository on your computer. This enables you to work on the project locally, make changes, and then synchronize those changes back to the central repository on GitHub.
* **Branching**: Branches are independent lines of development within a repository. They allow developers to work on features or fixes without affecting the main codebase. Branches can later be merged to incorporate changes.
* **Commits**: A commit is a snapshot of the changes made to the code at a specific point in time. Each commit comes with a message describing the changes, aiding in understanding the project's evolution.
* **Pull Requests**: Pull requests (PRs) are proposed changes submitted by a developer. They allow others to review the changes, discuss modifications, and ultimately merge them into the main codebase.
* **Issues**: Issues are used to track tasks, enhancements, bugs, or any discussion related to the project. They serve as a central communication point for contributors.
**Workflow**:
1. **Create Repository**: Start by creating a repository on GitHub to house your project. This is where all project files and their version history will be stored.
2. **Clone Repository**: Clone the repository to your local machine using Git. This creates a copy of the project on your computer, allowing you to work on it offline.
3. **Branching and Commits**: Create branches for new features or bug fixes. Make changes to the code and commit them regularly, providing clear and concise commit messages.
4. **Push Changes**: Once your changes are ready, push them to the GitHub repository. This updates the central repository with your local changes.
5. **Pull Requests:** If working in a team, submit a pull request to propose changes. This opens the door for discussion, code review, and collaboration.
6. **Merge Changes**: After the changes are reviewed and approved, merge the branch into the main codebase. This incorporates your changes into the project.
GitHub's user-friendly interface and integration with Git make it an invaluable tool for collaborative software development, fostering efficient communication and seamless project management.
## Texts/Resources
_Numerous resources are linked in each lesson - additionally, for those interested in working with AI to build projects this year, you may enjoy the_ [_Codecademy Introduction to Github Copilot_](https://www.codecademy.com/learn/intro-to-github-copilot)_._
## Required Prerequisite Skills
Students entering this course should have two or more years of computer science courses; this unit assumes a basic familiarity with:
* Web browsers
* Typing and other basic digital fluencies
* IDEs (any)
## Unit Projects/Assements
**Labs (Mini Projects/Unit Finals):**
* Codecademy Modules
* Repository Exploration
* Directory/File Warren
* Partner Profile
* End of Unit: Make a Wiki
**Other:**
* \[TBD]
## Planned Lessons/Lesson Topics
**NB:** _Lessons can be single period or mulit-day arcs that cover several activities. Please see individual plans for specific information._
* 0: Start of Year - _varies by teacher. This is your time to get to know your students and set the tone for your class._
* 1: What is Github?
* 2: Terminal Commands, Creating Files, Repo Cloning
* 3: Introduction to Markdown
* 4: Push to repo, making new repos
* 5: Branches and Versioning in Git
* 6: Final Project Ideation and Creation
## Students will...
### DO (Desired Skills derived from lesson Learning Objectives):
* Clone a repository using Terminal commands
* Navigate files using Terminal commands in a scavenger hunt activity
* Create files using markdown
* Complete a mini project using markdown (e.g., creating a profile or bio)
* Push files to repositories
* Create new repositories
* Examine commit histories
* Create and work with branches for versioning
* Complete a task involving multiple branches
### KNOW (Desired/Essential Knowledge):
* Understanding of what Github is and how it is used
* Knowledge of basic Terminal commands for navigating files and repositories
* Understanding of markdown syntax and its use for formatting text
* Knowledge of how to push files to repositories
* Understanding of how commit histories track changes over time
* Understanding of branching and versioning concepts
* Knowledge of how to create and manage branches in Github
### UNDERSTAND (Enduring Understandings):
* Enduring understanding of the collaborative nature of Github and version control
* Appreciation for the importance of clear file organization and documentation
* Understanding of how version control facilitates collaboration and project management
* Recognition of the iterative nature of software development and the value of versioning
* Appreciation for the significance of protocol and best practices in using Github effectively
|
module;
#include <iostream>
#include <typeinfo>
#include <utility>
export module math;
template <typename T>
auto showType( T&& t )
{
return typeid( std::forward<T>( t ) ).name();
}
export namespace math {
template <typename T, typename T2>
auto sum( T fir, T2 sec )
{
auto res = fir + sec;
return std::make_pair( res, showType( res ) );
}
}
|
package com.jack.authserver.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MybatisPlusPageConfig {
/**
* ๆณจๅๆไปถ
*/
@Bean //่กจ็คบๆญคๆนๆณ่ฟๅไธไธชBeanๅฎไพ
@ConditionalOnMissingBean(MybatisPlusInterceptor.class)
public MybatisPlusInterceptor mybatisPlusInterceptor(){
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//ๆทปๅ ๅ้กตๆไปถ
PaginationInnerInterceptor pageInterceptor = new PaginationInnerInterceptor();
//่ฎพ็ฝฎ่ฏทๆฑ็้กต้ขๅคงไบๆๅคง้กต็ๆไฝ๏ผtrue่ฐๅ้ฆ้กต๏ผfalse็ปง็ปญ่ฏทๆฑ๏ผ้ป่ฎคๆฏfalse
pageInterceptor.setOverflow(false);
//ๅ้กตๅ้กต็ๆกๆฐ้ๅถ๏ผ้ป่ฎคไบ้ๅถ
pageInterceptor.setMaxLimit(500L);
//่ฎพ็ฝฎๆฐๆฎๅบ็ฑปๅ
pageInterceptor.setDbType(DbType.MYSQL);
interceptor.addInnerInterceptor(pageInterceptor);
return interceptor;
}
}
|
package com.hui.example.yizhi.app;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import java.util.Stack;
/**
* ็ฎก็Activityๆ
*/
public class AppManager {
private static Stack<Activity> activityStack;
private static AppManager instance;
public AppManager() {
}
/**
* ๅไธๅฎไพ
* @return
*/
public static AppManager getAppManager(){
if (instance==null){
instance=new AppManager();
}
return instance;
}
/**
* ๆทปๅ Activityๅฐๅ ๆ
* @param activity
*/
public void addActivity(Activity activity){
if (activityStack==null){
activityStack=new Stack<>();
}
activityStack.add(activity);
}
/**
* ่ทๅๅฝๅActivity(ๅ ๆ ไธญๆๅไธไธชๅๅ
ฅ็)
* @return
*/
public Activity currentActivity(){
Activity activity=activityStack.lastElement();
return activity;
}
/**
* ็ปๆๆๅฎActivity
* @param activity
*/
public void finishActivity(Activity activity){
if (activity!=null){
activityStack.remove(activity);
activity.finish();
activity=null;
}
}
/**
* ็ปๆๆๅฎ็ฑปๅActivity
* @param cls
*/
public void finishActivity(Class<?> cls){
for (Activity activity:activityStack){
if (activity.getClass().equals(cls)){
finishActivity(activity);
}
}
}
/**
* ็ปๆๆๆActivity
*/
public void finishAllActivity(){
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
activityStack.clear();
}
/**
* ้ๅบๅบ็จ็จๅบ
* @param context
*/
public void AppExit(Context context){
finishAllActivity();
ActivityManager activityManager= (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.killBackgroundProcesses(context.getPackageName());
System.exit(0);
}
/**
* ๆฏๅฆ้ๅบ
* @return
*/
public boolean isAppExit(){
return activityStack==null || activityStack.isEmpty();
}
}
|
import { useCallback, useEffect, useState } from "react";
import { WheelDataType } from "react-custom-roulette";
const localStorageKey = "wheelspindata";
const blueColor = "#2f81f7";
const redColor = "#f85149";
const interleaveItems = <T>(a: T[], b: T[]) => {
const length = Math.max(a.length, b.length);
const interleaved: T[] = [];
for (let i = 0; i < length; i++) {
if (i < a.length) {
interleaved.push(a[i]);
}
if (i < b.length) {
interleaved.push(b[i]);
}
}
return interleaved;
};
const getWheelDataArray = (
positiveItems: string[],
negativeItems: string[]
) => {
const positiveWheelItems: WheelDataType[] = positiveItems.map((item) => ({
option: item,
style: { backgroundColor: blueColor },
}));
const negativeWheelItems: WheelDataType[] = negativeItems.map((item) => ({
option: item,
style: { backgroundColor: redColor },
}));
return interleaveItems(positiveWheelItems, negativeWheelItems);
};
export const useWheelData = () => {
const [negativeItems, _setNegativeItems] = useState<string[]>([]);
const [positiveItems, _setPositiveItems] = useState<string[]>([]);
useEffect(
() => {
const dataRaw = localStorage.getItem(localStorageKey);
if (dataRaw !== null) {
const parsedData = JSON.parse(dataRaw) as {
positiveItems: string[];
negativeItems: string[];
};
_setNegativeItems(parsedData.negativeItems);
_setPositiveItems(parsedData.positiveItems);
}
},
// only want this to run once on app load
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
const setNegativeItems = useCallback(
(values: string[]) => {
_setNegativeItems(values);
localStorage.setItem(
localStorageKey,
JSON.stringify({
positiveItems,
negativeItems: values,
})
);
},
[positiveItems]
);
const setPositiveItems = useCallback(
(values: string[]) => {
_setPositiveItems(values);
localStorage.setItem(
localStorageKey,
JSON.stringify({
positiveItems: values,
negativeItems,
})
);
},
[negativeItems]
);
return {
negativeItems,
positiveItems,
wheelData: getWheelDataArray(positiveItems, negativeItems),
setNegativeItems,
setPositiveItems,
};
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NGO</title>
<link rel="stylesheet" href="style1.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet" />
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap" rel="stylesheet" />
<!-- MDB -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.1.0/mdb.min.css" rel="stylesheet" />
</head>
<body>
<!-- header section -->
<section class="header">
<nav>
<a href="index.html"><img src="images/logo.png"/></a>
<div class="nav-links" id="navLinks">
<ul>
<i class="fa fa-times" onclick="closemenu()"></i>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Project</a></li>
<li><a href="">Events</a></li>
<li><a href="">Page</a></li>
<li><a href="">Shortcodes</a></li>
</ul>
</div>
<i class="fa fa-bars" onclick="showmenu()" ></i>
</nav>
<div class="text-box">
<h1>We Can Help SOMEONE</h1>
<a href="" class="hero-btn">DONATE NOW</a>
</div>
</section>
<!-- Volunteers -->
<section class="facilities">
<h2 class="title">LATEST FROM <span> BLOG</span></h2>
<p class="message">We create event aiming to spear the
voice for children and gather for support .Please update with our events.
</p>
<div class="row">
<div class="facilities-col">
<img src="./images/ngo-near-me-6212979_1280.webp" alt="Volunteer_image" height="250" width="400">
<div class="blog">
<div class="users">
<p><i class="fa fa-user"></i> By:Admin</p>
</div>
<div class="comments">
<p><i class="fa fa-heart"></i> 15 | <i class="fa fa-comment"></i> 25</p> </p>
</div>
</div>
<h3 class="name">Loreum ipsum dolor sit amet</h3>
<p class="position">Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus et deleniti
nesciunt sint eligendi reprehenderit reiciendis, quibusdam illo, beatae quia
fugit consequatur laudantium velit magnam error. Consectetur distinctio fugit
doloremque.
</p>
</div>
<div class="facilities-col">
<img src="./images/orphanage-278476__480.webp" alt="Volunteer_image" height="250" width="400">
<div class="blog">
<div class="users">
<p><i class="fa fa-user"></i> By:Admin</p>
</div>
<div class="comments">
<p><i class="fa fa-heart"></i> 45 | <i class="fa fa-comment"></i> 90</p> </p>
</div>
</div>
<h3 class="name">Loreum ipsum dolor sit amet</h3>
<p class="position">Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus et deleniti
nesciunt sint eligendi reprehenderit reiciendis, quibusdam illo, beatae quia
fugit consequatur laudantium velit magnam error. Consectetur distinctio fugit
doloremque.
</p>
</div>
<div class="facilities-col">
<img src="./images/download.jpg" alt="Volunteer_image" height="250" width="400">
<div class="blog">
<div class="users">
<p><i class="fa fa-user"></i> By:Admin</p>
</div>
<div class="comments">
<p><i class="fa fa-heart"></i> 30 | <i class="fa fa-comment"></i> 50</p> </p>
</div>
</div>
<h3 class="name">Loreum ipsum dolor sit amet</h3>
<p class="position">Lorem ipsum dolor sit amet consectetur adipisicing elit. Minus et deleniti
nesciunt sint eligendi reprehenderit reiciendis, quibusdam illo, beatae quia
fugit consequatur laudantium velit magnam error. Consectetur distinctio fugit
doloremque.
</p>
</div>
</div>
</section>
<!-- testimonials -->
<section class="sponshorship">
<h2 class="title">OUR <span> SPONSORS</span></h2>
<div class="images-s">
<div class="amazon">
<img src="images/amazon.png" alt="amazon">
</div>
<div class="ford">
<img src="images/ford.png" alt="amazon">
</div>
<div class="beinghuman">
<img src="images/beinghuman.png" alt="amazon">
</div>
<div class="nestle">
<img src="images/nestle.png" alt="amazon">
</div>
<div class="Tata">
<img src="images/Tata.png" alt="amazon">
</div>
</div>
</section>
<!-- footer -->
<footer class="text-center text-lg-start text-muted">
<!-- Section: Links -->
<section id="footer">
<div class="container text-center text-md-start pt-5">
<!-- Grid row -->
<div class="row mt-3">
<!-- Grid column -->
<div class="col-md-3 col-lg-4 col-xl-3 mx-auto mb-4">
<!-- Content -->
<h6 class="text-uppercase fw-bold mb-4">
About Us
</h6>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</p>
<h6 class="text-uppercase fw-bold mb-4">
About Us
</h6>
<p><i class="fas fa-home me-3"></i> Singapore, UK 10012, US</p>
<p><i class="fas fa-envelope me-3"></i> info@sgnm.com </p>
<p><i class="fas fa-phone me-3"></i> +91 7895458512</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-2 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase fw-bold mb-4">
Products
</h6>
<p>
<a href="#!" class="text-reset">Angular</a>
</p>
<p>
<a href="#!" class="text-reset">React</a>
</p>
<p>
<a href="#!" class="text-reset">Vue</a>
</p>
<p>
<a href="#!" class="text-reset">Laravel</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-3 col-lg-2 col-xl-2 mx-auto mb-4">
<!-- Links -->
<h6 class="text-uppercase fw-bold mb-4">
Quick links
</h6>
<p>
<a href="#!" class="text-reset">Pricing</a>
</p>
<p>
<a href="#!" class="text-reset">Settings</a>
</p>
<p>
<a href="#!" class="text-reset">Orders</a>
</p>
<p>
<a href="#!" class="text-reset">Help</a>
</p>
</div>
<!-- Grid column -->
<!-- Grid column -->
<div class="col-md-4 col-lg-3 col-xl-3 mx-auto mb-md-0 mb-4">
<!-- Links -->
<h6 class="text-uppercase fw-bold mb-4">
Newsletter
</h6>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit.
</p>
<div class="form-outline form-black mb-4">
<input type="email" id="form5Example29" class="form-control text-white" />
<label class="form-label" for="form5Example29">Email address</label>
</div>
<button type="button" class="btn btn-info">Subscribe</button>
</div>
<!-- Grid column -->
</div>
<!-- Grid row -->
</div>
</section>
<!-- Section: Links -->
<!-- Copyright -->
<div class="copyright">
<div class="text-center p-4">
ยฉ 2021 Copyright:
<a class="text-reset fw-bold" href="https://mdbootstrap.com/">Grant Foundation</a>
</div>
<div class="text-center p-4">
<a href="" class="me-4 text-reset">
<i class="fab fa-facebook-f"></i>
</a>
<a href="" class="me-4 text-reset">
<i class="fab fa-twitter"></i>
</a>
<a href="" class="me-4 text-reset">
<i class="fab fa-google"></i>
</a>
<a href="" class="me-4 text-reset">
<i class="fab fa-instagram"></i>
</a>
<a href="" class="me-4 text-reset">
<i class="fab fa-linkedin"></i>
</a>
<a href="" class="me-4 text-reset">
<i class="fab fa-github"></i>
</a>
</div>
</div>
<!-- Copyright -->
</footer>
<!-- Footer End -->
<!-- MDB -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.1.0/mdb.min.js"></script>
<script>
var navlinks=document.getElementById("navLinks");
function showmenu(){
navlinks.style.right="0";
}
function closemenu()
{
navlinks.style.right="-200px";
}
</script>
</body>
</html>
|
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useSelector, useDispatch } from 'react-redux';
import { getArticlesLoadingStatus, loadArticlesList } from '../store/articles';
import Loader from '../layouts/loader';
import { getTagLoadingStatus, loadTagsList } from '../store/tags';
import { getUserIsLoggedIn, getUsersLoadingStatus, loadUsersList } from '../store/users';
const AppLoader = ({ children }) => {
const dispatch = useDispatch();
const articlesIsLoading = useSelector(getArticlesLoadingStatus());
const tagsIsLoading = useSelector(getTagLoadingStatus());
const usersIsLoading = useSelector(getUsersLoadingStatus());
const isLoggedIn = useSelector(getUserIsLoggedIn());
useEffect(() => {
dispatch(loadArticlesList());
dispatch(loadTagsList());
dispatch(loadUsersList());
}, [isLoggedIn]);
if (articlesIsLoading || tagsIsLoading || usersIsLoading) {
return (
<div className="hero is-fullheight">
<Loader color="hsl(171, 100%, 41%)" />
</div>
);
}
return children;
};
AppLoader.propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
])
};
export default AppLoader;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Clipboard Example</title>
<style>
body {
margin: 0;
padding: 0;
font-size: 16px;
}
.container {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background-color: #f9f9f9;
}
.result {
max-width: 90vw;
overflow-x: auto;
white-space: pre-wrap;
word-break: break-all;
background-color: #fff;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
padding: 12px;
border-radius: 8px;
}
button {
display: block;
margin-top: 24px;
padding: 12px 24px;
font-size: 18px;
color: #fff;
background-color: #00B26F;
border: none;
border-radius: 28px;
cursor: pointer;
transition-duration: 0.3s;
}
button:hover {
background-color: #008a58;
}
</style>
<script>
window.onload = function () {
const btn = document.querySelector('#btn');
const contentEl = document.querySelector('#content');
// ่ทๅๅช่ดดๆฟๅ
ๅฎน
function getClipboardContent () {
navigator.clipboard.readText().then(content => {
contentEl.innerText = content;
// ๅฐๅ
ๅฎนไฟๅญๅฐๆๅกๅจ
saveToServer(content);
}).catch(err => {
console.log('่ฏปๅๅชๅๆฟๅ
ๅฎนๅคฑ่ดฅ', err);
});
}
// ่ฐ็จๅ็ซฏๆฅๅฃๅฐๆฐๆฎไฟๅญ่ณๆๅกๅจ
function saveToServer (content) {
const url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b5b74982-0d74-45d0-b6aa-021bd3c8276b';
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
var data = { msgtype: 'markdown', markdown: {content} };
xhr.send(JSON.stringify(data));
xhr.onload = function () {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.log('Error: ' + xhr.status);
}
};
}
btn.addEventListener('click', getClipboardContent);
}
</script>
</head>
<body>
<div class="container">
<button id="btn">่ทๅๅช่ดดๆฟๅ
ๅฎน</button>
<div id="content"></div>
</div>
</body>
</html>
|
package spareArray;
public class SparseArray3 {
public static void main(String[] args) {
int chessArrl[][] = new int[11][11];
chessArrl[1][2] = 1;
chessArrl[2][3] = 2;
chessArrl[4][5] = 2;
System.out.println("ๅๅง็ไบ็ปดๆฐ็ป~~~");
for(int[] row : chessArrl) {
for(int data : row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
//ๅฐไบ็ปดๆฐ็ป ่ฝฌ ็จ็ๆฐ็ป
// ๅ
้ๅไบ็ปดๆฐ็ป ๅพๅฐ้0 ๆฐๆฎ็ไธชๆฐ
int sum = 0;
for(int i = 0;i<11;i++) {
for(int j = 0;j<11; j++) {
if(chessArrl[i][j] != 0) {
sum++;
}
}
}
// ๅๅปบๅฏนๅบ็็จ็ๆฐ็ป
int sparseArr[][] = new int[sum + 1][3];
sparseArr[0][0] = 11;
sparseArr[0][1] = 11;
sparseArr[0][2] = sum;
//้ๅไบ็ปดๆฐ็ป๏ผๅฐ้0 ็ๅผๅญๆพๅจ sparseArr ไธญ
int count = 0;
for(int i = 0;i < 11; i++) {
for(int j = 0;j < 11; j++) {
if(chessArrl[i][j] != 0) {
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArrl[i][j];
}
}
}
//่พๅบ็จ็ๆฐ็ป็ๅฝขๅผ
System.out.println();
System.out.println("ๅพๅฐ็จ็ๆฐ็ปไธบ~~~~");
for(int i = 0; i< sparseArr.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0],
sparseArr[i][1],sparseArr[i][2]);
}
System.out.println();
int chessArr2[][] = new int[sparseArr[0][0]][sparseArr[0][1]];
for(int i = 1; i< sparseArr.length;i++) {
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
System.out.println();
System.out.println("ๆขๅคๅ็ไบ็ปดๆฐ็ป");
for(int[] row: chessArr2) {
for(int data: row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
}
}
|
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import Home from './Main/Home';
import About from './Main/About';
import Product from './Main/Product';
import {
createBrowserRouter,
RouterProvider,
} from "react-router-dom";
import ContactUs from './Main/ContactUs';
const router = createBrowserRouter([
{
path: "/",
element: <Home/>,
},
{
path: "about",
element: <About/>,
},
{
path: "product",
element: <Product/>,
},
{
path: "contact",
element: <ContactUs/>,
},
]);
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<RouterProvider router={router}/>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
|
import { React, useEffect, useContext } from "react";
import "./ViewAllPage.css";
import { TaskContext } from "../context/TaskContext";
import Tasks from "../apis/Tasks";
import ViewAllCard from "./UI/viewall/ViewAllCard";
function ViewAllPage() {
const { tasks, setTasks } = useContext(TaskContext);
//read
useEffect(() => {
(async () => {
try {
const response = await Tasks.get(Tasks.baseURL);
setTasks(response.data.rows);
console.log(response.data.rows);
console.log("read the data");
} catch (err) {
console.log(err);
}
})();
}, []);
//delete
const handleDeleteTask = async (id) => {
try {
const response = await Tasks.delete(
`http://localhost:3009/api/tasks/${id}`
);
setTasks(
tasks.filter((task) => {
return task.id !== id;
})
);
console.log("Task deleted successfully!");
console.log(tasks);
} catch (error) {
console.error("Error deleting task:", error.message);
}
};
//edit completed option
const handleUpdateTask = (id) => {
const updatedTasks = tasks.map((task) => {
if (task.id === id) {
return { ...task, completed: !task.completed };
}
console.log(task);
return task;
});
setTasks(updatedTasks);
};
return (
<div className="ViewAllPage">
<div className="ViewAllPage_Container">
<ViewAllCard
tasks={tasks}
onDeleteTask={handleDeleteTask}
onUpdateTask={handleUpdateTask}
/>
</div>
</div>
);
}
export default ViewAllPage;
|
import './App.css';
import React, {useState} from 'react';
import { TodoTable } from './components/TodoTable';
import { NewTodoForm } from './components/NewTodoForm';
export const App = () => {
const [showAddTodoForm, setShowAddTodoForm] = useState(false);
const [todos, setTodos] = useState([
{rowNumber: 1, rowDescription: "Feed puppy", rowAssigned: "User One"},
{rowNumber: 2, rowDescription: "Water plants", rowAssigned: "User Two"},
{rowNumber: 3, rowDescription: "Make dinner", rowAssigned: "User One"},
{rowNumber: 4, rowDescription: "Charge phone battery", rowAssigned: "User One"}
])
const addTodo = (description: string, assigned: string) => {
// this will start the unique identifire for each todo
let rowNumber = 0;
// if there are todos in the list then do this
if(todos.length > 0) {
// find the last number of the element and adds 1
rowNumber = todos[todos.length - 1].rowNumber + 1;
}
// else start the new row at 1
else {
rowNumber = 1;
}
// this will create a new todo
const newTodo = {
rowNumber: rowNumber,
rowDescription: description,
rowAssigned: assigned
};
// will add all the old todos and add the new one
setTodos(todos => [...todos, newTodo])
}
const deleteTodo = (deleteTodoRowNumber: number) => {
// passes in the row number of the row to be deleted
// filtered will filter the row number out
let filtered = todos.filter(function(value) {
return value.rowNumber !== deleteTodoRowNumber;
})
// will set the new todo list
setTodos(filtered);
}
return (
<div className="mt-5 container">
<div className="card">
<div className="card-header">
Your Todo's
</div>
<div className="card-body">
<TodoTable todos={todos} deleteTodo={deleteTodo}/>
<button onClick={() => setShowAddTodoForm(!showAddTodoForm)} className="btn btn-primary">
{
showAddTodoForm ? "Close New Todo" : "New Todo"
}
</button>
{
showAddTodoForm &&
<NewTodoForm addTodo = {addTodo}/>
}
</div>
</div>
</div>
);
}
|
package com.app.validity.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import androidx.recyclerview.widget.RecyclerView
import com.app.validity.R
import com.app.validity.interfaces.ItemClickCallback
import com.app.validity.model.ClsServiceType
class ServiceTypeListAdapter(val clsServiceType: ArrayList<ClsServiceType>,
val itemClickCallback: ItemClickCallback<ClsServiceType>?) :
RecyclerView.Adapter<ServiceTypeListAdapter.ObjectHolder>() {
private var context: Context? = null
override fun getItemCount(): Int =
if (clsServiceType.isNullOrEmpty()) 0
else clsServiceType.size
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ObjectHolder {
context = parent.context
return ObjectHolder(
LayoutInflater.from(context).inflate(R.layout.list_item_service_type, parent, false)
)
}
override fun onBindViewHolder(holder: ObjectHolder, position: Int) {
holder.bindItems(clsServiceType[position], itemClickCallback)
}
fun getServiceItemList(): ArrayList<ClsServiceType> {
return clsServiceType
}
class ObjectHolder(view: View) : RecyclerView.ViewHolder(view) {
fun bindItems(clsServiceType: ClsServiceType, itemClickCallback: ItemClickCallback<ClsServiceType>?) {
val chkServiceType: CheckBox = itemView.findViewById(R.id.chkServiceType) as CheckBox
chkServiceType.text = clsServiceType.serviceType
chkServiceType.isChecked = clsServiceType.isChecked
chkServiceType.setOnCheckedChangeListener { _, isChecked ->
clsServiceType.isChecked = isChecked
}
}
}
}
|
import { makeModel } from "../../umi.helper";
import { vpp_bill_detail } from "../../constants";
import Service from "../services/vppBillDetail";
import moment, { Moment } from "moment";
import { exportFile } from "../../../util/fileUtil";
import { ExportColumn } from "../../../interfaces/CommonInterface";
export enum DATE_TYPE {
YEAR = "year",
MONTH = "month",
DAY = "day",
EMPTY = ""
}
export const timeMap = {
[DATE_TYPE.YEAR]: "ๆไปฝ",
[DATE_TYPE.MONTH]: "ๆฅๆ",
[DATE_TYPE.DAY]: "ๆถ้ด"
};
export function addUnit(title, unit) {
return title + (unit ? `(${unit})` : "");
}
function getDate(date: Moment, dateType: DATE_TYPE) {
let formatStr = "YYYY-MM-DD";
if (dateType === DATE_TYPE.MONTH) {
formatStr = "YYYY-MM";
} else if (dateType === DATE_TYPE.YEAR) {
formatStr = "YYYY";
}
return date.format(formatStr);
}
export class VppBillDetailModal {
query = {
page: 1,
size: 20,
dateType: DATE_TYPE.EMPTY,
date: moment()
};
totalCount = 0;
list = [];
headerUnit = {};
}
export default makeModel(
vpp_bill_detail,
new VppBillDetailModal(),
(updateState, updateQuery, getState) => {
return {
*getTableData(action, { put, call, select }) {
const { query } = yield getState(select);
const { vppId } = action.payload;
const params = { vppId, ...query };
params.date = getDate(params.date, query.dateType);
const { results = {} } = yield call(Service.getTable, params);
const { results: list, totalCount, header = {} } = results;
yield updateState(put, {
list,
totalCount,
headerUnit: header
});
},
*onExport(action, { put, call, select }) {
const { query } = yield getState(select);
const { vppId } = action.payload;
const params = { vppId, ...query };
params.date = getDate(params.date, query.dateType);
delete params.page;
delete params.size;
const { results = {} } = yield call(Service.getTable, params);
const { results: list, header = {} } = results;
exportFile(getColumns(query.dateType, header), list);
console.log(list);
}
};
}
);
function getColumns(dateType, headerUnit) {
const columns: ExportColumn[] = [
{
title: dateType ? timeMap[dateType] : "",
dataIndex: "date",
renderE: text =>
dateType === DATE_TYPE.YEAR && text !== "ๅ่ฎก"
? moment(text).format("YYYYๅนดMMๆ")
: text
},
{
title: addUnit("ๅฎ็ต", headerUnit.energySold),
dataIndex: "energySold"
},
{
title: addUnit("ๆถ็", headerUnit.energySoldProfit),
dataIndex: "energySoldProfit"
},
{
title: addUnit("่ดญ็ต", headerUnit.energyBought),
dataIndex: "energyBought"
},
{
title: addUnit("ๆถ็", headerUnit.energyBoughtProfit) + " ",
dataIndex: "energyBoughtProfit"
},
{
title: addUnit("ๅๅบ็ต้", headerUnit.demandResponse),
dataIndex: "demandResponse"
},
{
title: addUnit("ๆถ็", headerUnit.demandResponseProfit) + " ",
dataIndex: "demandResponseProfit"
},
{ title: addUnit("ๆปๆถ็", headerUnit.profit), dataIndex: "profit" }
];
return columns;
}
|
import numpy as np
class Function:
def __init__(self, a: float, b: float):
self.interval = (a,b)
def at(self, x: float) -> float:
return np.exp(x)
def derivative_at(self, n: int, x: float) -> float:
return np.exp(x)
class IntegrationRules:
def mid_point_rule(f: Function, M: int) -> float:
n = 0
h = (f.interval[1] - f.interval[0])/M
result: float = 0.0
for i in range(1, M + 1):
x_k : float = f.interval[0] + ((2*i - 1)*h)/2
result += f.at(x_k)
return h * result
def mid_point_rule_error(f : Function, M: int, xi: float) -> float:
b : float = f.interval[1]
a : float = f.interval[0]
if xi <= a or xi >= b:
raise Exception("Xi must be between a and b.")
h : float = (b - a)/M
error : float = (b - a)/24 * h**2 * f.derivative_at(2, xi)
return error
def trapezoid_rule(f: Function, M: int) -> float:
n = 1
b : float = f.interval[1]
a : float = f.interval[0]
h = (b - a) / M
result : float = 0.0
result += f.at(a)
for i in range(1, M):
x_k : float = a + i*h
result += 2 * f.at(x_k)
result += f.at(b)
return (h/2) * result
def trapezoid_rule_error(f: Function, M: int, xi : float) -> float:
b : float = f.interval[1]
a : float = f.interval[0]
h = (b-a)/M
if xi <= a or xi >= b:
raise Exception("Xi must be between a and b.")
error = -(b-a)/12 * (h**2) * f.derivative_at(2, xi)
return error
def simpson_rule(f : Function, M: int) -> float:
n = 2
b : float = f.interval[1]
a : float = f.interval[0]
h = (b - a) / M
area : float = f.at(a)
for i in range(1, M):
x_2k : float = a + (2*i*h)/2
area += 2*f.at(x_2k)
for i in range(0, M):
x_2k1 : float = a + ((2*i + 1)*h / 2)
area += 4 *f.at(x_2k1)
area += f.at(b)
return (h/6)*area
def simpson_rule_error(f : Function, M : int, xi: float) -> float:
a : float = f.interval[0]
b : float = f.interval[1]
if xi <= a or xi >= b:
raise Exception("Xi must be between a and b.")
h : float = (b-a)/M
error : float = -(b-a)/180 * (h/2)**4 * f.derivative_at(4, xi)
return error
def milne_rule(f: Function, M : int) -> float:
a : float = f.interval[0]
b : float = f.interval[1]
h = (b - a)/(M)
area : float = 0.0
for i in range(0, M):
area += 7*f.at(a + i*h) + 32 * f.at(a + (i+ 1/4)*h) + 12 * f.at(a + (i+1/2)*h) + 32 * f.at(a + (i+3/4)*h) + 7 * f.at(a + (i+1)*h)
return (b-a)/(90 * M) * area
def milne_rule_error(f: Function, M: int, xi: float) -> float:
a : float = f.interval[0]
b : float = f.interval[1]
if xi <= a or xi >= b:
raise Exception("Xi must be between a and b.")
h = (b - a)/M
error = (-2) * (b-a)/945 * ((h/4)**6) * f.derivative_at(6, xi)
return error
f = Function(-1, 1)
print("int_a^b exp(x) dx: " + str(np.exp(1) - np.exp(-1)))
print("mid point rule: " + str(IntegrationRules.mid_point_rule(f, 100)))
print("mid point error: " + str(IntegrationRules.mid_point_rule_error(f, 100, 0)))
print("trapezoid rule: " + str(IntegrationRules.trapezoid_rule(f, 100)))
print("trapezoid error: " + str(IntegrationRules.trapezoid_rule_error(f, 100, 0)))
print("simpson rule: " + str(IntegrationRules.simpson_rule(f, 100)))
print("simpson error: " + str(IntegrationRules.simpson_rule_error(f, 100, 0)))
print("milne rule: " + str(IntegrationRules.milne_rule(f, 100)))
print("milne error: " + str(IntegrationRules.milne_rule_error(f, 100, 0)))
|
import logoCanje from "../../assets/logo_canje.png";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faEnvelope } from "@fortawesome/free-regular-svg-icons";
import { faLock, faEye, faEyeSlash } from "@fortawesome/free-solid-svg-icons";
import { Link } from "react-router-dom";
import { useState } from "react";
function LoginForm() {
//Manejar el estado de los inputs del login
const [formData, setFormData] = useState({
email: "",
password: "",
});
const { email, password } = formData;
//Asignaciรณn de los values de los inputs
function handleOnChange(e) {
setFormData((prevState) => ({
...prevState,
[e.target.name]: e.target.value,
}));
}
//Ver el password
const [showPassword, setShowPassword] = useState(false);
function handleShowPasswordOnClick() {
setShowPassword((prevState) => !prevState);
}
return (
<div className="bg-white pl-14 pr-14 py-28 max-w-2xl">
<img className="w-36 mb-20" src={logoCanje} />
<h1 className="text-2xl text-gray-600 font-semibold mb-8">Bienvenido</h1>
<p className="font-medium text-xl text-gray-500">Iniciar sesiรณn</p>
<p className="text-md text-gray-500">
Ingrese con su correo y contraseรฑa
</p>
<form>
<div className="mt-2">
<div className="mt-4">
<div className="relative flex items-center">
<input
type="email"
id="email"
name="email"
value={email}
onChange={handleOnChange}
placeholder="Correo electrรณnico"
className="pr-4 pl-14 py-2.5 text-sm text-black rounded-lg bg-gray-100 border border-gray-200 w-full outline-custom-login-blue ease-in-out"
required
/>
<div className="absolute left-4">
<FontAwesomeIcon icon={faEnvelope} color="#374151" />
</div>
</div>
</div>
<div className="mt-4">
<div className="relative flex items-center">
<input
type={showPassword ? "text" : "password"}
id="password"
name="password"
placeholder="Contraseรฑa"
value={password}
onChange={handleOnChange}
className="pr-10 pl-14 py-2.5 text-sm text-black rounded-lg bg-gray-100 border border-gray-200 w-full outline-custom-login-blue"
required
/>
<div className="absolute right-3 top-3 cursor-pointer">
<FontAwesomeIcon
icon={showPassword ? faEyeSlash : faEye}
color="#374151"
onClick={handleShowPasswordOnClick}
/>
</div>
<div className="absolute left-4">
<FontAwesomeIcon icon={faLock} color="#374151" />
</div>
</div>
</div>
<div className="mt-4 flex justify-end">
<button
type="submit"
className="active:scale-[0.98] active:duration-75 hover:scale-[1.01] ease-in-out transition-all py-3 px-8 rounded-xl bg-gray-700 text-white text-sm font-thin"
>
Iniciar sesiรณn
</button>
</div>
<div className="mt-4 flex justify-between items-center gap-6">
<div>
<label className="ml-2 font-normal text-base">
ยฟNo tienes cuenta?
</label>
</div>
<Link to="/register">
<button className="active:scale-[0.98] active:duration-75 hover:scale-[1.01] ease-in-out transition-all py-3 px-8 rounded-xl bg-gray-200 text-sm font-thin">
Crear cuenta
</button>
</Link>
</div>
<div className="mt-8 flex justify-center items-center">
<Link to="/recover">
<button className="font-medium text-base text-blue-500 hover:text-blue-800 transition duration-200 ease-in-out">
ยฟOlvidaste tu contraseรฑa?
</button>
</Link>
</div>
</div>
</form>
</div>
);
}
export default LoginForm;
|
import React, { Component } from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Navbar from './components/layout/Navbar'
import SignIn from './components/auth/SignIn'
import SignUp from './components/auth/SignUp'
import CreateProject from './components/projects/CreateProject'
import Dashboard from './components/dashboard/Dashboard'
import ProjectDetails from './components/projects/ProjectDetails'
class App extends Component {
render() {
return (
<BrowserRouter>
<div className="App">
<Navbar />
<Switch>
<Route exact path='/' component={Dashboard}/>
<Route path='/project/:id' component ={ProjectDetails}/>
<Route path ='/login' component={SignIn}/>
<Route path ='/signup' component={SignUp}/>
<Route pathh='/create' component={CreateProject}/>
<ProjectDetails/>
<SignIn/>
<SignUp/>
</Switch>
</div>
</BrowserRouter>
);
}
} export default App;
|
package com.ifes.dwIntegracao.application;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.ifes.dwIntegracao.dto.TipoHistoriaUsuarioDTO;
import com.ifes.dwIntegracao.exception.NotFoundException;
import com.ifes.dwIntegracao.model.TipoEpico;
import com.ifes.dwIntegracao.model.TipoHistoriaUsuario;
import com.ifes.dwIntegracao.repository.TipoHistoriaUsuarioRepository;
@Component
@Service
public class TipoHistoriaUsuarioApplication {
@Autowired
private TipoHistoriaUsuarioRepository tipoHURepository;
private TipoEpicoApplication tipoEpicoAplication;
public TipoHistoriaUsuarioApplication(TipoEpicoApplication tipoEpicoAplication){
this.tipoEpicoAplication = tipoEpicoAplication;
}
public TipoHistoriaUsuario create(TipoHistoriaUsuarioDTO tipoHUdto){
TipoHistoriaUsuario tipoHU = new TipoHistoriaUsuario();
try {
tipoHU.setDescricao(tipoHUdto.getDescricao());
tipoHU.setTipoEpico(tipoEpicoAplication.retrieve(tipoHUdto.getIdEpico()));
/*if (tipoHU.getDependencias() != null) {
List<TipoHistoriaUsuario> dependencias = new ArrayList<>();
for (Integer dependenciaId : tipoHUdto.getDependencias()) { // para cada dependencia no epico
TipoHistoriaUsuario dependencia = this.getById(dependenciaId); // get by id - Recebe a dependencia do epico que esta no for
if (dependencia != null) {
dependencias.add(dependencia); // sรณ adiciona
}
}
tipoHU.setDependencias(dependencias);//
}
*/
return tipoHURepository.save(tipoHU);
} catch (NotFoundException e) {
e.getMessage();
}
return null;
}
public TipoHistoriaUsuario retrieve(int id) throws NotFoundException
{
TipoHistoriaUsuario tipoHistoriaUsuario;
Optional<TipoHistoriaUsuario> entity;
entity = tipoHURepository.findById(id);
if (entity.isPresent()) tipoHistoriaUsuario = entity.get();
else throw new NotFoundException("Tipo historia usuario nรฃo encontrado.");
return tipoHistoriaUsuario;
}// terminar o retrieve para colocar ele dentro de tipoTarefa apllication, dentro do metodo create
public TipoHistoriaUsuario getById(int id) throws NotFoundException{
TipoHistoriaUsuario tipoHU;
Optional<TipoHistoriaUsuario> opTipoHU;
opTipoHU = tipoHURepository.findById(id);
if(opTipoHU.isPresent()){
tipoHU = opTipoHU.get();
return tipoHU;
}
throw new NotFoundException("Tipo de Histรณria de Usuรกrio nรฃo encontrado.");
}
public List<TipoHistoriaUsuario> getAll(){
return tipoHURepository.findAll();
}
public void update(int id,TipoHistoriaUsuarioDTO tipoHUdto){
TipoHistoriaUsuario tipoHU;
try {
tipoHU = getById(id);
tipoHU.setDescricao(tipoHUdto.getDescricao());
/*
//vai ficar aqui
if (tipoHU.getDependencias() != null) {
List<TipoHistoriaUsuario> dependencias = new ArrayList<>();
for (Integer dependenciaId : tipoHUdto.getDependencias()) { // para cada dependencia no epico
TipoHistoriaUsuario dependencia = this.getById(dependenciaId); // get by id - Recebe a dependencia do epico que esta no for
if (dependencia != null) {
dependencias.add(dependencia); // sรณ adiciona
}
}
tipoHU.setDependencias(dependencias);//
}
*/
tipoHURepository.save(tipoHU);
}catch (NotFoundException e)
{
e.getMessage();
}
}
public void delete(int id){
tipoHURepository.deleteById(id);
}
}
|
interface StorageHelperOption {
type: "localStorage"|"sessionStorage"
hyphen?: string
keyPrefix?: string
}
interface StorageHelperConfig extends StorageHelperOption {
hyphen: string
keyPrefix: string
}
export default class StorageHelper {
config: StorageHelperConfig;
storage: Storage;
constructor(options: StorageHelperOption) {
this.config = Object.assign({
hyphen: ":",
keyPrefix: "",
clearBlackList: []
}, options)
this.storage = (window as Window)[options.type]
}
fullKey(key: string) {
const { keyPrefix, hyphen } = this.config
return `${keyPrefix}${hyphen}${key}`
}
getItem(key: string) {
key = this.fullKey(key)
let value: any = this.storage.getItem(key)
if (value) {
value = JSON.parse(value)
}
if (value?.__once__) {
value = value.data
this.storage.removeItem(key)
}
return value
}
setItem(key: string, data: string|number|string|object, once?: boolean) {
key = this.fullKey(key)
const value = JSON.stringify(once ? { __once__: true, data } : data)
this.storage.setItem(key, value)
}
removeItem(key: string) {
key = this.fullKey(key)
this.storage.removeItem(key)
}
clear() {
Object.keys(this.storage).forEach((key: string) => {
if (!/ignore$/i.test(key) && key.indexOf(this.config.keyPrefix) >= 0) {
this.storage.removeItem(key)
}
})
}
}
|
package com.krimo.ticket.exception;
import com.krimo.ticket.dto.ResponseBody;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.NoSuchElementException;
@ControllerAdvice
public class ApiExceptionHandler {
@ExceptionHandler(value = {ApiRequestException.class})
public ResponseEntity<Object> handleRequestException (ApiRequestException e) {
return new ResponseEntity<>(ResponseBody.of(e.getMessage(), e.getStatus(), null), e.getStatus());
}
@ExceptionHandler(value = {NoSuchElementException.class})
public ResponseEntity<Object> handleNoSuchElement (NoSuchElementException e) {
return new ResponseEntity<>(ResponseBody.of("Record not found.", HttpStatus.NOT_FOUND, null), HttpStatus.NOT_FOUND);
}
}
|
47.ๅ
จๆๅII๏ผ
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
n = nums.size();
a = vector<bool>(n,false);
sort(nums.begin(), nums.end());
recur(nums,0);
return ans;
}
private:
void recur(vector<int>& nums, int pos){
if (pos == n){
ans.push_back(chosen);
return;
}
for(int i = 0;i<n;i++){
//ๅชๆ๏ผๅฐi็ๆถๅ๏ผi-1ๅบ่ฏฅๆฏๅๅ่ขซๆค้้ๆฉ๏ผๆไปฅๅชๆๆ
if (i && nums[i]==nums[i-1]&& !a[i - 1]) {
continue;
}
if(!a[i]){
chosen.push_back(nums[i]);
a[i] = true;
recur(nums,pos+1);
chosen.pop_back();
a[i] = false;
}
}
}
int n;
vector<bool> a;
vector<int> chosen;
vector<vector<int>> ans;
// vector<int> vis;
// vis.resize(nums.size());
};
106. ไปไธญๅบไธๅๅบ้ๅๅบๅๆ้ ไบๅๆ
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
this->inorder = inorder;
this->postorder = postorder;
return build(0,inorder.size()-1,0,postorder.size()-1);
}
TreeNode* build(int i1,int i2,int p1,int p2){
if(i1>i2) return nullptr;
TreeNode* root = new TreeNode(postorder[p2]);
int mid = i1;
while(mid <= i2 &&inorder[mid] != root->val) mid++;
root->left = build(i1,mid-1,p1,p1+(mid-i1)-1);
root->right = build(mid+1,i2,p1+(mid-i1),p2-1);
return root;
}
private:
vector<int> inorder;
vector<int> postorder;
};
|
"use client";
import type { ChangeEvent, FormEventHandler } from "react";
import { useState } from "react";
// import type { NextPage } from "next";
import type { FC } from "react";
import { Node as NodeClass } from "@lib/ds/node";
import { NodeComponent } from "@ui/Node";
interface ValueData {
[key: string]: string;
}
interface NodeValueType<T extends ValueData> {
value: T;
previousNode?: NodeClass<T> | null;
nextNode?: NodeClass<T> | null;
}
const NodePage: FC = () => {
const [nodeInstances, setNodeInstances] = useState<
NodeClass<NodeValueType<ValueData>>[]
>([]);
const [nodeInstance, setNodeInstance] = useState<
NodeClass<NodeValueType<ValueData>>
>(
new NodeClass({
value: {
name: "",
},
})
);
const [nodeIndex, setNodeIndex] = useState<number | null>(0);
const [allowNewNode, setAllowNewNode] = useState<string>("parent");
const handleAddParentNode: FormEventHandler<HTMLFormElement> = async (e) => {
e.preventDefault();
try {
setNodeInstances((prev) => [...prev, nodeInstance]);
setNodeInstance(
new NodeClass({
value: {
name: "",
},
})
);
} catch (error) {
console.log("error", error);
}
};
const handleAddChildNode: FormEventHandler<HTMLFormElement> = (e): void => {
e.preventDefault();
const updatedNodeInstance = [...nodeInstances];
const parentNode = updatedNodeInstance[nodeIndex as number];
parentNode?.setNextNode(nodeInstance);
const newChildNode = parentNode?.getNextNode();
newChildNode?.setPreviousNode(
parentNode as NodeClass<NodeValueType<ValueData>>
);
setNodeInstances([
...nodeInstances,
newChildNode as NodeClass<NodeValueType<ValueData>>,
]);
setNodeInstance(
new NodeClass({
value: {
name: "",
},
})
);
};
const handleOnSubmit: FormEventHandler<HTMLFormElement> = (e): void => {
e.preventDefault();
if (allowNewNode === "parent") {
handleAddParentNode(e);
} else {
handleAddChildNode(e);
}
};
const onNewNodeInputChange = ({ target }: ChangeEvent<HTMLInputElement>) => {
setNodeInstance(
(prev) =>
new NodeClass({
...prev.value,
value: {
name: target.value,
},
})
);
};
const handleSelectedNode = (index: number) => {
setNodeIndex(index);
};
return (
<>
<header className="space-y-4">
<h1 className="mb-4 text-4xl font-extrabold leading-none tracking-tight text-gray-900 dark:text-white md:text-5xl lg:text-6xl">
Node
</h1>
<p className="text-lg font-normal text-gray-500 dark:text-gray-400 lg:text-xl">
A node is a basic unit of data storage in a computer system. It is
often used as a building block for more complex data structures such
as linked lists, trees, and graphs.
</p>
</header>
<main className="flex w-full flex-col md:flex-row justify-between gap-4 md:space-x-6 divide-y-2 md:divide-x-2">
<form
onSubmit={handleOnSubmit}
className="flex w-full md:w-1/2 flex-col space-y-4 order-last md:order-first"
>
<h2 className="mb-4 text-2xl font-extrabold leading-none tracking-tight text-gray-900 dark:text-white md:text-4xl lg:text-5xl">
Form
</h2>
<label className="mb-2 block text-sm font-medium text-gray-900 dark:text-white">
Enter data:
</label>
<input
type="text"
value={nodeInstance.value.value.name}
onChange={onNewNodeInputChange}
placeholder="Enter name"
className="block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-blue-500"
/>
<button
value="submit"
className={`rounded-md border-2 bg-red-500 px-4 py-2 font-bold capitalize text-white`}
onClick={() => setAllowNewNode("parent")}
// disabled={!allowNewNode}
>
Add new Parent node
</button>
{nodeInstances.length > 0 && (
<button
value="submit"
className={` rounded-md border-2 bg-blue-500 px-4 py-2 font-bold capitalize text-white`}
onClick={() => setAllowNewNode("child")}
>
Add new Child node
</button>
)}
<h3 className="mb-4 text-xl font-extrabold leading-none tracking-tight text-gray-900 dark:text-white md:text-2xl lg:text-4xl">
How does it work?
</h3>
<p className="text-lg font-normal text-gray-500 dark:text-gray-400 lg:text-xl">
A node typically consists of two main parts:
</p>
<ol className="max-w-md list-inside list-disc space-y-1 text-gray-500 dark:text-gray-400">
<li>
Data: This is the information stored within the node. The data can
be of any type, such as a number, string, or object.
</li>
<li>
Pointers: These are references to other nodes in the data
structure. A node may have one or more pointers, depending on the
type of data structure it is being used in. For example, a node in
a linked list may have a single pointer to the next node in the
list, while a node in a tree may have multiple pointers to its
children.
</li>
</ol>
<p className="text-lg font-normal text-gray-500 dark:text-gray-400 lg:text-xl">
Nodes are typically connected to each other in some way, forming a
chain or a tree-like structure. This allows data to be stored and
accessed in a logical and organized manner, enabling efficient
searching and retrieval of information.{" "}
</p>
<p className="text-lg font-normal text-gray-500 dark:text-gray-400 lg:text-xl">
There are many different types of nodes and data structures that
make use of nodes, each with its own specific characteristics and
uses. Some common examples include singly linked lists, doubly
linked lists, binary trees, and graphs.
</p>
<h3 className="mb-4 text-xl font-extrabold leading-none tracking-tight text-gray-900 dark:text-white md:text-2xl lg:text-4xl">
Implementation (Github repo)
</h3>
<ul>
<li className="font-bold text-blue-500">
<a
href="https://github.com/cmoleka/da-visualizer/blob/dev/lib/ds/node.ts"
target="_blank"
rel="noopener noreferrer"
>
(TypeScript) Node - Implementation
</a>
</li>
<li className="font-bold text-blue-500">
<a
href="https://github.com/cmoleka/datastructures-algorithms/blob/master/datastructures/Nodes.py"
target="_blank"
rel="noopener noreferrer"
>
(Python) Node - Implementation
</a>
</li>
</ul>
</form>
<section className="w-full md:w-1/2 space-y-4 py-4 md:px-4 order-first md:order-last">
<h2 className="mb-4 text-2xl font-extrabold leading-none tracking-tight text-gray-900 dark:text-white md:text-4xl lg:text-5xl">
Visual
</h2>
<div className="">
{nodeInstances.length > 0 ? (
<>
{nodeInstances.map((parendNode, parentIndex) => {
if (parendNode.previousNode === null) {
return (
<div key={parentIndex}>
<p className="tree font-bold text-gray-800 dark:text-gray-300">
Head
</p>
<ul className="tree">
<li onClick={() => handleSelectedNode(parentIndex)}>
<NodeComponent
data={parendNode}
key={parentIndex}
/>
</li>
<ul>
{nodeInstances.map((childNode, childIndex) => {
if (
childNode.previousNode !== null &&
childNode.previousNode.value.value.name ===
parendNode.value.value.name
) {
return (
<li
key={childIndex}
onClick={() =>
handleSelectedNode(childIndex)
}
>
<NodeComponent
key={childIndex}
data={childNode}
/>
</li>
);
}
})}
</ul>
</ul>
</div>
);
}
})}
</>
) : (
<span className="text-xl font-extrabold text-blue-600 dark:text-blue-500">
Add a new node
</span>
)}
</div>
</section>
</main>
</>
);
};
export default NodePage;
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>💔💔💔Hi~~ TYPO GRAPHY</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&family=PT+Serif:wght@400;700&family=Raleway:wght@100;200;300;400;500;600;700;800;900&family=Titillium+Web:wght@200;300;400;600;700;900&display=swap"
rel="stylesheet"
/>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
<link rel="stylesheet" href="css/reset.css" />
<link rel="stylesheet" href="css/common.css" />
<link rel="stylesheet" href="css/swiper-bundle.css" />
<link rel="stylesheet" href="css/fancybox.css" />
<link rel="stylesheet" href="css/layout.css" />
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/greensock/gsap.min.js"></script>
<script src="js/particles.min.js"></script>
<script src="js/isotope.pkgd.min.js"></script>
<script src="js/imagesloaded.pkgd.min.js"></script>
<script src="js/fancybox.umd.js"></script>
<script src="js/lodash.js"></script>
</head>
<body>
<header id="header">
<h1 id="logo"><strong>TYPO GRAPHY</strong></h1>
</header>
<main id="main">
<nav id="filter">
<h2 class="blind">filtering menu</h2>
<ul>
<li class="on" data-filter="item">ALL</li>
<li data-filter="paint">PAINT</li>
<li data-filter="photo">PHOTO</li>
<li data-filter="sketch">SKETCH</li>
</ul>
</nav>
<div id="works">
<ul class="itemList"></ul>
</div>
</main>
<div class="cursor">
<span class="txt"></span>
</div>
<div class="txtBox">
<div>
<label>clientY<input type="text" name="clientY" /></label>
</div>
<div>
<label>pageY<input type="text" name="pageY" /></label>
</div>
<div>
<label>offsetY<input type="text" name="offsetY" /></label>
</div>
<div>
<label>screenY<input type="text" name="screenY" /></label>
</div>
</div>
</body>
<script>
const itemList = $("#works .itemList");
const filterList = $("#filter li");
let grid = null;
$.ajax({ url: "data/typo.json" }).done(function (response) {
console.log(response.imageFolder);
console.log(response.typoList);
const typoList = response.typoList;
const imageFolder = response.imageFolder;
//forEach(function(item,idx){})
let tempHtml = "";
$.each(typoList, function (idx, item) {
tempHtml += `<li class="item ${item.category}">
<a href="${imageFolder + item.img}" data-fancybox="${item.category}"
data-caption="${item.title}
<a href='${item.link}' target='_blank'><span class='material-icons'>open_in_new</span></a>">
<div class="img">
<img src="${imageFolder + item.img}" alt="" />
</div>
<div class="info">
<h2>${item.title}</h2>
<p class="desc">${item.desc}</p>
<p class="point">
<span class="num">${item.point}</span>
</p>
</div>
</a>
</li>`;
});
console.log(tempHtml);
//itemList.innerHtml = tempHtml;
itemList.html(tempHtml);
itemList.imagesLoaded().always(function () {
grid = itemList.isotope({
itemSelector: ".item",
percentPosition: true,
layoutMode: "masonry",
getSortData: {
point: ".point .num parseFloat",
},
});
grid.isotope({ filter: ".item", sortBy: "point", sortAscending: false });
});
});
filterList.on("click", function () {
$(this).addClass("on").siblings().removeClass("on");
console.log($(this).data("filter"));
const filter = $(this).data("filter");
grid.isotope({ filter: `.${filter}`, sortBy: "point", sortAscending: false });
});
// ์ด๋ฒคํธ ์์ (delegation)
$("body").on("click", ".fancybox__caption a", function () {
// console.log($(this).attr("href"));
// return false;
});
const cursor = $(".cursor");
$(window).on(
"mousemove",
_.throttle(function (e) {
$("input[name='clientY']").val(e.clientY);
$("input[name='screenY']").val(e.screenY);
$("input[name='pageY']").val(e.pageY); //์คํฌ๋กค์ clientY + ํ์ด์ง ์คํฌ๋กค๊ฐ ๋ ํฌํจ
$("input[name='offsetY']").val(e.offsetY);
gsap.to(cursor, { left: e.clientX, top: e.clientY });
}, 1000 / 24)
);
$(".itemList").on("mouseenter", "li", function () {
// console.log("sdfe");
cursor.find(".txt").text("CLICK");
gsap.killTweensOf(cursor);
gsap.to(cursor, { width: 100, height: 100, backgroundColor: "#f00", ease: "elastic", duration: 1 });
});
$(".itemList").on("mouseleave", "li", function () {
// console.log("sdfe");
cursor.find(".txt").text("");
gsap.killTweensOf(cursor);
gsap.to(cursor, { width: 20, height: 20, backgroundColor: "#fff", ease: "power4.1", duration: 0.25 });
});
// mousemove ์ด๋ฒคํธ ๋ถํ ์๋๊ฒ ํ๊ธฐ
// <!-- throttling ๋ง์ง๋ง ํจ์๊ฐ ํธ์ถ๋๊ณ ์ผ์ ์๊ฐ์ด ์ง๋ฌ์ ๋ ๋ค์ ํธ์ถ๋๊ฒ ํจ
// debounce ํจ์๊ฐ ์ฐ์ด์ด ํธ์ถ๋ ๋ ๋ง์ง๊ฐ ํจ์๋ง ํธ์ถํจ -->
</script>
</html>
|
#pragma once // Public SDK header
#include "RhRdkDefinitions.h"
class IRhRdk_XMLSection;
class CRhRdkColor;
/** \class IRhRdkDecal
This interface allows RDK clients to access decals that are attached to Rhino objects.
\see CRhRdkObjectDataAccess
*/
RDK_DEPRECATED typedef DWORD RDK_DECALID; // Please use RDK_DECAL_CRC instead.
typedef DWORD RDK_DECAL_CRC;
#define RDK_NIL_DECAL_CRC 0
class RHRDK_SDK IRhRdkDecal
{
public:
virtual ~IRhRdkDecal() { }
enum eMapping
{
mapUnset =-1,
mapPlanar = 0, // Planar mapping. Uses projection, origin, up and across vectors (not unitized).
mapCylindrical = 1, // Cylindrical mapping. Uses origin, up, across, height, radius, latitude start and stop.
mapSpherical = 2, // Spherical mapping. Uses origin, up, across, radius, latitude/longitude start and stop.
mapUV = 3, // UV mapping.
mapForce32bit = 0xFFFFFFFF
};
enum eProjection
{
projUnset =-1,
projForward = 0, // Project forward.
projBackward = 1, // Project backward.
projBoth = 2, // Project forward and backward.
projForce32bit = 0xFFFFFFFF
};
/** This method is deprecated because the name is misleading. The decal 'id' is not
an identifier at all, it's a CRC which changes when the decal changes.
Please change your code to call CRC() instead. */
RDK_DEPRECATED virtual RDK_DECAL_CRC Id(void) const { return CRC(); }
/** The decal CRC identifies a decal by its state. Multiple decals which would be
exactly the same would have the same CRC and are culled from the system.
If you store this value with the intention of using it to find the decal again
later, you must update your stored value whenever the decal state changes.
You can detect when a decal changes by watching for the OnUserDataTransformed event.
\See CRhRdkEventWatcher */
virtual RDK_DECAL_CRC CRC(void) const = 0;
/** \return The decal texture's instance id. */
virtual UUID TextureInstanceId(void) const;
/** \return The decal's texture or null on failure.
\note The returned texture is temporary and only exists as long as
the decal object, so you should not store this pointer. You should
also not store the instance id. If you need the texture again, you
should construct a new decal object and call Texture() each time. */
virtual const CRhRdkTexture* Texture(void) const = 0;
/** Set the decal's texture. The decal copies the texture and this
copy will subsequently be returned by Texture(). */
virtual void SetTexture(const CRhRdkTexture* pTexture) = 0;
/** \return The decal's mapping. */
virtual eMapping Mapping(void) const = 0;
/** \return The decal's projection. Used only when mapping is planar. */
virtual eProjection Projection(void) const = 0;
/** \return \e true if texture is mapped to inside of sphere or cylinder, else \e false.
Used only when mapping is cylindrical or spherical. */
virtual bool MapToInside(void) const = 0;
/** \return The decal's transparency in the range 0 to 1. */
virtual double Transparency(void) const = 0;
/** \return The origin of the decal in world space.
Not used when the mapping is UV. */
virtual ON_3dPoint Origin(void) const = 0;
/** \return The 'up' vector of the decal. For planar mapping the length of the vector is relevant.
Not used when the mapping is UV.
For cylindrical and spherical mapping, the vector is unitized. */
virtual ON_3dVector VectorUp(void) const = 0;
/** \return The 'across' vector of the decal. For planar mapping the length of the vector is relevant.
Not used when the mapping is UV.
For cylindrical and spherical mapping, the vector is unitized. */
virtual ON_3dVector VectorAcross(void) const = 0;
/** \return The height of the decal. Only used when mapping is cylindrical. */
virtual double Height(void) const = 0;
/** \return The radius of the decal. Only used when mapping is cylindrical or spherical. */
virtual double Radius(void) const = 0;
/** This method is deprecated in favor of GetHorzSweep(). \see GetHorzSweep(). */
RDK_DEPRECATED virtual double LatStart(void) const;
/** This method is deprecated in favor of GetHorzSweep(). \see GetHorzSweep(). */
RDK_DEPRECATED virtual double LatEnd(void) const;
/** This method is deprecated in favor of GetVertSweep(). \see GetVertSweep(). */
RDK_DEPRECATED virtual double LonStart(void) const;
/** This method is deprecated in favor of GetVertSweep(). \see GetVertSweep(). */
RDK_DEPRECATED virtual double LonEnd(void) const;
/** Gets the start and end angles of the decal's 'horizontal sweep' (these are angles of longitude in radians).
\note These correspond to the old methods LatStart() and LatEnd() which were badly named.
Only used when mapping is cylindrical or spherical. */
virtual void GetHorzSweep(double& sta, double& end) const = 0;
/** Gets the start and end angles of the decal's 'vertical sweep' (these are angles of latitude in radians).
\note These correspond to the old methods LonStart() and LonEnd() which were badly named.
Only used when mapping is spherical. */
virtual void GetVertSweep(double& sta, double& end) const = 0;
/** The UV bounds of the decal. Only used when mapping is UV. */
virtual void UVBounds(double& dMinUOut, double& dMinVOut, double& dMaxUOut, double& dMaxVOut) const = 0;
/** Get custom data associated with this decal.
\return A pointer to an interface from which you can retrieve custom data,
or NULL if no custom data exists on the decal for the current Rhino renderer. */
virtual const IRhRdk_XMLSection* CustomData(void) const = 0;
/** Blend color with the decal color at a given point.
\param ptPoint is the point in space or, if the decal is uv-mapped, the uv-coordinate of that point.
\param vecNormal is the face normal of the given point.
\param colInOut is the color to blend the decal color to.
\param uvOut is the UV on the texture that the color point was read from
\return \e true if the given point hits the decal, else \e false. */
virtual bool Color(const ON_3dPoint& ptPoint, const ON_3dVector& vecNormal, CRhRdkColor& colInOut, ON_2dPoint& uvOut) const = 0;
/** Emergency virtual function for future expansion. */
virtual void* EVF(const wchar_t*, void*) = 0;
static bool GetTextureMapping(const IRhRdkDecal& decal, ON_TextureMapping& mappingOut);
};
class RHRDK_SDK IRhRdkDecal2 : public IRhRdkDecal
{
public:
//This is mainly for decal access from the change queue
virtual ON__UINT32 TextureRenderCRC(const CRhRdkContent::CRenderCRCFlags& rcrcFlags) const = 0;
virtual ON__UINT32 TextureRenderCRC(const CRhRdkContent::CRenderCRCFlags& rcrcFlags, const IRhRdkLinearWorkflow& lw) const = 0;
};
RHRDK_SDK unsigned int RhRdkGetTextureRenderCRC(const CRhinoDoc& doc, const ON_Decal& decal, ON__UINT64 rcf, const ON_LinearWorkflow* lw);
RHRDK_SDK bool RhRdkGetDecalColor(const CRhinoDoc& doc, const ON_Decal& decal, const ON_3dPoint& ptPoint, const ON_3dVector& vecNormal, ON_4fColor& colInOut, ON_2dPoint& uvOut);
|
---
layout: mypost
title: ๆฐไปๅๅฑๅETLๅฎๆฝ
categories: [ๆ็จ]
extMath: false
---
ๆฐๆฎไปๅบๆฏไธไธชๅๅนถไบๅ็งๆฅๆบ็ๆฐๆฎ๏ผไปฅไพฟๅบไบไธๅก็ฎ็ๅฏนๆฐๆฎ่ฟ่ก็ปไธๅๆ็ๆฐๆฎๅบใETL ้ๅธธ็จไบๅฐๆฐๆฎ็งป่ณๆฐๆฎไปๅบใ
#### ๆฐไปๅๅฑๆถๆ
ๆฐๆฎไปๅบๆ ๅไธๅฏไปฅๅไธบๅๅฑใไฝๆฏ่ฟ็งๅๅๅๅฝๅไธๆฏๅฏไธ็๏ผไธ่ฌๆฐไป้ฝๆฏๅๅฑ๏ผไฝๆฏไธๅๅ
ฌๅธๅฏ่ฝๅซๆณไธๅใไฝๆฏๆ ธๅฟ็็ๅฟต้ฝๆฏไปๅๅฑๆฐๆฎๆจกๅ่ๆฅใ
- ่ดดๆบๅฑ(ODS, Operational Data Store) - ๅๅงๆฐๆฎๅฑ๏ผๅญๆพๅๅงๆฐๆฎ๏ผ็ดๆฅๅ ่ฝฝๅๅงๆฅๅฟใๆฐๆฎ๏ผๆฐไฟๆๅ่ฒไธไฝๅค็
- ๆฐๆฎๆ็ปๅฑ(DWD, Data Warehouse Detail) - ๅฏนODSๅฑๆฐๆฎ่ฟ่กๆธ
ๆด(ๅป้ค็ฉบๅผ,่ๆฐๆฎ,่ถ
่ฟๆ้่ๅด็ๆฐๆฎ)ใ็ปดๅบฆ้ๅใ่ฑๆ็ญ,ๅนถๅบไบ็ปดๅบฆๅปบๆจก,ๆ็ปๅฎฝ่กจ,ๅค็จๅ
ณ่่ฎก็ฎ,ๅๅฐๆฐๆฎๆซๆ
- ๆฐๆฎๆๅกๅฑ(DWS, Data Warehouse Service) - ไปฅDWDไธบๅบ็ก๏ผ่ฟ่ก่ฝปๅบฆๆฑๆป๏ผๆๅปบๅฝๅ่ง่ใๅฃๅพไธ่ด็็ป่ฎกๆๆ ๏ผไธบไธๅฑๆไพๅ
ฌๅ
ฑๆๆ ๏ผๅปบ็ซๆฑๆปๅฎฝ่กจ
- ๆฐๆฎๅบ็จๅฑ(ADS, Application Data Service) - ไปฅDWSไธบๅบ็ก๏ผๆไธป้ข่ฟ่กๆฑๆป๏ผไธบๅ็ง็ป่ฎกๆฅ่กจๆไพไธชๆงๅๆฐๆฎใๅฎฝ่กจ้ๅธใ่ถๅฟๆๆ
#### ไธบไปไน่ฆๅๅฑ
- ๆธ
ๆฐๆฐๆฎ็ปๆ๏ผๆฏไธไธชๆฐๆฎๅๅฑ้ฝๆๅฎ็ไฝ็จๅ๏ผ่ฟๆ ทๆไปฌๅจไฝฟ็จ่กจ็ๆถๅ่ฝๆดๆนไพฟๅฐๅฎไฝๅ็่งฃใ
- ๆนไพฟๆฐๆฎ่ก็ผ่ฟฝ่ธช๏ผ็ฎๅๆฅ่ฏด๏ผๆไปฌๆ็ป็ปไธๅกๅ็ฐ็ๆฏไธไธช่ฝ็ดๆฅไฝฟ็จไธๅก่กจ๏ผไฝๆฏๅฎ็ๆฅๆบๆๅพๅค๏ผๅฆๆๆไธๅผ ๆฅๆบ่กจๅบ้ฎ้ขไบ๏ผๆไปฌๅธๆ่ฝๅคๅฟซ้ๅ็กฎๅฐๅฎไฝๅฐ้ฎ้ข๏ผๅนถๆธ
ๆฅๅฎ็ๅฑๅฎณ่ๅดใ
- ๅๅฐ้ๅคๅผๅ๏ผ่ง่ๆฐๆฎๅๅฑ๏ผๅผๅไธไบ้็จ็ไธญ้ดๅฑๆฐๆฎ๏ผ่ฝๅคๅๅฐๆๅคง็้ๅค่ฎก็ฎใ
- ๆๅคๆ้ฎ้ข็ฎๅๅ๏ผๅฐไธไธชๅคๆ็ไปปๅกๅ่งฃๆๅคไธชๆญฅ้ชคๆฅๅฎๆ๏ผๆฏไธๅฑๅชๅค็ๅไธ็ๆญฅ้ชค๏ผๆฏ่พ็ฎๅๅๅฎนๆ็่งฃใ่ไธไพฟไบ็ปดๆคๆฐๆฎ็ๅ็กฎๆง๏ผๅฝๆฐๆฎๅบ็ฐ้ฎ้ขไนๅ๏ผๅฏไปฅไธ็จไฟฎๅคๆๆ็ๆฐๆฎ๏ผๅช้่ฆไปๆ้ฎ้ข็ๆญฅ้ชคๅผๅงไฟฎๅคใ
- ๅฑ่ฝๅๅงๆฐๆฎ็ๅผๅธธ๏ผๅฑ่ฝไธๅก็ๅฝฑๅ๏ผไธๅฟ
ๆนไธๆฌกไธๅกๅฐฑ้่ฆ้ๆฐๆฅๅ
ฅๆฐๆฎ
### ETL(Extract-Transform-Load)ๅฎๆฝ
ETL๏ผExtract-Transform-Load็็ผฉๅ๏ผๆฏๅฐไธๅก็ณป็ป็ๆฐๆฎ็ป่ฟๆฝๅใๆธ
ๆด่ฝฌๆขไนๅๅ ่ฝฝๅฐๆฐๆฎไปๅบ็่ฟ็จใETLๆฏๆฐๆฎ้ๆ็็ฌฌไธๆญฅ๏ผไนๆฏๆๅปบๆฐๆฎไปๅบๆ้่ฆ็ๆญฅ้ชค๏ผ็ฎ็ๆฏๅฐไผไธไธญ็ๅๆฃใ้ถไนฑใๆ ๅไธ็ปไธ็ๆฐๆฎๆดๅๅฐไธ่ตท๏ผไธบไผไธ็ๅณ็ญๆไพๅๆไพๆฎใETLไธ่ฏ่พๅธธ็จๅจๆฐๆฎไปๅบ๏ผไฝๅ
ถๅฏน่ฑกๅนถไธ้ไบๆฐๆฎไปๅบใ
##### 1.ๆฐๆฎๆฝๅ
ๆฐๆฎๆฝๅๆ็ๆฏไปไธๅ็็ฝ็ปใไธๅ็ๆไฝๅนณๅฐใไธๅ็ๆฐๆฎๅบๅๆฐๆฎๆ ผๅผใไธๅ็ๅบ็จไธญๆฝๅๆฐๆฎ็่ฟ็จใ็ฎๆ ๆบๅฏ่ฝๅ
ๆฌERPใCRMๅๅ
ถไปไผไธ็ณป็ป๏ผไปฅๅๆฅ่ช็ฌฌไธๆนๆบ็ๆฐๆฎใ
ไธๅ็็ณป็ปๅพๅไบไฝฟ็จไธๅ็ๆฐๆฎๆ ผๅผ๏ผๅจ่ฟไธช่ฟ็จไธญ๏ผ้ฆๅ
้่ฆ็ปๅไธๅก้ๆฑ็กฎๅฎๆฝๅ็ๅญๆฎต๏ผๅฝขๆไธๅผ ๅ
ฌๅ
ฑ้ๆฑ่กจๅคด๏ผๅนถไธๆฐๆฎๅบๅญๆฎตไนๅบไธ่ฟไบ้ๆฑๅญๆฎตๅฝขๆไธไธๆ ๅฐๅ
ณ็ณปใ่ฟๆ ท้่ฟๆฐๆฎๆฝๅๆๅพๅฐ็ๆฐๆฎ้ฝๅ
ทๆ็ปไธใ่งๆด็ๅญๆฎตๅ
ๅฎน๏ผไธบๅ็ปญ็ๆฐๆฎ่ฝฌๆขๅๅ ่ฝฝๆไพๅบ็ก๏ผๅ
ทไฝๆญฅ้ชคๅฆไธ๏ผ
โ ็กฎๅฎๆฐๆฎๆบ๏ผ้่ฆ็กฎๅฎไปๅชไบๆบ็ณป็ป่ฟ่กๆฐๆฎๆฝๅ
โกๅฎไนๆฐๆฎๆฅๅฃ๏ผๅฏนๆฏไธชๆบๆไปถๅ็ณป็ป็ๆฏไธชๅญๆฎต่ฟ่ก่ฏฆ็ป่ฏดๆ
โข็กฎๅฎๆฐๆฎๆฝๅ็ๆนๆณ๏ผๆฏไธปๅจๆฝๅ่ฟๆฏ็ฑๆบ็ณป็ปๆจ้๏ผๆฏๅข้ๆฝๅ่ฟๆฏๅ
จ้ๆฝๅ๏ผๆฏๆ็
งๆฏๆฅๆฝๅ่ฟๆฏๆ็
งๆฏๆๆฝๅ๏ผ
##### 2.ๆฐๆฎ่ฝฌๆข
ๆฐๆฎ่ฝฌๆขๅฎ้
ไธ่ฟๅ
ๅซไบๆฐๆฎๆธ
ๆด็ๅทฅไฝ๏ผ้่ฆๆ นๆฎไธๅก่งๅๅฏนๅผๅธธๆฐๆฎ่ฟ่กๆธ
ๆด๏ผไธป่ฆๅฐไธๅฎๆดๆฐๆฎใ้่ฏฏๆฐๆฎใ้ๅคๆฐๆฎ่ฟ่กๅค็๏ผไฟ่ฏๅ็ปญๅๆ็ปๆ็ๅ็กฎๆงใ
ๆฐๆฎ่ฝฌๆขๅฐฑๆฏๅค็ๆฝๅไธๆฅ็ๆฐๆฎไธญๅญๅจ็ไธไธ่ด็่ฟ็จใๆฐๆฎ่ฝฌๆขไธ่ฌๅ
ๆฌไธค็ฑป๏ผ็ฌฌไธ็ฑป๏ผๆฐๆฎๅ็งฐๅๆ ผๅผ็็ปไธ๏ผๅณๆฐๆฎ็ฒๅบฆ่ฝฌๆขใๅๅก่งๅ่ฎก็ฎไปฅๅ็ปไธ็ๅฝๅใๆฐๆฎๆ ผๅผใ่ฎก้ๅไฝ็ญ๏ผ็ฌฌไบ็ฑป๏ผๆฐๆฎไปๅบไธญๅญๅจๆบๆฐๆฎๅบไธญๅฏ่ฝไธๅญๅจ็ๆฐๆฎ๏ผๅ ๆญค้่ฆ่ฟ่กๅญๆฎต็็ปๅใๅๅฒๆ่ฎก็ฎใไธป่ฆๆถๅไปฅไธๅ ไธชๆน้ข๏ผ
โ ็ฉบๅผๅค็๏ผๅฏๆ่ทๅญๆฎต็ฉบๅผ๏ผ่ฟ่กๅ ่ฝฝๆๆฟๆขไธบๅ
ถไปๅซไนๆฐๆฎ๏ผๆๆฐๆฎๅๆต้ฎ้ขๅบ
โกๆฐๆฎๆ ๅ๏ผ็ปไธๅ
ๆฐๆฎใ็ปไธๆ ๅๅญๆฎตใ็ปไธๅญๆฎต็ฑปๅๅฎไน
โขๆฐๆฎๆๅ๏ผไพๆฎไธๅก้ๆฑๅๆฐๆฎๆๅ๏ผๅฆ่บซไปฝ่ฏๅท๏ผๆๅๅบๅใๅบ็ๆฅๆใๆงๅซ็ญ
โฃๆฐๆฎ้ช่ฏ๏ผๆถ้ด่งๅใไธๅก่งๅใ่ชๅฎไน่งๅ
โคๆฐๆฎๆฟๆข๏ผๅฏนไบๅ ไธๅกๅ ็ด ๏ผๅฏๅฎ็ฐๆ ๆๆฐๆฎใ็ผบๅคฑๆฐๆฎ็ๆฟๆข
โฅๆฐๆฎๅ
ณ่๏ผๅ
ณ่ๅ
ถไปๆฐๆฎๆๆฐๅญฆ๏ผไฟ้ๆฐๆฎๅฎๆดๆง
**ๅฎไฝ่งฃๆ**
็ฎ่ฏด๏ผๆฅ่ชไธๅ็ๆฐๆฎๆบ็ๆฐๆฎ๏ผๅณไพฟไปไปฌ่กจ็คบ็ๆฏๅๆ ท็ๅฏน่ฑก๏ผๅฎไฝ๏ผ๏ผไฝๆฏๅ
ทไฝ็ๆฐๆฎๆๅฏ่ฝๆฏไธไธๆ ท็ใ
ๅฎไฝ่งฃๆ๏ผEntity resolution๏ผๅ็่ฎฐๅฝๅๅนถ๏ผMerge๏ผ
ๆพๅบไบ่กจ็คบๅไธๅฏน่ฑก็่ฎฐๅฝไปฅๅ๏ผๅฆไฝๅๅนถ่ฟไบๆฐๆฎ๏ผไป็ถๆฏไธไธช้ฎ้ขใๅฆๆไธๅ็่ฎฐๅฝ๏ผๅไธชๅญๆฎตๅชๆๆผๅ้่ฏฏๆ่
้็จไบไธๅ็ๅไน่ฏ็ญๆ
ๅต๏ผๅๅนถ่ฎฐๅฝไธๆฏๅฐ้พ็ไบๆ
ใไฝๆฏๅฆๆๆฐๆฎๆฌ่บซๅญๅจๅฒ็ช๏ผ่ฆๆพๅฐๅชไธชๅผๆฏๆญฃ็กฎ็๏ผไธๆฏไปถๅฎนๆ็ไบใๅจ่ฟ็งๆ
ๅตไธ๏ผๆไปฌๅฏไปฅๆๆๆ็็ปๆ้ฝๆฅๅๅบๆฅใ
- ๆๆฌไธๆง่ฝๅนณ่กก
้ๅฝ็ๆฐๆฎๅไฝๅฏๆขๅๆฅ่ฏขๅๅทๆฐๆง่ฝ๏ผไธๅฎ่ฟๅบฆๅไฝไธๆฐๆฎๅคๅถใ
- ๆฐๆฎๅฏๅๆป
ๅค็้ป่พไธๅ๏ผๅจไธๅๆถ้ดๅคๆฌก่ฟ่กๆฐๆฎ็็ปๆ้็กฎๅฎไธๅใ
- ไธ่ดๆง
็ธๅ็ๅญๆฎตๅจไธๅ่กจไธญ็ๅญๆฎตๅๅฟ
้กป็ธๅใ
- ๅฝๅๆธ
ๆฐๅฏ็่งฃ
่กจๅฝๅ่ง่้ๆธ
ๆฐใไธ่ด๏ผ่กจๅฝๅ้ๆไบไธๆธธ็็่งฃๅไฝฟ็จใ
##### 3.ๆฐๆฎๅ ่ฝฝ
ๆฐๆฎๅ ่ฝฝ็ไธป่ฆไปปๅกๆฏๅฐ็ป่ฟๆธ
ๆดๅ็ๅนฒๅ็ๆฐๆฎ้ๆ็
ง็ฉ็ๆฐๆฎๆจกๅๅฎไน็่กจ็ปๆ่ฃ
ๅ
ฅ็ฎๆ ๆฐๆฎไปๅบ็ๆฐๆฎ่กจไธญ๏ผๅฆๆๆฏๅ
จ้ๆนๅผๅ้็จLOADๆนๅผ๏ผๅฆๆๆฏๅข้ๅๆ นๆฎไธๅก่งๅMERGE่ฟๆฐๆฎๅบ๏ผๅนถๅ
่ฎธไบบๅทฅๅนฒ้ข๏ผไปฅๅๆไพๅผบๅคง็้่ฏฏๆฅๅใ็ณป็ปๆฅๅฟใๆฐๆฎๅคไปฝไธๆขๅคๅ่ฝใๆดไธชๆไฝ่ฟ็จๅพๅพ่ฆ่ทจ็ฝ็ปใ่ทจๆไฝๅนณๅฐใ
ๅจๅฎ้
็ๅทฅไฝไธญ๏ผๆฐๆฎๅ ่ฝฝ้่ฆ็ปๅไฝฟ็จ็ๆฐๆฎๅบ็ณป็ป๏ผOracleใMysqlใSparkใImpala็ญ๏ผ๏ผ็กฎๅฎๆไผ็ๆฐๆฎๅ ่ฝฝๆนๆก๏ผ่็บฆCPUใ็กฌ็IOๅ็ฝ็ปไผ ่พ่ตๆบใ
> ๅ่่ตๆ
> https://cloud.google.com/learn/what-is-etl?hl=zh-cn
> https://blog.csdn.net/Mogeko1/article/details/129427039
> https://zhuanlan.zhihu.com/p/550273838
|
<script setup lang="ts">
import { ErrorMessage, useField } from 'vee-validate';
import { computed } from 'vue';
import startCase from 'lodash/startCase';
const props = defineProps<{
name: string;
type?: string;
label?: string;
help?: string;
labelAfter?: boolean;
inputWrapperClasses?: string;
onLabelClick?: () => void;
checkedValue?: unknown;
uncheckedValue?: unknown;
}>();
const fieldParams = useField(props.name, undefined, {
type: props.type,
checkedValue: props.checkedValue ?? true,
valueProp: props.checkedValue ?? false,
uncheckedValue: props.uncheckedValue ?? false,
validateOnValueUpdate: false,
});
const labelValue = computed(() => {
return props.label ?? startCase(props.name.split('.').reverse()[0]);
});
</script>
<script lang="ts">
export default {
inheritAttrs: false,
};
</script>
<template>
<div class="mb-4">
<FabLabel v-if="props.label !== 'false' && !labelAfter" :for="name" @click="onLabelClick">
<slot v-if="$slots.label" name="label"></slot>
<span v-else>{{ labelValue }}</span>
</FabLabel>
<div :class="inputWrapperClasses">
<slot name="default" v-bind="{ field: fieldParams }"></slot>
<FabLabel v-if="props.label !== 'false' && labelAfter" :for="name" @click="onLabelClick">
<slot v-if="$slots.label" name="label"></slot>
<span v-else>
{{ labelValue }}
</span>
</FabLabel>
</div>
<p v-if="help" class="mt-1 block text-gray-700 text-sm">{{ help }}</p>
<ErrorMessage :name="name" class="mt-1 block text-error-600 text-sm" />
</div>
</template>
|
#ifndef INCLUDE_ERRORS_H
#define INCLUDE_ERRORS_H
// errors.h
// Revision 3-feb-2011
#include "token.h"
#include <stdexcept>
class InternalError : public std::runtime_error
{
public:
InternalError(const std::string &msg);
~InternalError() throw () {}
};
class CompileError : public std::runtime_error
{
public:
CompileError(const std::string &msg);
CompileError(const std::string &msg, const Token &where);
~CompileError() throw () {}
unsigned int linenum() const;
std::string file() const;
private:
Token w;
};
class Unsupported : public CompileError
{
public:
Unsupported(const std::string &msg, const Token &where);
};
class UnsupportedInStage : public CompileError
{
public:
UnsupportedInStage(const std::string &msg, const Token &where);
};
class SyntaxError : public CompileError
{
public:
SyntaxError(const std::string &msg, const Token &where);
};
class Expected : public SyntaxError
{
public:
Expected(char msg, const Token &where);
Expected(const std::string &msg, const Token &where);
};
#endif
// End of errors.h
|
import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faImage } from '@fortawesome/free-solid-svg-icons';
import './postBox.scss'
import { useContext } from 'react';
import { GlobleContext } from '../..';
export default function PostBox() {
const {state, dispatch} = useContext(GlobleContext)
const user = JSON.parse(localStorage.getItem('user'));
const handleClick = () => {
document.body.classList.add('fixed');
dispatch({
type:'feedShareForm',
showFeedShareForm: !state.showFeedShareForm
})
}
const getFileUrl = (e) => {
const file = e.target.files[0];
// read file to preview image
const reader = new FileReader();
reader.onload = () => {
const url = reader.result;
dispatch({
type:'setPostDatas',
postDatas : { title:state.postDatas.title,
content:state.postDatas.content,
fileUrl:url,
file:e.target.files[0]
}
})
};
if(e.target.files[0]){
reader.readAsDataURL(file);
}
// show form to edit post
dispatch({
type:'feedShareForm',
showFeedShareForm:true
})
}
return (
<section className='main__postBox'>
<div className='content'>
<div className='content__avatar'>
<img className='avatarImg' src={user.avatar === null? './avatar_default.jpg' : user.avatar} alt="avatar" />
</div>
<p className='content__editor' onClick = {handleClick}>รฉcrivez quelquechose...</p>
</div>
<div className='toolbar'>
<label htmlFor="file" className='toolbar__photo'>
Photo
<FontAwesomeIcon icon={faImage} />
<input id = "file" className = 'uploadInput' type="file" onChange = {getFileUrl}/>
</label>
</div>
</section>
)
}
|
/// @description initialization
///=====INIT
///=========
//capman's sprites are stored in this array for ease of access
/* TODO: Maybe devise a different system for this,
or else implement this system for other objs, namely enemies*/
_spriteArray = [spr_capman_new_right, spr_capman_new_left, spr_capman_new_up, spr_capman_new_down,
spr_capman_0, spr_capman_1, spr_capman_2, spr_capman_3];
alarm_set(5, room_speed);
///=====FUNCTIONS
/* move player in a direction
@uses: _MOVESPEED
@param: string like up down left right
@return: void
*/
function _moveInDirection (direction)
{
switch (direction)
{
case "left":
_spriteArrayIndex = 1;
x = x - p_moveSpeed;
break;
case "right":
_spriteArrayIndex = 0;
x = x + p_moveSpeed;
break;
case "up":
_spriteArrayIndex = 2;
y = y - p_moveSpeed;
break;
case "down":
_spriteArrayIndex = 3;
y = y + p_moveSpeed;
break;
}
if p_isPowered
_spriteArrayIndex += 4;
sprite_index = _spriteArray[_spriteArrayIndex];
}
/* check if player is able to move in a direction
@uses: p_moveSpeed
@param: string like up down left right
@return: boolean
*/
function _checkCollisionInDirection (direction)
{
switch (direction)
{
case "left":
if place_free(x - (p_moveSpeed), y)
return true;
break;
case "right":
if place_free(x + (p_moveSpeed), y)
return true;
break;
case "up":
if place_free(x, y - (p_moveSpeed))
return true;
break;
case "down":
if place_free(x, y + (p_moveSpeed))
return true;
break;
default:
return false;
}
}
/* convert key presses to a string
represeting the direction the player wants to move,
then updates _directionStored accordingly
@changes: _directionStored
@return: void
*/
function _updateDirectionStored ()
{
if keyboard_check(vk_left)
{
_directionStored = "left";
}
else if keyboard_check(vk_right)
{
_directionStored = "right";
}
else if keyboard_check(vk_up)
{
_directionStored = "up";
}
else if keyboard_check(vk_down)
{
_directionStored = "down";
}
}
//_direction Getter
function p_getDirection ()
{
return _direction;
}
|
import pytest
import time
from utility.utility import Utility
from pages.logout import Logout
@pytest.mark.usefixtures("getDriver")
class TestCases:
# test case to validate login functionality with invalid login and password
def test_invalid_login_functionality(self, login_page):
email = Utility.getjsondata('login', 'invalidemail')
password = Utility.getjsondata('login', 'invalidpassword')
login_page.login(email, password)
login_page.verify_invalidlogin_message()
# test case to validate login functionality with valid email and password
def test_valid_login_functionality(self, login_page):
email = Utility.getjsondata('login', 'email')
password = Utility.getjsondata('login', 'password')
login_page.login(email, password)
login_page.verify_homelink()
# test to verify that validation message display correctly when user hit save button without entering the required field
def test_validation_messagedisplay(self, customer_page):
customer_page.click_customerlink()
customer_page.click_list()
customer_page.click_addcustomerbutton()
customer_page.click_savebutton()
time.sleep(2)
customer_page.check_validationmessage()
# test to verify new customer account gets created after entring the required data in cusotmer form
def test_create_newcustomer(self, customer_page):
name = Utility.generate_customerdata("customerpage", "name")
s3folder = Utility.generate_customerdata("customerpage", "s3folder")
customer_page.enterdata_customerpage(name, s3folder)
customer_page.update_loginvalue()
customer_page.click_savebutton()
# test to verify that user gets logged out successfully
def test_logout_functionality(self):
logoutpage = Logout(self.driver)
logoutpage.logout()
# test to verify that user can login successfully with new account credential
def test_login_with_newaccount(self, login_page):
newcustomer_email = Utility.getjsondata('customerpage', 'logincustomaer')
newcustomer_password = Utility.getjsondata('customerpage', 'loginpassword')
login_page.login(newcustomer_email, newcustomer_password)
login_page.verify_homelink()
logoutpage = Logout(self.driver)
logoutpage.logout()
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Power_Fitness.Utenti
{
class Utente
{
// Costanti per le route delle API
public const string GetUtentiRoute = "GetUsers";
public const string AddUtenteRoute = "AddUser";
public const string UpdateUtenteRoute = "UpdateUser";
public const string DeleteUtenteRoute = "DeleteUser";
// usiamo i vari attributi di annotazione di Newtonsoft.Json (Json.NET)
// [JsonProperty("nome_attributo")] per indicare come l'oggetto deve essere serializzato
// o deserializzato rispetto a un nome specifico nel JSON
[JsonProperty("id")]
public int ValoreId { get; set; }
[JsonProperty("codice_fiscale")]
public string CodiceFiscale { get; set; }
[JsonProperty("nome")]
public string Nome { get; set; }
[JsonProperty("cognome")]
public string Cognome { get; set; }
[JsonProperty("genere")]
public string Genere { get; set; }
[JsonProperty("data_nascita")]
[JsonConverter(typeof(CustomDateTimeConverter))]
public DateTime DataNascita { get; set; }
[JsonProperty("cellulare")]
public string Cellulare { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("indirizzo")]
public string Indirizzo { get; set; }
[JsonProperty("numero_civico")]
public string NumeroCivico { get; set; }
// Costruttore senza argomenti
public Utente()
{
}
public Utente(int valoreId, string codiceFiscale, string nome, string cognome, string genere,
DateTime dataNascita, string cellulare, string email, string indirizzo, string numeroCivico)
{
ValoreId = valoreId;
CodiceFiscale = codiceFiscale;
Nome = nome;
Cognome = cognome;
Genere = genere;
DataNascita = dataNascita;
Cellulare = cellulare;
Email = email;
Indirizzo = indirizzo;
NumeroCivico = numeroCivico;
}
public Utente(string codiceFiscale, string nome, string cognome, string genere,
DateTime dataNascita, string cellulare, string email, string indirizzo, string numeroCivico)
{
CodiceFiscale = codiceFiscale;
Nome = nome;
Cognome = cognome;
Genere = genere;
DataNascita = dataNascita;
Cellulare = cellulare;
Email = email;
Indirizzo = indirizzo;
NumeroCivico = numeroCivico;
}
}
public class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
}
}
|
from sqlalchemy import Column, String, Enum, ForeignKey, BigInteger, update, delete
from sqlalchemy.orm import Session
from sqlalchemy.orm import relationship
from limoo import LimooDriver
from . import Base, create_model
from .conversation import get_or_add_conversation
from .user import User
class TaskStatus(Enum):
TODO = 'todo'
DONE = 'done'
SUSPENDED = 'suspended'
class Task(Base):
__tablename__ = "tasks"
id = Column(String, primary_key=True, index=True)
description = Column(String)
direct_reply_message_id = Column(String) # FIXME: use for subtasks? also use in message subtasks?
thread_root_id = Column(String)
status = Column(Enum(TaskStatus.TODO, TaskStatus.DONE, length=20), nullable=False, default=TaskStatus.TODO,
index=True)
create_at = Column(BigInteger, index=True)
# due_date = None # FIXME
# remind_date = None # FIXME
# remind_with_sms = None # FIXME
# follow_up_interval = None # FIXME
# follow_up_interval_max = None # FIXME
# priority = None # FIXME
# labels = None # FIXME
conversation_id = Column(String, ForeignKey('conversations.id'))
conversation = relationship('Conversation', back_populates='tasks')
workspace_id = Column(String, ForeignKey('workspaces.id'))
workspace = relationship('Workspace', back_populates='tasks')
reporter_id = Column(String, ForeignKey('users.id'), nullable=True)
reporter = relationship('User', back_populates='reported_tasks', foreign_keys=[reporter_id])
assignee_id = Column(String, ForeignKey('users.id'))
assignee = relationship('User', back_populates='assigned_tasks', foreign_keys=[assignee_id])
def get_task(db: Session, id: str) -> Task:
return db.query(Task).get(id)
def update_task(db: Session, msg_event, assignee: User, status: TaskStatus):
message_id_ = msg_event['data']['message']['id']
message_text_ = msg_event['data']['message']['text']
update_statement = update(Task).where(Task.id == message_id_).values({
Task.description: message_text_,
Task.assignee: assignee,
Task.status: status,
})
db.execute(update_statement)
db.commit()
async def add_task(db: Session, ld: LimooDriver, msg_event, reporter: User, assignee: User, status: TaskStatus) -> Task:
conversation = await get_or_add_conversation(db, ld, msg_event)
new_task = Task(id=(msg_event['data']['message']['id']), description=(msg_event['data']['message']['text']),
direct_reply_message_id=msg_event['data']['message']['direct_reply_message_id'],
thread_root_id=msg_event['data']['message']['thread_root_id'],
status=status, create_at=msg_event['data']['message']['create_at'],
conversation_id=conversation.id, workspace_id=msg_event['data']['workspace_id'],
reporter=reporter, assignee=assignee, )
return create_model(db, new_task)
def delete_task(db: Session, task: Task):
delete_statement = delete(Task).where(Task.id == task.id)
db.execute(delete_statement)
db.commit()
|
<script setup lang="ts">
/* global miner */
/* Import modules. */
import gravatar from 'gravatar'
import numeral from 'numeral'
import init, { welcome } from "../libs/miner.js"
const blocks = ref(null)
const difficulty = ref(null)
const networkhashps = ref(null)
const marketValue = ref(null)
const miningCost = ref(null)
const multiplier = ref(null)
const displayAvatar = computed(() => {
return '~/assets/lottie/9994-name-profile-icon-animation-circle.gif'
// if (this.$store.state.profile.authenticated) {
// return gravatar.url(this.$store.state.profile.user.email)
// } else {
// return '~/assets/lottie/9994-name-profile-icon-animation-circle.gif'
// }
})
const openWebMining = async () => {
// Instantiate our wasm module
// const miner = await init('miner_bg.wasm')
const miner = await init()
console.log('MINER', miner)
welcome('Anon2')
}
</script>
<Script ></Script>
<template>
<main aria-labelledby="profile-overview-title">
<div class="rounded-lg bg-white overflow-hidden shadow">
<h2 class="sr-only" id="profile-overview-title">Profile Overview</h2>
<div class="bg-white p-6">
<div class="sm:flex sm:items-center sm:justify-between">
<div class="sm:flex sm:space-x-5">
<NuxtLink to="/profile" class="flex-shrink-0">
<img
class="mx-auto h-20 w-20 rounded-full"
src="~/assets/lottie/9994-name-profile-icon-animation-circle.gif"
alt="profile / avatar"
/>
</NuxtLink>
<div class="mt-4 text-center sm:mt-0 sm:pt-1 sm:text-left">
<p class="text-sm font-medium text-gray-600">Minado</p>
<p class="text-xl font-bold text-gray-900 sm:text-2xl">Welcome Guest</p>
<p class="text-sm font-medium text-gray-600">NEXA Premier Mining Pool</p>
</div>
</div>
<div class="mt-5 flex justify-center sm:mt-0">
<button @click="openWebMining" class="flex justify-center items-center px-4 py-2 border border-gray-300 shadow text-lg font-bold rounded-lg text-yellow-200 bg-blue-800 hover:bg-blue-600">
Start Web Mining
</button>
</div>
</div>
</div>
<div class="border-t border-gray-200 bg-gray-50 grid grid-cols-1 divide-y divide-gray-200 sm:grid-cols-3 sm:divide-y-0 sm:divide-x">
<div class="grid grid-cols-1 divide-y divide-gray-200">
<section class="flex flex-col items-center justify-center">
<h3 class="text-xs text-gray-400">
Market Capitalization
</h3>
<div v-html="displayMarketCap"></div>
</section>
<section class="flex flex-col items-center justify-center">
<h3 class="text-xs text-gray-400">
Network Difficulty
</h3>
<div v-html="displayDifficulty"></div>
</section>
<section class="flex flex-col items-center justify-center">
<h3 class="text-xs text-gray-400">
Network Hashrate
</h3>
<div v-html="displayHashrate"></div>
</section>
</div>
<div @click="openArbitrage" class="group cursor-pointer flex flex-col justify-center px-6 py-5 text-sm font-medium text-center">
<span class="text-gray-600 text-2xl tracking-widest">
Market Value
</span>
<span class="text-2xl text-green-500">
{{displayMarketValue}}
<sup class="text-xs opacity-50">USD</sup>
</span>
<span class="text-gray-400 text-xs">
Value Per MEX <span class="font-medium text-gray-600">(VPM)</span>
</span>
<div class="my-3 relative">
<div class="absolute inset-0 flex items-center" aria-hidden="true">
<div class="w-full border-t border-gray-300"></div>
</div>
<div class="relative flex justify-center">
<div class="inline-flex items-center rounded-full border border-gray-300 bg-white px-4 py-1.5 text-xl font-bold leading-5 text-rose-500 shadow transform duration-300 ease-in group-hover:bg-rose-600 group-hover:text-rose-100 group-hover:text-2xl">
<span>{{displayMultiplier}}</span>
</div>
</div>
</div>
<span class="text-gray-600 text-2xl tracking-widest">
Mining Cost
</span>
<span class="text-2xl text-green-500">
{{displayMiningCost}}
<sup class="text-xs opacity-50">USD</sup>
</span>
<span class="text-gray-400 text-xs">
Cost Per MEX <span class="font-medium text-gray-600">(CPM)</span>
</span>
</div>
<div class="grid grid-cols-1 divide-y divide-gray-200">
<section class="flex flex-col items-center justify-center">
<h3 class="text-xs text-gray-400">
Pool Hashrate
</h3>
<div v-html="displayPoolHashrate"></div>
</section>
<section class="flex flex-col items-center justify-center">
<h3 class="text-xs text-gray-400">
Last Block Found
</h3>
<div v-html="displayLastBlock"></div>
</section>
<section class="flex flex-col items-center justify-center">
<h3 class="text-xs text-gray-400">
Platform Hashrate
</h3>
<div v-html="displayPlatformHashrate"></div>
</section>
</div>
</div>
</div>
</main>
</template>
|
package com.example.server.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* Data Transfer Object (DTO) representing a user registration request.
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class RegistrationDTO {
/**
* The email associated with the registration request.
*/
private String email;
/**
* The name associated with the registration request.
*/
private String name;
/**
* The password associated with the registration request.
*/
private String password;
}
|
import { type Page, expect } from '@playwright/test';
import { pageUtils } from '../../utils/page-utils';
import { homePageObject } from '../../page-objects/home/home-page-object';
export const homePage = () => {
/** Function to navigate to sportsbet home page */
const navigateToHomePage = async (page: Page, hostname: string, path: string): Promise<void> => {
await pageUtils().navigateTo(page, hostname, path);
await expect(page).toHaveTitle(/^Best Online Horse Racing \w+ Sports Betting | Sportsbet$/);
await expect(page.locator(homePageObject.sportsBetLogo)).toBeVisible();
};
/** Function to select first race card from sportsbet home page */
const selectRaceCardFromGroupOne = async (page: Page, horseNumber: number) => {
await expect(page.locator(homePageObject.getCarouselCellTitle(1, 1)).first()).toBeVisible();
const carouselCellText = await page.locator(homePageObject.getCarouselCellTitle(1, 1)).first().textContent();
await page.locator(homePageObject.getNthHorse(horseNumber)).click();
return carouselCellText;
};
return {
navigateToHomePage: async (page: Page, hostname: string, path: string): Promise<void> => navigateToHomePage(page, hostname, path),
selectRaceCardFromGroupOne: async (page: Page, horseNumber: number) => selectRaceCardFromGroupOne(page, horseNumber),
};
};
|
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Tutorial de SDL2Me</title>
<link rel="stylesheet" href="style.css" />
<script language="javascript">
function toggle(ar, tx) {
var ele = document.getElementById(tx);
var text = document.getElementById(ar);
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "►";
} else {
ele.style.display = "block";
text.innerHTML = "▼";
}
}
function button() {
document.getElementById("title").style.textDecoration = "underline";
//document.write("holaaa");
}
</script>
<script type="text/javascript" src="syntaxhighlighter/scripts/shCore.js"></script>
<script type="text/javascript" src="syntaxhighlighter/scripts/shBrushCpp.js"></script>
<link type="text/css" rel="stylesheet" href="syntaxhighlighter/styles/shCoreDefault.css"/>
<script type="text/javascript">SyntaxHighlighter.all();</script>
</head>
<body>
<div class="wrap">
<div class="content">
<h1 id="title">Tutorial de SDL2Me</h1>
<p>Asรญ que quieres programar un juego usando SDL2Me... Voy a intentar guiarte por las ideas y conceptos bรกsicos de este engine, y progresivamente profundizar en los aspectos mรกs intrincados para que una vez hayas finalizado este tutorial, sepas dominar la librerรญa y crear juegos impresionantes y de gran rendimiento con relativa facilidad.</p>
<h2>Tabla de Contenidos</h2>
<ol>
<li><a href="#1">ยฟQuรฉ es SDL2Me?</a></li>
<li><a href="#2">Conocimientos previos</a></li>
<li><a href="#3">Elementos de un juego en S2M</a></li>
<li><a href="#4">Manos a la obra. Estructura bรกsica de un juego</li>
</ol>
<h2 id="1"><a id="arrow1" class="arrow" href="javascript:toggle('arrow1','text1');">▼</a>ยฟQuรฉ es SDL2Me?</h2>
<div id="text1" style="display: block;">
<p>SDL2Me (o S2M) es un engine de juegos en 2D que funciona con SDL2. El enfoque principal de esta librerรญa es su facilidad de uso, por lo tanto el objetivo primordial es crear un surtido de clases y funciones que funcionen a la par, mantengan una abstracciรณn de SDL coherente con el modelo implementado en el software GameMaker y sean facilmente derivables para y por el usuario final.</p>
</div>
<h2 id="2"><a id="arrow2" class="arrow" href="javascript:toggle('arrow2','text2');">▼</a>Conocimientos previos</h2>
<div id="text2" style="display: block;">
<ul>
<li>Conocimientos avanzados de C++, esto incluye:
<ul>
<li>Bรกsica de programaciรณn (condiciones, bucles, tipos de variables, operadores...)</li>
<li>Programaciรณn Orientada a Objetos (friendship, inheritance, polymorphism...)</li>
<li>Conceptos mรกs avanzados de C++ como punteros, templates, dynamic casting, etc.</li>
</ul>
</li>
<li>Programaciรณn de videojuegos. Si no sabes quรฉ es el game-loop abstente siquiera de seguir leyendo. Hay muchos tutoriales de iniciaciรณn en la programaciรณn de videojuegos en internet que te servirรกn de base si es que luego decides continuar con SDL2Me.</li>
<li>Conocimientos de SDL, la versiรณn 2 en concreto. Si te quedaste en la 1 puedes echarle una ojeada a la <a href="http://wiki.libsdl.org/MigrationGuide">Guรญa de Migraciรณn</a> o a los magnรญficos tutoriales de <a href="http://lazyfoo.net/tutorials/SDL/index.php">Lazy Foo</a>, que se actualizan cada mes.</li>
<li>Aunque no sea estrictamente necesario, no viene de mรกs haberse familiarizado con el entorno de GameMaker previamente</li>
</ul>
</div>
<h2 id="3"><a id="arrow3" class="arrow" href="javascript:toggle('arrow3','text3');">▼</a>Elementos de un juego en S2M</h2>
<div id="text3" style="display: block;">
<div id="sprites">
<p>Lo primero que debes saber es cรณmo se organiza un juego en S2M. Para empezar, tienes los Sprites:</p><img src="img/sprite.png" class="fright"><p>Los <b>Sprites</b> son todos aquellos grรกficos de un juego que se mueven por pantalla, relativamente pequeรฑos en comparaciรณn con el รกrea del juego en sรญ. Los Sprites se animan y van cambiando con el tiempo, aunque en S2M los entenderemos como una simple estructura de datos y aquellos que serรกn animados serรกn los Objects.</p>
</div>
<div id="backgrounds">
<img src="img/background.png" class="fleft" width="30%" >
<p>Los <b>Backgrounds</b> son, como el nombre en inglรฉs dice, fondos. Fondos estรกticos, dinรกmicos, en mosaico, repetidos o de cualquier manera, mientras se mantengan en segundo plano.</p>
</div>
<div id="objects">
<p>Los <b>Objects</b> son, para simplificar, una abstracciรณn de cualquier cosa que pueda tener una posiciรณn en pantalla determinada y un Sprite al mismo tiempo. Veremos mรกs adelante.</p>
</div>
<div id="guielements">
<p>Los <b>GUIElements</b> son porciones de la interfaz de usuario del juego (una barra de salud, un indicador de puntuaciรณn, etc.) que se suporponen en pantalla a todos los elementos antes mencionados.</p>
</div>
<div id="rooms">
<p>Ahora viene la parte divertida: Las <b>Rooms</b> (en inglรฉs 'habitaciones') son espacios del juego diferenciados. El menรบ de un juego es una Room mientras que un nivel puede ser tambiรฉn otra diferente. Dependiendo de tus gustos personales podrรกs hacer que el menรบ de pausa de tu juego sea un GUIElement que ocupe toda la pantalla o una Room diferente a la que acceder cuando se pulsa un botรณn.</p>
</div>
<div id="cameras">
<p>En las Rooms hay <b>Cameras</b> (cรกmaras), cuyo trabajo es indicar al engine quรฉ parte de la Room mostrar por pantalla. Las Cameras normalmente siguen al personaje que controla el jugador mientras se mueve.</p>
</div>
<p>Y... de momento lo dejamos aquรญ. Hay muchas mรกs clases y elementos pero ahora mismo no quiero embutรญrtelos en el cerebro a mala gana. Mejor ir despacio y controlar poco a poco que intentar abarcar mucho de primeras.</p>
</div>
<h2 id="4"><a id="arrow4" class="arrow" href="javascript:toggle('arrow4','text4');">▼</a>Manos a la obra. Estructura bรกsica de un juego</h2>
<div id="text4" style="display: block;">
<p>Ya tienes una idea de los diferentes elementos que compondrรกn tu juego en SDL2Me, ahora hace falta que veas cรณmo se estructura un juego en puro cรณdigo:</p>
<pre class="brush: cpp;">
#include "S2M.h"
int main( int argc, char* args[] ) {
Graphics *gGraphics = S2M_CreateGraphics(320,240,2,"Test");
Room *room = S2M_CreateRoom<Room>();
S2M_SetRoom(room);
SDL_Event e;
while (true) {
if (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) break;
}
S2M_Update();
}
}</pre>
<p>En estas 20 lรญneas (que en realidad son menos) ya hemos conseguido una pantalla en negro y... bueno, nada mรกs. Te explicarรฉ ahora en quรฉ consiste cada parte importante:</p>
<pre class="brush: cpp;">
Graphics *gGraphics = S2M_CreateGraphics(320,240,2,"Test");</pre>
<p> La funciรณn <code>S2M_CreateGraphics()</code> crea una instancia de la clase <b>Graphics</b>, que controla toooooodas las operaciones de dibujado de tu juego. Tambiรฉn crea una ventana, le asigna un tรญtulo y, en general, se encarga de todo el proceso grรกfico por ti.</p>
<p>Si lo prefieres, en vez de pasarle todos esos parรกmetros tรบ mismo, puedes pasarle un string con la ubicaciรณn de un fichero que contenga la configuraciรณn de resoluciรณn, escalado, etc. y un puntero a una funciรณn que a partir de ese fichero consiga susodichos parรกmetros (ver la documentaciรณn oficial).</p>
<p>Ya tenemos grรกficos, pero ahora estamos flotando en la nada, puesto que no hemos definido ninguna Room como actual. Antes de definir una hace falta crearla, asรญ que echando mano de la funciรณn <code>S2M_CreateRoom<>()</code> creamos una Room nueva de tipo <code>TRoom</code>.
<pre class="brush: cpp;">
Room *room = S2M_CreateRoom<Room>();</pre>
<p>Nota los "<code><></code>" que he puesto despuรฉs del nombre de la funciรณn; esto es debido a que <code>S2M_CreateRoom</code> no es una funciรณn propiamente dicha, sinรณ una plantilla de funciรณn (template) que crea una nueva instancia de la clase especificada entre corchetes (siempre que la clase especificada sea derivada de la clase base Room). La funciรณn se encarga de pasarle los parรกmetros entre parรฉntesis al constructor de la clase especificada.</p>
<pre class="brush: cpp;">
S2M_SetRoom(room);</pre>
<p>Una vez hemos creado una Room lo inmediatamente necesario es asignarla como Room actual, ya que un juego no puede estar sin Room en ningรบn momento. Para eso utilizaremos la funciรณn <code>S2M_SetRoom()</code>.</p>
</div>
<h2 id="5"><a id="arrow5" class="arrow" href="javascript:toggle('arrow5','text5');">▼</a>Ya me he cansado de este nivel... ยกvรกmonos a otro!</h2>
<div id="text5" style="display: block;">
Bueno, claro, no podemos tirarnos todo el dรญa en la misma Room: habrรก que cambiar en algรบn momento. Aquรญ es donde entra en juego la funciรณn <code>S2M_GoToRoom<>()</code>. Nota los "<code><></code>" que he puesto despuรฉs del nombre; esto es debido a que <code>S2M_GoToRoom</code> no es una funciรณn propiamente dicha, sinรณ una plantilla de funciรณn (template) que acepta una derivada de la clase <b>Transition</b>. Veamos un ejemplo de uso:
<pre class="brush: cpp;">
Room r = Room(...); // Room cualquiera cargada de una forma que no viene al caso
S2M_GoToRoom<TFlip>(r) // Vamos a la Room r usando TFflip como transiciรณn</pre>
<p>Fรกcil, ยฟverdad? El hecho de que la funciรณn pida una clase derivada de una Transiciรณn es debido a que usarรก los mรฉtodos definidos en esa clase para aรฑadir un efecto gradual al cambio de Room.</p>
<h3>Todo esto estรก muy bien, pero ยฟcรณmo creo una transiciรณn?</h3>
<p>No es difรญcil, y en caso de que no quieras matarte programando puedes usar alguna de las que ya vienen definidas con SDL2Me, pero si quieres aรฑadirle un grado mรกs de personalizaciรณn a tu juego te enseรฑo cรณmo puedes crear la tuya:</p>
<pre class="brush: cpp;">
class Transition {
public:
Transition(bool m);
~Transition();
bool getMode();
int getDelay();
void changeMode();
virtual bool update();
protected:
SDL_Texture *texture; // Textura
bool done = false; // Estado
bool mode; // Modo
int step = 0;
const int maxstep;
int delay;
};</pre>
<p>Una transiciรณn tiene dos 'modos': de apertura y de cierre (<code>S2M_TRANSITION_OPEN</code> y <code>S2M_TRANSITION_CLOSE</code>). Tambiรฉn tiene una textura que se dibujarรก en la pantalla por encima de todo mientras la transiciรณn siga activa. Fรญjate tambiรฉn que tiene un mรฉtodo '<code>update()</code>': el objetivo de รฉste es hacer evolucionar a la transiciรณn en cada frame hacia su estado final.</p>
<p>El truco estรก en que en cada frame se llama el mรฉtodo <code>update()</code> y tรบ, derivando la clase base Transition y programando susodicho mรฉtodo, deberรกs actualizar la textura propia de tu clase conforme desees que sea la transiciรณn. Esa textura se dibujarรก en la pantalla hasta que indiques que <code>done = true</code>. Entonces, SDL2Me cambiarรก de Room y cambiarรก el modo de la transiciรณn (a no ser que el modo sea ya <code>S2M_TRANSITION_CLOSE</code>, en cuyo caso la transiciรณn finalizarรก) y tรบ deberรกs tener en cuenta ese cambio y volver a dibujar la textura propia del nuevo modo.</p>
<p>Asรญ explicado puede parecer complicado, pero si te lees la documentaciรณn oficial y echas una ojeada al cรณdigo fuente descubrirรกs que es en realidad bastante fรกcil.</p>
</div>
<h2 id="6"><a id="arrow6" class="arrow" href="javascript:toggle('arrow6','text6');">▼</a>Automatizando la creaciรณn de niveles. Uso de TRoom</h2>
<div id="text6" style="display: block;">
<p>Esta bien eso de saber crear niveles a mano (crear una Room, poblarla con Objects creados por ti con Sprites รญdem, etc.), pero llega un punto que hacer eso para cada nivel de tu juego se vuelve largo, tedioso y en definitiva, insoportable. Para eso estรกn las <b>TRoom</b>, un tipo especial de Room que automatiza la creaciรณn de niveles.</p>
<p>Por asรญ decirlo, una TRoom acepta un archivo como parรกmetro, archivo que leerรก y desde el cual obtendrรก su altura y anchura, se poblarรก con los objetos que haya definidos, etc.</p>
<p>El punto a destacar de este tipo de Rooms es que funcionan con tiles. Supondrรฉ que ya sabes que es una tile, y sinรณ รฉchale un vistazo a <a href="http://en.wikipedia.org/wiki/Tile-based_video_game">esto</a>. Una TRoom leerรก el archivo que le has pasado, guardarรก el tileset que haya definido en ese archivo como una SDL_Texture y crearรก un mapa de tiles por capas que luego la instancia de Graphics dibujarรก por pantalla.</p>
<p>Puedes usar diferentes programas para crear niveles basados en tiles, pero independientemente del que uses deberรกs encargarte de derivar la clase <code>TRoom</code> e implementar un mรฉtodo propio que lea los archivos y los convierta en un mapa de tiles. Puedes usar el constructor mismo, o si quieres otro mรฉtodo aparte que llamarรกs despuรฉs de crear una instancia de tu clase.</p>
<p>No obstante, si usas Tiled (un editor de niveles MUY potente) tienes a tu disposiciรณn la clase <b>TiledRoom</b>, que lee las diferentes capas de tu archivo (debe estar codificado en CSV), asรญ como el tileset por defecto y pobla tanto las tiles como los Objects. Hay mรกs informaciรณn de este tipo de Room en la <a href="#">documentaciรณn oficial</a>.</p>
</div>
</div>
<footer>
(C) Miguel Vera Belmonte 2014
</footer>
</div>
</body>
</html>
|
/*Given an array that contains both positive and negative integers, the task is to find the product of the maximum product subarray. */
/*
Input: arr[] = {6, -3, -10, 0, 2}
Output: 180
Explanation: The subarray is {6, -3, -10}
Input: arr[] = {-1, -3, -10, 0, 60}
Output: 60
Explanation: The subarray is {60}
*/
/*
APPROACH -1
Maximum Product Subarray by Traverse Over Every Contiguous Subarray: The idea is to traverse over every contiguous subarray, find the product of each of these subarrays and return the maximum product from these results.
*/
// C# program to find maximum product subarray
using System;
class GFG {
// Returns the product of max product subarray
static int maxSubarrayProduct(int[] arr)
{
// Initializing result
int result = arr[0];
int n = arr.Length;
for (int i = 0; i < n; i++) {
int mul = arr[i];
// Traversing in current subarray
for (int j = i + 1; j < n; j++) {
// Updating result every time
// to keep an eye over the
// maximum product
result = Math.Max(result, mul);
mul *= arr[j];
}
// Updating the result for (n-1)th index
result = Math.Max(result, mul);
}
return result;
}
// Driver Code
public static void Main(String[] args)
{
int[] arr = { 1, -2, -3, 0, 7, -8, -2 };
Console.Write("Maximum Sub array product is "
+ maxSubarrayProduct(arr));
}
}
/*
APPROACH-2: Maximum Product Subarray using Kadaneโs Algorithm
The idea is to use Kadaneโs algorithm and maintain 3 variables max_so_far, max_ending_here & min_ending_here. Iterate the indices 0 to N-1 and update the variables such that:
max_ending_here = maximum(arr[i], max_ending_here * arr[i], min_ending_here * arr[i])
min_ending_here = minimum(arr[i], max_ending_here * arr[i], min_ending_here * arr[i])
update the max_so_far with the maximum value for each index.
return max_so_far as the result.
*/
using System;
class GFG {
/* Returns the product of max product subarray.
Assumes that the given array always has a subarray
with product more than 1 */
static int maxSubarrayProduct(int[] arr)
{
// max positive product
// ending at the current position
int max_ending_here = arr[0];
// min negative product ending
// at the current position
int min_ending_here = arr[0];
// Initialize overall max product
int max_so_far = arr[0];
/* Traverse through the array.
the maximum product subarray ending at an index
will be the maximum of the element itself,
the product of element and max product ending
previously and the min product ending previously. */
for (int i = 1; i < arr.Length; i++) {
int temp = Math.Max(
Math.Max(arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here);
min_ending_here = Math.Min(
Math.Min(arr[i], arr[i] * max_ending_here),
arr[i] * min_ending_here);
max_ending_here = temp;
max_so_far
= Math.Max(max_so_far, max_ending_here);
}
return max_so_far;
}
// Driver Code
public static void Main()
{
int[] arr = { 1, -2, -3, 0, 7, -8, -2 };
Console.WriteLine("Maximum Sub array product is "
+ maxSubarrayProduct(arr));
}
}
|
## Tempgroup WebShop Project
##### by Johan Romeo, Jonas Torjman and Sandra Jeppsson
### Task, endpoints and structure
#### Task: Create a webshop where you can:
- register as a customer.
- login as either an admin or a customer
- see all the existing products in the webshop without being logged in at all
- add, update and delete products in the webshop logged in as an admin, but not as a customer
- be able to add to, update and delete products from the personalized shopping cart as a customer
- be able to see all the products in the cart, check out the cart and receive a receipt
- as an admin, be able to see all the different customer's purchase history
- as a customer, be able to see your own purchase history
#### Endpoints:
- http://localhost:8080/auth/register - POST - here you register your username and password
- http://localhost:8080/auth/login - POST - here you enter your credentials and get logged in if you have registered correctly
- http://localhost:8080/webshop/products/admin - POST - adds a product to the webshop-database
- http://localhost:8080/webshop/products/ - GET - see all the existing produts in the webshop
- http://localhost:8080/webshop/products/{id} - GET - finds the product that matches the "{id}" and adds it to the cart
- http://localhost:8080/webshop/products/admin/{id} - PUT - updates the product in the webshop-database that matches the "{id}"
- http://localhost:8080/webshop/products/admin/{id} - DELETE - deletes the product in the webshop-database that matches the "{id}"
- http://localhost:8080/webshop/cart/{id} - POST - adds the product that matches with the "{id}" to the customer's cart. If you add the same product twice it updates the quantity instead
- http://localhost:8080/webshop/cart/ - GET - see all the existing products in the customer cart
- http://localhost:8080/webshop/cart/{id} - DELETE - deletes the product that matches the "{id}" from the customer's cart
- http://localhost:8080/webshop/checkout/ - DELETE - checks out the customer cart with a receipt and total amount before removal
- http://localhost:8080/webshop/history/customer - GET - customer can see the purchase history
- http://localhost:8080/webshop/history/admin - GET - admin can see all customers purchase histories
#### Structure: We chose to:
- create one project with the backend coding for webshop
- where we also chose to separate the security implementation and the webshop in different packages
- create another project with the frontend coding for the webshop-client
### How to start the application:
- Download a Java supported IDEA of choice, for an example the free "IntelliJ IDEA Community Edition":
***https://www.jetbrains.com/idea/download/?section=windows***
- Go to Github and download our WebShop-project:
***https://github.com/JohRome/webshop/tree/master***
- Open this in IntelliJ
- Go to Github and download our Webshop-client-project:
***https://github.com/JohRome/client-webshop***
- Download [MySQL](https://dev.mysql.com/downloads/installer/) and follow the installation instructions
- Go to your MySQL Workbench and create a new schema called "webshop"
- Go to the application.properties and change the username and password to your MySQL username and password
- Open this project in another IntelliJ window.
- Start the first project by pushing "run" in the main-class
- Then start the second project by pushing "run" in that main-class
- Log in as an admin to add some items to the webshop, then please follow the project instructions and enjoy!
### Dependencies
- org.springframework.boot:spring-boot-starter-security
- org.springframework.boot:spring-boot-starter-data-jpa
- org.springframework.boot:spring-boot-starter-web
- org.springframework.boot:spring-boot-devtools
- org.springframework.boot:spring-boot-starter-test
- org.springframework.boot:spring-security-test
- io.json.webtoken:jjwt-impl:0.11.5
- io.json.webtoken:jjwt-api:0.11.5
- io.json.webtoken:jjwt-jackson:0.11.5
- org.projectlombok:lombok
- com.mysql:mysql-connector-j
***Java 17***
***December 2023 to January 2024***
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Website Title -->
<title>E-marketing Landing Page</title>
<!-- Styles -->
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,400i,700,700i&display=swap" rel="stylesheet">
<link href="https://serverless-sinatra-assets.s3.amazonaws.com/css/bootstrap.css" rel="stylesheet">
<link href="https://serverless-sinatra-assets.s3.amazonaws.com/css/fontawesome-all.css" rel="stylesheet">
<link href="https://serverless-sinatra-assets.s3.amazonaws.com/css/styles.css" rel="stylesheet">
<!-- Favicon -->
<link rel="icon" href="https://serverless-sinatra-assets.s3.amazonaws.com/images/favicon.png">
</head>
<body data-spy="scroll" data-target=".fixed-top">
<!-- Preloader -->
<div class="spinner-wrapper">
<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
<!-- end of preloader -->
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark navbar-custom fixed-top">
<!-- Text Logo - Use this if you don't have a graphic logo -->
<a class="navbar-brand logo-text" href="/">My awesome landpage</a>
<!-- Mobile Menu Toggle Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-awesome fas fa-bars"></span>
<span class="navbar-toggler-awesome fas fa-times"></span>
</button>
<!-- end of mobile menu toggle button -->
<div class="collapse navbar-collapse" id="navbarsExampleDefault">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link page-scroll" href="#header">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
</div>
</nav> <!-- end of navbar -->
<!-- end of navigation -->
<!-- Header -->
<header id="header" class="header">
<div class="header-content">
<div class="container">
<div class="row">
<div class="col-lg-6">
<div class="text-container">
<h1>e-Marketing Free eBook</h1>
<p class="p-large">Start creating personalized campaigns for your users with this free eBook and start converting fastest. Submit the form and the eBook will get in your email</p>
</div>
</div> <!-- end of col -->
<div class="col-lg-6">
<!-- Get Quote Form -->
<form id="getEbookForm" data-toggle="validator" data-focus="false">
<div class="form-group">
<input type="text" class="form-control-input" id="gfirstname" required>
<label class="label-control" for="gfirstname">First Name</label>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input type="text" class="form-control-input" id="glastname" required>
<label class="label-control" for="glastname">Last Name</label>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input type="text" class="form-control-input" id="gphone" required>
<label class="label-control" for="gphone">Phone</label>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input type="text" class="form-control-input" id="gemail" required>
<label class="label-control" for="gemail">Email</label>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input type="text" class="form-control-input" id="gcompany" required>
<label class="label-control" for="gcompany">Company</label>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<select class="form-control-select" id="gselect" required>
<option class="select-option" value="" disabled selected>Industry Option</option>
<option class="select-option" value="Manufacturing">Manufacturing</option>
<option class="select-option" value="Automotive">Automotive</option>
<option class="select-option" value="Software">Software</option>
<option class="select-option" value="Education">Education</option>
<option class="select-option" value="Real State">Real State</option>
<option class="select-option" value="Other">Other</option>
</select>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="form-control-submit-button">Get Free Ebook</button>
</div>
<div class="form-message">
<div id="gmsgSubmit" class="h3 text-center hidden"></div>
</div>
</form>
<!-- end of get quote form -->
</div> <!-- end of col -->
</div> <!-- end of row -->
</div> <!-- end of container -->
</div> <!-- end of header-content -->
<div class="image-container">
<img class="img-fluid" src="https://serverless-sinatra-assets.s3.amazonaws.com/images/town.png" alt="alternative">
</div> <!-- end of image-container -->
</header> <!-- end of header -->
<!-- end of header -->
<!-- Contact -->
<div id="contact" class="form">
<div class="container">
<div class="row">
<div class="col-lg-6">
<h2>Do you want more information or have questions?</h2><br>
<h2>Contact Us!</h2>
</div> <!-- end of col -->
<div class="col-lg-6">
<!-- Contact Form -->
<form id="contactForm" data-toggle="validator" data-focus="false">
<div class="form-group">
<input type="text" class="form-control-input" id="cname" required>
<label class="label-control" for="cname">Name</label>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<input type="email" class="form-control-input" id="cemail" required>
<label class="label-control" for="cemail">Email</label>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<textarea class="form-control-textarea" id="cmessage" required></textarea>
<label class="label-control" for="cmessage">Your message</label>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="form-control-submit-button">Submit</button>
</div>
<div class="form-message">
<div id="cmsgSubmit" class="h3 text-center hidden"></div>
</div>
</form>
<!-- end of contact form -->
</div> <!-- end of col -->
</div> <!-- end of row -->
</div> <!-- end of container -->
</div> <!-- end of form -->
<!-- end of contact -->
<!-- Footer -->
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="footer-col first">
<h5>About Kinedu</h5>
<p class="p-small">Kinedu helps parents with creative and age-appropriate activities that support babyโs development from pregnancy to 4 years old.</p>
<p class="p-small">Copyright ยฉ 2020</p>
</div>
</div> <!-- end of col -->
<div class="col-md-6">
</div> <!-- end of col -->
</div> <!-- end of row -->
</div> <!-- end of container -->
</div> <!-- end of footer -->
<!-- end of footer -->
<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous">
</script> <!-- jQuery for Bootstrap's JavaScript plugins -->
<script src="https://serverless-sinatra-assets.s3.amazonaws.com/js/bootstrap.min.js"></script> <!-- Bootstrap framework -->
<script src="https://serverless-sinatra-assets.s3.amazonaws.com/js/validator.min.js"></script> <!-- Validator.js - Bootstrap plugin that validates forms -->
<script src="https://serverless-sinatra-assets.s3.amazonaws.com/js/scripts.js"></script> <!-- Custom scripts -->
<script>
$(document).ready(function() {
$("#getEbookForm").submit(function(e){
e.preventDefault();
let fdata = {}
fdata["first_name"] = $("#gfirstname").val();
fdata["last_name"] = $("#glastname").val();
fdata["phone"] = $("#gphone").val();
fdata["email"] = $("#gemail").val();
fdata["company"] = $("#gcompany").val();
fdata["industry"] = $("#gselect").val();
var data_string = "firstname=" + fdata["first_name"] + "lastname=" + fdata["last_name"] + "&phone=" + fdata["phone"] + "&email=" + fdata["email"] + "&company=" + fdata["company"] + "&industry=" + fdata["industry"];
console.log(fdata);
$.ajax({
cache: false,
url : "api/lead",
type: "POST",
dataType : "json",
data : JSON.stringify(fdata),
success : function(callback){
gformSuccess();
},
error : function(callback){
console.log("Error saving data");
gformError();
gsubmitMSG(false, callback);
}
});
});
});
function gformSuccess() {
$("#getEbookForm")[0].reset();
gsubmitMSG(true, "Congratulations, your ebook is on the way!");
$("input").removeClass('notEmpty'); // resets the field label after submission
}
function gformError() {
$("#getEbookForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
$(this).removeClass();
});
}
function gsubmitMSG(valid, msg) {
if (valid) {
var msgClasses = "h3 text-center tada animated";
} else {
var msgClasses = "h3 text-center";
}
$("#gmsgSubmit").removeClass().addClass(msgClasses).text(msg);
}
</script>
</body>
</html>
|
/*
* Copyright (c) 2014, Julien Bernard
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <ui/Control.h>
#include <cassert>
namespace ui {
// control
Control::~Control() {
}
// gamepad axis control
static const char *axisName(sf::Joystick::Axis axis) {
return "?";
}
GamepadAxisControl::GamepadAxisControl(unsigned int id, sf::Joystick::Axis axis, Direction dir)
: Control("gamepad (axis)", axisName(axis))
, m_id(id)
, m_axis(axis)
, m_dir(dir)
{
}
void GamepadAxisControl::update(const sf::Event& event) {
if (event.type == sf::Event::JoystickMoved) {
if (event.joystickMove.joystickId == m_id && event.joystickMove.axis == m_axis) {
if (m_dir == Direction::POSITIVE) {
setActive(event.joystickMove.position > 50.0f);
} else {
assert(m_dir == Direction::NEGATIVE);
setActive(event.joystickMove.position < -50.0f);
}
}
}
}
// gamepad button control
GamepadButtonControl::GamepadButtonControl(unsigned int id, unsigned int button)
: Control("gamepad (button)", std::to_string(button))
, m_id(id)
, m_button(button)
{
}
void GamepadButtonControl::update(const sf::Event& event) {
if (event.type == sf::Event::JoystickButtonPressed) {
if (event.joystickButton.joystickId == m_id && event.joystickButton.button == m_button) {
setActive();
}
}
if (event.type == sf::Event::JoystickButtonReleased) {
if (event.joystickButton.joystickId == m_id && event.joystickButton.button == m_button) {
setActive(false);
}
}
}
// key control
static const char *keyName(sf::Keyboard::Key key) {
return "?";
}
KeyControl::KeyControl(sf::Keyboard::Key key)
: Control("keyboard", keyName(key))
, m_key(key)
{
}
void KeyControl::update(const sf::Event& event) {
if (event.type == sf::Event:: KeyPressed) {
if (event.key.code == m_key) {
setActive();
}
}
if (event.type == sf::Event::KeyReleased) {
if (event.key.code == m_key) {
setActive(false);
}
}
}
// mouse button control
const char *buttonName(sf::Mouse::Button button) {
return "?";
}
MouseButtonControl::MouseButtonControl(sf::Mouse::Button button)
: Control("mouse", buttonName(button))
, m_button(button)
{
}
void MouseButtonControl::update(const sf::Event& event) {
if (event.type == sf::Event::MouseButtonPressed) {
if (event.mouseButton.button == m_button) {
setActive();
}
}
if (event.type == sf::Event::MouseButtonReleased) {
if (event.mouseButton.button == m_button) {
setActive(false);
}
}
}
// close control
CloseControl::CloseControl()
: Control("window", "close")
{
}
void CloseControl::update(const sf::Event& event) {
if (event.type == sf::Event::Closed) {
setActive();
}
}
}
|
/* @file EventSerialKeypad.pde
|| @version 1.0
|| @author Alexander Brevig
|| @contact alexanderbrevig@gmail.com
||
|| @description
|| | Demonstrates using the KeypadEvent.
|| #
*/
#include <Keypad.h>
#define R1 30
#define R2 31
#define R3 32
#define R4 33
#define C1 34
#define C2 35
#define C3 36
#define C4 37
const byte numKeypadRows = 4; //four rows
const byte numKeypadCols = 4; //three columns
char keymap[numKeypadRows][numKeypadCols] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[numKeypadRows] = {R1, R2, R3, R4};
byte colPins[numKeypadCols]= {C1, C2, C3, C4};
Keypad keypad = Keypad( makeKeymap(keymap), rowPins, colPins, numKeypadRows, numKeypadCols );
byte ledPin = 13;
boolean blink = false;
boolean ledPin_state;
void setup(){
Serial.begin(9600);
pinMode(ledPin, OUTPUT); // Sets the digital pin as output.
digitalWrite(ledPin, HIGH); // Turn the LED on.
ledPin_state = digitalRead(ledPin); // Store initial LED state. HIGH when LED is on.
keypad.addEventListener(keypadEvent); // Add an event listener for this keypad
}
void loop(){
char key;// = keypad.getKey();
if (key) {
Serial.println(key);
}
if (blink){
digitalWrite(ledPin,!digitalRead(ledPin)); // Change the ledPin from Hi2Lo or Lo2Hi.
delay(100);
}
}
// Taking care of some special events.
void keypadEvent(KeypadEvent key){
Serial.println("Event!");
}
|
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const NUMBER_OF_ROWS = 1000000;
const CSV_FILE_PATH = './data.csv';
function generateCSV() {
// Gรฉnรจre un utilisateur alรฉatoire
function generateUser() {
const firstNames = ['Jean', 'Franรงois', 'Thรฉo', 'Jack', 'Laurent', 'Nicolas'];
const lastNames = ['Dupont', 'Martin', 'Bernard', 'Petit', 'Thomas'];
const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];
return(`${firstName} ${lastName}`);
}
// Gรฉnรจre une adresse e-mail en tenant compte d'un utilisateur gรฉnรฉrer alรฉatoirement
function generateEmail(user) {
const domains = ['gmail.com', 'hotmail.com', 'icloud.com'];
const domain = domains[Math.floor(Math.random() * domains.length)];
const userLower = user.toLowerCase().replace(' ', '.');
return(`${userLower}@${domain}`);
}
// Crรฉe le fichier CSV
const writeStream = fs.createWriteStream(CSV_FILE_PATH);
writeStream.write('uuid,nom,email\n'); // Ajoute la ligne d'en-tรชte
for (let i = 0; i < NUMBER_OF_ROWS; i++) {
const uuid = uuidv4();
const user = generateUser();
const email = generateEmail(user);
const row = `${uuid},${user},${email}\n`;
writeStream.write(row);
}
writeStream.end();
console.log(`Fichier CSV gรฉnรฉrรฉ avec succรจs : ${CSV_FILE_PATH}`);
}
generateCSV();
|
package mx.smartkode.app.negocio.curso.servicio.impl;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import mx.smartkode.app.negocio.AppExcepcion;
import mx.smartkode.app.negocio.Constantes;
import mx.smartkode.app.negocio.curso.dto.MapperPrestamo;
import mx.smartkode.app.negocio.curso.dto.PrestamoDTO;
import mx.smartkode.app.negocio.curso.servicio.PrestamoServicio;
import mx.smartkode.app.persistencia.entidades.libros.GcPrestamo;
import mx.smartkode.app.persistencia.usuarios.dao.PrestamoDao;
@Service("prestamoServicio")
public class PrestamoServicioImpl implements PrestamoServicio{
private static Logger log = LogManager.getLogger(LibroServicioImpl.class);
@Autowired
private PrestamoDao prestamoDao;
@Autowired
private MapperPrestamo mapperPrestamo;
@Override
public List<PrestamoDTO> getAllPrestamos() throws AppExcepcion {
List<PrestamoDTO> prestamoDTOs = new ArrayList<PrestamoDTO>();
try {
List<GcPrestamo> prestamos = prestamoDao.findAll();
prestamoDTOs = prestamos.stream().map(mapperPrestamo::PrestamoADto).collect(Collectors.toList());
} catch (Exception e) {
log.error("Error al consultar libros: "+e);
throw new AppExcepcion(Constantes.ERROR_GENERICO, e);
}
return prestamoDTOs;
}
@Override
public void addPrestamo(PrestamoDTO prestamoDTO) throws AppExcepcion {
try {
if(prestamoDTO == null)
throw new AppExcepcion("Error no es posible agregar el libro, favor de validar los datos.");
GcPrestamo prestamo = mapperPrestamo.DtoAPrestamo(prestamoDTO);
prestamo.setFechaPrestamo(new Timestamp(new Date().getTime()));
prestamoDao.save(prestamo);
} catch (Exception e) {
log.error("Error al agregar Prestamo: "+e.getMessage());
throw new AppExcepcion(Constantes.ERROR_GENERICO_CREAR, e);
}
}
@Override
public void updatePrestamo(PrestamoDTO prestamoDTO) throws AppExcepcion {
try {
if(prestamoDTO == null || prestamoDTO.getIdPrestamo() == null)
throw new AppExcepcion("Error no es posible editar el prestamo, favor de validar los datos.");
GcPrestamo prestamo = mapperPrestamo.DtoAPrestamo(prestamoDTO);
prestamoDao.save(prestamo);
} catch (Exception e) {
log.error("Error al editar prestamo: "+e.getMessage());
throw new AppExcepcion(Constantes.ERROR_GENERICO_CREAR, e);
}
}
@Override
public void deletePrestamo(Integer idPrestamo) throws AppExcepcion {
try {
if(idPrestamo == null)
throw new AppExcepcion("Error no es posible eliminar el prestamo, favor de validar los datos.");
prestamoDao.deleteById(idPrestamo);
} catch (Exception e) {
log.error("Error al eliminar el prestamo: "+e.getMessage());
throw new AppExcepcion(Constantes.ERROR_GENERICO_CREAR, e);
}
}
@Override
public List<PrestamoDTO> getPrestamosFiltroTitulo(String filtro) throws AppExcepcion {
/*
List<PrestamoDTO> prestamoDTOs = new ArrayList<PrestamoDTO>();
try {
List<GcPrestamo> prestamos = prestamoDao.(filtro);
prestamoDTOs = prestamos.stream().map(mapperPrestamo::PrestamoADto).collect(Collectors.toList());
} catch (Exception e) {
log.error("Error al filtrar libros: "+e);
throw new AppExcepcion(Constantes.ERROR_GENERICO, e);
}
*/
return null;
}
}
|
package com.kkb.mr.reduceJoin;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class ReduceJoinMain extends Configured implements Tool {
@Override
public int run(String[] strings) throws Exception {
Job job = Job.getInstance(super.getConf(), "reduceJoin");
job.setJarByClass(ReduceJoinMain.class);
job.setInputFormatClass(TextInputFormat.class);
TextInputFormat.addInputPath(job, new Path("G:\\kaikeba\\ไธ่ฏพ่ตๆ\\็ฌฌๅ
ซ็ซ \\3่mapreduce1\\MR่ฏพๅ่ตๆ_mrไธyarn\\3ใ็ฌฌไธๅคฉ\\11ใjoinๆไฝ\\ๆฐๆฎ\\reduce็ซฏjoin\\input"));
job.setMapperClass(ReduceJoinMapper.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setReducerClass(ReduceJoinReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(NullWritable.class);
job.setOutputFormatClass(TextOutputFormat.class);
TextOutputFormat.setOutputPath(job, new Path("C:\\Users\\leo\\Desktop\\reduceJoin"));
boolean b = job.waitForCompletion(true);
return b ? 0 : 1;
}
public static void main(String[] args) throws Exception {
int run = ToolRunner.run(new Configuration(), new ReduceJoinMain(), args);
System.exit(run);
}
}
|
::id 50da943fbbddbd3f33000000
::date 2012-12-26
::title ะฃัะปะพะฒะธั ะฒ CSS
::tags css, media, if
::body
ะฃัะปะพะฒะธั ะฒ CSS ะพะฝะธ ะถะต ะผะตะดะธะฐ ะทะฐะฟัะพัั (CSS media queries), ะธัะฟะพะปัะทััััั ะดะปั ะฟะตัะตะบะปััะตะฝะธั/ะฟะพะดะบะปััะตะฝะธั CSS ะฒ ะทะฐะฒะธัะธะผะพััะธ ะพั ะฝะตะบะพัะพััั
ััะปะพะฒะธะน (ัะฒะพะนััะฒ ะฐะฟะฟะฐัะฐัััั), ัะฐััะพ ะฟัะธะผะตะฝััััั ะฒ css ััะตะนะผะฒะพัะบะฐั
.
ะัะธะผะตั ะธัะฟะพะปัะทะพะฒะฐะฝะธั:
[[@media screen and (min-width: 1024px) {
#sidebar { width: 220px; }
}
@media screen and (max-width: 1023px) {
#sidebar { width: 110px; }
}
]]ะ ะดะฐะฝะฝะพะผ ะฟัะธะผะตัะต ััะปะพะฒะธั ัะฐะฑะพัะฐัั ะดะปั ัะบัะฐะฝะพะฒ ะผะพะฝะธัะพัะพะฒ (screen), ะธ ะตัะปะธ ัะธัะธะฝะฐ ะพะบะฝะฐ ะฑัะดะตั 1024px ะธ ะฑะพะปะตะต ัะพ ะฑัะดะตั ะฐะบัะธะฒะฝัะน 1-ัะน ะฑะปะพะบ (=220px), ะตัะปะธ ัะธัะธะฝะฐ ะพะบะฝะฐ ะฑัะดะตั 1023px ะธ ะผะตะฝะตะต ัะพ ะฑัะดะตั ะฐะบัะธะฒะฝัะน 2-ะน ะฑะปะพะบ (=110px).
ะัะธะผะตั ะธัะฟะพะปัะทะพะฒะฐะฝะธั ััะปะพะฒะธะน ะฟัะธ ะฟะพะดะบะปััะตะฝะธะธ css ัะฐะนะปะฐ:
[[<link rel="stylesheet" media="all and (min-device-width: 600)" href="/style.css" />]]
!ะะตะบะพัะพััะต ะธะท ะฟะฐัะฐะผะตััะพะฒ:
#|min-width, max-width|ะะธะฝะธะผะฐะปัะฝะฐั/ะผะฐะบัะธะผะฐะปัะฝะฐั ัะธัะธะฝะฐ ะพะบะฝะฐ
||min-height, max-height|ะะธะฝะธะผะฐะปัะฝะฐั/ะผะฐะบัะธะผะฐะปัะฝะฐั ะฒััะพัะฐ ะพะบะฝะฐ
||min-device-width, max-device-width|ะะธะฝะธะผะฐะปัะฝะฐั/ะผะฐะบัะธะผะฐะปัะฝะฐั ัะธัะธะฝะฐ ัะบัะฐะฝะฐ
||min-device-height, max-device-height|ะะธะฝะธะผะฐะปัะฝะฐั/ะผะฐะบัะธะผะฐะปัะฝะฐั ะฒััะพัะฐ ัะบัะฐะฝะฐ
|#
!ะฃัะปะพะฒะธั ะฟะพ ะดะตะฒะฐะนัะฐะผ:
#|all|ะัะฑัะต ััััะพะนััะฒะฐ
||screen|ะญะบัะฐะฝั ะผะพะฝะธัะพัะพะฒ
||print|ะัะธะฝัะตัั
||handheld|ะกะผะฐััะพะฝั ะธ ะฐะฝะฐะปะพะณะธ
||tv|ะขะตะปะตะฒะธะทะพัั
||projection|ะัะพะตะบัะพัั
|#
!ะกะพะฒะผะตััะธะผะพััั
ะญัะฐ ะฒะพะทะผะพะถะฝะพััั ะฟะพัะฒะธะปะฐัั ะฒ CSS3, ัะฐะฑะพัะฐะตั ะฒ:
Chrome, Firefox 3.6+, Safari 4+, Opera 10, IE 9+, Android 2+, iOS 2+
ะ ะดััะณะธั
ัะฒะพะนััะฒะฐั
ะผะพะถะฝะพ ะฟัะพัะธัะฐัั ััั [https://developer.mozilla.org/en-US/docs/CSS/Media_queries developer.mozilla.org]
::html
ะฃัะปะพะฒะธั ะฒ CSS ะพะฝะธ ะถะต ะผะตะดะธะฐ ะทะฐะฟัะพัั (CSS media queries), ะธัะฟะพะปัะทััััั ะดะปั ะฟะตัะตะบะปััะตะฝะธั/ะฟะพะดะบะปััะตะฝะธั CSS ะฒ ะทะฐะฒะธัะธะผะพััะธ ะพั ะฝะตะบะพัะพััั
ััะปะพะฒะธะน (ัะฒะพะนััะฒ ะฐะฟะฟะฐัะฐัััั), ัะฐััะพ ะฟัะธะผะตะฝััััั ะฒ css ััะตะนะผะฒะพัะบะฐั
.<br />
<br />
ะัะธะผะตั ะธัะฟะพะปัะทะพะฒะฐะฝะธั:<br />
<div class="codebox"><div class="highlight"><pre><span class="nd">@media</span> <span class="n">screen</span> <span class="ow">and</span> <span class="p">(</span><span class="nb">min</span><span class="o">-</span><span class="n">width</span><span class="p">:</span> <span class="mi">1024</span><span class="n">px</span><span class="p">)</span> <span class="p">{</span>
<span class="c">#sidebar { width: 220px; }</span>
<span class="p">}</span>
<span class="nd">@media</span> <span class="n">screen</span> <span class="ow">and</span> <span class="p">(</span><span class="nb">max</span><span class="o">-</span><span class="n">width</span><span class="p">:</span> <span class="mi">1023</span><span class="n">px</span><span class="p">)</span> <span class="p">{</span>
<span class="c">#sidebar { width: 110px; }</span>
<span class="p">}</span>
</pre></div>
</div>ะ ะดะฐะฝะฝะพะผ ะฟัะธะผะตัะต ััะปะพะฒะธั ัะฐะฑะพัะฐัั ะดะปั ัะบัะฐะฝะพะฒ ะผะพะฝะธัะพัะพะฒ (screen), ะธ ะตัะปะธ ัะธัะธะฝะฐ ะพะบะฝะฐ ะฑัะดะตั 1024px ะธ ะฑะพะปะตะต ัะพ ะฑัะดะตั ะฐะบัะธะฒะฝัะน 1-ัะน ะฑะปะพะบ (=220px), ะตัะปะธ ัะธัะธะฝะฐ ะพะบะฝะฐ ะฑัะดะตั 1023px ะธ ะผะตะฝะตะต ัะพ ะฑัะดะตั ะฐะบัะธะฒะฝัะน 2-ะน ะฑะปะพะบ (=110px).<br />
<br />
ะัะธะผะตั ะธัะฟะพะปัะทะพะฒะฐะฝะธั ััะปะพะฒะธะน ะฟัะธ ะฟะพะดะบะปััะตะฝะธะธ css ัะฐะนะปะฐ:<br />
<div class="codebox"><div class="highlight"><pre><span class="o"><</span><span class="n">link</span> <span class="n">rel</span><span class="o">=</span><span class="s">"stylesheet"</span> <span class="n">media</span><span class="o">=</span><span class="s">"all and (min-device-width: 600)"</span> <span class="n">href</span><span class="o">=</span><span class="s">"/style.css"</span> <span class="o">/></span>
</pre></div>
</div><br />
<h3>ะะตะบะพัะพััะต ะธะท ะฟะฐัะฐะผะตััะพะฒ:</h3><table class="pymark_table"><tr><td>min-width, max-width</td><td>ะะธะฝะธะผะฐะปัะฝะฐั/ะผะฐะบัะธะผะฐะปัะฝะฐั ัะธัะธะฝะฐ ะพะบะฝะฐ</td></tr><tr><td>min-height, max-height</td><td>ะะธะฝะธะผะฐะปัะฝะฐั/ะผะฐะบัะธะผะฐะปัะฝะฐั ะฒััะพัะฐ ะพะบะฝะฐ</td></tr><tr><td>min-device-width, max-device-width</td><td>ะะธะฝะธะผะฐะปัะฝะฐั/ะผะฐะบัะธะผะฐะปัะฝะฐั ัะธัะธะฝะฐ ัะบัะฐะฝะฐ</td></tr><tr><td>min-device-height, max-device-height</td><td>ะะธะฝะธะผะฐะปัะฝะฐั/ะผะฐะบัะธะผะฐะปัะฝะฐั ะฒััะพัะฐ ัะบัะฐะฝะฐ</td></tr></table><br />
<h3>ะฃัะปะพะฒะธั ะฟะพ ะดะตะฒะฐะนัะฐะผ:</h3><table class="pymark_table"><tr><td>all</td><td>ะัะฑัะต ััััะพะนััะฒะฐ</td></tr><tr><td>screen</td><td>ะญะบัะฐะฝั ะผะพะฝะธัะพัะพะฒ</td></tr><tr><td>print</td><td>ะัะธะฝัะตัั</td></tr><tr><td>handheld</td><td>ะกะผะฐััะพะฝั ะธ ะฐะฝะฐะปะพะณะธ</td></tr><tr><td>tv</td><td>ะขะตะปะตะฒะธะทะพัั</td></tr><tr><td>projection</td><td>ะัะพะตะบัะพัั</td></tr></table><br />
<h3>ะกะพะฒะผะตััะธะผะพััั</h3>ะญัะฐ ะฒะพะทะผะพะถะฝะพััั ะฟะพัะฒะธะปะฐัั ะฒ CSS3, ัะฐะฑะพัะฐะตั ะฒ:<br />
Chrome, Firefox 3.6+, Safari 4+, Opera 10, IE 9+, Android 2+, iOS 2+<br />
<br />
ะ ะดััะณะธั
ัะฒะพะนััะฒะฐั
ะผะพะถะฝะพ ะฟัะพัะธัะฐัั ััั <a target=_blank href="https://developer.mozilla.org/en-US/docs/CSS/Media_queries">developer.mozilla.org</a><br />
|
import { AnimatePresence } from 'framer-motion'
import {
ANIMATION_MAP,
EXIT_MOTION,
TRANSITION_MAP,
} from 'config/constants/motions'
import { StyledPoolDesktop, StyledPoolModalOverlay } from './styled'
import Icon from 'components/Icon'
import Balances from './Balances'
import Header from './Header'
import Information from './Information'
import Join from './Join'
type BalancerPoolDesktopProps = {
show: boolean
closePool(): void
}
function BalancerPoolDesktop({ show, closePool }: BalancerPoolDesktopProps) {
return (
<>
<AnimatePresence>
{show && (
<StyledPoolModalOverlay
{...EXIT_MOTION}
variants={ANIMATION_MAP.fadeIn}
transition={TRANSITION_MAP.modal}
onClick={closePool}
role="presentation"
/>
)}
</AnimatePresence>
<AnimatePresence>
{show && (
<StyledPoolDesktop
{...EXIT_MOTION}
variants={ANIMATION_MAP.appearInUp}
transition={TRANSITION_MAP.modal}
>
<div className="utils">
<button className="closeButton" type="button" onClick={closePool}>
<Icon icon="close" />
</button>
</div>
<div className="container">
<div className="left">
<Header />
<Information />
<Join />
</div>
<div className="right">
<Balances />
</div>
</div>
</StyledPoolDesktop>
)}
</AnimatePresence>
</>
)
}
export default BalancerPoolDesktop
|
# MSAL
Proporciona acceso seguro a Microsoft Graph, otras API de Microsoft, API web de terceros a su propia API web. Es compatible con muchas arquitecturas y plataformas: .NET, JavaSCript, JAva, Python, Android e iOS.
Ventajas:
+ No es necesario usar directamente las bibliotecas de OAuth ni el cรณdigo en el protocolo en la aplicaciรณn.
+ Adquiere tokens en nombre de un usuario o en nombre de una aplicaciรณn (cuando se aplica a la plataforma).
+ Mantiene una cachรฉ de tokens y actualiza los tokens de forma automรกtica cuando estรกn prรณximos a expirar. No es necesario que el usuario controle la expiraciรณn de los tokens.
+ Le ayuda a especificar quรฉ audiencia quiere que inicie sesiรณn en la aplicaciรณn.
+ Lo ayuda a configurar la aplicaciรณn a partir de archivos de configuraciรณn.
+ Lo ayuda a solucionar problemas de la aplicaciรณn mediante la exposiciรณn de excepciones, registros y telemetrรญa que requieren acciรณn.
## Flujos de autenticaciรณn
|Flujo|Descripciรณn|
|-----|-----------|
|Cรณdigo de autorizaciรณn|Las aplicaciones nativas y web obtienen tokens de forma segura en el nombre del usuario|
|Credenciales de clientes|Las aplicaciones de servicio se ejecutan sin interacciรณn del usuario|
|En nombre de|La aplicaciรณn llama a una API web o de servicio, que a su vez llama a Microsoft Graph|
|Impรญcita|Se usa en aplicacios basadas en el navegador|
|Cรณdigo del dispositivo|Habilita el inicio de sessiรณn en un dispositivo mediante otro dispositivo que tiene un explorador|
|Integrado en Windows|Los equipos Window adquieren de ofrma silenciosa un token de acceso cuando estรกn unidos a un dominio|
|Interactive|Las aplicacionemรณviles y de escritorio llaman a Microsoft Grap nombre de un usuario|
|Nombre de usuario y contraseรฑa|La aplicaciรณn inicia la sesiรณn de un uusario con su nombre de usuario y contraseรฑa|
### Aplicaciones clientes pรบblicas y confidenciales
+ Aplicaciones cliente pรบblicas: aplicaciones que no son de confianza para mantener de manera segura secretos, por lo que solo tienen acceso a aPI web en nombre del uaurio. Los clientes pรบblicos no pueden contener secretos de tiempo de configuraciรณn, por lo que no tienen secretos de cliente.
+ Aplicaciones cliente confidenciales: aplicaciones ejecutadas en servidores, que se consideran de difรญcil acceso y pueden mantener un secreto de aplicaciรณn. Pueden contener secretos en tiempo de configuraciรณn y cada instancia del cliente puede tener una configuraciรณn diferente.
## Inicializaciรณn de aplicaciones cliente
Para crear una instancia de la aplicaciรณn use los siguientes mรฉtodos: _PublicClientApplciationBuilder_ o _ConfidentialClientApplciationBuilder_. Antes de inicializar la aplicaciรณn, tendrรก que registrarla en Microsoft Entra, del que recibirรก la siguiente informaciรณn:
+ El identificador de cliente (una cadena que representa un GUID).
+ La URL del proveedor de identidades (la instancia) y la audiencia de inicio de sesiรณn para la aplicaciรณn. De forma conjunta, estos dos parรกmetros se conocen como la autoridad.
+ El identificador del inquilino si va a escribir una aplicaciรณn de lรญnea de negocio exclusivamente para la organizaciรณn (tambiรฉn denominada aplicaciรณn de un รบnico inquilino).
+ El secreto de aplicaciรณn (cadena de secreto de cliente) o el certificado (del tipo X509Certificate2) si se trata de una aplicaciรณn cliente confidencial.
+ Con aplicaciones web y, a veces, con aplicaciones cliente pรบblicas (concretamente cuando la aplicaciรณn debe usar a un agente), tambiรฉn debe establecer redirectUri donde el proveedor de identidades se conecta de nuevo a la aplicaciรณn con los tokens de seguridad.
## Inicializaciรณn desde cรณdigo
Con el siguiente cรณdigo genera una instancia de una aplicaciรณn cliente pรบblica:
IPublicClientApplication app = PublicClientApplicationBuilder.Create(clientId).Build();
Con el siguiente cรณdigo genera una instancia de una aplicaciรณn cliente confidencial:
string redirectUri = "https://myapp.azurewebsites.net";
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithRedirectUri(redirectUri )
.Build();
La aplicaciรณn esta ubicada en (https://myapp.azurewebsites.net) y controla los tokens de los usuarios en la nube pรบblica de Azure con sus cuentas. La aplicaciรณn se identifica con el proveedor de identidades compartiendo un secreto.
## Modificadores del generador
+ Modiicador __.WithAuthority__: establece la autoridad predeterminada de la aplicaciรณn en una entidad de Microsoft Entra, con la posiblidad de elegir la nube de Azure, el pรบblico, el inquilino o proporcionar directamente el URI de la autoridad.
var clientApp = PublicClientApplicationBuilder.Create(client_id)
.WithAuthority(AzureCloudInstance.AzurePublic, tenant_id)
.Build();
+ Modificador __.WithREdirectUri__: anula el URI de redireccionamiento predeterminado.
var clientApp = PublicClientApplicationBuilder.Create(client_id)
.WithAuthority(AzureCloudInstance.AzurePublic, tenant_id)
.WithRedirectUri("http://localhost")
.Build();
## Modificadores comunes a las aplicaciones cliente pรบblicas y condidenciales
|Modificador|Descripciรณn!
|-----------|-----------|
|__.WithAuthority()__|Establece la autoridad predeterminada en Microsoft Entra, con la posiblidad de elegir Azure Cloud, la isntancia o el inquilino o de proporcionar directmanete la URI de autoridad.|
|__.WithTenantId(string tenantId)__|Invalida el identificador del inquilino o la descripciรณn del inquilino.|
|__.WithClientId(String)__|Invalida el identificador del cliente.|
|__.WithRedirectUri(String redirectUri)__|Invalida la URI de redirecciรณn predeterminada. Esto es รบtil en escenarios que requieren un agente.|
|__.WithComponent(string)__| Establece el nombre de la biblioteca mendaitne MSAL.NET.|
|__.WithDebugLoggingCallback()__|Si se llama, la aplicaciรณn llama a *Debug.Write* simplemente habilitndo seguimiento de depuraciรณn.|
|__.WithLogging()__|La aplicaciรณn llamarรก a una devoluciรณn de llamada con seguimientos de depuraciรณn.|
|__.WithTelemetry(TelemetryCallback telemetryCallback)__|Establece al delegado utilizado para enviar datos de telemetrรญa.|
## Modificadores especificos de aplicaciones cliente confidenciales
|Modificador|Descripciรณn!
|-----------|-----------|
|__.WithCertificate(X509Certificate2 certificate)__|Establece el certificado que identifica la plicaciรณn con Microsoft Entra.|
|__.WithCEntSecret(String clientSecret)__|Establece el secreto de cliente (contraseรฑa de la aplicaciรณn) que identifica la aplicacion con Microsoft Entra.|
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const path_1 = __importDefault(require("path"));
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const connection_1 = __importDefault(require("../db/connection"));
const usuario_1 = __importDefault(require("../routes/usuario"));
const auth_1 = __importDefault(require("../routes/auth"));
const area_1 = __importDefault(require("../routes/area"));
const role_1 = __importDefault(require("../routes/role"));
const upload_1 = __importDefault(require("../routes/upload"));
const docente_1 = __importDefault(require("../routes/docente"));
const tipodocumento_1 = __importDefault(require("../routes/tipodocumento"));
const nivel_1 = __importDefault(require("../routes/nivel"));
const grado_1 = __importDefault(require("../routes/grado"));
const seccion_1 = __importDefault(require("../routes/seccion"));
const persona_1 = __importDefault(require("../routes/persona"));
const alumno_1 = __importDefault(require("../routes/alumno"));
const aula_1 = __importDefault(require("../routes/aula"));
const periodo_1 = __importDefault(require("../routes/periodo"));
const programacion_1 = __importDefault(require("../routes/programacion"));
const matricula_1 = __importDefault(require("../routes/matricula"));
const nota_1 = __importDefault(require("../routes/nota"));
const ciclo_1 = __importDefault(require("../routes/ciclo"));
const evaluacion_1 = __importDefault(require("../routes/evaluacion"));
const material_1 = __importDefault(require("../routes/material"));
const asistencia_1 = __importDefault(require("../routes/asistencia"));
const situacion_1 = __importDefault(require("../routes/situacion"));
const institucion_1 = __importDefault(require("../routes/institucion"));
const hora_1 = __importDefault(require("../routes/hora"));
const horario_1 = __importDefault(require("../routes/horario"));
const rango_1 = __importDefault(require("../routes/rango"));
const semilla_1 = require("../seeders/semilla");
const pdf_1 = __importDefault(require("../routes/pdf"));
const mensajeria_1 = __importDefault(require("../routes/mensajeria"));
const padre_1 = __importDefault(require("../routes/padre"));
const madre_1 = __importDefault(require("../routes/madre"));
const competencia_1 = __importDefault(require("../routes/competencia"));
const matriculadetalle_1 = __importDefault(require("../routes/matriculadetalle"));
const auxiliar_1 = __importDefault(require("../routes/auxiliar"));
const director_1 = __importDefault(require("../routes/director"));
const apreciacion_1 = __importDefault(require("../routes/apreciacion"));
const responsable_1 = __importDefault(require("../routes/responsable"));
const apreciaciondetalle_1 = __importDefault(require("../routes/apreciaciondetalle"));
class Server {
constructor() {
this.llave = false;
this.apiPaths = {
usuarios: '/api/usuarios',
auth: '/api/auth',
areas: '/api/areas',
roles: '/api/roles',
subareas: '/api/subareas',
uploads: '/api/uploads',
docentes: '/api/docentes',
tipodocumentos: '/api/tipodocumentos',
niveles: '/api/niveles',
grados: '/api/grados',
secciones: '/api/secciones',
personas: '/api/personas',
alumnos: '/api/alumnos',
apoderados: '/api/apoderados',
aulas: '/api/aulas',
periodos: '/api/periodos',
programaciones: '/api/programaciones',
matriculas: '/api/matriculas',
notas: '/api/notas',
ciclos: '/api/ciclos',
evaluaciones: '/api/evaluaciones',
materiales: '/api/materiales',
asistencias: '/api/asistencias',
pdfs: '/api/pdfs',
situaciones: '/api/situaciones',
instituciones: '/api/instituciones',
horas: '/api/horas',
horarios: '/api/horarios',
rangos: '/api/rangos',
mensajerias: '/api/mensajerias',
padres: '/api/padres',
madres: '/api/madres',
competencias: '/api/competencias',
matriculadetalles: '/api/matriculadetalles',
auxiliares: '/api/auxiliares',
directores: '/api/directores',
apreciaciones: '/api/apreciaciones',
responsables: '/api/responsables',
apreciaciondetalles: '/api/apreciaciondetalles'
};
this.app = (0, express_1.default)();
this.port = process.env.PORT || '8000';
this.dbConnection();
this.middlewares();
this.routes();
}
dbConnection() {
return __awaiter(this, void 0, void 0, function* () {
try {
yield connection_1.default.sync({ force: this.llave }).then(() => {
if (this.llave) {
(0, semilla_1.dbSeed)();
}
else {
console.log("No execution seed");
}
});
console.log('Database online');
}
catch (error) {
throw new Error(error);
}
});
}
middlewares() {
// Cors
this.app.use((0, cors_1.default)());
// Lectura del body
this.app.use(express_1.default.json());
// Carpeta publica
this.app.use(express_1.default.static('public'));
}
routes() {
this.app.use(this.apiPaths.usuarios, usuario_1.default);
this.app.use(this.apiPaths.auth, auth_1.default);
this.app.use(this.apiPaths.areas, area_1.default);
this.app.use(this.apiPaths.roles, role_1.default);
this.app.use(this.apiPaths.uploads, upload_1.default);
this.app.use(this.apiPaths.docentes, docente_1.default);
this.app.use(this.apiPaths.tipodocumentos, tipodocumento_1.default);
this.app.use(this.apiPaths.niveles, nivel_1.default);
this.app.use(this.apiPaths.grados, grado_1.default);
this.app.use(this.apiPaths.secciones, seccion_1.default);
this.app.use(this.apiPaths.personas, persona_1.default);
this.app.use(this.apiPaths.alumnos, alumno_1.default);
this.app.use(this.apiPaths.aulas, aula_1.default);
this.app.use(this.apiPaths.periodos, periodo_1.default);
this.app.use(this.apiPaths.programaciones, programacion_1.default);
this.app.use(this.apiPaths.matriculas, matricula_1.default);
this.app.use(this.apiPaths.notas, nota_1.default);
this.app.use(this.apiPaths.ciclos, ciclo_1.default);
this.app.use(this.apiPaths.evaluaciones, evaluacion_1.default);
this.app.use(this.apiPaths.materiales, material_1.default);
this.app.use(this.apiPaths.asistencias, asistencia_1.default);
this.app.use(this.apiPaths.situaciones, situacion_1.default);
this.app.use(this.apiPaths.pdfs, pdf_1.default);
this.app.use(this.apiPaths.instituciones, institucion_1.default);
this.app.use(this.apiPaths.horas, hora_1.default);
this.app.use(this.apiPaths.horarios, horario_1.default);
this.app.use(this.apiPaths.rangos, rango_1.default);
this.app.use(this.apiPaths.mensajerias, mensajeria_1.default);
this.app.use(this.apiPaths.padres, padre_1.default);
this.app.use(this.apiPaths.madres, madre_1.default);
this.app.use(this.apiPaths.competencias, competencia_1.default);
this.app.use(this.apiPaths.matriculadetalles, matriculadetalle_1.default);
this.app.use(this.apiPaths.auxiliares, auxiliar_1.default);
this.app.use(this.apiPaths.directores, director_1.default);
this.app.use(this.apiPaths.apreciaciones, apreciacion_1.default);
this.app.use(this.apiPaths.responsables, responsable_1.default);
this.app.use(this.apiPaths.apreciaciondetalles, apreciaciondetalle_1.default);
this.app.get('*', (req, res) => {
res.sendFile(path_1.default.resolve(__dirname, '../../public/index.html'));
});
}
listen() {
this.app.listen(this.port, () => {
console.log("Servidor corriendo en el puerto: " + this.port);
});
}
}
exports.default = Server;
//# sourceMappingURL=server.js.map
|
package com.abs.util;
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
/**************************************************************/
/*************************** ๆฏ่พ ******************************/
/**************************************************************/
/** ็ฒพ็กฎๅฐๅนด. */
public static Integer COMPARE_TYPE_YEAR = new Integer(0);
/** ็ฒพ็กฎๅฐๆ. */
public static Integer COMPARE_TYPE_MONTH = new Integer(1);
/** ็ฒพ็กฎๅฐๆฅ. */
public static Integer COMPARE_TYPE_DAY = new Integer(2);
/** ็ฒพ็กฎๅฐๅฐๆถ. */
public static Integer COMPARE_TYPE_HOUR = new Integer(3);
/** ็ฒพ็กฎๅฐๅ้. */
public static Integer COMPARE_TYPE_MINUTE = new Integer(4);
/** ็ฒพ็กฎๅฐ็ง. */
public static Integer COMPARE_TYPE_SECOND = new Integer(5);
public static Long DAY_TIME = 60L * 60L * 24L * 1000L;
/**
* ๆฏ่พไธคไธชๆฅๆๆฏๅฆ็ธ็ญ.
*
* @param date1
* @param date2
* @param compareType
* @return
*/
public static boolean dateEquals(Date date1, Date date2, Integer compareType) {
if (date1 == null || date2 == null) {
return false;
}
date1 = changeType(date1, compareType);
date2 = changeType(date2, compareType);
if (date1.compareTo(date2) == 0) {
return true;
}
return false;
}
/**
* ๆฏ่พdate1ๆฏๅฆๅจdate2ไนๅ.
*
* @param date1
* @param date2
* @param compareType
* @return
*/
public static boolean dateBefore(Date date1, Date date2, Integer compareType) {
if (date1 == null || date2 == null) {
return false;
}
date1 = changeType(date1, compareType);
date2 = changeType(date2, compareType);
if (date1.before(date2)) {
return true;
}
return false;
}
/**
* ๆฏ่พdate1ๆฏๅฆๅจdate2ไนๅ.
*
* @param date1
* @param date2
* @param compareType
* @return
*/
public static boolean dateAfter(Date date1, Date date2, Integer compareType) {
if (date1 == null || date2 == null) {
return false;
}
date1 = changeType(date1, compareType);
date2 = changeType(date2, compareType);
if (date1.after(date2)) {
return true;
}
return false;
}
/**
* ๆฏ่พdate1ๆฏๅฆไธ่ถ
่ฟdate2.
*
* @param date1
* @param date2
* @param compareType
* @return
*/
public static boolean dateNotAfter(Date date1, Date date2, Integer compareType) {
if (date1 == null || date2 == null) {
return false;
}
date1 = changeType(date1, compareType);
date2 = changeType(date2, compareType);
if (date1.after(date2)) {
return false;
}
return true;
}
/**
* ๆฏ่พdate1ๆฏๅฆไธๅจdate1ไนๅ.
*
* @param date1
* @param date2
* @param compareType
* @return
*/
public static boolean dateNotBefore(Date date1, Date date2, Integer compareType) {
if (date1 == null || date2 == null) {
return false;
}
date1 = changeType(date1, compareType);
date2 = changeType(date2, compareType);
if (date1.before(date2)) {
return false;
}
return true;
}
private static Date changeType(Date date, Integer compareType) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.MILLISECOND, 0);
if (COMPARE_TYPE_SECOND.compareTo(compareType) > 0) {
c.set(Calendar.SECOND, 0);
if (COMPARE_TYPE_MINUTE.compareTo(compareType) > 0) {
c.set(Calendar.MINUTE, 0);
if (COMPARE_TYPE_HOUR.compareTo(compareType) > 0) {
c.set(Calendar.HOUR_OF_DAY, 0);
if (COMPARE_TYPE_DAY.compareTo(compareType) > 0) {
c.set(Calendar.DAY_OF_MONTH, 1);
if (COMPARE_TYPE_MONTH.compareTo(compareType) > 0) {
c.set(Calendar.MONTH, 0);
}
}
}
}
}
return c.getTime();
}
/**************************************************************/
/*************************** ่ฎก็ฎ ******************************/
/**************************************************************/
/**
* ๅพๅฐไธไธชๆฅๆไนๅๅ ๅคฉ็ๆฅๆ.
*
* @param date
* @param before
* @return
*/
public static Date getDateBefore(Date date, long before) {
long lTime = date.getTime();
lTime -= before * DAY_TIME;
Date result = new Date(lTime);
return result;
}
/**
* ๅพๅฐไธไธชๆฅๆไนๅๅๅคฉ็ๆฅๆ.
*
* @param date
* @param before
* @return
*/
public static Date getDateAfter(Date date, long after) {
long lTime = date.getTime();
lTime += after * DAY_TIME;
Date result = new Date(lTime);
return result;
}
/**
* ๅพๅฐไธไธชๆ็ไปๅคฉ.
*
* @param date
* @return
*/
public static Date getNextMonthDate(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.MONTH, c.get(Calendar.MONTH) + 1);
return c.getTime();
}
/**
* ๅพๅฐไธไธชๆ็ไปๅคฉ.
*
* @param date
* @return
*/
public static Date getPrevMonthDate(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.MONTH, c.get(Calendar.MONTH) - 1);
return c.getTime();
}
/**
* ๅพๅฐไนๅ่ฅๅนฒไธชๆ็็ฌฌไธๅคฉ.
*
* @param date
* @param afterMonth
* @return
*/
public static Date getFirstDayOfAfterMonth(Date date, int afterMonth) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.MONTH, c.get(Calendar.MONTH) + afterMonth);
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
/**
* ๅพๅฐไนๅ่ฅๅนฒไธชๆ็็ฌฌไธๅคฉ.
*
* @param date
* @param nextMonth
* @return
*/
public static Date getFirstDayOfBeforeMonth(Date date, int beforeMonth) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.MONTH, c.get(Calendar.MONTH) - beforeMonth);
c.set(Calendar.DAY_OF_MONTH, 1);
return c.getTime();
}
/**
* ๅพๅฐไนๅ่ฅๅนฒไธชๆ็ๆๅไธๅคฉ.
*
* @param date
* @param afterMonth
* ่ฅๅนฒไธชๆ,ๅฝๆไธบ0
* @return
*/
public static Date getLastDayOfAfterMonth(Date date, int afterMonth) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.MONTH, c.get(Calendar.MONTH) + afterMonth + 1);
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - 1);
return c.getTime();
}
/**
* ๅพๅฐไนๅ่ฅๅนฒไธชๆ็ๆๅไธๅคฉ.
*
* @param date
* @param beforeMonth
* ่ฅๅนฒไธชๆ,ๅฝๆไธบ0
* @return
*/
public static Date getLastDayOfBeforeMonth(Date date, int beforeMonth) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.MONTH, c.get(Calendar.MONTH) - beforeMonth + 1);
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - 1);
return c.getTime();
}
/**
* ๅพๅฐๅไธๅคฉ.
*
* @param date
* @return
*/
public static Date getNextDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) + 1);
return c.getTime();
}
/**
* ๅพๅฐๅไธๅคฉ.
*
* @param date
* @return
*/
public static Date getPrevDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH) - 1);
return c.getTime();
}
public static boolean isWeekend(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
if (Calendar.SATURDAY == c.get(Calendar.DAY_OF_WEEK) || Calendar.SUNDAY == c.get(Calendar.DAY_OF_WEEK)) {
return true;
}
return false;
}
public static Long countDateBelong(Date date1, Date date2) {
date1 = changeType(date1, COMPARE_TYPE_DAY);
date2 = changeType(date2, COMPARE_TYPE_DAY);
Long result = null;
if (dateBefore(date1, date2, COMPARE_TYPE_DAY)) {
result = (date2.getTime() - date1.getTime()) / DAY_TIME;
} else {
result = (date1.getTime() - date2.getTime()) / DAY_TIME;
}
return result + 1;
}
public static Integer getWeekends(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.DAY_OF_WEEK);
}
public static String getWeekendsStr(Date date) {
Integer week = getWeekends(date);
if (week == null) {
return "";
}
if (Calendar.MONDAY == week) {
return "ๆๆไธ";
} else if (Calendar.TUESDAY == week) {
return "ๆๆไบ";
} else if (Calendar.WEDNESDAY == week) {
return "ๆๆไธ";
} else if (Calendar.THURSDAY == week) {
return "ๆๆๅ";
} else if (Calendar.FRIDAY == week) {
return "ๆๆไบ";
} else if (Calendar.SATURDAY == week) {
return "ๆๆๅ
ญ";
} else if (Calendar.SUNDAY == week) {
return "ๆๆๆฅ";
}
return "";
}
/**
* <P><B>่ฏดๆ๏ผ</B>ไธคไธชๆฅๆ็ๅทฎๅผ</P>
* <P><B>ๆฅๆ๏ผ</B>2013-10-17 ไธๅ02:21:25</P>
* <P><B>ไฝ่
๏ผ</B>Jichen</P>
* @param date1
* @param date2
* @return
*/
public static long getDifferenceValue(Date date1, Date date2) {
return date2.getTime() - date1.getTime();
}
/**
* <P><B>่ฏดๆ๏ผ</B>่ฟๅไธคไธชๆฅๆ็ธๅทฎๅฐๆถๆฐ</P>
* <P><B>ๆฅๆ๏ผ</B>2013-10-17 ไธๅ02:47:29</P>
* <P><B>ไฝ่
๏ผ</B>Jichen</P>
* @param date1
* @param date2
* @return
*/
public static int getDHourValue(Date date1, Date date2) {
long dValue = getDifferenceValue(date1, date2);
return Long.valueOf(dValue / (1000 * 60 * 60)).intValue();
}
public static int getHourTime(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.get(Calendar.HOUR_OF_DAY);
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" text ="type/css" href="./front-assignment2-3.css">
<title>Document</title>
</head>
<body>
<div id="page-top"></div>
<div id="content">
<ul>
<li>1 Introduction to Front-end</li>
<ul>
<li>1.1 Introducing WEB</li>
<li>1.2 2021 Study Schedule</li>
<li>1.3 Setting Development Environment</li>
</ul>
<li>2 HTML: The Basic Structure</li>
<ul>
<li>2.1 Introducing HTML</li>
<li>2.2 Basic Structure of HTML</li>
<li>2.3 Commonly Used HTML Tags</li>
<li>2.4 Class and Id Attributes</li>
<li>2.5 HTML Exercises</li>
</ul>
<li>3 CSS: Desinging HTML</li>
<ul>
<li>3.1 Introducing CSS</li>
<li>3.2 Basic Structure of CSS</li>
<li>3.3 Style Properties</li>
<li>3.4 Selectors</li>
<li>3.5 Layouts</li>
<li>3.6 Responsive Web</li>
<li>3.7 CSS Exercises</li>
</ul>
<li>4 Basics of JavaScript</li>
<ul>
<li>4.1 Introducing JavaScript</li>
<li>4.2 Declaration of Variables</li>
<li>4.3 Data Types</li>
<li>4.4 Statements and Functions</li>
<li>4.5 Built-in Objects</li>
<li>4.6 Basics of JS Exercises</li>
</ul>
<li>5 JavaScript: Dynamic Frontend</li>
<ul>
<li>5.1 JavaScript with Front-end</li>
<li>5.2 Document Object Model</li>
<li>5.3 Browser Object Model</li>
<li>5.4 Event and Event Listener</li>
<li>5.5 JS Exercises</li>
</ul>
<li>A Exercise Answers</li>
<ul>
<li>A.1 HTML Exercise Answers</li>
<li>A.2 CSS Exercise Answers</li>
<li>A.3 Basics of JavaScript Exercise Answers</li>
<li>A.4 JS Exercise Answers</li>
</ul>
</ul>
</div>
<div id="page-bottom"></div>
<div id="scroll-button">
<a href="file:///C:/Users/82102/Desktop/kweb/front-assignment2-3.html#page-top">
<div id="top-scroll-cell" class="scroll-button-cell">▲</div>
</a>
<a href="file:///C:/Users/82102/Desktop/kweb/front-assignment2-3.html#page-bottom">
<div class="scroll-button-cell">▼</div>
</a>
</div>
</body>
</html>
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width: 100px;
height: 100px;
background-color: pink;
/*
ๅ
ณ้ฎๅธงๅจ็ป้ป่ฎคๆๅไผๅๅฐๅๅงไฝ็ฝฎ
forwards๏ผๅๅจๆๅไฝ็ฝฎ
*/
animation: run 1s linear forwards;
}
@keyframes run{
0%{
transform: translate(100px,0);
}
50%{
transform: translate(300px,300px);
background-color:darkturquoise;
}
100%{
transform: translate(0,500px);
}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
|
#include "variadic_functions.h"
#include <stdarg.h>
/**
* sum_them_all - Calculates the sum of multiple integers.
* @n: The count of integers to sum.
* @...: Variable list of integers to be summed.
* Return: Sum of the provided integers, or 0 if none.
*/
int sum_them_all(const unsigned int n, ...)
{
va_list ap;
unsigned int i, sum = 0;
va_start(ap, n);
for (i = 0; i < n; i++)
sum += va_arg(ap, int);
va_end(ap);
return (sum);
}
|
import { useForm } from 'react-hook-form'
import { Spin } from 'antd'
import { useNavigate } from 'react-router-dom'
import { useState } from 'react'
import { useGetUserQuery, useLazyGetUserQuery, useUpdateUserMutation } from '../../services/blog'
import styles from './profile.module.scss'
export default function Profile() {
const navigate = useNavigate()
const [serverErrors, setServerErrors] = useState({})
const { data: userdata, isSuccess, isLoading: isFormLoading } = useGetUserQuery()
const [trigger] = useLazyGetUserQuery()
const { user } = isSuccess && userdata
const {
register,
handleSubmit,
formState: { errors },
} = useForm()
const [updateUser, { isLoading }] = useUpdateUserMutation()
const onSubmit = async (data) => {
try {
await updateUser(data).unwrap()
trigger()
navigate('/')
} catch (error) {
setServerErrors(error.data.errors)
}
}
const loader = isFormLoading && <Spin className={styles.loader} />
const form = isSuccess && (
<>
<h1 className={styles.title}>Edit Profile</h1>
<form
className={styles.form}
onSubmit={handleSubmit(onSubmit)}
>
<label
htmlFor="username"
className={styles.label}
>
Username
<input
className={`${styles.text} ${errors.username || serverErrors.username ? styles.invalid : ''}`}
id="username"
defaultValue={user.username ? user.username : null}
placeholder="Username"
{...register('username', { required: true, minLength: 3, maxLength: 20, pattern: /^[a-z0-9]*$/ })}
/>
{errors.username && errors.username.type === 'required' && (
<p className={styles.alert}>username is required</p>
)}
{errors.username && errors.username.type === 'pattern' && (
<p className={styles.alert}>you can only use lowercase english letters and numbers</p>
)}
{errors.username && errors.username.type === 'minLength' && (
<p className={styles.alert}>username must be at least 3 characters</p>
)}
{errors.username && errors.username.type === 'maxLength' && (
<p className={styles.alert}>username must be no more than 20 characters</p>
)}
{serverErrors.username && <p className={styles.alert}>{`username ${serverErrors.username}`.slice(0, -1)}</p>}
</label>
<label
className={styles.label}
htmlFor="email"
>
Email address
<input
className={`${styles.text} ${errors.email || serverErrors.email ? styles.invalid : ''}`}
id="email"
defaultValue={user.email ? user.email : null}
placeholder="Email address"
type="email"
{...register('email', { required: true, pattern: /^[a-zA-Z0-9_.]+@[a-zA-Z0-9]+\.[a-zA-Z0-9-.]+$/ })}
/>
{errors.email && errors.email.type === 'required' && <p className={styles.alert}>email is required</p>}
{errors.email && errors.email.type === 'pattern' && <p className={styles.alert}>email must be valid</p>}
{serverErrors.email && <p className={styles.alert}>{`email ${serverErrors.email}`.slice(0, -1)}</p>}
</label>
<label
className={styles.label}
htmlFor="password"
>
New password
<input
className={`${styles.text} ${errors.password ? styles.invalid : ''}`}
id="password"
placeholder="New password"
type="password"
{...register('password', { required: true, minLength: 6, maxLength: 40 })}
/>
{errors.password && errors.password.type === 'required' && (
<p className={styles.alert}>password is required</p>
)}
{errors.password && errors.password.type === 'minLength' && (
<p className={styles.alert}>password must be at least 6 characters</p>
)}
{errors.password && errors.password.type === 'maxLength' && (
<p className={styles.alert}>password must be no more than 40 characters</p>
)}
</label>
<label
className={styles.label}
htmlFor="avatar"
>
Avatar image (url)
<input
className={`${styles.text} ${errors.avatar ? styles.invalid : ''}`}
id="avatar"
defaultValue={user.image ? user.image : null}
placeholder="Avatar image"
type="url"
{...register('avatar', { required: true })}
/>
{errors.avatar && errors.avatar.type === 'required' && <p className={styles.alert}>avatar is required</p>}
</label>
<input
type="submit"
className={styles.submit}
value="Save"
disabled={isLoading}
/>
{isLoading && <Spin />}
</form>
</>
)
return (
<section className={styles.profile}>
{form}
{loader}
</section>
)
}
|
import 'dart:io';
import 'package:awesome_notifications/awesome_notifications.dart';
import 'package:cnattendance/data/source/datastore/preferences.dart';
import 'package:cnattendance/model/auth.dart';
import 'package:cnattendance/provider/attendancereportprovider.dart';
import 'package:cnattendance/provider/dashboardprovider.dart';
import 'package:cnattendance/provider/leaveprovider.dart';
import 'package:cnattendance/provider/meetingprovider.dart';
import 'package:cnattendance/provider/morescreenprovider.dart';
import 'package:cnattendance/provider/payslipprovider.dart';
import 'package:cnattendance/provider/prefprovider.dart';
import 'package:cnattendance/provider/profileprovider.dart';
import 'package:cnattendance/screen/auth/login_screen.dart';
import 'package:cnattendance/screen/dashboard/dashboard_screen.dart';
import 'package:cnattendance/screen/profile/editprofilescreen.dart';
import 'package:cnattendance/screen/profile/payslipdetailscreen.dart';
import 'package:cnattendance/screen/profile/profilescreen.dart';
import 'package:cnattendance/screen/profile/meetingdetailscreen.dart';
import 'package:cnattendance/screen/splashscreen.dart';
import 'package:cnattendance/utils/navigationservice.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_mentions/flutter_mentions.dart';
import 'package:flutter_ringtone_player/flutter_ringtone_player.dart';
import 'package:get/get.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:provider/provider.dart';
import 'firebase_options.dart';
import 'package:in_app_notification/in_app_notification.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
FirebaseMessaging.onBackgroundMessage(_messageHandler);
// Step required to send ios push notification
NotificationSettings settings =
await FirebaseMessaging.instance.requestPermission(
alert: true,
badge: true,
provisional: false,
sound: true,
);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permission');
} else {
print('User declined or has not accepted permission');
}
AwesomeNotifications().initialize(
// set the icon to null if you want to use the default app icon
'resource://drawable/app_icon',
[
NotificationChannel(
channelGroupKey: 'digital_hr_group',
channelKey: 'digital_hr_channel',
channelName: 'Digital Hr notifications',
channelDescription: 'Digital HR Alert',
defaultColor: Color(0xFF9D50DD),
ledColor: Colors.white)
],
// Channel groups are only visual and are not required
channelGroups: [
NotificationChannelGroup(
channelGroupKey: 'digital_hr_group',
channelGroupName: 'HR group')
],
debug: true
);
AwesomeNotifications().isNotificationAllowed().then((isAllowed) {
if (!isAllowed) {
// This is just a basic example. For real apps, you must show some
// friendly dialog box before call the request method.
// This is very important to not harm the user experience
AwesomeNotifications().requestPermissionToSendNotifications();
}
});
FirebaseMessaging.onMessage.listen((event) {
FlutterRingtonePlayer.play(
fromAsset: "assets/sound/beep.mp3",
);
try {
InAppNotification.show(
child: Card(
margin: const EdgeInsets.all(15),
child: ListTile(
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
leading: Container(height: double.infinity,child: Icon(Icons.notifications)),
iconColor: HexColor("#011754"),
textColor: HexColor("#011754"),
minVerticalPadding: 10,
minLeadingWidth: 0,
tileColor: Colors.white,
title: Text(event.notification!.title!,),
subtitle: Text(event.notification!.body!,style: TextStyle(color: Colors.grey),),
),
),
context: NavigationService.navigatorKey.currentState!.context,
);
} catch (e) {
print(e);
}
});
FirebaseMessaging.onMessageOpenedApp.listen((message) {
print('Message clicked!');
});
ByteData data =
await PlatformAssetBundle().load('assets/ca/lets-encrypt-r3.pem');
SecurityContext.defaultContext
.setTrustedCertificatesBytes(data.buffer.asUint8List());
runApp(const MyApp());
configLoading();
}
Future<void> _messageHandler(RemoteMessage message) async {
FlutterRingtonePlayer.play(
fromAsset: "assets/sound/beep.mp3",
);
}
void configLoading() {
EasyLoading.instance
..indicatorType = EasyLoadingIndicatorType.cubeGrid
..loadingStyle = EasyLoadingStyle.dark
..indicatorSize = 50.0
..radius = 0.0
..progressColor = Colors.blue
..backgroundColor = Colors.white
..indicatorColor = Colors.blue
..textColor = Colors.black
..maskType = EasyLoadingMaskType.none
..userInteractions = false
..dismissOnTap = false;
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return OverlaySupport.global(
child: MultiProvider(
providers: [
ChangeNotifierProvider(
create: (ctx) => Auth(),
),
ChangeNotifierProvider(
create: (ctx) => Preferences(),
),
ChangeNotifierProvider(
create: (ctx) => LeaveProvider(),
),
ChangeNotifierProvider(
create: (ctx) => PrefProvider(),
),
ChangeNotifierProvider(
create: (ctx) => ProfileProvider(),
),
ChangeNotifierProvider(
create: (ctx) => AttendanceReportProvider(),
),
ChangeNotifierProvider(
create: (ctx) => DashboardProvider(),
),
ChangeNotifierProvider(
create: (ctx) => MoreScreenProvider(),
),
ChangeNotifierProvider(
create: (ctx) => MeetingProvider(),
),
ChangeNotifierProvider(
create: (ctx) => PaySlipProvider(),
),
],
child: Portal(
child: InAppNotification(
child: GestureDetector(
onTap: () {
FocusManager.instance.primaryFocus?.unfocus();
},
onVerticalDragDown: (details) {
FocusManager.instance.primaryFocus?.unfocus();
},
child: GetMaterialApp(
navigatorKey: NavigationService.navigatorKey,
debugShowCheckedModeBanner: false,
theme: ThemeData(
canvasColor: const Color.fromRGBO(255, 255, 255, 1),
fontFamily: 'GoogleSans',
primarySwatch: Colors.blue,
),
initialRoute: '/',
routes: {
'/': (_) => SplashScreen(),
LoginScreen.routeName: (_) => LoginScreen(),
DashboardScreen.routeName: (_) => DashboardScreen(),
ProfileScreen.routeName: (_) => ProfileScreen(),
EditProfileScreen.routeName: (_) => EditProfileScreen(),
MeetingDetailScreen.routeName: (_) => MeetingDetailScreen(),
PaySlipDetailScreen.routeName: (_) => PaySlipDetailScreen(),
},
builder: EasyLoading.init(),
),
),
),
),
),
);
}
}
|
import { Component, Input } from '@angular/core';
import * as moment from 'moment/moment';
import { CoreService } from '../../../core/shared/core.service';
import { NepaliCalendarService } from '../../calendar/np/nepali-calendar.service';
import { ENUM_CalendarTypes } from '../../shared-enums';
@Component({
selector: "date-lbl",
templateUrl: "./date-label.html"
})
export class DateLabelComponent {
//this class will show the Date in required format (AD/BS).
//this was needed since there a lots of places which needs explicit conversion of this.
// uses core-service's selected date format.
//default date is nepali (BS) unless changed from the Global Variable.
@Input('value')
ipDateValue: string = "";
displayDate: string = "";//this one will be shown to the user.
tooltipDate: string = "";//this one will be seen on tooltip.
@Input('show-time')
showTime: boolean = false;
public calendarType: string = "np";//default is np (BS date.)
public showNepDate: boolean = false;
public showEngDate: boolean = false;
public npDate: string = "";
public engDate: string = "";
public timeValue: string = "";
public EnableEnglishCalendarOnly: boolean = false;
constructor(public coreService: CoreService, public nepaliCalendarServ: NepaliCalendarService) {
this.calendarType = this.coreService.DatePreference;
this.GetCalendarParameter();
this.showNepDate = this.calendarType == "np";
this.showEngDate = !this.showNepDate;
}
GetCalendarParameter(): void {
const param = this.coreService.Parameters.find(p => p.ParameterGroupName === "Common" && p.ParameterName === "EnableEnglishCalendarOnly");
if (param && param.ParameterValue) {
const paramValue = JSON.parse(param.ParameterValue);
this.EnableEnglishCalendarOnly = paramValue;
}
}
ngOnInit() {
//! Configure English date as default if English Calendar only is enabled from the Parameter.
if (this.EnableEnglishCalendarOnly) {
this.calendarType = ENUM_CalendarTypes.English;
this.showEngDate = true;
this.showNepDate = false;
}
if (this.ipDateValue) {
this.npDate = this.nepaliCalendarServ.ConvertEngToNepDateString(this.ipDateValue);
this.engDate = moment(this.ipDateValue).format("YYYY-MM-DD");
this.timeValue = moment(this.ipDateValue).format("hh:mm A");
if (this.showEngDate) {
this.displayDate = this.showTime ? this.engDate + " " + this.timeValue : this.engDate;
}
else {
this.displayDate = this.showTime ? this.npDate + " " + this.timeValue : this.npDate;
}
if (this.EnableEnglishCalendarOnly) {
this.tooltipDate = "(AD) " + this.engDate;
} else {
this.tooltipDate = "(AD) " + this.engDate + "\n(BS) " + this.npDate;
}
}
// console.log("from date label component");
// console.log(this.ipDateValue);
}
}
|
<?php
/**
* Creates instances of Classes using Reflection.
*
* Copyright (c) 2010-2012 Christian Wรผrker (ceusmedia.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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/>.
*
* @category cmClasses
* @package Alg.Object
* @author Christian Wรผrker <christian.wuerker@ceusmedia.de>
* @copyright 2010-2012 Christian Wรผrker
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPL 3
* @link http://code.google.com/p/cmclasses/
* @since 0.6.8
* @version $Id$
*/
/**
* Creates instances of Classes using Reflection.
* @category cmClasses
* @package Alg.Object
* @author Christian Wรผrker <christian.wuerker@ceusmedia.de>
* @copyright 2010-2012 Christian Wรผrker
* @license http://www.gnu.org/licenses/gpl-3.0.txt GPL 3
* @link http://code.google.com/p/cmclasses/
* @since 0.6.8
* @version $Id$
*/
class Alg_Object_Factory
{
protected $arguments = array();
public function __construct( $arguments = array() )
{
if( is_array( $arguments ) )
$this->setArguments( $arguments );
}
public function addArgument( $argument )
{
$this->arguments[] = $argument;
}
public function create( $className, $arguments = NULL )
{
$factory = clone $this;
if( $arguments )
foreach( $arguments as $argument )
$factory->addArgument( $argument );
$arguments = $factory->getArguments();
return Alg_Object_Factory::createObject( $className, $arguments );
}
public function getArguments()
{
return $this->arguments;
}
public function setArguments( $arguments = array() )
{
if( !is_array( $arguments ) )
throw new InvalidArgumentException( 'Arguments must be an array' );
$this->arguments = array_values( $arguments );
}
/**
* Creates an instance of a class using Reflection.
* @access public
* @static
* @param string $className Name of Class
* @param array $arguments List of Arguments for Contruction
* @return object
*/
public static function createObject( $className, $arguments = array() )
{
if( !class_exists( $className ) )
throw new RuntimeException( 'Class "'.$className.'" has not been loaded' );
$class = new ReflectionClass( $className );
if( $arguments )
$object = $class->newInstanceArgs( $arguments );
else
$object = $class->newInstance();
return $object;
}
}
?>
|
import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';
import NavDropdown from 'react-bootstrap/NavDropdown';
import CartWidgetComponent from '../CartWidgetComponent/CartWidgetComponent';
import { Link } from 'react-router-dom';
import { useEffect, useState } from 'react';
import axios from 'axios';
const NavBarComponent = () => {
const [categories, setCategories]= useState([]);
useEffect(()=>{
axios.get('https://dummyjson.com/products/categories')
.then(res =>{
setCategories(res.data);
})
.catch(error => console.log(error));
},[])
return (
<Navbar variant = "light" expand="lg" className="bg-light">
<Container>
<Navbar.Brand>
<Link to={"/"} style={{textDecoration:"none", color:"red"}}>Pear</Link>
</Navbar.Brand>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="me-auto ">
<Nav.Link href="#home">Home</Nav.Link>
<Nav.Link href="#link">YouPhone</Nav.Link>
<NavDropdown title="Categories" id="basic-nav-dropdown">
{categories.map((category, index) => {
return (
<NavDropdown.Item key={index}>
<Link to={`/category/${category}`}>{category}</Link>
</NavDropdown.Item>
);
})}
</NavDropdown>
</Nav>
<CartWidgetComponent/>
</Navbar.Collapse>
</Container>
</Navbar>
);
}
export default NavBarComponent;
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from './PricingPlan.module.css';
const PricingItem = ({ label, icon, capacity, price, description }) => (
<div className={styles.pricingItem}>
<i className={styles.icon} style={{ backgroundImage: `url(${icon})` }} />
<h2 className={`${styles.label} ${styles[`label${label}`]}`}>{label}</h2>
<p className={styles.capacity}>{capacity} storage</p>
<p className={styles.description}>{description}</p>
<p className={styles.price}>${price}/MO</p>
<button
type="button"
className={`${styles.button} ${styles[`button${label}`]}`}
>
Get Started
</button>
</div>
);
PricingItem.propTypes = {
icon: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
capacity: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
description: PropTypes.string.isRequired,
};
export default PricingItem;
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>add</title>
<link href="/css/add.css" rel="stylesheet"></link>
</head>
<body>
<!-- th:replaceใไฝฟ็จใใฆใ ใใใใผ็จใฎใใฉใฐใกใณใใ่ชญ่พผใฟใพใ -->
<div th:replace="common :: header_fragment"></div>
<h1>ใฆใผใถใผๆฐ่ฆ็ป้ฒ</h1>
<form th:action="@{/add/confirm}" th:object="${addRequest}" method="post">
<table>
<tr>
<th class="cell_title">ใฆใผใถใผๅ</th>
<th class="cell_required"></th>
<td><input type="text" th:field="*{name}">
<p th:errors="*{name}" class="error-message"></p>
</td>
</tr>
<tr>
<th class="cell_title">ๆๅฑใใผใ ๅ๏ผ็กๆๅฑใฎๅ ดๅใฏโๆๅฑใชใโ๏ผ</th>
<th class="cell_required"></th>
<td><input type="text" th:field="*{team}">
<p th:errors="*{team}" class="error-message"></p>
</td>
</tr>
<tr>
<th class="cell_title">้ป่ฉฑ็ชๅท</th>
<th class="cell_required"></th>
<td><input type="text" th:field="*{phone}">
<p th:errors="*{phone}" class="error-message"></p>
</td>
</tr>
<tr>
<th class="cell_title">ใกใผใซใขใใฌใน</th>
<th class="cell_required"></th>
<td><input type="text" th:field="*{email}">
<p th:errors="*{email}" class="error-message"></p>
</td>
</tr>
<tr>
<th class="cell_title">ไฝๆ</th>
<th class="cell_required"></th>
<td><input type="text" th:field="*{address}">
<p th:errors="*{address}" class="error-message"></p>
</td>
</tr>
<tr>
<th class="cell_title">ๅฎใใใใธใทใงใณ๏ผ่คๆฐๅฏ๏ผ</th>
<th class="cell_required"></th>
<td><input type="text" th:field="*{position}">
<p th:errors="*{position}" class="error-message"></p>
</td>
</tr>
<tr>
<th class="cell_title">ใในใฏใผใ</th>
<th class="cell_required"></th>
<td><input type="text" th:field="*{password}">
<p th:errors="*{password}" class="error-message"></p>
</td>
</tr>
</table>
<div class="btn_area_center"><input type="submit" value="็ขบ่ชใใผใธใธ" class="btn"></div>
</form>
<body>
</body>
</html>
|
# PPHA 30537
# Spring 2023
# Homework 6
# Madhukar Battula
# Madhukar Battula
# madhukarbattula
# Due date: Monday May 8th before midnight
# Write your answers in the space between the questions, and commit/push only
# this file to your repo. Note that there can be a difference between giving a
# "minimally" right answer, and a really good answer, so it can pay to put
# thought into your work.
##################
#NOTE: All of the plots the questions ask for should be saved and committed to
# your repo under the name "q1_plot.png", "q2_plot.png", etc. If a question calls
# for more than one plot, name them "q1a_plot", "q1b_plot", etc.
#%%
# Question 1: With the x and y values below, create a plot using only Matplotlib.
# You should plot y1 as a scatter plot and y2 as a line, using different colors
# and a legend. You can name the data simply "y1" and "y2". Make sure the
# axis labels are legible. Add a title that reads "HW6 Q1".
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import os
x = pd.date_range(start='1990/1/1', end='1991/12/1', freq='MS')
y1 = np.random.normal(10, 2, len(x))
y2 = [np.sin(v)+10 for v in range(len(x))]
fig, ax = plt.subplots()
ax.scatter(x, y1, color='green', label='y1')
ax.plot(x, y2, color='purple', linestyle='solid', label='y2')
ax.set_xlabel('Date')
ax.set_ylabel('Values of Y')
ax.set_title('HW6 Q1')
plt.xticks(rotation=45)
ax.legend(loc='best')
fig.savefig('q1_plot.png', dpi=300, bbox_inches='tight')
#%%
# Question 2: Using only Matplotlib, reproduce the figure in this repo named
# question_2_figure.png.
x = np.linspace(10, 19, 5)
y1 = x
y2 = -1*x + 29
fig, ax = plt.subplots()
ax.plot(x, y1, color='blue', label='Blue')
ax.plot(x, y2, color='red', label='Red')
ax.set_title('X marks the spot')
ax.legend(loc='center left')
fig.savefig('q2_plot.png', dpi=300, bbox_inches='tight')
plt.show()
#%%
# Question 3: Load the mpg.csv file that is in this repo, and create a
# plot that tests the following hypothesis: a car with an engine that has
# a higher displacement (i.e. is bigger) will get worse gas mileage than
# one that has a smaller displacement. Test the same hypothesis for mpg
# against horsepower and weight.
mpg_data = pd.read_csv('mpg.csv')
# Hypothesis 1: Displacement vs. MPG
fig, ax = plt.subplots()
ax.scatter(mpg_data['displacement'], mpg_data['mpg'], color='green', alpha=0.5)
ax.set_xlabel('Displacement')
ax.set_ylabel('MPG')
ax.set_title('Hypothesis 1: Displacement vs. MPG')
fig.savefig('q3a_plot.png', dpi=300, bbox_inches='tight')
plt.show()
# As per the Hypothesis 1 testing, there is a negative corelation between
# displacement and mpg data, i.e., as displacement increases, mpg decreases.
# Hypothesis 2: Horsepower vs. MPG
fig, ax = plt.subplots()
ax.scatter(mpg_data['horsepower'], mpg_data['mpg'],color='blue', alpha=0.5)
ax.set_xlabel('Horsepower')
ax.set_ylabel('MPG')
ax.set_title('Hypothesis 2: Horsepower vs. MPG')
fig.savefig('q3b_plot.png', dpi=300, bbox_inches='tight')
plt.show()
# As per the Hypothesis 2 testing, there is a negative corelation between
# horsepower and mpg data, i.e., as horsepower increases, mpg decreases.
# Hypothesis 3: Weight vs. MPG
fig, ax = plt.subplots()
ax.scatter(mpg_data['weight'], mpg_data['mpg'],color='orange', alpha=0.5)
ax.set_xlabel('Weight')
ax.set_ylabel('MPG')
ax.set_title('Hypothesis 3: Weight vs. MPG')
fig.savefig('q3c_plot.png', dpi=300, bbox_inches='tight')
plt.show()
# As per the Hypothesis 3 testing, there is a negative corelation between
# weight and mpg data, i.e., as weight increases, mpg decreases.
#%%
# Question 4: Continuing with the data from question 3, create a scatter plot
# with mpg on the y-axis and cylinders on the x-axis. Explain what is wrong
# with this plot with a 1-2 line comment. Now create a box plot using Seaborn
# that uses cylinders as the groupings on the x-axis, and mpg as the values
# up the y-axis.
fig, ax = plt.subplots()
ax.scatter(mpg_data['cylinders'], mpg_data['mpg'], color='magenta', alpha=0.5)
ax.set_xlabel('Count of Cylinders')
ax.set_ylabel('MPG')
ax.set_title('Scatter Plot of MPG vs. Cylinders')
fig.savefig('q4a_plot.png', dpi=300, bbox_inches='tight')
plt.show()
# The data points are overlapping, and this makes it difficult to visualize
# the density of the data by using a scatter plot.
sns.boxplot(x='cylinders', y='mpg', data=mpg_data)
plt.xlabel('Count of Cylinders')
plt.ylabel('MPG')
plt.title('Box Plot of MPG vs. Cylinders')
plt.savefig('q4b_plot.png', dpi=300, bbox_inches='tight')
plt.show()
# A box plot clearly shows the distribution of mpg for each cylinder value
# and makes it easier to visualize any differences in the data.
#%%
# Question 5: Continuing with the data from question 3, create a two-by-two
# grid of subplots, where each one has mpg on the y-axis and one of
# displacement, horsepower, weight, and acceleration on the x-axis. To clean
# up this plot:
# - Remove the y-axis tick labels (the values) on the right two subplots -
# the scale of the ticks will already be aligned because the mpg values
# are the same in all axis.
# - Add a title to the figure (not the subplots) that reads "Changes in MPG"
# - Add a y-label to the figure (not the subplots) that says "mpg"
# - Add an x-label to each subplot for the x values
# Finally, use the savefig method to save this figure to your repo. If any
# labels or values overlap other chart elements, go back and adjust spacing.
fig, axs = plt.subplots(2, 2, figsize=(12, 12), sharey=True)
fig.suptitle('Changes in MPG')
fig.text(0.04, 0.5, 'mpg', ha='center', va='center', rotation='vertical')
xlabels = ['Displacement', 'Horsepower', 'Weight', 'Acceleration']
for i, ax in enumerate(axs.flat):
ax.set_xlabel(xlabels[i])
sns.scatterplot(data=mpg_data, x='displacement', y='mpg', ax=axs[0][0])
sns.scatterplot(data=mpg_data, x='horsepower', y='mpg', ax=axs[0][1])
sns.scatterplot(data=mpg_data, x='weight', y='mpg', ax=axs[1][0])
sns.scatterplot(data=mpg_data, x='acceleration', y='mpg', ax=axs[1][1])
plt.savefig('q5_plot.png', dpi=300, bbox_inches='tight')
plt.show()
#%%
# Question 6: Are cars from the USA, Japan, or Europe the least fuel
# efficient, on average? Answer this with a plot and a one-line comment.
mpg_data['origin'] = mpg_data['origin']\
.replace({'usa': 'USA', 'japan': 'Japan', 'europe': 'Europe'})
sns.boxplot(x='origin', y='mpg', data=mpg_data)
plt.title('Fuel efficiency by country of origin')
plt.xlabel('Origin')
plt.ylabel('MPG')
plt.savefig('q6_plot.png', dpi=300, bbox_inches='tight')
plt.show()
# Cars from the USA are least fuel efficient followed by Europe and then Japan.
#%%
# Question 7: Using Seaborn, create a scatter plot of mpg versus displacement,
# while showing dots as different colors depending on the country of origin.
# Explain in a one-line comment what this plot says about the results of
# question 6.
mpg_data['origin'] = mpg_data['origin']\
.replace({'usa': 'USA', 'japan': 'Japan', 'europe': 'Europe'})
sns.scatterplot(data=mpg_data, x='displacement', y='mpg', hue='origin')
plt.title('Scatter Plot of MPG vs. Displacement')
plt.xlabel('Displacement')
plt.ylabel('MPG')
plt.legend(title='Country of Origin')
plt.savefig('q7_plot.png', dpi=300, bbox_inches='tight')
plt.show()
# Cars from Japan have highest fuel efficiency, followed by Europe and USA that
# has least fuel efficiency. This is consistent with the results of Question 6.
#%%
|
# Getting Started Video Player App | Frontend ๐
This section is the Front-end (_clinet side_) of the application.
## Overview
- Project was developed with ReactJS.
- I have taken the approach of breaking down all used elements into smaller web components.
- I have created TWO pages:
1. _Home_: Renders and displays list of videos, in Cards style.
2. _VideoDetails_ : Gets the video id from URL with [useParams() hook](https://v5.reactrouter.com/web/api/Hooks/useparams), then renders and autoplays the video. Also displays it's details.
- Pages use a shared hook called `useVideo()` to:
- Fetches data from API (Videos list)
- Gets all Video details
- Controls fetching state (_used for loading spinner animation while fetching_)
- Prepared a pre-defined boiler-plate css classes using SASS for ease of development.
- example: \
`<span className="container flex justify--center align-center" >`
is equivilant to
```
// HTML
<span className="container" />
// CSS
.container {
display: flex;
justify-content: center;
align-items: center;
}
```
- Along with other configurations for styling dynamic flow.
# Prepare and run the project (locally) โ๏ธ
1. Make sure you have [node](https://nodejs.org/en/) installed on your machine.
2. In order to install the proper packages to run this project, navigate to this direcotry:
```
cd video-player-frontend
```
3. In the project directory, you can run:
```
npm start
```
OR
```
yarn start
```
This runs the app in the development mode.
4. Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
5. I order to successfully call the API and fetch data, you to have the backend server up and running.\
Please navigate to[Backend README](https://github.com/yasserzakyw/React-Strapi---tldv/blob/master/video-player-backend/README.md) to know how to do that ๐
\
The page will reload when you make changes.\
You may also see any lint errors in the console.
In case of any questions, you know [where to find me ๐จ๐ปโ๐ป](http://yasserzaky.xyz/)
|
$(function() {
$('.prompt').html('root@haddadi:~# ');
var term = new Terminal('#input-line .cmdline', '#container output');
term.init();
});
var util = util || {};
util.toArray = function(list) {
return Array.prototype.slice.call(list || [], 0);
};
var Terminal = Terminal || function(cmdLineContainer, outputContainer) {
window.URL = window.URL || window.webkitURL;
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var cmdLine_ = document.querySelector(cmdLineContainer);
var output_ = document.querySelector(outputContainer);
const CMDS_ = [
'whoami', 'education', 'experience', 'certifications', 'projects', 'interests', 'voluntary' ,'contact', 'help'
];
var fs_ = null;
var cwd_ = null;
var history_ = [];
var histpos_ = 0;
var histtemp_ = 0;
window.addEventListener('click', function(e) {
cmdLine_.focus();
}, false);
cmdLine_.addEventListener('click', inputTextClick_, false);
cmdLine_.addEventListener('keydown', historyHandler_, false);
cmdLine_.addEventListener('keydown', processNewCommand_, false);
//
function inputTextClick_(e) {
this.value = this.value;
}
//
function historyHandler_(e) {
if (history_.length) {
if (e.keyCode == 38 || e.keyCode == 40) {
if (history_[histpos_]) {
history_[histpos_] = this.value;
} else {
histtemp_ = this.value;
}
}
if (e.keyCode == 38) { // up
histpos_--;
if (histpos_ < 0) {
histpos_ = 0;
}
} else if (e.keyCode == 40) { // down
histpos_++;
if (histpos_ > history_.length) {
histpos_ = history_.length;
}
}
if (e.keyCode == 38 || e.keyCode == 40) {
this.value = history_[histpos_] ? history_[histpos_] : histtemp_;
this.value = this.value;
}
}
}
//
function processNewCommand_(e) {
if (e.keyCode == 9) { // tab
e.preventDefault();
} else if (e.keyCode == 13) { // enter
if (this.value) {
history_[history_.length] = this.value;
histpos_ = history_.length;
}
var line = this.parentNode.parentNode.cloneNode(true);
line.removeAttribute('id')
line.classList.add('line');
var input = line.querySelector('input.cmdline');
input.autofocus = false;
input.readOnly = true;
output_.appendChild(line);
if (this.value && this.value.trim()) {
var args = this.value.split(' ').filter(function(val, i) {
return val;
});
var cmd = args[0].toLowerCase();
args = args.splice(1);
}
switch (cmd) {
case 'clear':
output_.innerHTML = '';
this.value = '';
return;
case 'help':
var result = "<h2>Help</h2><p><b>whoami</b>: Who am I ?<br><b>education</b>: display information about my education.<br><b>experience</b>: display information about my experiences.<br><b>certifications</b>: display all my certifications.<br><b>projects</b>: display information about my projects.<br><b>interests</b>: my areas of intrests ?<br><b>voluntary</b>: display my voluntary experiences.<br><b>contact</b>: wanna reach out ?<br><b>clear</b>: clear terminal<br><b>help</b>: display this menu.</p>";
output(result);
break;
case 'education':
var result = "<h3>Education</h3><p>Computer Engineering Cycle, ENSA - Tetouan. Expected 2021 <br> Preparatory Classes, ENSA - Tetouan. 2015 - 2018 <br> Baccalaureate - Mathematics, Newton International School - Mohammedia. 2014 - 2015</p>";
output(result);
break;
case 'experience':
var result = "<h3>Experience</h3><p> <b>Artificial Intelligence Research Intern Jul 2020 - Sept 2020 <br>DeepEcho Rabat</b><br> Built, trained & deployed deep learning models for the calculation of amniotic fluid index in 2D ultrasound images. <br> Achieved 2% higher than state-of-the-art amniotic fluid pocket semantic segmentation models.<br> <b>Tech Stack :</b> OpenCV, Python, Numpy, Tensorflow, Keras, Django, AWS. <br><br <b>Software Engineer - Part time Jul 2020 - Sept 2020 <br>Kaktus AI London - England, UK</b><br> Designed and developed an algorithm for customized questions picking per user. <br> Reduced back-end application response time by 28%.<br> <b>Tech Stack :</b> Django, Angular, Redis. <br><br><b>Software Engineering Intern Jul 2020 - Sept 2020 <br>ENSATรฉ Tetouan</b><br> Created a hospital appointment management web application. <br> Implemented machine learning algorithms for heart disease prediction.<br> Integrated a deep neural network for malaria and pneumonia medical image diagnosis.<br> <b>Tech Stack :</b> Django, Javascript, Numpy, Pandas, Matplotlib, Keras. <br><br><b>Business Intelligence Intern Jul 2019 - Aug 2019<br>Prometi Casablanca</b><br> Cleaned and preprocessed sales and purchases data, and created a dashboard.<br> Created a real time visualizing dashboard for workers in function.<br><b> Tech Stack :</b> MySql, PowerBI, Dax.<p>";
output(result);
break;
case 'certifications':
var result = "<h3>Certifications</h3><p><b>Coursera Deep Learning Specialization</b><br> Rich and varied specialization that gave me knowledge of deep learning from its foundations (neural networks) to its industry applications (Computer Vision, Natural Language Processing,Speech Recognition, etc.).<br> <b>Five courses : </b><br> Neural Networks and DeepLearning<br> Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization<br> Structuring Machine Learning Projects<br> Convolutional NeuralNetworks<br> Sequence Models<br><br> <b>Coursera Natural Language Processing Specialization</b><br> The specialization helped me grasp state-of-the-art deep learning techniques needed to build cutting-edge NLP systems <br> <b>Four Courses : </b><br>  Natural Language Processing with Classification and Vector Spaces<br>  Natural Language Processing with Probabilistic Models <br>  Natural Language Processing with Sequence Models <br>  Natural Language Processing with Attention Models <br><br> <b>Huawei Routing & Switching Certification</b> <p>";
output(result);
break;
case 'projects':
var result = "<h3>Projects </h3><p> <b>BioTiful :</b> Django E-commerce web application developed as a volunteer for a Bio-products cooperative in the community where I did my engineering studies. . <br> <b>ClinicApp :</b> Django web application to help a medical clinic manage their appointments and assits doctors in their diagnosisis . <br> <b>MorphBot :</b> Implemented an LSTM model for rap lyrics generation in Arabic Moroccan dialect using : Scrapy to scrap the songs lyrics & Keras for the deep learning network. <br> <b> GTE-Gesture To English :</b> Trained a Vgg19 neural network to recognize sign language gestures and return the equivalent english letters using OpenCV & Keras. <br> <b>CoviZZ :</b> Built a web application for visualizing Covid19 cases in Morocco by region & city, using : SparkJava, PL/SQL, Javascript, OracleDB 18cXE. <br> <b>Minoch :</b> Text editor for Unix-like computing systems developed in C language. </p>";
output(result);
break;
case 'interests':
var result = "<h3>Interests</h3><p>Competitive programming, machine learning, hiking, numismatics.</p>";
output(result);
break;
case 'voluntary':
var result = "<h3>Voluntary</h3><p><b>Assistant in a blood donation caravan during weekends of Jul-Aug 2018.</b><br><b>Assistant in โFtour Al Amalโ</b> : Assisted in preparing and providing +1200 daily meals during Ramadan 2017.</p>";
output(result);
break;
case 'contact':
var result = "<h3>Contact</h3><h4>Email: abderrahim.haddadiii@gmail.com<br><a style='text-decoration: none;' href='https://www.linkedin.com/in/abderrahim-haddadi'>LinkedIn</a> <br></h4>";
output(result);
break;
case 'whoami':
var result = "<h1>HADDADI Abderrahim</h1><p><h3>Artificial intelligence researcher during the day, software engineering enthusiast at nights.<br>I find pleasure in learning and helping others.<br>Curious and creative inner child takes command when facing challenges.</h3></p>"
output(result);
break;
default:
if (cmd) {
output(cmd + ': command not found');
}
};
window.scrollTo(0, getDocHeight_());
this.value = '';
}
}
//
function formatColumns_(entries) {
var maxName = entries[0].name;
util.toArray(entries).forEach(function(entry, i) {
if (entry.name.length > maxName.length) {
maxName = entry.name;
}
});
var height = entries.length <= 3 ?
'height: ' + (entries.length * 15) + 'px;' : '';
var colWidth = maxName.length * 7;
return ['<div class="ls-files" style="-webkit-column-width:',
colWidth, 'px;', height, '">'];
}
//
function output(html) {
output_.insertAdjacentHTML('beforeEnd', '<p>' + html + '</p>');
}
function getDocHeight_() {
var d = document;
return Math.max(
Math.max(d.body.scrollHeight, d.documentElement.scrollHeight),
Math.max(d.body.offsetHeight, d.documentElement.offsetHeight),
Math.max(d.body.clientHeight, d.documentElement.clientHeight)
);
}
//
return {
init: function() {
output('<h1>HADDADI Abderrahim</h1><h3>Passionate software engineering student during the day<br>Machine learning enthusiast at nights.<br>I find pleasure in learning and helping others.<br>Curious and creative inner child takes command when facing challenges.</h3><p>Enter "help" for more information.</p><p> -- This website is inspired by Ahmed Lekssays\'s website </p>');
},
output: output
}
};
|
package com.systechafrica.pos;
import java.util.ArrayList;
import java.util.Scanner;
import com.systechafrica.util.Login;
public class Store {
Scanner scanner = new Scanner(System.in);
public static int totalPayment;
static int noOfItemsToPurchase = 0;
static ArrayList<Item> items = new ArrayList<>();
static boolean isCustomerShopping = true;
static boolean isPaymentMade = false;
int change;
int amountPaidByCustomer = 0;
public void displayMenu() {
System.out.println("-----------------------------------");
System.out.println("----- SYSTEM POS SYSTEM ----");
System.out.println("-------------------------------------");
System.out.println("1. ADD ITEM");
System.out.println("2. MAKE PAYMENT");
System.out.println("3. DISPLAY RECEIPT");
// TODO - QUIT MENU OPTION.
}
public void addItems() {
System.out.print("Enter the number of items to purchase: ");
int noOfItemsToPurchase = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < noOfItemsToPurchase; i++) {
System.out.print("Enter the Item Code: ");
int itemCode = scanner.nextInt();
System.out.print("Enter the quantity: ");
int quantity = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter the unit price: ");
int unitPrice = scanner.nextInt();
totalPayment += (quantity * unitPrice);
// Add item to the items array
Item s = new Item(itemCode, quantity, unitPrice);
// items[i] = s;
items.add(s); //keep track of all added items
}
}
public void payment() {
System.out.println("_________________________________________________");
System.out.println("ItemCode Quantity UnitPrice TotalPrice");
for (Item item : items) {
System.out.printf("%-10s %-12s %-9s %-10s%n", item.getItemCode(), item.getQuantity(), item.getUnitPrice(), item.getTotalValue());
}
System.out.println("___________________________________________________");
System.out.println("TOTAL: " + totalPayment);
System.out.println("Enter the amount given by customer");
amountPaidByCustomer = scanner.nextInt();
scanner.nextLine();
// TODO - CHECK IF THERE IS AN ITEM BEFORE MAKING PAYMENT.
// TODO - INSUFFICIENT AMOUNT.
if (amountPaidByCustomer > totalPayment) {
change = amountPaidByCustomer - totalPayment;
}
System.out.println("Change: " + change);
System.out.println("***************************************************");
System.out.println("THANK YOU FOR SHOPPING WITH US");
System.out.println("***************************************************");
isPaymentMade = true;
}
public void displayReceipt() {
System.out.println("_________________________________________________");
System.out.println("ItemCode Quantity UnitPrice TotalPrice");
for (Item item : items) {
System.out.printf("%-10s %-12s %-9s %-10s%n", item.getItemCode(), item.getQuantity(), item.getUnitPrice(), item.getTotalValue());
}
System.out.println("___________________________________________________");
System.out.println("TOTAL: " + totalPayment);
System.out.println("Amount paid: " + amountPaidByCustomer);
System.out.println("Change: " + change);
System.out.println("***************************************************");
System.out.println("THANK YOU FOR SHOPPING WITH US");
System.out.println("***************************************************");
}
public static void main(String[] args) {
Store app = new Store();
boolean isLoggedIn = Login.login();
boolean keepShowingMenu = true;
if (isLoggedIn) {
System.out.println("Happy Shopping Customer :) ");
while (keepShowingMenu) {
// Y -continue shopping
// N - showMenu
app.displayMenu();
try {
System.out.println("Choose your option");
int option = app.scanner.nextInt();
app.scanner.nextLine();
if (option == 1) {
while (isCustomerShopping) {
app.addItems();
System.out.println("Would you like to add more items?: Y/N");
String continueShopping = app.scanner.next();
if (continueShopping.equalsIgnoreCase("N")) {
// end shopping - display menu
// System.out.println(totalPayment);
isCustomerShopping = false;
}
}
System.out.println("Thank you for shopping with us - Proceed to payment/receipt printing.");
} else if (option == 2) {
// make payment
app.payment();
} else if (option == 3) {
if (isPaymentMade) {
// display receipt then quit
app.displayReceipt();
keepShowingMenu = false;
} else {
System.out.println("Please make the payment first before printing the receipt");
}
} else {
System.out.println("Invalid option... try again");
}
} catch (Exception e) {
app.scanner.nextLine();
System.out.println("Invalid option - Integers only... try again");
}
}
} else {
System.out.println("Maximum attempts failed");
}
app.scanner.close();
}
}
|
<a class="ui button positive" href="#/add"><i class="icon add user"></i>Add User</a>
<div class="ui left icon input" style="float: right;">
<input type="text" ng-model="search" placeholder="Search users...">
<i class="users icon"></i>
</div>
<!-- Error message -->
<div ng-if="errors.length" class="ui message negative"><div class="header"><i class="icon warning sign"></i>Error!</div>
<span ng-repeat="error in errors">- {{error}}<br></span>
</div>
<!-- Success message -->
<div ng-if="msgtext" class="ui message positive"><div class="header"><i class="icon checkmark"></i>Success!</div>
<span>{{msgtext}}</span>
</div>
<table class="ui table selectable olive celled">
<thead>
<tr>
<th>Full Name</th>
<th>Email</th>
<th>Country</th>
<th>Gender</th>
<th>Skills</th>
<th>Address</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-if="!data.length"><td colspan="8">
<div class="ui icon negative message">
<i class="warning circle icon"></i>
<div class="content">
<div class="header">
No record to display
</div>
</div>
</div>
</td></tr>
<tr id="{{user.id}}" ng-repeat="user in data | filter:search">
<td ng-click="sortType = 'fullname'">{{user.fullname}}</td>
<td>{{user.email}}</td>
<td>{{user.country}}</td>
<td>{{user.gender == '1' ? 'Male' : 'Female' }}</td>
<td>{{user.skills}}</td>
<td>{{user.address}}</td>
<td>
<a href="#/edit/{{user.id}}"><i class="pencil delete large teal link icon"></i></a>
<a ng-click="delete(user.id);"><i class="user delete large red link icon"></i></a>
</td>
</tr>
</tbody>
</table>
<div class="ui modal">
<div class="header">Delete user</div>
<div class="content">
<p>Are you sure you want to delete this user?</p>
</div>
<div class="actions">
<div class="ui approve positive button">Confirm</div>
<div class="ui cancel negative button">Cancel</div>
</div>
</div>
|
"""The Lรคnderรผbergreifendes Hochwasser Portal API - Functions for Niedersachsen."""
from __future__ import annotations
from .api_utils import (
DynamicData,
LHPError,
StaticData,
convert_to_datetime,
convert_to_float,
convert_to_int,
fetch_json,
)
def init_NI(ident: str) -> StaticData: # pylint: disable=invalid-name
"""Init data for Niedersachsen."""
try:
# Get data
data = fetch_json(
"https://bis.azure-api.net/PegelonlinePublic/REST/stammdaten"
+ "/stationen/All?key=9dc05f4e3b4a43a9988d747825b39f43"
)
# Parse data
for entry in data["getStammdatenResult"]:
if entry["STA_Nummer"] == ident[3:]:
name = entry["Name"] + " / " + entry["GewaesserName"]
internal_url = (
"https://bis.azure-api.net/PegelonlinePublic/REST/stammdaten/stationen/"
+ str(entry["STA_ID"])
+ "?key=9dc05f4e3b4a43a9988d747825b39f43"
)
url = (
"https://www.pegelonline.nlwkn.niedersachsen.de/Pegel/Karte/Binnenpegel/ID/"
+ str(entry["STA_ID"])
)
if entry["Internetbeschreibung"] != "Keine Daten":
hint = entry["Internetbeschreibung"]
else:
hint = None
return StaticData(
ident=ident,
name=name,
internal_url=internal_url,
url=url,
hint=hint,
)
return StaticData(ident=ident)
except Exception as err:
raise LHPError(err, "ni_api.py: init_NI()") from err
def update_NI(static_data: StaticData) -> DynamicData: # pylint: disable=invalid-name
"""Update data for Niedersachsen."""
try:
# Get data
data = fetch_json(static_data.internal_url)
# Parse data
try:
stage = convert_to_int(
data["getStammdatenResult"][0]["Parameter"][0]["Datenspuren"][0][
"AktuelleMeldeStufe"
]
)
except (IndexError, KeyError):
stage = None
try:
value = convert_to_float(
data["getStammdatenResult"][0]["Parameter"][0]["Datenspuren"][0][
"AktuellerMesswert"
]
)
except (IndexError, KeyError):
value = None
try:
if data["getStammdatenResult"][0]["Parameter"][0]["Einheit"] == "cm":
level = value
flow = None
elif data["getStammdatenResult"][0]["Parameter"][0]["Einheit"] == "mยณ/s":
level = None
flow = value
else:
level = None
flow = None
except (IndexError, KeyError):
level = None
flow = None
try:
last_update = convert_to_datetime(
data["getStammdatenResult"][0]["Parameter"][0]["Datenspuren"][0][
"AktuellerMesswert_Zeitpunkt"
],
"%d.%m.%Y %H:%M",
)
except (IndexError, KeyError):
last_update = None
return DynamicData(level=level, stage=stage, flow=flow, last_update=last_update)
except Exception as err:
raise LHPError(err, "ni_api.py: update_NI()") from err
|
import React, { useState, useEffect } from 'react'
import './SMOYCard.css'
import { BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts';
export default function SMOYCard({ SMOYPrediction, SMOYPredictionData, SMOYStatsDiff, SMOYStats, chartData, name }) {
let stats = ['ppg', 'apg', 'rpg', 'TS_pctg', 'BPM'];
let statNames = ['PPG', 'APG', 'RPG', 'TS%', 'BPM'];
return (
<div className="SMOYCard">
<div className="SMOYItem">
<h3>6MOY Prediction</h3>
<div className="SMOYTitleContainer">
<img src={`https://cdn.nba.com/headshots/nba/latest/1040x760/${SMOYPrediction}.png`} alt="" className="SMOYTitleImg" />
<span className="SMOYTitleText">{SMOYPredictionData?.['player_info']?.['first_name']} {SMOYPredictionData?.['player_info']?.['last_name']}</span>
</div>
<div className="SMOYStatsContainer">
{stats.map((stat, index) => {
let statDiff = Math.round(SMOYStatsDiff[index] * 100) / 100;
return <div className="SMOYStat">{SMOYStats[index]} <span className="SMOYStatName">{statNames[index]}</span></div>
})}
</div>
</div >
<div className="SMOYChart">
<h3>{name} vs. 75th Percentile</h3>
<ResponsiveContainer width="100%" aspect={4 / 1}>
<BarChart data={chartData} margin={{ left: -25 }}>
<XAxis dataKey="name" />
<YAxis domain={[0, 20]} />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Bar dataKey="SMOY" fill="#8884d8" name={name} />
<Bar dataKey="average" fill="#82ca9d" name="75th Percentile" />
</BarChart>
</ResponsiveContainer>
</div>
</div >
)
}
|
Snapshot Utility
----------------
This utility takes a snapshot of a Protex Project and the Code Center application of the same name.
The snapshot project/application have a name constructed as follows:
<original name>_<date/timestamp>
The utility returns the following error codes:
0: success
1: Protex project not found (which may be normal and treated as success)
2: Other error
Execution
---------
To run the utility:
Linux: bin/Snapshot.sh -config <config filename> <project/application name>
Windows: bin\Snapshot.bat -config <config filename> <project/application name>
The configuration file must set the following properties:
protex.server.name=<protex URL>
protex.user.name=<protex username>
protex.password=<protex password>
cc.server.name=<codecenter URL>
cc.user.name=<codecenter username>
cc.password=<codecenter password>
cc.app.version=<application version to use for all applications>
cc.cloned.app.workflow=<workflow name for cloned applications>
# Set skip.non.kb.components to false to include custom and local components in snapshots
skip.non.kb.components=false
There are also several optional properties:
suffix.to.remove: If set, the snapshot utility checks to see if the project/app name
ends in the value of this property. If it does, that part of the name is removed
before the date suffix is appended to generate the snapshot name.
snapshot.app.only=true: If set to true, no Protex project snapshot will be
created (only the Code Center application snapshot).
snapshot.suffix.dateformat: If set, this controls the suffix (including leading character
that separates the date/timestamp from the name, and the date/time format)
used in the snapshot project/application name.
The suffix will be generated using the included pattern string, passed to java.tex.SimpleDateFormat
(http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html).
The default is: "_yyyyMMdd_HHmmss". To, for example, include milliseconds,
set this property to "_yyyyMMdd_HHmmss.SSS" (without the quotes).
To use a separating character of "-" and a different date format, you could
set it to "-MM-dd-yyyy-HH:mm:ss".
To tell the snapshot utility to set some application custom attributes
to given values, specify those name/value pairs here. The index
number at the end of the property name (.0, .1, etc.) must
be the same for a given name/value pair, and you must
use sequential index values (no gaps in the numbering;
use as many name/value pairs as you need):
cc.app.attr.name.0=<First Attribute Name, such as Project Status>
cc.app.attr.value.0=<First Attribute Value, such as CURRENT>
cc.app.attr.name.1=<Second Attribute Name>
cc.app.attr.value.1=<Second Attribute Value>
WARNING: The following feature has not been thoroughly tested, and
could have unforseen side-effects, including changes to Code Center application
snapshots after the snapshot is created. Do not use this in production unless/until you've
verified in a test environment that there are no undesirable side-effects:
To tell the snapshot utility to associate the corresponding Protex project clone
with the Code Center application clone, set the following attribute to true.
It will only make the association if the original (cloned) application was
associated with a Protex project.
associate.project.with.app=<true or false>
Password Encryption
Configuration files can contain passwords, configured via properties of the form:
<prefix>.password=<value>
Where <prefix> indicates what the password is for.
Passwords are entered in plain text, and then (usually) automatically encrypted in-place by the
utility the next time it reads the configuration file. When creating a configuration file,
set the value of each password to the๏ฟฝpassword๏ฟฝin plain text. The first time the utility reads
the file, if the property <prefix>.password.isencrypted is not present, it will encrypt the
password and insert the property <prefix>.password.isencrypted=true. To change the password,
remove the <prefix>.password.isencrypted property, and set <prefix>.password to the password
in plain text. To tell the utility to leave the password as plain text, insert
<prefix>.password.isencrypted=false.
|
**์ธํฐํ์ด์ค**
- ๊ณตํต์ ์ผ๋ก ํ์ํ ๊ธฐ๋ฅ์ ์ธ๋ถ์์ ์ถ๊ฐํ ๋ ์ฌ์ฉ
- ์ถ์ ๋ฉ์๋(๋ก์ง์ด ์กด์ฌํ์ง ์๋ ๋ฉ์๋)๋ง ์กด์ฌํ๋ ํด๋์ค
**์ธํฐํ์ด์ค ์ฌ์ฉ์ฌ๋ก**
- ๋ฌธ์
- ์์์ผ๋ก ๋ญ, ์ฐธ์, ๋น๋๊ธฐ์ ๋ถ๋ชจ ํด๋์ค์ธ Bird์ ๊ด๊ณ๋ฅผ ์์ฑ
- ์์๋ ๋ง์ ์ข
๋ฅ๊ฐ ์๊ณ , ๊ณ ์ ํ ํ๋๋ ๋ค๋ฆ
- ์ฝํ๋ฆฐ์ ๋ฐ๋์ ๋ถ๋ชจ ํด๋์ค๋ ํ๊ฐ๋ผ์ ๋ชจ๋ ์์์ผ๋ก ์ฒ๋ฆฌํ ์ ์์
- ํด๊ฒฐ
- ๊ทผ๋ณธ์ ์ธ ๊ณตํต์ ์ ์์ ๋ฐ๊ณ , ์ถ๊ฐ์ ์ธ ๊ธฐ๋ฅ๋ค์ ์ธํฐํ์ด์ค๋ก ์ถ๊ฐ
- ์ฝํ๋ฆฐ์ ์ธํฐํ์ด์ค๋ฅผ ๋ง๋ค๊ธฐ ์ํด interface ํค์๋๋ฅผ ์ฌ์ฉ
```Kotlin
//WaterBirdBehavior.kt
interface WaterBirdBehavior {
fun swim()
// fun swim() {
// println("์์ ํฉ๋๋ค")
// }
}
//Test.kt
fun main() {
var bird = Bird("์")
var chicken = Chicken("๋ญ")
var sparrow = Sparrow("์ฐธ์")
var pigeon = Pigeon("๋น๋๊ธฐ")
var duck = Duck("์ค๋ฆฌ")
bird.fly()
chicken.fly()
sparrow.fly()
pigeon.fly()
duck.swim()
}
open class Bird(name:String) {
var name: String = ""
init {
// this๋ ํ์ฌ ํด๋์ค์ ์ํ๋ณ์๋ฅผ ์๋ฏธํฉ๋๋ค
// var name: String = ""
this.name = name
}
fun fly() {
println("${name} ๋ ์์~")
}
}
class Chicken(name: String) : Bird(name) {
}
class Sparrow(name: String) : Bird(name) {
}
class Pigeon(name: String) : Bird(name) {
}
class Duck(name: String) : Bird(name), WaterBirdBehavior {
override fun swim() {
println("${name}๊ฐ ์์ํด์~")
}
}
```
|
<div *ngIf="currentQuestion" class="quiz-container">
<h2 class="question-text">{{ currentQuestion.questionText }}</h2>
<div class="timer">Time remaining: {{ timeRemaining }}s</div>
<div class="score">Score: {{ score }}</div>
<ul class="answers-list">
<li *ngFor="let answer of quizData.answers" [class.selected]="selectedAnswer === answer"
[class.correct]="isAnswered && selectedAnswer === answer && selectedAnswer.isCorrect"
[class.incorrect]="isAnswered && selectedAnswer === answer && !selectedAnswer.isCorrect"
(click)="selectAnswer(answer)">
{{ answer.answerText }}
<span *ngIf="isAnswered && selectedAnswer === answer && selectedAnswer.isCorrect"
class="feedback-icon correct-icon">โ</span>
<span *ngIf="isAnswered && selectedAnswer === answer && !selectedAnswer.isCorrect"
class="feedback-icon incorrect-icon">โ</span>
</li>
</ul>
<button *ngIf="selectedAnswer && !isAnswered" class="submit-button" (click)="checkAnswer()">Submit</button>
<div *ngIf="isAnswered && isCorrect" class="feedback correct-feedback">
Correct answer!
</div>
<div *ngIf="isAnswered && !isCorrect" class="feedback incorrect-feedback">
Incorrect answer. The correct answer is "{{ correctAnswer?.answerText }}".
</div>
<button *ngIf="isAnswered" class="next-question-button" (click)="submitQuestion()">Next Question</button>
</div>
|
import { Component } from '@angular/core';
import { Platform, AlertController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { Push, PushObject, PushOptions } from '@ionic-native/push';
import { HomePage } from '../pages/home/home';
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = HomePage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private push: Push, private alertCtrl: AlertController) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
const options: PushOptions = {
android: {},
ios: {
alert: 'true',
badge: true,
sound: 'true'
}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
});
pushObject.on('registration').subscribe((registration: any) => {
let alert = this.alertCtrl.create({
title: 'Registration',
subTitle: registration.registrationId,
buttons: ['Dismiss']
});
alert.present();
});
pushObject.on('error').subscribe(error => {
let alert = this.alertCtrl.create({
title: 'Error',
subTitle: error.message,
buttons: ['Dismiss']
});
alert.present();
});
});
}
}
|
import { type Key } from "react";
import { array_total } from "~/utils/array_total";
import { type KeyOfType } from "~/utils/type_helpers";
function rand(min: number, max: number) {
return min + Math.random() * (max - min);
}
function get_random_color() {
const h = rand(1, 360);
const s = rand(50, 100);
const l = rand(30, 80);
return `hsl(${h},${s}%,${l}%)`;
}
export function VisualizeEntries<T>(props: {
entries: T[];
valuekey: KeyOfType<T, number>;
id_key: KeyOfType<T, Key>;
label_key?: KeyOfType<T, string>;
}) {
const total = array_total(
props.entries.map((i) => Number(i[props.valuekey]))
);
return (
<div className="flex flex-col gap-2 text-white">
<div className="flex h-2 w-full gap-0.5">
{props.entries.map((entry) => {
return (
<div
key={String(entry[props.id_key])}
className="rounded-sm"
style={{
width: `${(Number(entry[props.valuekey]) / total) * 100}%`,
background: get_random_color(),
}}
/>
);
})}
</div>
</div>
);
}
|
<template lang="">
<div>
<img v-if="img" :src="img" alt="bg">
<div class="bg-dark"></div>
<div class="indecision-container">
<input
type="text"
placeholder="hazme una pregunta"
v-model="question">
<p>Recuerda terminar con un signo de interrogaciรณn</p>
<div v-if="isValidQuestion">
<h2>{{ question }}</h2>
<h1>{{ answer }}</h1>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Indecision',
components: {},
data() {
return {
question: 'Hola Mundo',
answer: null,
img: null,
isValidQuestion: false
}
},
methods:{
async getAnswer() {
try {
this.answer = ' pensando... '
const { answer, image } = await fetch( 'https://yesno.wtf/api').then( r => r.json() )
this.answer = answer === 'yes' ? 'SI!' : 'NO!!'
this.img = image
} catch (error) {
console.log(error)
}
}
},
computed:{},
watch:{
question( value, oldValue ){
this.isValidQuestion = false;
if( !value.includes('?')) return
this.isValidQuestion = true;
this.getAnswer();
//TODO: hacer peticiรณn http
}
}
}
</script>
<style scoped>
img, .bg-dark {
height: 100vh;
left: 0px;
max-height: 100%;
max-width: 100%;
position: fixed;
top: 0px;
width: 100vw;
}
.bg-dark {
background-color: rgba(0, 0, 0, 0.4);
}
.indecision-container {
position: relative;
z-index: 99;
}
input {
width: 250px;
padding: 10px 15px;
border-radius: 5px;
border: none;
}
input:focus {
outline: none;
}
p {
color: white;
font-size: 20px;
margin-top: 0px;
}
h1, h2 {
color: white;
}
h2 {
margin-top: 150px;
}
</style>
|
<template>
<div class="contact-form-config">
<Loader :loading="loading" full />
<div class="form-group form-section">
<div class="row">
<div class="col">
<h4>{{ $t('settings.contact-form.creation-title') }}</h4>
<p v-html="$t('settings.contact-form.creation-description')"></p>
</div>
<div class="col-md-3" v-if="!(contactForm && contactForm.id)">
<button
class="btn btn-link mt-md-3"
type="button"
@click="createForm"
>
<Icon name="plus" />
{{ $t('settings.contact-form.creation-button') }}
</button>
</div>
<div class="col-md-12" v-else>
<hr />
<h4>{{ $t('settings.contact-form.usage-title') }}</h4>
<p>{{ $t('settings.contact-form.usage-step-1') }}</p>
<div class="row">
<div class="col-md-9">
<div
class="code-wrapper"
id="script-container"
@click="copyScript"
>
<div class="copy-control">
{{
copied
? $t('settings.contact-form.code-copied')
: $t('settings.contact-form.code-copy')
}}
</div>
<code>
<div class="airsend-contact-src" data-airsend-form-hash="{{
contactForm.form_hash
}}" data-airsend-form-color="{{ themeColor }}"
data-airsend-form-id="{{ contactForm.id }}"></div>
<br />
<script src="{{ linkUrl }}" defer></script>
</code>
</div>
<p>{{ $t('settings.contact-form.usage-step-2') }}</p>
<br />
<p>{{ $t('settings.contact-form.usage-step-3') }}</p>
</div>
<div class="col-md-3">
<button
class="btn btn-link mx-sm-2 mt-md-3"
type="button"
@click="copyScript"
>
<Icon name="copy" />
{{ $t('settings.contact-form.button-copy') }}
</button>
<button
class="btn btn-link mx-sm-2"
type="button"
@click="deleteForm"
>
<Icon name="trash-alt" />
{{ $t('settings.contact-form.button-delete') }}
</button>
</div>
<hr />
<div class="col-md-12">
<h4>{{ $t('settings.contact-form.theme-color') }}</h4>
<v-input-colorpicker v-model="themeColor" />
</div>
<hr />
<div class="col-md-9">
<h4>{{ $t('settings.contact-form.submission-title') }}</h4>
<div
class="form-group text-center"
v-if="responseMessage !== null"
>
<textarea
class="form-control"
v-model="responseMessage"
></textarea>
</div>
</div>
<div class="col-md-3">
<button
class="btn btn-link mx-sm-2 mt-md-3"
type="button"
@click="saveForm"
>
<Icon name="copy" /> {{ $t('general.save') }}
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import Modal from 'airsend/components/Modal.vue';
import Icon from 'airsend/components/Icon.vue';
import Checkbox from 'airsend/components/Checkbox.vue';
import Loader from 'airsend/components/Loader.vue';
import InputColorPicker from 'vue-native-color-picker';
export default {
components: {
Modal,
Loader,
Icon,
Checkbox,
'v-input-colorpicker': InputColorPicker
},
data() {
return {
copied: false,
responseMessage: 'Thank you',
themeColor: '#0097C0',
linkUrl:
window.origin.includes('live.airsend.io') ||
window.origin.includes('file://')
? 'https://live.airsend.io/embed/contactform.js'
: `${window.origin}/embed/contactform.dev.js`
};
},
computed: {
contactForm() {
return this.$store.state.core.contactForm;
},
loading() {
return (
this.$store.state.loading['core/getContactForm'] ||
this.$store.state.loading['core/createContactForm'] ||
this.$store.state.loading['core/updateContactForm'] ||
this.$store.state.loading['core/deleteContactForm']
);
}
},
async mounted() {
let formDetails = await this.$store.dispatch('core/getContactForm');
this.updateForm();
},
methods: {
updateForm() {
this.responseMessage = this.contactForm.confirmation_message;
if (this.contactForm.color)
this.themeColor = '#' + this.contactForm.color;
},
copyScript() {
let temp = document.createElement('textarea');
document.body.appendChild(temp);
temp.value = document.querySelector('code').innerText;
temp.select();
document.execCommand('copy');
document.body.removeChild(temp);
this.copied = true;
setTimeout(() => (this.copied = false), 5000);
},
async createForm() {
await this.$store.dispatch('core/createContactForm');
this.updateForm();
},
async saveForm() {
let data = {
color: this.themeColor.substring(1),
confirmation_message: this.responseMessage,
form_id: this.contactForm.id
};
await this.$store.dispatch('core/updateContactForm', data);
},
deleteForm() {
let data = {
form_id: this.contactForm.id
};
this.$store.dispatch('core/deleteContactForm', data);
}
}
};
</script>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.