text
stringlengths
184
4.48M
import React, { ChangeEvent, useCallback } from "react"; import "./InputSearch.css"; import { actionSetLatAndLong, actionSetTextSearchInput, } from "../../Store/Action"; import { useDispatch, useSelector } from "react-redux"; import { selectorSearchVariants, selectorTextSearchInput, } from "../../Store/Selector"; import { effectGetHourlyWeather, effectGetWeather, effectGetWeatherCity, effectGetWeekWeather, } from "../../Store/Effects"; const debounce = require("lodash.debounce"); function InputSearch() { const dispatch = useDispatch(); const textSearchInput: string = useSelector(selectorTextSearchInput); const searchVariants: object[] = useSelector(selectorSearchVariants); const reqSearch = (valueText: string) => { dispatch(effectGetWeatherCity(valueText)); }; const debouncedSave = useCallback( debounce((newValue: string) => reqSearch(newValue), 1000), [debounce] ); const writeInput = (e: ChangeEvent<HTMLInputElement>) => { dispatch(actionSetTextSearchInput(e.target.value)); debouncedSave(e.target.value); }; const selectItem = (geometry: string[]) => { const [long, lat] = geometry; dispatch(actionSetLatAndLong(lat, long)); dispatch(effectGetWeather(lat, long)); dispatch(effectGetHourlyWeather(lat, long)); dispatch(effectGetWeekWeather(lat, long)); }; return ( <div className={"root-input-wrap"}> <input className={"input-search-wrap"} placeholder={"Find city..."} type={"text"} onChange={writeInput} value={textSearchInput || ""} /> <div className={ searchVariants?.length > 1 ? "visible-class" : "hidden-class" } > {searchVariants?.map((item: any, index) => ( <div key={index} data-testid={"block-tests"} className={"item-search"} onClick={() => selectItem(item.center)} > {item.place_name} </div> ))} </div> </div> ); } export default InputSearch;
<!--I have used parts of the course notes, course examples and the My Apps example provided as inspiration and guideline on how to structure this sheet--> <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="classproject.css"> <title>The Most Major Takeaways</title> </head> <body> <h1 class="title">Major Takeaways For Myself</h1> <div class="Lesson"> <h2>Lesson 1</h2> <div class="concept"> <div class="concept-title"> How The Web Works </div> <div class="description"> <p> <span class="italic">Computer</span> sends messages over HTML through the internet to <span class="bold">servers</span>. These servers then send info back to the <span class="italic">computers</span>. </p> <p> This <span class="bold"><a href="https://www.udacity.com/course/viewer#!/c-ud721/l-3508959201/e-48329854/m-48480496">video</a></span> provided by the Udacity course notes is a great example of what we are talking about. </p> </div> </div> <div class="concept"> <div class="concept-title"> Are Computers Intelligent? </div> <div class="description"> <p> Absolutely <span class="bold">NOT</span>! Computers are incredibly stupid. </p> <p> Why you might ask? Great question! That's because computers have no room for interpretation. They do <span class="italic">exactly</span> what they are told to do. </p> </div> </div> <div class="concept"> <div class="concept-title"> What Are All Those Lesser Than and Great Than Symbols Used For? </div> <div class="description"> <p> Those interesting lesser and greater symbols is what we use to code. They essentially hold 'tags'. Most of the time we need an opening tag and a closing tag. Although there are sometimes void tags such as the br tag. </p> <p> We put symbols such as b or em (both inline, check Lesson 2) or div or p (block, also check Lesson 2)inside of them and they then produce a different result. </p> </div> </div> </div> <div class="Lesson"> <h2>Lesson 2</h2> <div class="concept"> <div class="concept-title"> Tree of Knowledge </div> <div class="description"> <p> As mentioned in the course, it is important to note, that CSS and HTML are both "languages". HTML controls the structure while CSS controls the style. A DOM, is the tree structure of the page. </p> <p> When coding, it is best to think of relationships like that of a tree hierachy system. The browser takes an HTML tag and turns it into an element in the tree because of the DOM. </p> <p> What I mean by that is that on the same branch there are siblings, when we go up the branch there are the parents. This is the <span class=italic>parent child relationship</span>. </p> <p> You can also have an uncle branch that is at the parents line. For this to happen it has to have the same <span class="bold">ancestors</span> (or root). Each of these nodes represent either text or images or videos. </p> </div> </div> <div class="concept"> <div class="concept-title"> Inline and Block </div> <div class="description"> <p> Tags can be either <span class="italic">inline</span> or <span class="bold">block</span>, the latter meaning that the code creates an invisible box around it. Examples of <span class="italic">Inline tags</span> are em and b. Example of <span class="bold">Block tag</span> are div an p. </p> </div> </div> </div> <div class="Lesson"> <h2>Lesson 3</h2> <div class="concept"> <div class="concept-title"> Structure and Repeat After Me </div> <div class="description"> <p> If you have a good structure within your html code, you will save a ton of time not repeating yourself when styling in CSS (Cascading Style Sheets). CSS allows us to avoid repetition and not repeating yourself is critical to writing good code. </p> <p> A bit more detail...You can div class an item and then control the style in CSS. This allows you not to have to repeat yourself as much. Anything within that class will have a rule. If you Span Class, then you need to say what it does in CSS, but that whole class will be the same, thus saving time and less likelyhood of errors. </p> <p> A bit more about CSS. As the course specifies, it can be thought of as a search and replace tool. You identify a class or tag that you want to match and then tell it what you want it to do or what property values you want to change. </p> <p> Another important fact about CSS, as mentioned in the course, is that order matters. As you move down the list you can overwrite previous definitions. </p> <p> To understand what I mean by the fact that order matters, I have set the font for the body as Times, but with the h1 (which is found in the body) I have said that this rule does not apply and instead apply Helvetica. If I did not do that, then the body would not have been in Times or the h1 would not of been in Helvetica. </p> </div> </div> <div class="concept"> <div class="concept-title"> The Box Model </div> <div class="description"> <p> Box sizes are adjusted in css. There are four components to a box. Starting from inside to outside, content, padding, borders, and margins. </p> <p> Using a % will allow the screen size to be adjusted without affecting the layout of your boxes. Each box is an element. </p> </div> </div> <div class="concept"> <div class="concept-title"> Final Takeaway </div> <div class="description"> <p> <span class="bold">Code, Test, Refine. </span> </p> <p> That is all...oh! and enjoy! </p> </div> </div> </div> </body>
<% layout('/layouts/boilerplate') %> <div class="row"> <div class="col-6"> <div class="card mb-3"> <img src="<%= campground.image %>" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title"> <%= campground.title %> </h5> <p class="card-text"> <%= campground.description %> </p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item text-muted"> <%= campground.location %> </li> <li class="list-group-item"> Submitted by <%= campground.author.username %> </li> <li class="list-group-item">$<%=campground.price%>/night</li> </ul> <% if(currentUser && campground.author.equals(currentUser._id)) { %> <div class="card-body"> <a class="card-link btn btn-info" href="/campgrounds/<%= campground._id %>/edit">Edit</a> <form class="d-inline" action="/campgrounds/<%= campground._id %>?_method=DELETE" method="POST"> <button class="btn btn-danger">Delete</button> </form> </div> <% } %> <div class="card-footer text-muted"> <a href="/campgrounds">All Campgrounds</a> </div> </div> </div> <div class="col-6"> <% if(currentUser) { %> <h2>Leave a Review</h2> <form action="/campgrounds/<%=campground._id%>/reviews" method="POST" class="mb-3 validated-form" novalidate> <div class="mb-3"> <label class="form-label" for="rating">Rating</label> <input class="form-range" type="range" min="1" max="5" name="review[rating]" id="rating"> </div> <div class="mb-3"> <label class="form-label" for="body">Review</label> <textarea class="form-control" name="review[body]" id="body" cols="30" rows="3" required></textarea> <div class=valid-feedback> Looks good! </div> </div> <button class="btn btn-success">Submit</button> </form> <% } %> <% for(let review of campground.reviews) { %> <div class="card mb-3"> <div class="card-body"> <h5 class="card-title">Rating: <%= review.rating %> </h5> <h6 class="card-subtile mb-2 text-muted">By <%= review.author.username %> </h6> <p class="card-text">Rating: <%= review.body %> </p> <% if(currentUser && review.author.equals(currentUser._id)) { %> <form action="/campgrounds/<%=campground._id%>/reviews/<%=review._id%>?_method=DELETE" method="POST"> <button class="btn btn-sm btn-danger">Delete</button> </form> <% } %> </div> </div> <% } %> </div> </div>
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; import "./BananaswapV1ERC20.sol"; import "./libraries/Math.sol"; import "./libraries/BananaswapV1Library.sol"; import "@openzeppelin/contracts/interfaces/IERC20.sol"; contract BananaswapV1Pair is BananaswapV1ERC20 { uint256 public constant MIN_LIQUIDITY = 10**3; address token; uint256 tokenReserve; uint256 ethReserve; bool locked; modifier lock() { locked = true; _; locked = false; } function initialize(address token_) external { require(token == address(0), "BananaswapV1Pair::initialize: CALL_ONCE"); token = token_; } function getReserves() public view returns (uint256, uint256) { return (tokenReserve, ethReserve); } function mint(address to_) external lock returns (uint256 liquidity) { // get qty of deposits uint256 tokenBal = IERC20(token).balanceOf(address(this)); uint256 _ethBal = address(this).balance; uint256 _tokenReserve = tokenReserve; uint256 _ethReserve = ethReserve; uint256 _totalSupply = totalSupply; uint256 tokenAmt = tokenBal - _tokenReserve; uint256 ethAmt = _ethBal - _ethReserve; // calculate liquidity to grant to LP // handle initial liquidity deposit if (_totalSupply == 0) { liquidity = Math.sqrt(tokenAmt * ethAmt) - MIN_LIQUIDITY; _mint(address(0), MIN_LIQUIDITY); } else { liquidity = Math.min((tokenAmt * _totalSupply) / _tokenReserve, (ethAmt * _totalSupply) / _ethReserve); } _mint(to_, liquidity); _update(tokenBal, _ethBal); // TODO emit Mint event } function burn(address to_) external lock returns (uint256 tokenAmt, uint256 ethAmt) { // get liquidity burned uint256 liquidityToBurn = balanceOf[address(this)]; uint256 tokenBal = IERC20(token).balanceOf(address(this)); uint256 ethBal = address(this).balance; uint256 _totalSupply = totalSupply; // get token and eth amounts to distribute to LP tokenAmt = (tokenBal * liquidityToBurn) / _totalSupply; ethAmt = (ethBal * liquidityToBurn) / _totalSupply; BananaswapV1Library.transfer(token, to_, tokenAmt); BananaswapV1Library.transferEth(to_, ethAmt); tokenBal = IERC20(token).balanceOf(address(this)); ethBal = address(this).balance; _update(tokenBal, ethBal); _burn(address(this), liquidityToBurn); } function swap( uint256 tokensOut_, uint256 ethOut_, address to_ ) external lock { require(tokensOut_ > 0 || ethOut_ > 0, "BananaswapV1Pair::swap: INSUFFICIENT_AMOUNT_OUT"); require(tokenReserve >= tokensOut_ && ethReserve >= ethOut_, "BananaswapV1Pair::swap: INSUFFICIENT_LIQUIDITY"); if (tokensOut_ > 0) { BananaswapV1Library.transfer(token, to_, tokensOut_); } if (ethOut_ > 0) { BananaswapV1Library.transferEth(to_, ethOut_); } uint256 tokenBal = IERC20(token).balanceOf(address(this)); uint256 ethBal = address(this).balance; uint256 tokensIn = tokenBal > tokenReserve - tokensOut_ ? tokenBal - tokenReserve - tokensOut_ : 0; uint256 ethIn = ethBal > ethReserve - ethOut_ ? ethBal - ethReserve - ethOut_ : 0; require(tokensIn > 0 || ethIn > 0, "BananaswapV1Pair::swap: INSUFFICIENT_AMOUNT_IN"); // compare balances less fees to K uint256 tokenBalLessFee = (tokenBal * 100) - tokensIn; uint256 ethBalLessFee = (ethBal * 100) - ethIn; require( tokenBalLessFee * ethBalLessFee >= tokenReserve * ethReserve * 100**2, "BananaswapV1Pair::swap: INVALID_K" ); _update(tokenBal, ethBal); // TODO emit Swap event } function _update(uint256 tokenBalance_, uint256 ethBalance_) private { tokenReserve = tokenBalance_; ethReserve = ethBalance_; // TODO emit Sync event } receive() external payable {} }
internal class Program { private static void Main(string[] args) { var x = new Client(); x.main(); } } class Client { public void main() { Console.WriteLine("ConcreteCreater1 is running"); ClientCode(new ConcreateCreator1()); Console.WriteLine("\n \n"); Console.WriteLine("ConcreteCreater2 is running"); ClientCode(new ConcreateCreator2()); } void ClientCode(Creator creator) { Console.WriteLine("Client: I'm not aware of the creator's class," + "but it still works.\n" + creator.SomeOperation()); } public interface IProduct { string operation(); } public class ConcreateProduct1 : IProduct { public string operation() { return "Result of ConcreateProduct1."; } } public class ConcreateProduct2 : IProduct { public string operation() { return "Result of ConcreateProduct2."; } } abstract class Creator { public abstract IProduct FactoryMethod(); public string SomeOperation() { var product = FactoryMethod(); return product.operation(); } } class ConcreateCreator1 : Creator { public override IProduct FactoryMethod() { return new ConcreateProduct1(); } } class ConcreateCreator2 : Creator { public override IProduct FactoryMethod() { return new ConcreateProduct2(); } } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>My Profile</title> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- font awesome --> <link rel="stylesheet" type="text/css" href="css/font-awesome.css" /> <!-- main css --> <link rel="stylesheet" type="text/css" href="css/style.css" /> <link rel="stylesheet" type="text/css" href="css/responsive.css" /> <!-- css warna desain default --> <link rel="stylesheet" type="text/css" href="css/background/warna1.css" /> <!-- css ganti warna bacground --> <link rel="stylesheet" type="text/css" class="alternate-style" title="warna1" href="css/background/warna1.css" /> <link rel="stylesheet" type="text/css" class="alternate-style" title="warna2" href="css/background/warna2.css" disabled /> <link rel="stylesheet" type="text/css" class="alternate-style" title="warna3" href="css/background/warna3.css" disabled /> <link rel="stylesheet" type="text/css" class="alternate-style" title="warna4" href="css/background/warna4.css" disabled /> <link rel="stylesheet" type="text/css" class="alternate-style" title="warna5" href="css/background/warna5.css" disabled /> <link rel="stylesheet" type="text/css" href="css/style-switcher.css" /> </head> <body class="dark"> <!-- loader --> <div class="preloader"> <div class="box"> <div></div> <div></div> <div></div> </div> </div> <!-- end loader --> <!-- header --> <header class="header"> <div class="container"> <div class="row justify-content-between"> <div class="logo"> <a href="index.html">H</a> </div> <div class="bar-btn outer-shadow hover-in-shadow"> <span></span> </div> </div> </div> </header> <!-- end header --> <!-- nav menu --> <nav class="nav-menu"> <div class="close-nav-menu outer-shadow hover-in-shadow">&times;</div> <div class="nav-menu-inner"> <ul> <li> <a href="#home" class="link-item inner-shadow active">Home</a> </li> <li> <a href="#about" class="link-item outer-shadow hover-in-shadow" >About</a > </li> <li> <a href="#services" class="link-item outer-shadow hover-in-shadow" >Services</a > </li> <li> <a href="#portfolio" class="link-item outer-shadow hover-in-shadow" >Portfolio</a > </li> <li> <a href="#sertifikat" class="link-item outer-shadow hover-in-shadow" >Sertifikat</a > </li> <li> <a href="#contact" class="link-item outer-shadow hover-in-shadow" >Contact</a > </li> </ul> </div> <!-- copyright text --> <p class="copyright-text">&copy; Hengky Darmawan 2021</p> </nav> <div class="fade-out-effect"></div> <!-- end nav menu --> <!-- home section--> <section class="home-section section active" id="home"> <!-- effect wrap --> <div class="effect-wrap"> <div class="effect effect-1"></div> <div class="effect effect-2"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> <div class="effect effect-3"></div> <div class="effect effect-4"></div> <div class="effect effect-5"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> </div> <!-- end effect wrap --> <div class="container"> <div class="row full-screen align-items-center"> <div class="home-text"> <p>Hello</p> <h2>I'm Hengky Darmawan</h2> <h1>Web Designer & Developer</h1> <a href="#about" class="link-item btn-1 outer-shadow hover-in-shadow" >More About Me</a > </div> <div class="home-img"> <div class="img-box inner-shadow"> <img src="img/hengky.png" class="outer-shadow" alt="profile-pic" /> </div> </div> </div> </div> </section> <!-- end home section --> <!-- about section --> <section class="about-section section" id="about"> <div class="container"> <div class="row"> <div class="section-title"> <h2 data-heading="main info">About Me</h2> </div> </div> <div class="row"> <div class="about-img"> <div class="img-box inner-shadow"> <img src="img/hengky.png" class="outer-shadow" alt="profile-pic" /> </div> <!-- sosial media --> <div class="social-links"> <a href="#" class="outer-shadow hover-in-shadow" ><i class="fab fa-facebook-f"></i ></a> <a href="#" class="outer-shadow hover-in-shadow" ><i class="fab fa-twitter"></i ></a> <a href="#" class="outer-shadow hover-in-shadow" ><i class="fab fa-instagram"></i ></a> <a href="www.linkedin.com/in/hengky-d-15b4801b3" class="outer-shadow hover-in-shadow" ><i class="fab fa-linkedin-in"></i ></a> </div> <!-- end my sosial media --> </div> <div class="about-info"> <p> <span >Hello! Nama Saya Hengky Darmawan. Saya adalah seorang Web Design And Web Developer.</span > Saya seorang mahasiswa semester 6 dengan IPK 3.81, yang memiliki kemampuan yang baik dalam mendesign dan developer serta saya menguasai komputer dengan baik. saya pribadi yang mandiri, tekun, dan komunikatif. </p> <p> Saya suka hal - hal yang bersifat penemuan, investasi dan teknologi terbaru. saya belajar pemograman berawal dari dumet school dan lulus pada 2019. Saya yakin dapat bekerja dengan baik untuk perusahaan dan saya selalu belajar untuk memperbaharui kemampuan saya dalam bidang pekerjaan yang akan saya tekuni. </p> <a href="#portfolio" class="link-item btn-1 outer-shadow hover-in-shadow" >See Portfolio</a > <a href="#contact" class="link-item btn-1 outer-shadow hover-in-shadow" >Hire Me</a > </div> </div> <!-- about tabs --> <div class="row"> <div class="about-tabs"> <span class="tab-item outer-shadow active" data-target=".skills" >skills</span > <span class="tab-item" data-target=".experience" >Informal Education</span > <span class="tab-item" data-target=".education" >Formal Education</span > </div> </div> <!-- end about tabs --> <!-- skills --> <div class="row"> <div class="skills tab-content active"> <div class="row"> <!-- skill item --> <div class="skill-item"> <p>HTML</p> </div> <!-- end skill item --> <!-- skill item --> <div class="skill-item"> <p>CSS</p> </div> <!-- end skill item --> <!-- skill item --> <div class="skill-item"> <p>Bootstrap</p> </div> <!-- end skill item --> <!-- skill item --> <div class="skill-item"> <p>JavaScript</p> </div> <!-- end skill item --> <!-- skill item --> <div class="skill-item"> <p>JQuery</p> </div> <!-- end skill item --> <!-- skill item --> <div class="skill-item"> <p>Figma</p> </div> <!-- end skill item --> <div class="skill-item"> <p>PHP</p> </div> <!-- end skill item --> <!-- end skill item --> <div class="skill-item"> <p>Mysql</p> </div> <!-- end skill item --> </div> </div> </div> <!-- end skills --> <!-- experience --> <div class="row"> <div class="experience tab-content"> <div class="row"> <div class="timeline"> <div class="row"> <!-- timeline item --> <div class="timeline-item"> <div class="timeline-item-inner outer-shadow"> <i class="fas fa-laptop-code icon"></i> <span>Juni, 2017 - 2019</span> <h3>Full Stack Developer</h3> <h4>Dumet School, Jakarta Barat</h4> </div> </div> <!-- end timeline item --> <!-- timeline item --> <div class="timeline-item"> <div class="timeline-item-inner outer-shadow"> <i class="fas fa-laptop-code icon"></i> <span>Oktober, 2019 - present</span> <h3>Frontend Web Development</h3> <h4>Progate, Online</h4> </div> </div> <!-- end timeline item --> <!-- timeline item --> <div class="timeline-item"> <div class="timeline-item-inner outer-shadow"> <i class="fas fa-laptop-code icon"></i> <span>September, 2020 - present</span> <h3>Frontend Web Development</h3> <h4>Skilvul, Online</h4> </div> </div> <!-- end timeline item --> <!-- timeline item --> <div class="timeline-item"> <div class="timeline-item-inner outer-shadow"> <i class="fas fa-laptop-code icon"></i> <span>8 November 2021 - 4 Desember 2021</span> <h3>Basic Intensive English Program</h3> <h4>LC, Bogor</h4> </div> </div> <!-- end timeline item --> </div> </div> </div> </div> </div> <!-- end experience --> <!-- education --> <div class="row"> <div class="education tab-content"> <div class="row"> <div class="timeline"> <div class="row"> <!-- timeline item --> <div class="timeline-item"> <div class="timeline-item-inner outer-shadow"> <i class="fas fa-graduation-cap icon"></i> <span>Juni, 2019 - present</span> <h3>S1</h3> <h4>Universitas Dian Nusantara, Jakarta Barat</h4> </div> </div> <!-- end timeline item --> <!-- timeline item --> <div class="timeline-item"> <div class="timeline-item-inner outer-shadow"> <i class="fas fa-graduation-cap icon"></i> <span>2019</span> <h3>Paket C</h3> <h4>Jakarta Barat</h4> </div> </div> <!-- end timeline item --> <!-- timeline item --> <div class="timeline-item"> <div class="timeline-item-inner outer-shadow"> <i class="fas fa-graduation-cap icon"></i> <span>2014 - 2017</span> <h3>SMP</h3> <h4>SMP Kartika, Kalimantan Barat</h4> </div> </div> <!-- end timeline item --> </div> </div> </div> </div> </div> <!-- end education --> </div> </section> <!-- end about section --> <!-- services section --> <section class="service-section section" id="services"> <div class="container"> <div class="row"> <div class="section-title"> <h2 data-heading="Services">What I Can Do?</h2> </div> </div> <div class="row"> <!-- service item --> <div class="service-item"> <div class="service-item-inner outer-shadow"> <div class="icon inner-shadow"> <i class="fas fa-mobile-alt"></i> </div> <h3>Responsive Design</h3> </div> </div> <!-- end serivice item --> <!-- service item --> <div class="service-item"> <div class="service-item-inner outer-shadow"> <div class="icon inner-shadow"> <i class="fas fa-laptop-code"></i> </div> <h3>Web design</h3> </div> </div> <!-- end serivice item --> <!-- service item --> <div class="service-item"> <div class="service-item-inner outer-shadow"> <div class="icon inner-shadow"> <i class="fab fa-figma"></i> </div> <h3>UI/UX</h3> </div> </div> <!-- end serivice item --> <!-- service item --> <div class="service-item"> <div class="service-item-inner outer-shadow"> <div class="icon inner-shadow"> <i class="fas fa-code"></i> </div> <h3>clean code</h3> </div> </div> <!-- end serivice item --> <!-- service item --> <div class="service-item"> <div class="service-item-inner outer-shadow"> <div class="icon inner-shadow"> <i class="fas fa-laptop-code"></i> </div> <h3>Frontend Web Development</h3> </div> </div> <!-- end serivice item --> <!-- service item --> <div class="service-item"> <div class="service-item-inner outer-shadow"> <div class="icon inner-shadow"> <i class="fas fa-file-code"></i> </div> <h3>Backend Web Development</h3> </div> </div> <!-- end serivice item --> </div> </div> </section> <!-- end services section --> <!-- portfolio section--> <section class="portfolio-section section" id="portfolio"> <div class="container"> <div class="row"> <div class="section-title"> <h2 data-heading="portfolio">Latest Works</h2> </div> </div> <!-- portfolio filter --> <div class="row"> <div class="portfolio-filter"> <span class="filter-item outer-shadow active" data-target="all" >all</span > <span class="filter-item" data-target="web-application" >web application</span > <!-- <span class="filter-item" data-target="photoshop">photoshop</span> --> <!-- <span class="filter-item" data-target="mobile-app">mobile app</span> --> <!-- <span class="filter-item" data-target="e-commerce">e commerce</span> --> <span class="filter-item" data-target="figma">figma</span> </div> </div> <!-- end portfolio filter --> <!-- portofoilio items --> <div class="row portfolio-items"> <!-- portfolio item --> <div class="portfolio-item" data-category="figma"> <div class="portfolio-item-inner outer-shadow"> <div class="portfolio-item-img"> <img src="img/portfolio/thumb/project-1.png" alt="portfolio" data-screenshots="img/portfolio/large/project-1/1.png, img/portfolio/large/project-1/2.png, img/portfolio/large/project-1/3.png, img/portfolio/large/project-1/4.png, img/portfolio/large/project-1/5.png" /> <!-- view project --> <span class="view-project">view project</span> </div> <p class="portfolio-item-title">Apk MyMart</p> <!-- portfolio item details --> <div class="portfolio-item-details"> <div class="row"> <div class="description"> <h3>Project Brief:</h3> <p>Design Aplikasi MyMart</p> </div> <div class="info"> <h3>Project info</h3> <ul> <li>Date - <span>17 Desember 2022</span></li> <li>Tools - <span>Figma, Photoshop</span></li> </ul> </div> </div> </div> <!-- end portfolio itemsdetai --> </div> </div> <!-- end portfolio item --> <!-- portfolio item --> <div class="portfolio-item" data-category="figma"> <div class="portfolio-item-inner outer-shadow"> <div class="portfolio-item-img"> <img src="img/portfolio/thumb/project-9.png" alt="portfolio" data-screenshots="img/portfolio/large/project-9/1.png, img/portfolio/large/project-9/2.png, img/portfolio/large/project-9/3.png, img/portfolio/large/project-9/4.png" /> <!-- view project --> <span class="view-project">view project</span> </div> <p class="portfolio-item-title">Menu Design</p> <!-- portfolio item details --> <div class="portfolio-item-details"> <div class="row"> <div class="description"> <h3>Project Brief:</h3> <p>Design menu untuk pembukaan cabang baru SSAMPAK.</p> </div> <div class="info"> <h3>Project info</h3> <ul> <li>Date - <span>12 Desember 2021</span></li> <li>Client - <span>SSAMPAK</span></li> <li>Tools - <span>Figma</span></li> <!-- <li>Play Store - <span><a href="#">myapp</a></span></li> --> </ul> </div> </div> </div> <!-- end portfolio itemsdetai --> </div> </div> <!-- end portfolio item --> <!-- portfolio item --> <div class="portfolio-item" data-category="figma"> <div class="portfolio-item-inner outer-shadow"> <div class="portfolio-item-img"> <img src="img/portfolio/thumb/project-10.png" alt="portfolio" data-screenshots="img/portfolio/large/project-10/1.png" /> <!-- view project --> <span class="view-project">view project</span> </div> <p class="portfolio-item-title">Apk Pesan Makanan Design</p> <!-- portfolio item details --> <div class="portfolio-item-details"> <div class="row"> <div class="description"> <h3>Project Brief:</h3> <p>Design Aplikasi Pemesanan Makanan</p> </div> <div class="info"> <h3>Project info</h3> <ul> <li>Date - <span>2021</span></li> <li>Tools - <span>Figma</span></li> </ul> </div> </div> </div> <!-- end portfolio itemsdetai --> </div> </div> <!-- end portfolio item --> <!-- portfolio item --> <div class="portfolio-item" data-category="figma"> <div class="portfolio-item-inner outer-shadow"> <div class="portfolio-item-img"> <img src="img/portfolio/thumb/project-11.png" alt="portfolio" data-screenshots="img/portfolio/large/project-11/1.png, img/portfolio/large/project-11/2.png, img/portfolio/large/project-11/3.png, img/portfolio/large/project-11/4.png, img/portfolio/large/project-11/5.png" /> <!-- view project --> <span class="view-project">view project</span> </div> <p class="portfolio-item-title">Apk Belajar Design</p> <!-- portfolio item details --> <div class="portfolio-item-details"> <div class="row"> <div class="description"> <h3>Project Brief:</h3> <p>Design Aplikasi Pembelajaran Online</p> </div> <div class="info"> <h3>Project info</h3> <ul> <li>Date - <span>2021</span></li> <li>Tools - <span>Figma</span></li> </ul> </div> </div> </div> <!-- end portfolio itemsdetai --> </div> </div> <!-- end portfolio item --> <!-- portfolio item --> <div class="portfolio-item" data-category="figma"> <div class="portfolio-item-inner outer-shadow"> <div class="portfolio-item-img"> <img src="img/portfolio/thumb/project-13.png" alt="portfolio" data-screenshots="img/portfolio/large/project-13/1.png, img/portfolio/large/project-13/2.png, img/portfolio/large/project-13/3.png, img/portfolio/large/project-13/4.png, img/portfolio/large/project-13/5.png, img/portfolio/large/project-13/6.png, img/portfolio/large/project-13/7.png" /> <!-- view project --> <span class="view-project">view project</span> </div> <p class="portfolio-item-title">Apk Undira Design</p> <!-- portfolio item details --> <div class="portfolio-item-details"> <div class="row"> <div class="description"> <h3>Project Brief:</h3> <p>Mendesign Website Undira</p> </div> <div class="info"> <h3>Project info</h3> <ul> <li>Date - <span>2021</span></li> <li>Tools - <span>Figma, Photoshop</span></li> </ul> </div> </div> </div> <!-- end portfolio itemsdetai --> </div> </div> <!-- end portfolio item --> </div> <!-- end portfolio items --> </div> </section> <!-- end portfolio section--> <!-- testimonial section --> <section class="testimonial-section section" id="sertifikat"> <div class="container"> <div class="row"> <div class="section-title"> <h2 data-heading="Sertifikat">My Sertifikat</h2> </div> </div> <div class="row"> <div class="testi-box"> <div class="testi-slider outer-shadow"> <div class="testi-slider-container"> <!-- testi item --> <div class="testi-item"> <i class="fas fa-quote-left left"></i> <i class="fas fa-quote-right right"></i> <img src="img/sertifikat/1.png" alt="sertifikat" /> <span>Dumet School</span> </div> <!-- end testi item --> <!-- testi item --> <div class="testi-item active"> <i class="fas fa-quote-left left"></i> <i class="fas fa-quote-right right"></i> <img src="img/sertifikat/2.png" alt="sertifikat" /> <span>Dumet School</span> </div> <!-- end testi item --> <!-- testi item --> <div class="testi-item active"> <i class="fas fa-quote-left left"></i> <i class="fas fa-quote-right right"></i> <img src="img/sertifikat/3.png" alt="sertifikat" /> <span>Progate</span> </div> <!-- end testi item --> <!-- testi item --> <div class="testi-item active"> <i class="fas fa-quote-left left"></i> <i class="fas fa-quote-right right"></i> <img src="img/sertifikat/4.png" alt="sertifikat" /> <span>Progate</span> </div> <!-- end testi item --> </div> </div> <div class="testi-slider-nav"> <span class="prev outer-shadow hover-in-shadow" ><i class="fas fa-angle-left"></i ></span> <span class="next outer-shadow hover-in-shadow" ><i class="fas fa-angle-right"></i ></span> </div> </div> </div> </div> </section> <!-- end testimonial secti0n --> <!-- contact section --> <section class="contact-section section" id="contact"> <div class="container"> <div class="row"> <div class="section-title"> <h2 data-heading="contact">Get In Touch</h2> </div> </div> <div class="row"> <!-- contact item --> <div class="contact-item"> <div class="contact-item-inner outer-shadow"> <i class="fab fa-whatsapp"></i> <span>Whatsapp</span> <p>082186629996</p> </div> </div> <!-- end contact item --> <!-- contact item --> <div class="contact-item"> <div class="contact-item-inner outer-shadow"> <i class="fas fa-envelope"></i> <span>Email</span> <p>[email protected]</p> </div> </div> <!-- end contact item --> <!-- contact item --> <div class="contact-item"> <div class="contact-item-inner outer-shadow"> <i class="fas fa-map-marker-alt"></i> <span>Address</span> <p>Jakarta Barat, Jembatan Besi V</p> </div> </div> <!-- end contact item --> </div> <div class="row"> <div class="contact-form"> <form> <div class="row"> <div class="w-50"> <div class="input-group outer-shadow hover-in-shadow"> <input type="text" placeholder="Name" class="input-control" /> </div> <div class="input-group outer-shadow hover-in-shadow"> <input type="text" placeholder="Email" class="input-control" /> </div> <div class="input-group outer-shadow hover-in-shadow"> <input type="text" placeholder="Subject" class="input-control" /> </div> </div> <div class="w-50"> <div class="input-group outer-shadow hover-in-shadow"> <textarea class="input-control" placeholder="Message" ></textarea> </div> </div> </div> <div class="row"> <div class="submit-btn"> <button type="submit" class="link-item btn-1 outer-shadow hover-in-shadow" > Send Message </button> </div> </div> </form> </div> </div> </div> </section> <!-- end contact section --> <!-- portfolio popup --> <div class="pp portfolio-popup"> <div class="pp-details"> <div class="pp-details-inner"> <div class="pp-title"> <h2>personal portfolio</h2> <p> Category - <span class="pp-project-category">Web Application</span> </p> </div> <div class="pp-project-details"> <div class="row"> <div class="description"> <h3>Project Brief:</h3> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> </div> <div class="info"> <h3>Project info</h3> <ul> <li>Date - <span>2020</span></li> <li>Client - <span>xyz</span></li> <li>Tools - <span>html, css, javascript</span></li> <li> Web - <span><a href="#">www.domain.com</a></span> </li> </ul> </div> </div> </div> </div> </div> <div class="separator"></div> <div class="pp-main"> <div class="pp-main-inner"> <div class="pp-project-details-btn outer-shadow hover-in-shadow"> Project Details <i class="fas fa-plus"></i> </div> <div class="pp-close outer-shadow hover-in-shadow">&times;</div> <img src="img/portfolio/large/project-1/1.png" alt="img" class="pp-img outer-shadow" /> <div class="pp-counter">1 of 6</div> </div> <div class="pp-loader"> <div></div> </div> <!-- pp navigation --> <div class="pp-prev"><i class="fas fa-play"></i></div> <div class="pp-next"><i class="fas fa-play"></i></div> </div> </div> <!-- end portfolio popup --> <!-- pengaturan menu warna --> <div class="style-switcher outer-shadow"> <div class="style-switcher-toggler s-icon outer-shadow hover-in-shadow"> <i class="fas fa-cog fa-spin"></i> </div> <div class="day-night s-icon outer-shadow hover-in-shadow"> <i class="fas"></i> </div> <h4>Theme Colors</h4> <div class="colors"> <span class="warna1" onclick="setActiveStyle('warna1')"></span> <span class="warna2" onclick="setActiveStyle('warna2')"></span> <span class="warna3" onclick="setActiveStyle('warna3')"></span> <span class="warna4" onclick="setActiveStyle('warna4')"></span> <span class="warna5" onclick="setActiveStyle('warna5')"></span> </div> </div> <!-- end pengaturan menu warna --> <!-- main js --> <script type="text/javascript" src="js/script.js"></script> <script type="text/javascript" src="js/style-switcher.js"></script> </body> </html>
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* echo.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tday <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/02/06 19:13:56 by tday #+# #+# */ /* Updated: 2024/04/14 17:47:14 by tday ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../inc/minishell.h" /* Summary static function to check if a string is a valid new line flag (-n) for the echo command. to ba valid the string must start with a '-' followed by one or more occurences of 'n'. Inputs [char *} str: a pointer to a string that represents either a new line flag or a word top be printed. Outputs true if the given string is a valid new line flag for the echo command. false if it's not. */ static bool is_nl_flag(char *str) { int i; if (!str || !str[0]) return (false); if (str[0] != '-') return (false); i = 1; while (str[i] != '\0') { if (str[i] != 'n') return (false); i++; } return (true); } /* Summary a helper function that checks for new line flags and updates the current token pointer in the linked list to be the first non new line flag token. Inputs [t_list **] curr_token: a pointer to the current token in the linked list. [bool *] print_newline: a pointer to a boolean variable that indicates whether a new line should be printed. Outputs none. */ static void check_for_nl_flags(t_list **curr_arg, bool *print_newline) { while (*curr_arg && (*curr_arg)->data && \ is_nl_flag((char *)(*curr_arg)->data)) { *print_newline = false; *curr_arg = (*curr_arg)->next; } } /* Summary prints the tokens stored in a linked list to the standard output. it also adds a space between tokens except for the last one. Inputs [t_list *] curr_token: a pointer to the current token in the linked list. Outputs none. the function prints the tokens stored in the linked list to the standard output. Each token is printed as a string, with a space between tokens except for the last one. */ static void print_tokens(t_msh *msh, t_cmd *cmd_struct) { t_list *curr_arg; curr_arg = cmd_struct->arguments; while (curr_arg && (char *)curr_arg->data) { if (ft_strcmp(curr_arg->data, "$?") == 0) { free(curr_arg->data); curr_arg->data = ft_itoa(msh->last_exit_status); } ft_printf_fd(cmd_struct->out_fd, "%s", (char *)curr_arg->data); curr_arg = curr_arg->next; if (curr_arg && (char *)curr_arg->data) ft_printf_fd(cmd_struct->out_fd, " "); } } /* Summary replicates the echo command by printing given argument strings to the standard output. also checks for a new line flag (-n) and handles it as echo would. Inputs [t_msh *] msh: pointer to the main minishell structure. [t_cmd *] cmd: pointer to the command structure containing arguments and output file descriptor. Outputs [int] 0 if successful, 1 if an error occurs. */ int ft_echo(t_msh *msh, t_cmd *cmd) { bool print_newline; if (!cmd) { msh_error_exit(msh, "ft_echo !cmd"); msh->last_exit_status = 1; return (1); } print_newline = true; if (!cmd->arguments) { ft_printf_fd(cmd->out_fd, "\n"); msh->last_exit_status = 0; return (0); } check_for_nl_flags(&(cmd->arguments), &print_newline); print_tokens(msh, cmd); if (print_newline) ft_printf_fd(cmd->out_fd, "\n"); msh->last_exit_status = 0; return (0); }
\subsection{Lumped capacitance} \begin{minipage}{0.39 \linewidth} Idea: The temperature in a body is almost uniform, so we can assume it to be uniform. Temperature within body will now be $T(t)$ instead of $T(t, x, y, z)$. That means, the temperature difference inside the body $\Delta T_i = T_{s, 1} - T_{s, 2}$ must be much smaller than the temperature difference outside the body $\Delta T_o = T_{s, 2} - T_{\infty}$. \end{minipage} \begin{minipage}{0.59 \linewidth} \includegraphics[width = \linewidth]{src/images/lumped_cap.png} \end{minipage} \begin{empheq}{align*} \dot{q} = \frac{\lambda A}{L} (T_{s, 1} - T_{s, 2}) = \alpha A (T_{s, 2} - T_{\infty})\\ \Rightarrow \frac{(T_{s, 1} - T_{s, 2})}{(T_{s, 2} - T_{\infty})} = \frac{\alpha L}{\lambda} = Bi\\ L_{\text{cylinder}} = \frac{r}{2} \quad \quad L_{\text{sphere}} = \frac{r}{3} \end{empheq}
import { useState, useEffect } from "react"; import Cell from "./Components/Cell"; const App = () => { const [cells, setCells] = useState(["", "", "", "", "", "", "", "", ""]); const [go, setGo] = useState("circle"); const [winningMessage, setWinningMessage] = useState(null); const message = go=="circle"?"Coca-cola":"Dolly" console.log(cells); const checkScore = () => { const winningCombinations = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; let circleWins = false; let crossWins = false; for (const array of winningCombinations) { circleWins = array.every((cell) => cells[cell] === "circle"); crossWins = array.every((cell) => cells[cell] === "cross"); if (circleWins || crossWins) { break; } } if (circleWins) { setWinningMessage("Coca Cola Venceu!"); } else if (crossWins) { setWinningMessage("Dollinho venceu!"); } }; useEffect(() => { checkScore(); }, [cells]); return ( <div className="app"> <h1>{winningMessage || message}</h1> <div className="gameboard"> {cells.map((cell, index) => ( <Cell key={index} id={index} go={go} setGo={setGo} cells={cells} cell={cell} setCells={setCells} winningMessege={winningMessage} /> ))} </div> </div> ); }; export default App;
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Carbon\Carbon; class BeritaWisataController extends Controller { public function index() { // Retrieve paginated data $data = DB::table('berita_wisata') ->where('isDeleted', 0) ->paginate(3); // Transform the paginated data to include formatted dates $data->getCollection()->transform(function ($item) { $item->formatted_date = Carbon::parse($item->tanggalBerita)->translatedFormat('l, d F Y'); return $item; }); return view('user.berita-wisata.index', ['data' => $data]); } public function detail($id) { $data = DB::table('berita_wisata') ->join('users', 'berita_wisata.penulis', '=', 'users.id') ->select('berita_wisata.*', 'users.name as penulis') ->where('berita_wisata.isDeleted', 0) ->where('berita_wisata.id', $id) ->first(); if ($data) { // Manually transform the data $data->formatted_date = Carbon::parse($data->tanggalBerita)->translatedFormat('l, d F Y'); return view('user.berita-wisata.detail', compact('data')); } else { // Handle the case when no data is found for the provided ID return redirect()->route('atraksiWisata.index')->with('error', 'Berita not found.'); } } }
import type { Meta, StoryObj } from '@storybook/react'; import { Loader } from './Loader'; // More on how to set up stories at: https://storybook.js.org/docs/react/writing-stories/introduction const meta = { title: 'UI/Loader', component: Loader, tags: ['autodocs'], argTypes: { size: { select: 'radio', options: ['sm', 'md', 'lg'] }, color: { control: { type: 'select' }, options: ['brand', 'accent', 'white', 'black'] } } } satisfies Meta<typeof Loader>; export default meta; type Story = StoryObj<typeof meta>; // More on writing stories with args: https://storybook.js.org/docs/react/writing-stories/args export const Pill: Story = { args: { type: 'pill' } }; export const Spinner: Story = { render: ({ ...args }) => { return <Loader {...args} />; }, args: { type: 'spinner', color: 'white', size: 'lg' } };
// // ChatListViewModel.swift // Ask ME // // Created by Omid on 5.08.2023. // import Foundation import SwiftUI import FirebaseFirestore import FirebaseFirestoreSwift import OpenAI class ChatListViewModel : ObservableObject { @Published var chats : [AppChat] = [] @Published var loadingState : ChatListState = .none @Published var isShowingProfileView : Bool = false private let db = Firestore.firestore() func fetchData(user : String){ // self.chats = [ // AppChat(id: "1", topic: "Some Topic", model: .gpt3_5_turbo, lastMessageSent: Date(), owner: "123"), // AppChat(id: "2", topic: "Some Other Topic", model: .gpt4, lastMessageSent: Date(), owner: "123"), // ] self.loadingState = .resultFound if loadingState == .none{ loadingState = .loading db.collection("chats").whereField("owner", isEqualTo: user ).addSnapshotListener{ [weak self] querySnapshot , error in guard let self = self , let document = querySnapshot?.documents , !document.isEmpty else { self?.loadingState = .noResult return } self.chats = document.compactMap({ snapshot -> AppChat? in return try? snapshot.data(as: AppChat.self) }) .sorted(by: {$0.lastMessageSent > $1.lastMessageSent}) self.loadingState = .resultFound } } } func createChat(user : String?) async throws -> String{ let document = try await db.collection("chats").addDocument(data: ["lastMessageSent" : Date() , "owner" : user ?? ""]) return document.documentID } func showProfile(){ isShowingProfileView = true } func createChat(){ } func deleteChat(chat : AppChat){ guard let id = chat.id else {return} db.collection("chats").document().delete() } } enum ChatListState { case loading case noResult case resultFound case none } struct AppChat : Codable , Identifiable { @DocumentID var id : String? let topic : String? var model : ChatModel? let lastMessageSent : FireStoreDate let owner : String var lastMessageTimeAgo : String { let now : Date = Foundation.Date() let components = Calendar.current.dateComponents([.second , .minute , .hour , .day ,.month , .year], from: lastMessageSent.date, to: now) let timeUnits : [(value : Int? , unit : String)] = [ (components.year , "year") , (components.month , "month") , (components.day , "day") , (components.hour , "hour") , (components.minute , "minute") , (components.second , "second") , ] for timeUnit in timeUnits { if let value = timeUnit.value , value > 0 { return "\(value) \(timeUnit.unit)\(value == 1 ? "" : "s") ago" } } return "just now" } } enum ChatModel: String , Codable , CaseIterable , Hashable { case gpt3_5_turbo = "GPT 3.5 Turbo" case gpt4 = "Gpt 4" var tintColor : Color { switch self { case .gpt3_5_turbo : return .green case .gpt4 : return .purple } } var model : Model { switch self { case .gpt3_5_turbo : return .gpt3_5Turbo case .gpt4 : return .gpt4 } } } struct FireStoreDate : Codable , Hashable , Comparable { static func < (lhs: FireStoreDate, rhs: FireStoreDate) -> Bool { lhs.date < rhs.date } var date : Date init(_ date : Date = Date()){ self.date = date } init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let timestamp = try container.decode(Timestamp.self) date = timestamp.dateValue() } func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() let timestamp = Timestamp(date: date) try container.encode(timestamp) } }
"use client"; import Form from "@/components/molecules/Form"; import Header from "@/components/molecules/Header"; import PostItem from "@/components/molecules/PostItem"; import CommentFeed from "@/components/organisms/CommentFeed"; import usePost from "@/hooks/usePost"; import { MoonLoader } from "react-spinners"; export default function PostView({ params }: { params: { postId: string } }) { const { data: post, isPending } = usePost(params.postId); if (isPending || !post) { return ( <div className="flex justify-center items-center h-full"> <MoonLoader color="lightblue" size={80} /> </div> ); } return ( <> <Header showBackArrow label={"Tweet"} /> <PostItem data={post} /> <Form placeholder="Tweet your reply" postId={params.postId} isComment /> <CommentFeed posts={post.comments} /> </> ); }
import React, { useContext } from "react"; import { Link } from "react-router-dom"; import MainContext from "../contextApi/MainContext"; import Logo from "../images/logo.png"; export default function Navbar() { const mainContext = useContext(MainContext); const { user, logout } = mainContext; const handleClick = () => { logout(); }; return ( // <!-- Header Section Start --> <header className="header w-full border-b pb-4 bg-white"> {/* <!-- Header containerNinish --> */} <div className="containerNinish mx-auto px-2 sm:flex justify-between items-center"> {/* <!-- Brand Logo --> */} <Link to="/"> <div className="logo mx-auto sm:mx-0 mt-2"> <img src={Logo} alt="Ninish Logo" /> </div> </Link> {/* <!-- Navigation Links For Desktop --> */} <nav className="desktopNavLinks"> <ul className="flex gap-2 items-center justify-center sm:justify-start mt-4"> <li> <a href="https://ninish.com" target="_blank" rel="noreferrer"> হোম </a> </li> <li> <a href="https://account.ninish.com" target="_blank" rel="noreferrer" > ড্যাশবোর্ড </a> </li> <li> {user && ( <button onClick={handleClick} className="bg-gradient-to-tr from-violet-700 to-indigo-800 text-white font-bold py-2 px-5 rounded-full" > লগ আউট </button> )} </li> </ul> </nav> </div> </header> // <!-- Header Section End --> ); }
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/ods_flutter_app_localizations.dart'; import 'package:ods_flutter/components/lists/ods_list_radio_button.dart'; import 'package:ods_flutter/components/lists/ods_list_switch.dart'; import 'package:ods_flutter/components/sheets_bottom/ods_sheets_bottom.dart'; import 'package:ods_flutter_demo/main.dart'; import 'package:ods_flutter_demo/ui/components/checkboxes/checkboxes_customization.dart'; import 'package:ods_flutter_demo/ui/main_app_bar.dart'; class ComponentRadioButtonsList extends StatefulWidget { const ComponentRadioButtonsList({super.key}); @override State<ComponentRadioButtonsList> createState() => _ComponentRadioButtonsListState(); } enum Options { option1, option2, option3 } class _ComponentRadioButtonsListState extends State<ComponentRadioButtonsList> { final _scaffoldKey = GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return CheckboxesCustomization( child: Scaffold( bottomSheet: OdsSheetsBottom( content: _CustomizationContent(), title: AppLocalizations.of(context)!.componentCustomizeTitle, ), key: _scaffoldKey, appBar: MainAppBar(AppLocalizations.of(context)!.listRadioButtonsTitle), body: _Body()), ); } } class _Body extends StatefulWidget { @override __BodyState createState() => __BodyState(); } class __BodyState extends State<_Body> { bool? isChecked0 = true; bool? isChecked1 = false; bool? isChecked2 = false; bool isEnable = true; bool isIndeterminate = true; Options? _selectedOption = Options.option1; @override Widget build(BuildContext context) { final CheckboxesCustomizationState? customizationState = CheckboxesCustomization.of(context); return SafeArea( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ OdsListRadioButton( title: OdsApplication.recipes[0].title, value: Options.option1, groupValue: _selectedOption, onCheckedChange: customizationState?.hasEnabled == true ? (Options? value) { setState( () { _selectedOption = value; }, ); } : null, ), OdsListRadioButton<Options>( title: OdsApplication.recipes[1].title, value: Options.option2, groupValue: _selectedOption, onCheckedChange: customizationState?.hasEnabled == true ? (value) { setState( () { _selectedOption = value; }, ); } : null, ), OdsListRadioButton<Options>( title: OdsApplication.recipes[2].title, value: Options.option3, groupValue: _selectedOption, onCheckedChange: customizationState?.hasEnabled == true ? (value) { setState( () { _selectedOption = value; }, ); } : null, ), ], ), ), ); } } class _CustomizationContent extends StatelessWidget { @override Widget build(BuildContext context) { final CheckboxesCustomizationState? customizationState = CheckboxesCustomization.of(context); return Column( children: [ OdsListSwitch( title: AppLocalizations.of(context)! .componentCheckboxesCustomizationEnabled, checked: customizationState?.hasEnabled ?? true, onCheckedChange: (bool value) { customizationState?.hasEnabled = value; }, ), ], ); } }
// // main.m // Prog_3.2 // Program to ork with fractions - class version // // Created by Perry R Gabriel on 12/12/14. // Copyright (c) 2014 Raw Games. All rights reserved. // #import <Foundation/Foundation.h> //---- @interface section --- @interface Fraction : NSObject -(void) print; -(void) setNumerator: (int) n; -(void) setDenominator: (int) d; @end //---- @implementation section ---- @implementation Fraction { int num, dem; } -(void) print { NSLog(@"%i/%i",num,dem); } -(void) setNumerator:(int)n { num = n; } -(void) setDenominator:(int)d { dem = d; } @end //---- program section ---- int main(int argc, const char * argv[]) { @autoreleasepool { Fraction *myFraction; // Create an instance of a Fraction myFraction = [[Fraction alloc] init]; // Set fraction to 1/3 [myFraction setDenominator:3]; [myFraction setNumerator:1]; // Display the fraction using the print method NSLog(@"The value of myFraction is: "); [myFraction print]; } return 0; }
package cnc; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.view.RedirectView; @Controller public class MyController { @Autowired private DaoService daoservice; @RequestMapping("/") public String index() { return "index"; } @RequestMapping("/index") public String home() { return "index"; } @RequestMapping("/submit") public RedirectView submit(@ModelAttribute("emp")Emp emp) { daoservice.addData(emp); RedirectView rv=new RedirectView(); rv.setUrl("display"); return rv; } @RequestMapping("/display") public String submit(Model model) { List <Emp> list=daoservice.displayData(); model.addAttribute("list",list); return "display"; } @RequestMapping("/edit/{id}") public String edit(@PathVariable("id")int id,Model mv) { Emp emp=daoservice.editData(id); mv.addAttribute("emp",emp); return "edit"; } @RequestMapping("/delete/{id}") public RedirectView delete(@PathVariable("id")int id,HttpServletRequest request) { daoservice.deleteData(id); RedirectView rv=new RedirectView(); rv.setUrl(request.getContextPath()+"/display"); return rv; } }
import Document, { Html, Head, Main, NextScript } from "next/document"; import CssBaseline from "@mui/material/CssBaseline"; class MyDocument extends Document { render() { return ( <Html> <Head> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@400;700&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet" /> <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v2.7.1/mapbox-gl.css" rel="stylesheet" /> <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" /> <link href="https://fonts.googleapis.com/css2?family=Cinzel&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Cinzel&family=Syncopate&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@300&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Roboto+Condensed:wght@400;700&family=Roboto:wght@400;500;700&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Carrois+Gothic+SC&display=swap" rel="stylesheet" /> <link href="https://fonts.googleapis.com/css2?family=Lora&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="https://unpkg.com/aos@next/dist/aos.css" /> <link rel="canonical" href="https://estudiojuridicopalomeque.com/" /> <title>{`Estudio Juridico Palomeque`}</title> <meta name="description" content="Estudio juridico Palomeque, Eugenia Palomeque, abogada especializada en Compliance. Revisor Externo Independiente, Auditoria, Diseño de procesos, Comite. " /> <meta name="description" content="Estudio juridico Palomeque" /> <meta httpEquiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="initial-scale=1.0, user-scalable=yes, viewport-fit=cover" /> <meta name="google-site-verification" content="y8KQAQmEDZVbhW1eJHqxwxu1gGZOLH5ufdhevFN8FpM" /> <meta name="keywords" content="Derecho, Abogados, Eugenia Palomeque, Estudio Juridico, Compliance, Law Firm, Palomeque, Abogado" ></meta> <link rel="icon" href="/images/logo.png" /> <meta name="robots" content="index, follow" /> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-198115111-1" /> <script dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-198115111-1'); `, }} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); } } export default MyDocument;
// // EpisodesView.swift // RickAndMorty // // Created by Manuel Rodriguez Sebastian on 17/4/24. // import SwiftUI struct EpisodesView: View { @StateObject var viewModel: EpisodesViewModel init(viewModel: EpisodesViewModel = EpisodesViewModel()) { self._viewModel = StateObject(wrappedValue: viewModel) } var body: some View { NavigationStack { List(viewModel.episodes) { episode in EpisodeItemView(episode: episode).onAppear { viewModel.loadEpisodes(currentItem: episode) } } .onAppear { viewModel.loadEpisodes(currentItem: nil) } .navigationTitle(RickMortyTabItem.episodes.title) } .alert(viewModel.errorMessage, isPresented: $viewModel.showError) { Button("accept", role: .cancel) {} } .autocorrectionDisabled() .tabItem { Label( RickMortyTabItem.episodes.title, systemImage: RickMortyTabItem.episodes.systemImage ).accessibilityIdentifier("episodes_tab_item") } .tag(RickMortyTabItem.episodes) } } #Preview { EpisodesView() }
{% extends 'base.html' %} {% load static %} {% load i18n %} {% block content %} <!-- END nav --> <section id="home-section" class="hero"> <div class="home-slider owl-carousel"> {% for item in carousel_items %} <div class="slider-item" style="background-image: url({{ item.image.url }});"> <div class="overlay"></div> <div class="container"> <div class="row slider-text justify-content-center align-items-center" data-scrollax-parent="true"> <div class="col-md-12 ftco-animate text-center"> <h1 class="mb-2">{{ item.title }}</h1> <h2 class="subheading mb-4">{{ item.subtitle }}</h2> <p><a href="{{ item.link }}" class="btn btn-primary">{{ item.buuton_text }}</a></p> </div> </div> </div> </div> {% endfor %} </div> </section> <section class="ftco-section"> <div class="container"> <div class="row no-gutters ftco-services"> <div class="col-md-3 text-center d-flex align-self-stretch ftco-animate"> <div class="media block-6 services mb-md-0 mb-4"> <div class="icon bg-color-1 active d-flex justify-content-center align-items-center mb-2"> <span class="flaticon-shipped"></span> </div> <div class="media-body"> <h3 class="heading">{% trans 'Pulsuz çatdırılma' %}</h3> <span>{% trans 'Sifariş $100-dan çox olsa' %}</span> </div> </div> </div> <div class="col-md-3 text-center d-flex align-self-stretch ftco-animate"> <div class="media block-6 services mb-md-0 mb-4"> <div class="icon bg-color-2 d-flex justify-content-center align-items-center mb-2"> <span class="flaticon-diet"></span> </div> <div class="media-body"> <h3 class="heading">{% trans 'Təbiyyətdən təbii olan' %}</h3> <span>{% trans 'Product well package' %}</span> </div> </div> </div> <div class="col-md-3 text-center d-flex align-self-stretch ftco-animate"> <div class="media block-6 services mb-md-0 mb-4"> <div class="icon bg-color-3 d-flex justify-content-center align-items-center mb-2"> <span class="flaticon-award"></span> </div> <div class="media-body"> <h3 class="heading">{% trans 'Yüksək keyfiyyət' %}</h3> <span>{% trans 'Keyfiyyətli məhsullar' %}</span> </div> </div> </div> <div class="col-md-3 text-center d-flex align-self-stretch ftco-animate"> <div class="media block-6 services mb-md-0 mb-4"> <div class="icon bg-color-4 d-flex justify-content-center align-items-center mb-2"> <span class="flaticon-customer-service"></span> </div> <div class="media-body"> <h3 class="heading">{% trans 'Qaynar xətt' %}</h3> <span>{% trans '24/7 Dəstək' %}</span> </div> </div> </div> </div> </div> </section> <section class="ftco-section"> <div class="container"> <div class="row justify-content-center mb-3 pb-3"> <div class="col-md-12 heading-section text-center ftco-animate"> <span class="subheading">{% trans 'Featured Products' %}</span> <h2 class="mb-4"><a href="{% url 'shop' %}">{% trans 'Our Products' %} </a></h2> <p>{% trans 'Far far away, behind the word mountains, far from the countries Vokalia and Consonantia' %}</p> </div> </div> </div> <div class="container"> <div class="row"> {% for i in x2 %} <div class="col-md-6 col-lg-3 ftco-animate"> <div class="product"> <a href="{% url 'detailproduct' slug=i.slug %}" class="img-prod"> <img class="img-fluid" src="{{ i.image.url }}" style="height: 280px; width: 230 px;" alt="Colorlib Template"> {% if i.discount %} <span class="status">{{ i.discount }}%</span> {% endif %} <div class="overlay"></div> </a> <div class="text py-3 pb-4 px-3 text-center"> <h3><a href="#">{{ i.title }}</a></h3> <div class="d-flex"> <div class="pricing"> {% if i.discount %} <p class="price"> <span class="price-sale">${{ i.price }}</span> </p> {% else %} <p class="price">${{ i.price }}</p> {% endif %} </div> </div> <div class="bottom-area d-flex px-3"> <div class="m-auto d-flex"> <a href="#" class="add-to-cart d-flex justify-content-center align-items-center text-center"> <span><i class="ion-ios-menu"></i></span> </a> </div> </div> </div> </div> </div> {% endfor %} </div> </div> </section> <section class="ftco-section testimony-section"> <div class="container"> <div class="row justify-content-center mb-5 pb-3"> <div class="col-md-7 heading-section ftco-animate text-center"> <span class="subheading">{% trans 'Testimony' %}</span> <h2 class="mb-4">{% trans 'Our satisfied customer says' %}</h2> <p>{% trans 'Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in' %} </p> </div> </div> <div class="row ftco-animate"> <div class="col-md-12"> <div class="carousel-testimony owl-carousel"> {% for i in mentor %} <div class="item"> <div class="testimony-wrap p-4 pb-5"> <div class="user-img mb-5" style="background-image: url({{i.image.url}})"> <span class="quote d-flex align-items-center justify-content-center"> <i class="icon-quote-left"></i> </span> </div> <div class="text text-center"> <p class="mb-5 pl-4 line">{{i.content}}</p> <p class="name"> {{i.name}}</p> <span class="position">{{i.position}}</span> </div> </div> </div> {% endfor %} </div> </div> </div> </div> </section> <hr> <section class="ftco-section ftco-partner"> <div class="container"> <div class="row"> <div class="col-sm ftco-animate"> <a href="#" class="partner"><img src="{% static 'images/partner-1.png' %}" class="img-fluid" alt="Colorlib Template"></a> </div> <div class="col-sm ftco-animate"> <a href="#" class="partner"><img src="{% static 'images/partner-2.png' %}" class="img-fluid" alt="Colorlib Template"></a> </div> <div class="col-sm ftco-animate"> <a href="#" class="partner"><img src="{% static 'images/partner-3.png' %}" class="img-fluid" alt="Colorlib Template"></a> </div> <div class="col-sm ftco-animate"> <a href="#" class="partner"><img src="{% static 'images/partner-4.png' %}" class="img-fluid" alt="Colorlib Template"></a> </div> <div class="col-sm ftco-animate"> <a href="#" class="partner"><img src="{% static 'images/partner-5.png' %}" class="img-fluid" alt="Colorlib Template"></a> </div> </div> </div> </section> {% endblock %}
/* eslint-disable */ import React, { useState, useEffect } from 'react'; import Typography from '@mui/material/Typography'; import { FormControl,Box, TextField, FormLabel, RadioGroup, Radio, FormControlLabel, Alert } from '@mui/material'; /** * This functional component renders the payment details form * when user purchases a ticket. The user can specify whether they want * to used their saved credit card or a new credit card to pay for their ticket */ const PaymentConfirmation= ({ paymentOption, setPaymentOption, setNewCreditCardNum, setNewCCV, setNewMonth, setNewYear, hasSeats, quantity, availTicketTypes, setChosenSeats }) => { const [creditCardNum, setCreditCardNum] = useState(''); const [month, setMonth] = useState(''); const [year, setYear] = useState(''); const [noSavedPayment, setNoSavedPayment] = useState(false); const handlePaymentChange = (event) => { setPaymentOption(event.target.value); } const fetchCardDetails = async () => { if (localStorage.getItem('token')) { const response = await fetch(`http://localhost:3000/user/profile/${localStorage.getItem('userId')}`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'auth-token': localStorage.getItem('token'), }, }); const json = await response.json(); if (json.user.creditCard !== undefined) { const unencryptedNum = json.user.creditCard.creditCardNum; const encryptedNum = `xxxxxxxxxxxx${unencryptedNum.substr(unencryptedNum.length-4)}` setCreditCardNum(encryptedNum); setMonth(json.user.creditCard.expiryMonth); setYear(json.user.creditCard.expiryYear); setNoSavedPayment(false); } else { setNoSavedPayment(true); } } } /** * This useEffect is used to check whether user came from a seat selection page or from * the initial ticket selection page. If user came from the initial ticket selection page * then chosenSeatsArray needs to populated. */ useEffect(()=> { fetchCardDetails(); if (hasSeats === false) { // initialise chosenSeats array let chosenSeatsArray = []; quantity.forEach((q, ticketTypeIdx) => { for(let ticketNum=0; ticketNum< q; ticketNum++) { const newSeatInfo = { ticketType: availTicketTypes[ticketTypeIdx].ticketType, section: '', seatId: '' } chosenSeatsArray.push(newSeatInfo); } }) setChosenSeats(chosenSeatsArray); } },[]) return ( <Box sx={{p:2}}> <Typography aria-label="Payment Option Title" variant="h4" width="100%">Payment Options</Typography> <FormControl > <Typography aria-label="Payment Option subheading" variant="h5" sx={{mt: 2}}>Pay With</Typography> <FormControl> <FormLabel id="payment-controlled-radio-buttons-group">Available Payment options</FormLabel> <RadioGroup aria-labelledby="payment-controlled-radio-buttons-group" name="controlled-radio-buttons-group" value={paymentOption} onChange={(event)=>handlePaymentChange(event)} > <FormControlLabel value="stored" control={<Radio />} label="Use Saved Payment details" /> <FormControlLabel value="notStored" control={<Radio />} label="Use New Payment Details " /> </RadioGroup> </FormControl> {paymentOption === "notStored"? ( <Box> <FormControl> <Typography id="modal-modal-title" variant="h6" component="h2"> Credit card Number: </Typography> <TextField required id="editNumber" placeholder="xxxxxxxxxxxxxxxx" onChange={e => setNewCreditCardNum(e.target.value)} type='text' /> <Typography id="modal-modal-title" variant="h6" component="h2"> CCV: </Typography> <TextField required id="editCCV" placeholder="xxx" onChange={e => setNewCCV(e.target.value)} type='text' /> <Typography id="modal-modal-title" variant="h6" component="h2"> Expiry Month: </Typography> <TextField required id="editMonth" placeholder="mm" onChange={e => setNewMonth(e.target.value)} type='text' /> <Typography id="modal-modal-title" variant="h6" component="h2"> Expiry Year: </Typography> <TextField required id="editYear" placeholder="yy" onChange={e => setNewYear(e.target.value)} type='text' /> </FormControl> </Box> ): null} {paymentOption === "stored"? ( <Box> <FormControl> <Typography variant="h5" sx={{ mt: 2 }}> Your saved credit card details </Typography> <Typography id="saved credit card" sx={{ mt: 2 }}> Credit card Number: {creditCardNum} </Typography> <Typography id="saved expiry month" sx={{ mt: 2 }}> Expiry Month: {month} </Typography> <Typography id="saved expiry month" sx={{ mt: 2 }}> Expiry Year: {year} </Typography> </FormControl> </Box> ): null} {(paymentOption === "stored" && noSavedPayment === true)?( (<Alert severity="warning">you have no saved card, please use new payment</Alert>) ) :null} </FormControl> </Box> ); }; export default PaymentConfirmation;
import client from '../../config/db/db'; import { user } from '../../api/models/types/user'; import User from '../../api/models/user.model'; describe('User Model', () => { beforeAll(async () => { const sql = `DELETE FROM users; ALTER SEQUENCE users_id_seq RESTART WITH 1;`; const conn = await client.connect(); await conn.query(sql); conn.release(); }); afterAll(async () => { const sql = `DELETE FROM users; ALTER SEQUENCE users_id_seq RESTART WITH 1;`; const conn = await client.connect(); await conn.query(sql); conn.release(); }); const testUser1 = { email: '[email protected]', first_name: 'ahmed', last_name: 'ahmed', password: 'ahmed', }; const testUser2 = { email: '[email protected]', first_name: 'ahmed2', last_name: 'ahmed2', password: 'ahmed2', }; let user1: user; let user2: user; it('creates two users', async () => { user1 = await User.create(testUser1); user2 = await User.create(testUser2); expect(user1).toEqual({ id: 1, email: testUser1.email, first_name: testUser1.first_name, last_name: testUser1.last_name, }); expect(user2).toEqual({ id: 2, email: testUser2.email, first_name: testUser2.first_name, last_name: testUser2.last_name, }); }); it('gets all users', async () => { const result = await User.index(); expect(result).toEqual([ { id: 1, email: testUser1.email, first_name: testUser1.first_name, last_name: testUser1.last_name, password: testUser1.password, }, { id: 2, email: testUser2.email, first_name: testUser2.first_name, last_name: testUser2.last_name, password: testUser2.password, }, ]); }); it('gets a user by id', async () => { const result = await User.show(1); expect(result).toEqual({ id: 1, email: testUser1.email, first_name: testUser1.first_name, last_name: testUser1.last_name, password: testUser1.password, }); }); });
/* * Copyright (C) 2008 Esmertec AG. * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.mms.transaction; import com.android.internal.telephony.PhoneFactory; import com.android.mms.ui.MessageUtils; import com.android.mms.ui.MessagingPreferenceActivity; import com.android.mms.util.SendingProgressTokenManager; import com.google.android.mms.InvalidHeaderValueException; import com.google.android.mms.MmsException; import com.google.android.mms.pdu.EncodedStringValue; import com.google.android.mms.pdu.GenericPdu; import com.google.android.mms.pdu.PduHeaders; import com.google.android.mms.pdu.PduPersister; import com.google.android.mms.pdu.ReadRecInd; import com.google.android.mms.pdu.SendReq; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SqliteWrapper; import android.net.Uri; import android.preference.PreferenceManager; import android.provider.Telephony.Mms; import android.telephony.TelephonyManager; import android.util.Log; public class MmsMessageSender implements MessageSender { private static final String TAG = "MmsMessageSender"; private final Context mContext; private final Uri mMessageUri; private final long mMessageSize; private int mPhoneId; // Default preference values private static final boolean DEFAULT_DELIVERY_REPORT_MODE = false; private static final boolean DEFAULT_READ_REPORT_MODE = false; private static final long DEFAULT_EXPIRY_TIME = 7 * 24 * 60 * 60; private static final int DEFAULT_PRIORITY = PduHeaders.PRIORITY_NORMAL; private static final String DEFAULT_MESSAGE_CLASS = PduHeaders.MESSAGE_CLASS_PERSONAL_STR; public MmsMessageSender(Context context, Uri location, long messageSize) { mContext = context; mMessageUri = location; mMessageSize = messageSize; mPhoneId = PhoneFactory.getDefaultPhoneId(); if (mMessageUri == null) { throw new IllegalArgumentException("Null message URI."); } } public MmsMessageSender(Context context, Uri location, long messageSize, int phoneId) { mContext = context; mMessageUri = location; mMessageSize = messageSize; mPhoneId = phoneId; if (mMessageUri == null) { throw new IllegalArgumentException("Null message URI."); } } public boolean sendMessage(long token) throws MmsException { // Load the MMS from the message uri PduPersister p = PduPersister.getPduPersister(mContext); GenericPdu pdu = p.load(mMessageUri); if (pdu.getMessageType() != PduHeaders.MESSAGE_TYPE_SEND_REQ) { throw new MmsException("Invalid message: " + pdu.getMessageType()); } SendReq sendReq = (SendReq) pdu; sendReq.setPhoneId(mPhoneId);//mPhoneId should be the same as phoneId in SendReq // Update headers. updatePreferencesHeaders(sendReq); // MessageClass. sendReq.setMessageClass(DEFAULT_MESSAGE_CLASS.getBytes()); // Update the 'date' field of the message before sending it. sendReq.setDate(System.currentTimeMillis() / 1000L); sendReq.setMessageSize(mMessageSize); p.updateHeaders(mMessageUri, sendReq); // Move the message into MMS Outbox p.move(mMessageUri, Mms.Outbox.CONTENT_URI); // Start MMS transaction service SendingProgressTokenManager.put(ContentUris.parseId(mMessageUri), token); //cienet edit yuanman 2011-6-15: if (TelephonyManager.getPhoneCount() > 1 || MessageUtils.isMSMS){ Log.i(TAG,"[MmsMessageSender] sendMessage TelephonyManager.getPhoneCount() > 1"); Log.i(TAG,"mPhoneId is"+mPhoneId); mContext.startService(new Intent(mContext, TransactionServiceHelper .getTransactionServiceClass(mPhoneId))); } else { Log.i(TAG,"[MmsMessageSender] sendMessage[ELSE]TelephonyManager.getPhoneCount() > 1"); mContext.startService(new Intent(mContext, TransactionService.class)); } //cienet end yuanman. return true; } // Update the headers which are stored in SharedPreferences. private void updatePreferencesHeaders(SendReq sendReq) throws MmsException { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext); // Expiry. sendReq.setExpiry(prefs.getLong( MessagingPreferenceActivity.EXPIRY_TIME, DEFAULT_EXPIRY_TIME)); // Priority. sendReq.setPriority(prefs.getInt(MessagingPreferenceActivity.PRIORITY, DEFAULT_PRIORITY)); // Delivery report. boolean dr = prefs.getBoolean(MessagingPreferenceActivity.MMS_DELIVERY_REPORT_MODE, DEFAULT_DELIVERY_REPORT_MODE); sendReq.setDeliveryReport(dr?PduHeaders.VALUE_YES:PduHeaders.VALUE_NO); // Read report. boolean rr = prefs.getBoolean(MessagingPreferenceActivity.READ_REPORT_MODE, DEFAULT_READ_REPORT_MODE); sendReq.setReadReport(rr?PduHeaders.VALUE_YES:PduHeaders.VALUE_NO); } public static void sendReadRec(Context context, String to, String messageId, int status) { EncodedStringValue[] sender = new EncodedStringValue[1]; sender[0] = new EncodedStringValue(to); // TODO: phoneId is not set @zha // zhanglj add begin 2011-05-27 // fix for bug17086 start //String selection = Mms._ID + " = " + messageId; String selection = Mms.MESSAGE_ID + " = '" + messageId + "' "; //// fix for bug17086 end int phoneId = -1; Cursor c = null; try{ c = SqliteWrapper.query(context, context.getContentResolver(), Mms.Inbox.CONTENT_URI, new String[] {Mms._ID, Mms.PHONE_ID }, selection, null, null); //cienet add yuanman 2011-6-15:TODO:set the phoneId's value if (c.getCount() == 0 || c.moveToFirst()) { Log.e(TAG,"fail to find the phoneId of original message"); return; } phoneId = c.getInt(1);// get the phone phoneId id //cienet end yuanman. }finally{ c.close(); } // zhanglj add end try { final ReadRecInd readRec = new ReadRecInd( new EncodedStringValue(PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()), messageId.getBytes(), PduHeaders.CURRENT_MMS_VERSION, status, sender, phoneId); readRec.setDate(System.currentTimeMillis() / 1000); PduPersister.getPduPersister(context).persist(readRec, Mms.Outbox.CONTENT_URI, phoneId); //cienet edit yuanman 2011-6-15: if (TelephonyManager.getPhoneCount() > 1 || MessageUtils.isMSMS){ context.startService(new Intent(context, TransactionServiceHelper .getTransactionServiceClass(phoneId))); } else { context.startService(new Intent(context, TransactionService.class)); } //cienet end yuanman. } catch (InvalidHeaderValueException e) { Log.e(TAG, "Invalide header value", e); } catch (MmsException e) { Log.e(TAG, "Persist message failed", e); } } }
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public void preOrder(TreeNode root, List<Integer> ans) { if (root == null) return ; ans.add(root.val); preOrder(root.left, ans); preOrder(root.right, ans); } public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<>(); preOrder(root, ans); return ans; } } /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<>(); Stack<TreeNode> sta = new Stack<>(); if (root != null) sta.push(root); while (!sta.isEmpty()) { TreeNode cur = sta.pop(); ans.add(cur.val); if (cur.right != null) sta.push(cur.right); if (cur.left != null) sta.push(cur.left); } return ans; } }
export default { load: () => { return async (dispatch, getState, services) => { dispatch({ type: 'teachers/load-start' }); try { const res = await services.api.request({ url: `/api/Teacher` }); dispatch({ type: 'teachers/load-success', payload: { data: res.data } }) } catch (e) { dispatch({ type: 'lesson-plan/load-error' }) } } }, search: (query) => { return async (dispatch, getState, services) => { dispatch({ type: 'teachers/search-start' }); try { const res = await services.api.request({ url: `/api/Teacher?query=${query}` }); dispatch({ type: 'teachers/search-success', payload: { data: res.data, query: query } }) } catch (e) { dispatch({ type: 'teachers/search-error' }) } } }, put: (teacher) => { return async (dispatch, getState, services) => { dispatch({ type: 'teachers/put-start' }); try { const res = await services.api.request({ url: `/api/Teacher`, method: 'PUT', body: JSON.stringify(teacher) }); dispatch({ type: 'teachers/put-success', payload: { data: res.data } }) } catch (e) { dispatch({ type: 'teachers/put-error' }) } } }, post: (teacher) => { return async (dispatch, getState, services) => { dispatch({ type: 'teachers/post-start' }); try { const res = await services.api.request({ url: `/api/Teacher`, method: 'POST', body: JSON.stringify(teacher) }); dispatch({ type: 'teachers/post-success', payload: { data: res.data } }) } catch (e) { dispatch({ type: 'teachers/post-error' }) } } }, delete: (id) => { return async (dispatch, getState, services) => { dispatch({ type: 'teachers/delete-start' }); try { const res = await services.api.request({ url: `/api/Teacher/${id}`, method: 'DELETE' }); dispatch({ type: 'teachers/delete-success', payload: { data: id } }) } catch (e) { dispatch({ type: 'teachers/delete-error' }) } } } }
import time import click import rich_click as click from rich.console import Console from rich.progress import Progress from rich.traceback import install import requests install() console = Console() def validate_symbol(ctx, param, value): if not value: raise click.BadParameter('Symbol must be provided') if len(value) < 1: raise click.BadParameter('Symbol must be at least 1 character long') return value @click.group() def cli(): pass @cli.command() @click.option('--symbol', callback=validate_symbol, help='The stock symbol to fetch.') def get(symbol): with Progress() as progress: task = progress.add_task("[cyan]Fetching price...", total=100) # Simulate long-running operation while not progress.finished: progress.update(task, advance=0.5) time.sleep(0.02) response = requests.get(f'https://api.example.com/stocks/{symbol}') price = response.json().get('price') console.print(f'Price for [bold green]{symbol}[/bold green]: [bold cyan]{price}[/bold cyan]') @cli.command() def list(): console.print('Listing all available stock symbols...') if __name__ == "__main__": cli()
"use client" import Footer from '@/src/components/Footer'; import Input from '@/src/components/Input'; import Menu from '@/src/components/Menu' import MenuMobile from '@/src/components/MenuMobile'; import React, { useState, FormEvent, useRef, RefObject } from 'react' import { Body, Folders, FolderName, Folder, PrimeiraParte, NomePasta, SubPasta, DivContact, FolterContact, Contact, ContactText, CodeSection, FileName, Code, Numbers, TechnologiesSection, Post, User, UserTop, Profile, UserData, UserName, PostContent, Text, Button, Message, OrangeText, Error, ThanksSection } from './styles'; import * as yup from "yup"; import emailjs from '@emailjs/browser'; import Loader from '@/src/components/Loader'; import ReCAPTCHA from "react-google-recaptcha"; import { useTranslations } from 'next-intl'; const ContactMe = () => { const [menuIsVisible, setMenuIsVisible] = useState(false); const [emailFolder, setEmailOpen] = useState(false); const [contactIsOpen, setContactIsOpen] = useState(false); const [loading, setLoading] = useState(false); const [name, setName] = useState(''); const [email, setEmail] = useState(''); const [message, setMessage] = useState(''); const [emailSent, setEmailSent] = useState(false); const [errors, setErrors] = useState({ name: '', email: '', message: '', captcha: '' }); const captchaRef: RefObject<ReCAPTCHA> = useRef(null); const t = useTranslations("Contact"); let dataAtual = new Date(); let nomeDoDia = dataAtual.toLocaleDateString('en', { weekday: 'long' }); let dia = dataAtual.getDate(); let nomeDoMes = dataAtual.toLocaleDateString('en', { month: 'long' }); let emailMessage = {} let token = '' const serviceId = process.env.NEXT_PUBLIC_SERVICE_ID; const templateId = process.env.NEXT_PUBLIC_TEMPLATE_ID; const publicKey = process.env.NEXT_PUBLIC_PUBLIC_KEY; const siteKey = process.env.NEXT_PUBLIC_SITE_KEY; let schema = yup.object().shape({ name: yup.string().required(t("nameError")).min(3, t("nameValidError")), email: yup.string().email(t("emailValidError")).required(t("emailError")), message: yup.string().required(t("messageError")).min(10, t("messageValidError")) }); async function sendEmail(event: FormEvent<HTMLFormElement>) { event.preventDefault(); token = captchaRef.current?.getValue() ?? ''; captchaRef.current?.reset(); emailMessage = { name, email, message }; schema .validate(emailMessage, { abortEarly: false }) .then(() => { setLoading(true) if (token) { setErrors({name: '', email: '', message: '', captcha: ''}) const params = { emailMessage, 'g-recaptcha-response': token, }; if (serviceId && templateId) { emailjs.send(serviceId, templateId, params, publicKey) .then(function(response) { console.log(response.status, response.text) response.status == 200 ? setLoading(false) : null; setEmail(''); setName(''); setMessage(''); token = ''; setEmailSent(true); }, function(error) { console.log('FAILED...', error); }); } } }) .catch((err) => { const errorsCopy = { ...errors }; err.errors?.forEach((error: string) => { if (error.includes('name') || error.includes('nome') ) { errorsCopy.name = error; } else if (error.includes('email')) { errorsCopy.email = error; } else { errorsCopy.message = error; } }); if (!token) { errorsCopy.captcha = t("captchaError") } setErrors(errorsCopy); }); } return ( <> <Menu setMenuIsVisible={setMenuIsVisible} /> <MenuMobile $menuIsVisible={menuIsVisible} setMenuIsVisible={setMenuIsVisible} /> <Body> <Folders> <div> <FolderName> <img src='/arrow-down.png' /> {t("folderTitle")} </FolderName> <div> <Folder onClick={() => setEmailOpen(!emailFolder)}> <PrimeiraParte> {emailFolder ? <img src={`/arrow-open.png`} /> : <img src={`/arrow-right.png`} />} <NomePasta> <img src='/pink-icon.png' /> email </NomePasta> </PrimeiraParte> {emailFolder ? ( <div onClick={(e) => { e.stopPropagation();}}> <SubPasta> <img src='/file.png' /> {t("subFolderTitle")} </SubPasta> </div> ) : null} </Folder> </div> </div> <DivContact isOpen={contactIsOpen} onClick={() => setContactIsOpen(!contactIsOpen)}> <FolterContact> <img src='/arrow-down.png' /> {t("folderTitle")} </FolterContact> <Contact isOpen={contactIsOpen}> <img src='/mail-icon.png' /> <ContactText> [email protected]</ContactText> </Contact> <Contact isOpen={contactIsOpen}> <img src='/phone-icon.png' /> <ContactText> (61) 99391-5306</ContactText> </Contact> </DivContact> </Folders> <CodeSection> <FileName> {t("folderTitle")} <img src='/close-icon.png' /> </FileName> <Code> { loading ? <Loader /> : emailSent ? <ThanksSection> <h3>{t("thank")}</h3> <p>{t("messageEmailSent")}</p> </ThanksSection> : <form onSubmit={sendEmail}> <Input label={t("inputName")} value={name} onChange={(e) => setName(e.target.value)} /> <Error>{errors.name}</Error> <Input label='email' value={email} onChange={(e) => setEmail(e.target.value)} /> <Error>{errors.email}</Error> <Input label={t("inputMessage")} value={message} size='big' onChange={(e) => setMessage(e.target.value)} /> <Error>{errors.message}</Error> <br /> <ReCAPTCHA sitekey={siteKey || ''} theme='dark' ref={captchaRef} hl={t("lang") == 'en' ? 'en' : 'pt-BR'} /> <Error>{errors.captcha}</Error> <br /> <Button type='submit'> submit-message </Button> </form> } </Code> </CodeSection> <TechnologiesSection> <div> <Message>const <span>button</span> = <span>document.querySelector('<OrangeText>#textBtn</OrangeText>');</span></Message> <Message>const <span>message</span> = <span> &#123; <br /> &nbsp;&nbsp;name: <OrangeText>"{name}",</OrangeText> <br /> &nbsp;&nbsp;email: <OrangeText>"{email}",</OrangeText> <br /> &nbsp;&nbsp;message: <OrangeText>"{message}",</OrangeText> <br /> &nbsp;&nbsp;date: <OrangeText>{nomeDoDia}, {dia} {nomeDoMes} </OrangeText> <br /> &#125; </span> </Message> </div> <Message> <span> button.addEventListener('<OrangeText>click</OrangeText>', () =&#62; &#123; <br/> &nbsp;&nbsp;form.send(message); <br /> &#125;); </span> </Message> </TechnologiesSection> </Body> <Footer /> </> ) } export default ContactMe
/* tslint:disable max-line-length */ import { ComponentFixture, TestBed, async, inject, fakeAsync, tick } from '@angular/core/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { Observable } from 'rxjs/Observable'; import { JhiEventManager } from 'ng-jhipster'; import { InvoiceappTestModule } from '../../../test.module'; import { OrganisationInvoiceDialogComponent } from '../../../../../../main/webapp/app/entities/organisation-invoice/organisation-invoice-dialog.component'; import { OrganisationInvoiceService } from '../../../../../../main/webapp/app/entities/organisation-invoice/organisation-invoice.service'; import { OrganisationInvoice } from '../../../../../../main/webapp/app/entities/organisation-invoice/organisation-invoice.model'; import { AddressInvoiceService } from '../../../../../../main/webapp/app/entities/address-invoice'; import { ContactInvoiceService } from '../../../../../../main/webapp/app/entities/contact-invoice'; import { TenantInvoiceService } from '../../../../../../main/webapp/app/entities/tenant-invoice'; describe('Component Tests', () => { describe('OrganisationInvoice Management Dialog Component', () => { let comp: OrganisationInvoiceDialogComponent; let fixture: ComponentFixture<OrganisationInvoiceDialogComponent>; let service: OrganisationInvoiceService; let mockEventManager: any; let mockActiveModal: any; beforeEach(async(() => { TestBed.configureTestingModule({ imports: [InvoiceappTestModule], declarations: [OrganisationInvoiceDialogComponent], providers: [ AddressInvoiceService, ContactInvoiceService, TenantInvoiceService, OrganisationInvoiceService ] }) .overrideTemplate(OrganisationInvoiceDialogComponent, '') .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(OrganisationInvoiceDialogComponent); comp = fixture.componentInstance; service = fixture.debugElement.injector.get(OrganisationInvoiceService); mockEventManager = fixture.debugElement.injector.get(JhiEventManager); mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); }); describe('save', () => { it('Should call update service on save for existing entity', inject([], fakeAsync(() => { // GIVEN const entity = new OrganisationInvoice(123); spyOn(service, 'update').and.returnValue(Observable.of(entity)); comp.organisation = entity; // WHEN comp.save(); tick(); // simulate async // THEN expect(service.update).toHaveBeenCalledWith(entity); expect(comp.isSaving).toEqual(false); expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'organisationListModification', content: 'OK'}); expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); }) ) ); it('Should call create service on save for new entity', inject([], fakeAsync(() => { // GIVEN const entity = new OrganisationInvoice(); spyOn(service, 'create').and.returnValue(Observable.of(entity)); comp.organisation = entity; // WHEN comp.save(); tick(); // simulate async // THEN expect(service.create).toHaveBeenCalledWith(entity); expect(comp.isSaving).toEqual(false); expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'organisationListModification', content: 'OK'}); expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); }) ) ); }); }); });
/*Example: address (&) v.s. dereferencing (*) */ #include <iostream> using namespace std; int main() { int a; int * aPtr; a = 7; aPtr = &a; cout << "The address of a is " << & a << "\nThe value of aPtr is " << aPtr; cout << "\n\nThe value of a is" << a << "\nThe value of * aPtr is" << * aPtr; cout << endl; cout << "&* aPtr: " << &* aPtr << "\t*& aPtr: " << *& aPtr << endl; //since & and * are inverses, they cancel each other out. But think about it logically as well for what's happening. //priority for * and & is read from right to left, so for &*aPtr, *aPtr is evlauted first, and then & is evaluated. return 0; }
/******************************************************************************* * Copyright (C) 2019 Michael Berger * * 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/>. ******************************************************************************/ package com.mbcsoft.ticketmaven.entity; /*- * #%L * tmee * %% * Copyright (C) 2019 Michael Berger * %% * 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/gpl-3.0.html>. * #L% */ import java.io.Serializable; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; import jakarta.persistence.JoinColumn; import jakarta.persistence.ManyToOne; import jakarta.persistence.MappedSuperclass; import jakarta.persistence.Version; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlTransient; @XmlRootElement(name = "Instance") @XmlAccessorType(XmlAccessType.FIELD) @MappedSuperclass public abstract class BaseAppTable implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue @XmlTransient private int recordId; @Version @XmlTransient private int version; @XmlTransient @ManyToOne(optional=false) @JoinColumn(name="instance_id") private Instance instance; @XmlTransient public Instance getInstance() { return instance; } public void setInstance(Instance instance) { this.instance = instance; } public BaseAppTable() { super(); } public int getRecordId() { return this.recordId; } public void setRecordId(int recordId) { this.recordId = recordId; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if( obj instanceof BaseAppTable) { BaseAppTable ba = (BaseAppTable) obj; if( ba.recordId == this.recordId) return true; } return super.equals(obj); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.recordId; } public String toString() { return "[" + recordId + "]"; } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" android:orientation="vertical"> <LinearLayout android:id="@+id/layoutSexo" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="60dp" android:orientation="horizontal"> <ImageButton android:id="@+id/maleBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:background="#00FFFFFF" android:contentDescription="@string/male" android:onClick="setMale" app:srcCompat="@drawable/hombre" tools:ignore="DuplicateSpeakableTextCheck" /> <Space android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /> <ImageButton android:id="@+id/femaleBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:background="#00FFFFFF" android:contentDescription="@string/female" android:onClick="setFemale" app:srcCompat="@drawable/mujer" /> </LinearLayout> <LinearLayout android:id="@+id/layoutDatos" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="20dp"> <TextView android:id="@+id/textView5" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/name_hint" android:textColor="@color/white" /> <EditText android:id="@+id/editNombre" android:layout_width="match_parent" android:layout_height="wrap_content" android:autofillHints="" android:background="#1C67B3" android:ems="10" android:hint="@string/name_hint" android:inputType="textPersonName" android:minHeight="48dp" android:padding="10dip" android:textColor="@color/white" android:textColorHint="@color/white" /> <TextView android:id="@+id/textView6" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/edad_hint" android:layout_marginTop="10dp" android:textColor="@color/white" /> <EditText android:id="@+id/editEdad" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#1C67B3" android:ems="10" android:hint="@string/edad_hint" android:importantForAutofill="no" android:inputType="number" android:minHeight="48dp" android:padding="10dip" android:textColor="@color/white" android:textColorHint="@color/white" /> <TextView android:id="@+id/textView7" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/peso_hint" android:layout_marginTop="10dp" android:textColor="@color/white" /> <EditText android:id="@+id/editPeso" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#1C67B3" android:ems="10" android:hint="@string/peso_hint" android:importantForAutofill="no" android:inputType="number" android:minHeight="48dp" android:padding="10dip" android:textColor="@color/white" android:textColorHint="@color/white" /> <TextView android:id="@+id/textView8" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/altura_hint" android:layout_marginTop="10dp" android:textColor="@color/white" /> <EditText android:id="@+id/editAltura" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#1C67B3" android:ems="10" android:hint="@string/altura_hint" android:importantForAutofill="no" android:inputType="number" android:minHeight="48dp" android:padding="10dip" android:textAllCaps="false" android:textColor="@color/white" android:textColorHint="@color/white" android:textIsSelectable="false" /> </LinearLayout> <LinearLayout android:id="@+id/layoutBotones" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal"> <Button android:id="@+id/btnPerfilGuardar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="60dp" android:background="@drawable/roundedbutton" android:onClick="runGuardar" android:text="@string/guardar_btn" android:textColor="@color/white" /> <Space android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" /> <Button android:id="@+id/btnPerfilCancelar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="60dp" android:background="@drawable/roundedbutton" android:onClick="runBorrar" android:text="@string/borrar_btn" android:textColor="@color/white" /> </LinearLayout> </LinearLayout>
/* ! tailwindcss v3.0.24 | MIT License | https://tailwindcss.com */ /* 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) 2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116) */ *, ::before, ::after { box-sizing: border-box; /* 1 */ border-width: 0; /* 2 */ border-style: solid; /* 2 */ border-color: currentColor; /* 2 */ } ::before, ::after { --tw-content: ''; } /* 1. Use a consistent sensible line-height in all browsers. 2. Prevent adjustments of font size after orientation changes in iOS. 3. Use a more readable tab size. 4. Use the user's configured `sans` font-family by default. */ html { line-height: 1.5; /* 1 */ -webkit-text-size-adjust: 100%; /* 2 */ /* 3 */ tab-size: 4; /* 3 */ font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; /* 4 */ } /* 1. Remove the margin in all browsers. 2. Inherit line-height from `html` so users can set them as a class directly on the `html` element. */ body { margin: 0; /* 1 */ line-height: inherit; /* 2 */ } /* 1. Add the correct height in Firefox. 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) 3. Ensure horizontal rules are visible by default. */ hr { height: 0; /* 1 */ color: inherit; /* 2 */ border-top-width: 1px; /* 3 */ } /* Add the correct text decoration in Chrome, Edge, and Safari. */ abbr:where([title]) { -webkit-text-decoration: underline dotted; text-decoration: underline dotted; } /* Remove the default font size and weight for headings. */ h1, h2, h3, h4, h5, h6 { font-size: inherit; font-weight: inherit; } /* Reset links to optimize for opt-in styling instead of opt-out. */ a { color: inherit; text-decoration: inherit; } /* Add the correct font weight in Edge and Safari. */ b, strong { font-weight: bolder; } /* 1. Use the user's configured `mono` font family by default. 2. Correct the odd `em` font sizing in all browsers. */ code, kbd, samp, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; /* 1 */ font-size: 1em; /* 2 */ } /* Add the correct font size in all browsers. */ small { font-size: 80%; } /* Prevent `sub` and `sup` elements from affecting the line height in all browsers. */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sub { bottom: -0.25em; } sup { top: -0.5em; } /* 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) 3. Remove gaps between table borders by default. */ table { text-indent: 0; /* 1 */ border-color: inherit; /* 2 */ border-collapse: collapse; /* 3 */ } /* 1. Change the font styles in all browsers. 2. Remove the margin in Firefox and Safari. 3. Remove default padding in all browsers. */ button, input, optgroup, select, textarea { font-family: inherit; /* 1 */ font-size: 100%; /* 1 */ line-height: inherit; /* 1 */ color: inherit; /* 1 */ margin: 0; /* 2 */ padding: 0; /* 3 */ } /* Remove the inheritance of text transform in Edge and Firefox. */ button, select { text-transform: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Remove default button styles. */ button, [type='button'], [type='reset'], [type='submit'] { -webkit-appearance: button; /* 1 */ background-color: transparent; /* 2 */ background-image: none; /* 2 */ } /* Use the modern Firefox focus style for all focusable elements. */ :-moz-focusring { outline: auto; } /* Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) */ :-moz-ui-invalid { box-shadow: none; } /* Add the correct vertical alignment in Chrome and Firefox. */ progress { vertical-align: baseline; } /* Correct the cursor style of increment and decrement buttons in Safari. */ ::-webkit-inner-spin-button, ::-webkit-outer-spin-button { height: auto; } /* 1. Correct the odd appearance in Chrome and Safari. 2. Correct the outline style in Safari. */ [type='search'] { -webkit-appearance: textfield; /* 1 */ outline-offset: -2px; /* 2 */ } /* Remove the inner padding in Chrome and Safari on macOS. */ ::-webkit-search-decoration { -webkit-appearance: none; } /* 1. Correct the inability to style clickable types in iOS and Safari. 2. Change font properties to `inherit` in Safari. */ ::-webkit-file-upload-button { -webkit-appearance: button; /* 1 */ font: inherit; /* 2 */ } /* Add the correct display in Chrome and Safari. */ summary { display: list-item; } /* Removes the default spacing and border for appropriate elements. */ blockquote, dl, dd, h1, h2, h3, h4, h5, h6, hr, figure, p, pre { margin: 0; } fieldset { margin: 0; padding: 0; } legend { padding: 0; } ol, ul, menu { list-style: none; margin: 0; padding: 0; } /* Prevent resizing textareas horizontally by default. */ textarea { resize: vertical; } /* 1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) 2. Set the default placeholder color to the user's configured gray 400 color. */ input::-webkit-input-placeholder, textarea::-webkit-input-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input:-ms-input-placeholder, textarea:-ms-input-placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } input::placeholder, textarea::placeholder { opacity: 1; /* 1 */ color: #9ca3af; /* 2 */ } /* Set the default cursor for buttons. */ button, [role="button"] { cursor: pointer; } /* Make sure disabled buttons don't get the pointer cursor. */ :disabled { cursor: default; } /* 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) This can trigger a poorly considered lint error in some tools but is included by design. */ img, svg, video, canvas, audio, iframe, embed, object { display: block; /* 1 */ vertical-align: middle; /* 2 */ } /* Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) */ img, video { max-width: 100%; height: auto; } /* Ensure the default browser behavior of the `hidden` attribute. */ [hidden] { display: none; } *, ::before, ::after { --tw-translate-x: 0; --tw-translate-y: 0; --tw-rotate: 0; --tw-skew-x: 0; --tw-skew-y: 0; --tw-scale-x: 1; --tw-scale-y: 1; --tw-pan-x: ; --tw-pan-y: ; --tw-pinch-zoom: ; --tw-scroll-snap-strictness: proximity; --tw-ordinal: ; --tw-slashed-zero: ; --tw-numeric-figure: ; --tw-numeric-spacing: ; --tw-numeric-fraction: ; --tw-ring-inset: ; --tw-ring-offset-width: 0px; --tw-ring-offset-color: #fff; --tw-ring-color: rgb(59 130 246 / 0.5); --tw-ring-offset-shadow: 0 0 #0000; --tw-ring-shadow: 0 0 #0000; --tw-shadow: 0 0 #0000; --tw-shadow-colored: 0 0 #0000; --tw-blur: ; --tw-brightness: ; --tw-contrast: ; --tw-grayscale: ; --tw-hue-rotate: ; --tw-invert: ; --tw-saturate: ; --tw-sepia: ; --tw-drop-shadow: ; --tw-backdrop-blur: ; --tw-backdrop-brightness: ; --tw-backdrop-contrast: ; --tw-backdrop-grayscale: ; --tw-backdrop-hue-rotate: ; --tw-backdrop-invert: ; --tw-backdrop-opacity: ; --tw-backdrop-saturate: ; --tw-backdrop-sepia: ; } .container { width: 100%; } @media (min-width: 640px) { .container { max-width: 640px; } } @media (min-width: 768px) { .container { max-width: 768px; } } @media (min-width: 1024px) { .container { max-width: 1024px; } } @media (min-width: 1280px) { .container { max-width: 1280px; } } @media (min-width: 1536px) { .container { max-width: 1536px; } } .relative { position: relative; } .m-0 { margin: 0px; } .mx-auto { margin-left: auto; margin-right: auto; } .mb-6 { margin-bottom: 1.5rem; } .ml-0 { margin-left: 0px; } .mb-4 { margin-bottom: 1rem; } .mt-16 { margin-top: 4rem; } .mb-10 { margin-bottom: 2.5rem; } .block { display: block; } .inline { display: inline; } .flex { display: flex; } .hidden { display: none; } .h-screen { height: 100vh; } .h-full { height: 100%; } .h-\[8\%\] { height: 8%; } .h-\[70\%\] { height: 70%; } .h-\[20\%\] { height: 20%; } .h-12 { height: 3rem; } .h-14 { height: 3.5rem; } .h-16 { height: 4rem; } .h-2 { height: 0.5rem; } .h-0 { height: 0px; } .h-\[7\%\] { height: 7%; } .h-\[10\%\] { height: 10%; } .h-48 { height: 12rem; } .h-2\/3 { height: 66.666667%; } .w-screen { width: 100vw; } .w-full { width: 100%; } .w-\[75\%\] { width: 75%; } .w-\[95\%\] { width: 95%; } .w-\[80\%\] { width: 80%; } .w-14 { width: 3.5rem; } .w-2 { width: 0.5rem; } .w-\[25\%\] { width: 25%; } .w-32 { width: 8rem; } .w-\[23\%\] { width: 23%; } .max-w-\[70\%\] { max-width: 70%; } .flex-1 { flex: 1 1 0%; } .cursor-pointer { cursor: pointer; } .flex-col { flex-direction: column; } .items-center { align-items: center; } .justify-start { justify-content: flex-start; } .justify-end { justify-content: flex-end; } .justify-center { justify-content: center; } .justify-between { justify-content: space-between; } .space-y-5 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1.25rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1.25rem * var(--tw-space-y-reverse)); } .space-y-6 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(1.5rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(1.5rem * var(--tw-space-y-reverse)); } .space-x-14 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(3.5rem * var(--tw-space-x-reverse)); margin-left: calc(3.5rem * calc(1 - var(--tw-space-x-reverse))); } .space-x-6 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(1.5rem * var(--tw-space-x-reverse)); margin-left: calc(1.5rem * calc(1 - var(--tw-space-x-reverse))); } .space-y-2 > :not([hidden]) ~ :not([hidden]) { --tw-space-y-reverse: 0; margin-top: calc(0.5rem * calc(1 - var(--tw-space-y-reverse))); margin-bottom: calc(0.5rem * var(--tw-space-y-reverse)); } .space-x-2 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(0.5rem * var(--tw-space-x-reverse)); margin-left: calc(0.5rem * calc(1 - var(--tw-space-x-reverse))); } .space-x-3 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(0.75rem * var(--tw-space-x-reverse)); margin-left: calc(0.75rem * calc(1 - var(--tw-space-x-reverse))); } .space-x-4 > :not([hidden]) ~ :not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(1rem * var(--tw-space-x-reverse)); margin-left: calc(1rem * calc(1 - var(--tw-space-x-reverse))); } .overflow-hidden { overflow: hidden; } .overflow-y-scroll { overflow-y: scroll; } .rounded-md { border-radius: 0.375rem; } .rounded-lg { border-radius: 0.5rem; } .rounded-full { border-radius: 9999px; } .rounded-b-lg { border-bottom-right-radius: 0.5rem; border-bottom-left-radius: 0.5rem; } .border-2 { border-width: 2px; } .border-b-\[1px\] { border-bottom-width: 1px; } .border-gray { --tw-border-opacity: 1; border-color: rgb(243 241 245 / var(--tw-border-opacity)); } .border-darkBlue { --tw-border-opacity: 1; border-color: rgb(14 24 95 / var(--tw-border-opacity)); } .border-white { --tw-border-opacity: 1; border-color: rgb(255 255 255 / var(--tw-border-opacity)); } .bg-lightBlue { --tw-bg-opacity: 1; background-color: rgb(117 121 231 / var(--tw-bg-opacity)); } .bg-white { --tw-bg-opacity: 1; background-color: rgb(255 255 255 / var(--tw-bg-opacity)); } .bg-gray { --tw-bg-opacity: 1; background-color: rgb(243 241 245 / var(--tw-bg-opacity)); } .bg-default { --tw-bg-opacity: 1; background-color: rgb(0 0 0 / var(--tw-bg-opacity)); } .bg-active { --tw-bg-opacity: 1; background-color: rgb(131 189 117 / var(--tw-bg-opacity)); } .bg-navBg { --tw-bg-opacity: 1; background-color: rgb(217 217 217 / var(--tw-bg-opacity)); } .bg-blue-200 { --tw-bg-opacity: 1; background-color: rgb(191 219 254 / var(--tw-bg-opacity)); } .p-3 { padding: 0.75rem; } .p-0 { padding: 0px; } .p-6 { padding: 1.5rem; } .p-2 { padding: 0.5rem; } .p-4 { padding: 1rem; } .p-1 { padding: 0.25rem; } .py-3 { padding-top: 0.75rem; padding-bottom: 0.75rem; } .px-5 { padding-left: 1.25rem; padding-right: 1.25rem; } .px-10 { padding-left: 2.5rem; padding-right: 2.5rem; } .px-6 { padding-left: 1.5rem; padding-right: 1.5rem; } .py-4 { padding-top: 1rem; padding-bottom: 1rem; } .px-2 { padding-left: 0.5rem; padding-right: 0.5rem; } .py-6 { padding-top: 1.5rem; padding-bottom: 1.5rem; } .px-4 { padding-left: 1rem; padding-right: 1rem; } .pl-7 { padding-left: 1.75rem; } .pt-4 { padding-top: 1rem; } .pl-6 { padding-left: 1.5rem; } .pl-4 { padding-left: 1rem; } .pb-10 { padding-bottom: 2.5rem; } .pl-10 { padding-left: 2.5rem; } .font-poppinsBold { font-family: PoppinsBold; } .font-poppins { font-family: Poppins; } .font-poppinsMedium { font-family: PoppinsMedium; } .text-base { font-size: 1rem; line-height: 1.5rem; } .text-sm { font-size: 0.875rem; line-height: 1.25rem; } .text-2xl { font-size: 1.5rem; line-height: 2rem; } .text-lg { font-size: 1.125rem; line-height: 1.75rem; } .text-5xl { font-size: 3rem; line-height: 1; } .text-xl { font-size: 1.25rem; line-height: 1.75rem; } .tracking-wide { letter-spacing: 0.025em; } .text-darkBlue { --tw-text-opacity: 1; color: rgb(14 24 95 / var(--tw-text-opacity)); } .text-white { --tw-text-opacity: 1; color: rgb(255 255 255 / var(--tw-text-opacity)); } .text-default { --tw-text-opacity: 1; color: rgb(0 0 0 / var(--tw-text-opacity)); } .text-lightBlue { --tw-text-opacity: 1; color: rgb(117 121 231 / var(--tw-text-opacity)); } .text-red-500 { --tw-text-opacity: 1; color: rgb(239 68 68 / var(--tw-text-opacity)); } .transition-height { transition-property: height; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .transition-all { transition-property: all; transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); transition-duration: 150ms; } .duration-1000 { transition-duration: 1000ms; } .ease-in-out { transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); } @font-face { font-family: "Poppins"; src: url("./assets/fonts/Poppins-Regular.ttf"); } @font-face { font-family: "PoppinsLight"; src: url("./assets/fonts/Poppins-Light.ttf"); } @font-face { font-family: "PoppinsMedium"; src: url("./assets/fonts/Poppins-Medium.ttf"); } @font-face { font-family: "PoppinsBold"; src: url("./assets/fonts/Poppins-Bold.ttf"); } .hover\:bg-gray:hover { --tw-bg-opacity: 1; background-color: rgb(243 241 245 / var(--tw-bg-opacity)); } @media (min-width: 1536px) { .\32xl\:container { width: 100%; } @media (min-width: 640px) { .\32xl\:container { max-width: 640px; } } @media (min-width: 768px) { .\32xl\:container { max-width: 768px; } } @media (min-width: 1024px) { .\32xl\:container { max-width: 1024px; } } @media (min-width: 1280px) { .\32xl\:container { max-width: 1280px; } } @media (min-width: 1536px) { .\32xl\:container { max-width: 1536px; } } }
/** * Copyright (c) 2020-present, Goldman Sachs * * 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. */ import { CORE_HASH_STRUCTURE } from '../../../../../../../../../graph/Core_HashUtils.js'; import { type Hashable, hashArray } from '@finos/legend-shared'; export abstract class V1_AuthenticationStrategy implements Hashable { abstract get hashCode(): string; } export class V1_DelegatedKerberosAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { serverPrincipal?: string | undefined; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.DELEGRATED_KEREBEROS_AUTHENTICATION_STRATEGY, this.serverPrincipal?.toString() ?? '', ]); } } export class V1_DefaultH2AuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { get hashCode(): string { return hashArray([CORE_HASH_STRUCTURE.DEFAULT_H2_AUTHENTICATION_STRATEGY]); } } export class V1_OAuthAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { oauthKey!: string; scopeName!: string; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.OAUTH_AUTHENTICATION_STRATEGY, this.oauthKey, this.scopeName, ]); } } export class V1_ApiTokenAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { apiToken!: string; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.API_TOKEN_AUTHENTICATION_STRATEGY, this.apiToken, ]); } } export class V1_SnowflakePublicAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { privateKeyVaultReference!: string; passPhraseVaultReference!: string; publicUserName!: string; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.SNOWFLAKE_PUBLIC_AUTHENTICATION_STRATEGY, this.privateKeyVaultReference, this.passPhraseVaultReference, this.publicUserName, ]); } } export class V1_GCPApplicationDefaultCredentialsAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.GCP_APPLICATION_DEFAULT_CREDENTIALS_AUTHENTICATION_STRATEGY, ]); } } export class V1_GCPWorkloadIdentityFederationAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { serviceAccountEmail!: string; additionalGcpScopes: string[] = []; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.GCP_WORKLOAD_IDENTITY_FEDERATION_AUTHENTICATION_STRATEGY, this.serviceAccountEmail, hashArray(this.additionalGcpScopes), ]); } } export class V1_UsernamePasswordAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { baseVaultReference?: string | undefined; userNameVaultReference!: string; passwordVaultReference!: string; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.USERNAME_PASSWORD_AUTHENTICATION_STRATEGY, this.baseVaultReference?.toString() ?? '', this.userNameVaultReference, this.passwordVaultReference, ]); } } export class V1_MiddleTierUsernamePasswordAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { vaultReference!: string; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.MIDDLE_TIER_USERNAME_PASSWORD_AUTHENTICATION_STRATEGY, this.vaultReference, ]); } } export class V1_TrinoDelegatedKerberosAuthenticationStrategy extends V1_AuthenticationStrategy implements Hashable { kerberosRemoteServiceName!: string; kerberosUseCanonicalHostname!: boolean; get hashCode(): string { return hashArray([ CORE_HASH_STRUCTURE.TRINO_DELEGATED_KERBEROS_AUTHENTICATION_STRATEGY, this.kerberosRemoteServiceName, this.kerberosUseCanonicalHostname.toString(), ]); } }
import React, { useEffect, useState } from "react"; import { getSign } from "../../../api/knowLedgeModule"; import "./index.less"; // Loading import Loading from "../../../components/Loading"; function Sign() { // 数据列表 const [list, setList] = useState([]); // 当前选中分类 const [currentCate, setCurrentCate] = useState(1); // 当前选中图标 const [currentSign, setCurrentSign] = useState(1); // 模态框是否显示 const [isModalVisiable, setIsModalVisiable] = useState(false); // 数据是否加载完成 let [listFlag, setListFlag] = useState(true); // 初始化获取数据 useEffect(() => { getSign().then((res) => { setListFlag(false); setList(res.signCategaries); setCurrentCate(res.signCategaries.find((item) => item.cate_id == 1)); }); }, []); return ( <div className="traffic-sign"> <Loading isLoading={listFlag} /> <ul> {list.map((item) => ( <li className={ item.cate_id === currentCate.cate_id ? "active sign-module" : "sign-module" } key={item.cate_id} onClick={() => setCurrentCate(item)} > <div className="module-title complete-center"> <span>{item.cate_name}</span> <img src={item.signList[4].sign_url} alt="" /> </div> <div className="module-content"> <div className="title"> <span>{item.cate_name}</span> <img src={item.signList[4].sign_url} alt="" /> </div> <div className="sign-list"> {item.signList.map((key) => ( <div className="sign-item" title={key.sign_name} key={key.sign_id} onClick={() => setCurrentSign(key) || setIsModalVisiable(true) } > <img src={key.sign_url} title={key.sign_name}></img> <br /> <span>{key.sign_name}</span> </div> ))} </div> </div> </li> ))} </ul> <div className={isModalVisiable ? "mask active" : "mask"} onClick={() => setIsModalVisiable(false)} ></div> <div className={isModalVisiable ? "modal active" : "modal"}> <div className="picture"> <img src={currentSign.sign_url} alt="" /> </div> <div className="name">{currentSign.sign_name}</div> <div className="module-name"> <span>{currentCate.cate_name}</span> </div> <div className="close" onClick={() => setIsModalVisiable(false)}> + </div> </div> </div> ); } export default Sign;
#pragma warning(disable : 4996) #include<iostream> #include<iomanip> using namespace std; bool IsLeapYear(short Year) { return (Year % 4 == 0 && Year % 100 != 0) || (Year % 400 == 0); } short ReadYear() { cout << "Enter a year: "; int Year; cin >> Year; return Year; } short ReadMonth() { cout << "Enter a month: "; int Month; cin >> Month; return Month; } short ReadDay() { cout << "Enter a day: "; int Day; cin >> Day; return Day; } struct sDate { short Year; short Month; short Day; }; sDate ReadFullDate() { sDate Date; Date.Day = ReadDay(); Date.Month = ReadMonth(); Date.Year = ReadYear(); return Date; } short NumbersOfDaysInMonth(short Year, short Month) { if (Month > 12 || Month < 1) return 0; short ArrDays[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; if (Month == 2) { if (IsLeapYear(Year)) return 29; else return 28; } else { return ArrDays[Month - 1]; } } bool IsLastDayInMonth(sDate Date) { return (Date.Day == NumbersOfDaysInMonth(Date.Year, Date.Month)); } bool IsLastMonthInYear(short Month) { return (Month == 12); } bool IsDate1BeforeDate2(sDate Date1, sDate Date2) { return (Date1.Year < Date2.Year) ? true : ((Date1.Year == Date2.Year) ? (Date1.Month < Date2.Month ? true : (Date1.Month == Date2.Month ? Date1.Day < Date2.Day : false)) : false); } sDate DateAfterAddingOneDay(sDate Date) { if (IsLastDayInMonth(Date)) { if (IsLastMonthInYear(Date.Month)) { Date.Month = 1; Date.Day = 1; Date.Year++; } else { Date.Month++; Date.Day = 1; } } else { Date.Day++; } return Date; } int GetDifferenceInDays(sDate Date1, sDate Date2, bool IncludeEndDay = false) { int Days = 0; while (IsDate1BeforeDate2(Date1, Date2)) { Days++; Date1 = DateAfterAddingOneDay(Date1); } return IncludeEndDay ? ++Days : Days; } sDate GetSysytemDate() { sDate Date; time_t t = time(0); tm* now = localtime(&t); Date.Year = now->tm_year + 1900; Date.Month = now->tm_mon + 1; Date.Day = now->tm_mday; return Date; } int main() { sDate Date1 = ReadFullDate(); cout << endl; sDate Date2 = GetSysytemDate(); cout << "\nYour Age is : " << GetDifferenceInDays(Date1, Date2, true) << " Day(s).\n\n"; system("pause>0"); return 0; }
package com.example.ecommerce.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.ecommerce.R import com.example.ecommerce.core.data.database.wishlist.Wishlist import com.example.ecommerce.databinding.ItemWishlistGridBinding import com.example.ecommerce.databinding.ItemWishlistLinearBinding import com.example.ecommerce.utils.convertToRupiah class WishlistAdapter : ListAdapter<Wishlist, RecyclerView.ViewHolder>(DIFF_CALLBACK) { var isGrid: Boolean = false private lateinit var onItemClickCallback: OnItemClickCallback fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) { this.onItemClickCallback = onItemClickCallback } override fun getItemViewType(position: Int): Int { return if (isGrid) { LIST_GRID } else { LIST_VIEW } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val binding = when (viewType) { LIST_GRID -> { ItemWishlistGridBinding.inflate( LayoutInflater.from(parent.context), parent, false ) } LIST_VIEW -> { ItemWishlistLinearBinding.inflate( LayoutInflater.from(parent.context), parent, false ) } else -> throw IllegalArgumentException("Undefined view type") } return if (viewType == LIST_GRID) { WishListGridViewHolder(binding as ItemWishlistGridBinding) } else { WishListLinearViewHolder(binding as ItemWishlistLinearBinding) } } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val viewType = getItemViewType(position) val cartItem = getItem(position) when (viewType) { LIST_GRID -> { val gridViewHolder = holder as WishListGridViewHolder gridViewHolder.bind(cartItem) } LIST_VIEW -> { val listViewHolder = holder as WishListLinearViewHolder listViewHolder.bind(cartItem) } else -> throw IllegalArgumentException("Undefined view type") } } override fun getItemCount(): Int { return currentList.size } inner class WishListLinearViewHolder(private val binding: ItemWishlistLinearBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(data: Wishlist) { Glide.with(binding.root).load(data.image).into(binding.imgProductView) binding.txtTitleProduct.text = data.productName binding.txtHargaProduct.text = data.productVariantPrice.convertToRupiah() binding.txtStoreName.text = data.store binding.txtProductRating.text = data.productRating binding.txtProductTerjual.text = binding.root.context.getString(R.string.terjual, data.sale.toString()) binding.btnDeleteItem.setOnClickListener { onItemClickCallback.onDeleteClicked(data.productId) } binding.btnTambahKeranjang.setOnClickListener { onItemClickCallback.onAddCartClicked(data, data.productId) } } } inner class WishListGridViewHolder(private val binding: ItemWishlistGridBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(data: Wishlist) { Glide.with(binding.root).load(data.image).into(binding.imgProduct) binding.txtTitleProduct.text = data.productName binding.txtHargaProduct.text = data.productVariantPrice.convertToRupiah() binding.txtProductBrand.text = data.brand binding.txtRatingProduct.text = data.totalRating.toString() binding.txtProductTerjual.text = binding.root.context.getString( R.string.terjual, data.sale.toString() ) binding.btnDeleteItem.setOnClickListener { onItemClickCallback.onDeleteClicked(data.productId) } binding.btnTambahKeranjang.setOnClickListener { onItemClickCallback.onAddCartClicked(data, data.productId) } } } interface OnItemClickCallback { fun onAddCartClicked(wishlist: Wishlist, itemId: String) fun onDeleteClicked(itemId: String) } companion object { private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Wishlist>() { override fun areContentsTheSame(oldItem: Wishlist, newItem: Wishlist): Boolean { return oldItem == newItem } override fun areItemsTheSame(oldItem: Wishlist, newItem: Wishlist): Boolean { return oldItem.productId == newItem.productId } } private const val LIST_VIEW = 0 private const val LIST_GRID = 1 } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!-- Title --> <title>Afrika Global Gender Academy</title> <!-- Link to css style file and queries file --> <link rel="stylesheet" href="./css/style.css" /> <link rel="stylesheet" href="./css/queries.css" /> <!-- Favicon --> <link rel="icon" type="image/x-icon" href="/images/favicon.ico" /> </head> <body> <!-- Navigation Bar --> <nav class="nav"> <div class="nav-container container"> <div class="nav-logo"> <img src="./img/logo.jpg" alt="logo" /> </div> <button class="menu-btn"> <img src="./img/hamburger.svg" alt="menu-btn" /> </button> <ul class="nav-list" id="navList"> <li><a href="./index.html">Home</a></li> <li class="has-submenu"> <a href="./about.html">About Us</a> <ul class="subnav-list"> <li><a href="./founder.html">Our Founder</a></li> <li><a href="./about.html#mission">Our Mission</a></li> <li><a href="./about.html#vision">Our Vision</a></li> <li><a href="./about.html#values">Our Values</a></li> <li><a href="./team.html">Our Global Team</a></li> <li><a href="./team.html#board">Our Advisory Board</a></li> <li><a href="#partners">Our Partners</a></li> <li><a href="./gallery.html">Our Gallery</a></li> </ul> </li> <li><a href="./index.html#services">Our Services</a></li> <li><a href="#">Our Initiatives</a></li> <li><a href="#">Our Program</a></li> <li><a href="./index.html#events">Our Events</a></li> <li><a href="./blog.html">Blog</a></li> <li><a href="./contact.html">Contact Us</a></li> <div id="google_translate_element"></div> </ul> </div> </nav> <!-- Header --> <header class="header header-section"> <div class="header-container container"> <div class="header-content"> <h1>Afrika Global Gender Academy</h1> <p> Empower Equality: Education for All Genders </p> <div class="header-btn-cont"> <button class="header-btn">Read More</button> </div> </div> </div> </header> <!-- About Section --> <section class="about section"> <div class="about-container container"> <div class="about-img"> <img src="./img/about-imgs.jpg" alt="about-img" /> </div> <div class="about-content"> <div class="about-title"> <h3>About Us</h3> <h1>Welcome to Afrika Global Gender Academy</h1> </div> <div class="about-briefing"> <div> <p> The Afrika Global Gender Academy is a pioneering organization committed to advancing gender equality and empowering individuals of all genders worldwide. Founded on the principle of inclusivity and advocacy, we strive to create a world where everyone has equal opportunities, rights, and recognition, regardless of gender identity or expression </p> </div> <div> <button class="about-btn">Read More</button> </div> </div> </div> </div> </section> <!-- Services section --> <section class="services section" id="services"> <div class="services-container container"> <div class="services-title"> <h1>Our Services</h1> </div> <div class="services-card-container"> <div class="services-card"> <div class="services-card-icon"> <i class="fa-solid fa-graduation-cap"></i> </div> <div class="services-card-content"> <h2>Education and Training</h2> <p> We offer workshops, seminars, and online courses on gender awareness, diversity, and inclusion for individuals, organizations, and educational institutions. </p> </div> <div class="services-card-btn"> <button>Learn More</button> </div> </div> <div class="services-card"> <div class="services-card-icon"> <i class="fa-solid fa-globe"></i> </div> <div class="services-card-content"> <h2>Consulting</h2> <p> Our consulting services provide tailored solutions for businesses, governments, and NGOs seeking to integrate gender equality into their policies, programs, and practices. </p> </div> <div class="services-card-btn"> <button>Learn More</button> </div> </div> <div class="services-card"> <div class="services-card-icon"> <i class="fa-solid fa-house"></i> </div> <div class="services-card-content"> <h2>Community Support:</h2> <p> We provide resources, support groups, and counseling services for individuals navigating gender identity, sexuality, and related challenges. </p> </div> <div class="services-card-btn"> <button>Learn More</button> </div> </div> <div class="services-card"> <div class="services-card-icon"> <i class="fa-solid fa-book-open-reader"></i> </div> <div class="services-card-content"> <h2>Research and Advocacy:</h2> <p> We conduct research and engage in advocacy campaigns to raise awareness, challenge stereotypes, and influence policies that promote gender equality. </p> </div> <div class="services-card-btn"> <button>Learn More</button> </div> </div> </div> </div> </section> <!-- Events section --> <section class="events section"> <div class="events-container container"> <div class="events-title"> <h1>Our Events</h1> </div> <div class="events-content"> <div class="events-card"> <div class="events-heading"> <div class="events-heading-title"> <h1>Annual Gender Equality Conference:</h1> </div> </div> <div class="events-description"> <p> A flagship event bringing together activists, scholars, policymakers, and community leaders to discuss key issues, share best practices, and inspire collective action </p> </div> </div> <div class="events-card"> <div class="events-heading"> <div class="events-heading-title"> <h1>Gender Empowerment Workshops:</h1> </div> </div> <div class="events-description"> <p> Interactive workshops focusing on skill-building, leadership development, and empowerment for individuals of all genders </p> </div> </div> <div class="events-card"> <div class="events-heading"> <div class="events-heading-title"> <h1>Film Screenings and Panel Discussions:</h1> </div> </div> <div class="events-description"> <p> Events showcasing films and documentaries that highlight gender-related issues followed by panel discussions with experts and activists. </p> </div> </div> <div class="events-card"> <div class="events-heading"> <div class="events-heading-title"> <h1>Gender-inclusive Networking Events:</h1> </div> </div> <div class="events-description"> <p> Social gatherings and networking opportunities designed to foster connections and collaborations among diverse communities. </p> </div> </div> <div class="events-card"> <div class="events-heading"> <div class="events-heading-title"> <h1>Youth Empowerment Programs:</h1> </div> </div> <div class="events-description"> <p> Workshops and mentorship programs tailored to empower young people to become agents of change in their schools and communities. </p> </div> </div> </div> </div> </section> <!-- partners section --> <section class="partners section" id="partners"> <div class="partners-container container"> <div class="partners-title"> <h1>Our Partners</h1> </div> <div class="partners-image-container"> <div> <img src="./img/logo.jpg" alt="partners-img" /> </div> <div> <img src="./img/hvc-partner.jpg" alt="partners-img" /> </div> </div> </div> </section> <!-- Footer --> <footer class="footer"> <div class="footer-container container"> <div class="footer-addresses"> <div class="footer-nav-title"> <h3>About Us</h3> </div> <div class="footer-description"> <p> The Afrika Global Gender Academy is a pioneering organization committed to advancing gender equality and empowering individuals of all genders worldwide. </p> <p class="copyright"> &copy;2024 Afrika Global Gender Academy. All rights reserved. </p> </div> </div> <div class="footer-navlist"> <div class="footer-nav-title"> <h3>Company</h3> </div> <ul class="footer-mainlist"> <li><a href="./about.html">About Us</a></li> <li><a href="./index.html#services">Our Services</a></li> <li><a href="./index.html#events">Our Events</a></li> <li><a href="./blog.html">Blog</a></li> <li><a href="./contact.html">Contact Us</a></li> </ul> </div> <div class="footer-form"> <div class="footer-nav-title"> <h3>Join a Newsletter</h3> </div> <div class="footer-form-cont"> <input type="email" placeholder="Enter Your Email" /> <div> <button class="news-btn">Subscribe</button> </div> </div> <div class="footer-socials"> <div> <i class="fa-brands fa-linkedin"></i> </div> <div> <i class="fa-brands fa-facebook"></i> </div> <div> <i class="fa-brands fa-twitter"></i> </div> <div> <i class="fa-brands fa-instagram"></i> </div> <div> <i class="fa-brands fa-tiktok"></i> </div> <div> <i class="fa-brands fa-youtube"></i> </div> </div> </div> </div> </footer> <!-- Script Tag --> <script src="./js/app.js"></script> <script src="https://kit.fontawesome.com/74b0f74a10.js" crossorigin="anonymous" ></script> <script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" ></script> </body> </html>
import React from 'react'; import ReactDOM from 'react-dom/client'; import { createBrowserRouter, RouterProvider } from "react-router-dom"; import reportWebVitals from './reportWebVitals'; import ErrorPage from './Pages/ErrorPage'; import Header from './Pages/Header/Header'; import Main from './Pages/Main'; import Product from './Pages/Product'; import ProductUpload from './Pages/ProductUpload'; import './index.css'; const router = createBrowserRouter([ { path: "/", element: <Header />, errorElement: <ErrorPage />, children: [ { path: "/", element: <Main />, }, { path: "/product/:productId", element: <Product />, }, { path: "/product/new", element: <ProductUpload /> } ], } ]) 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();
/** * Formata o tempo total em segundos para a impressão * * @param timeInSeconds Tempo total em segundos * * @returns Retorna o tempo formatado em "HH:MM:SS" */ export default function formatTime(timeInSeconds: number): string { const hours = Math.floor(timeInSeconds / (60 * 60)) const minutes = Math.floor(timeInSeconds % (60 * 60) / 60) const seconds = timeInSeconds % 60 if (hours) { return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}` } else { return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}` } }
import 'package:SMP/theme/common_style.dart'; import 'package:SMP/utils/Strings.dart'; import 'package:SMP/utils/size_utility.dart'; import 'package:flutter/material.dart'; class AdminOpenIssiesGridViewCard extends StatefulWidget { final Function press; final List users; final String baseImageIssueApi; final List selectedIssues; final Function(List) onSelectedMembersChanged; const AdminOpenIssiesGridViewCard({ super.key, required this.users, required this.press, required this.baseImageIssueApi, required this.selectedIssues, required this.onSelectedMembersChanged, }); @override State<AdminOpenIssiesGridViewCard> createState() => _AdminOpenIssiesGridViewCardState(); } class _AdminOpenIssiesGridViewCardState extends State<AdminOpenIssiesGridViewCard> { bool showSecurtiy = true; @override Widget build(BuildContext context) { return Container( child: ListView.builder( itemCount: widget.users.length, itemBuilder: (context, index) { final user = widget.users[index]; var issueCatagory = user.issueCatagory.catagoryName .replaceAll("ISSUE_CATAGORY_", "") .toUpperCase(); var issuePriority = user.issuePriority.priorityName .replaceAll("ISSUE_PRIORITY_", "") .toUpperCase(); final isSelected = widget.selectedIssues.contains(user); return Stack( clipBehavior: Clip.none, children: [ Padding( padding: const EdgeInsets.symmetric( vertical: 5, ), child: Column( children: [ GestureDetector( onLongPress: () { setState(() { widget.selectedIssues.add(user); widget .onSelectedMembersChanged(widget.selectedIssues); }); }, onTap: () { if (widget.selectedIssues.isNotEmpty) { setState(() { if (widget.selectedIssues.contains(user)) { widget.selectedIssues.remove(user); } else { widget.selectedIssues.add(user); } widget.onSelectedMembersChanged( widget.selectedIssues); }); } else { widget.press(user); } }, child: Container( decoration: AppStyles.selectedDecoration(context, isSelected), margin: const EdgeInsets.symmetric( horizontal: 5.0, vertical: 6.0), child: Column( children: [ Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.only( left: FontSizeUtil.SIZE_08, top: FontSizeUtil.SIZE_05), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ if (user.issuePriority.priorityName == Strings.ISSUE_PRIORITY_HIGH) Padding( padding: EdgeInsets.only( left: FontSizeUtil.SIZE_05, top: FontSizeUtil.SIZE_05), child: const Icon( Icons.circle, color: Colors.red, ), ) else if (user .issuePriority.priorityName == Strings.ISSUE_PRIORITY_MEDIUM) Padding( padding: EdgeInsets.only( left: FontSizeUtil.SIZE_05), child: const Icon( Icons.circle, color: Colors.orange, ), ) else if (user .issuePriority.priorityName == Strings.ISSUE_PRIORITY_LOW) Padding( padding: EdgeInsets.only( left: FontSizeUtil.SIZE_05), child: const Icon(Icons.circle, color: Colors.yellow), ), const SizedBox( width: 10, ), Text( issuePriority .substring(0, 1) .toUpperCase() + issuePriority .substring(1) .toLowerCase(), style: AppStyles.heading1(context), maxLines: 1, overflow: TextOverflow.ellipsis, ), ], ), ], ), ), ), SizedBox( child: ListTile( contentPadding: EdgeInsets.symmetric( horizontal: FontSizeUtil.SIZE_10, vertical: FontSizeUtil.SIZE_10), title: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text( Strings.ISSUE_ID, style: AppStyles.heading1(context), ), Expanded( child: Text( user.issueUniqueId, style: AppStyles.blockText(context), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), Row( children: [ Text( Strings.ISSUE_DESCRIPTION, style: AppStyles.heading1(context), ), Expanded( child: Text( user.description, style: AppStyles.blockText(context), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ], ), Row( children: [ Text( Strings.ISSUE_CATAGORY, style: AppStyles.heading1(context), ), Text( issueCatagory .substring(0, 1) .toUpperCase() + issueCatagory .substring(1) .toLowerCase(), style: AppStyles.blockText(context), maxLines: 1, overflow: TextOverflow.ellipsis, ), ], ), Row( children: [ Text( Strings.ISSUE_REPORTED_BY, style: AppStyles.heading1(context), ), Expanded( child: Padding( padding: EdgeInsets.symmetric( horizontal: FontSizeUtil.SIZE_08), child: Text( '${user.user.fullName}', style: AppStyles.blockText(context), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ), ], ), ], ), trailing: const Icon( Icons.arrow_forward, color: Color(0xff1B5694), ), ), ), ], ), ), ), ], ), ), ], ); }, ), ); } }
/* p、q分别为指向该二叉树中任意两个结点的指针,设p在q的左边。找到p和q的公共结点r 算发思想:采用后序遍历的非递归算法,使用两个辅助栈,一个栈存放p的所有祖先结点,另一个存放q的所有祖先结点,再从栈顶开始逐个匹配,第一个匹配的元素即为最近公共结点 */ #include <stdio.h> #include <stdlib.h> #define ElemType int typedef struct BiTNode { ElemType data; struct BiTNode *lchild, *rchild; } BiTNode, *BiTree; //先序遍历递归建立二叉链表 void CreateBiTree(BiTree &T) { ElemType ch; scanf("%d",&ch); if(ch == 0) { //递归结束,建立树 T = NULL; } else{ //生成根节点 T = (BiTNode *) malloc(sizeof(BiTNode)); T->data = ch; CreateBiTree(T->lchild); //递归创建左子树 CreateBiTree(T->rchild); //递归创建右子树 } } //链栈 typedef struct LNode { BiTNode *data; struct LNode *next; } LNode, *LinkStack; //初始化(带头结点) bool InitStack(LinkStack &S) { S = (LNode *) malloc(sizeof(LNode)); //内存不足,分配失败 if (S == NULL) return false; S->next = NULL; return true; } //判断栈是否为空(带头结点) bool StackEmpty(LinkStack S) { if (S->next == NULL) return true; else return false; } //入栈(带头结点) void Push(LinkStack &S, BiTNode *x) { LNode *node = (LNode *) malloc(sizeof(LNode)); node->data = x; node->next = S->next; S->next = node; } //出栈(带头结点) BiTNode * Pop(LinkStack &S) { if (S->next == NULL) return NULL; LNode *temp; temp = S->next; S->next = temp->next; BiTNode *tnode = temp->data; free(temp); return tnode; } BiTNode * GetTop(LinkStack S) { return S->next->data; } //判断栈中是否含有某个元素 bool Contain(LinkStack S, BiTNode *node) { if (StackEmpty(S)) return false; LNode *temp = S->next; while (temp) { if (temp->data == node) return true; temp = temp->next; } return false; } void visit(BiTNode *p) { printf("%d ", p->data); } void FindAllAncestor(BiTree T,LinkStack &S, BiTNode *node) { BiTNode *m = T; BiTNode *r = NULL; while (m || !StackEmpty(S)) { //走到最左边 if (m) { Push(S, m); m = m->lchild; } else { m = GetTop(S); //若右子树存在且未被访问过 if (m->rchild && m->rchild != r) { m = m->rchild; } else { m = Pop(S); if (m->data == node->data) //我他妈的疯了,把==写成=了,调试了2个小时,啊啊啊啊啊啊,我的时间啊啊啊啊啊 break; //记录最近访问过的结点 r = m; //结点访问完重置p指针 m = NULL; } } } } BiTNode * FindCommonAncestor(BiTree T, BiTNode *p, BiTNode *q) { LinkStack A, B; InitStack(A); InitStack(B); FindAllAncestor(T, A, p); FindAllAncestor(T, B, q); BiTNode *node; while (!StackEmpty(A)) { node = GetTop(A); if (Contain(B, node)) break; Pop(A); } return node; } int main() { BiTree T; CreateBiTree(T); BiTNode *p = T->lchild->lchild; BiTNode *q = T->rchild->rchild; BiTNode *node = FindCommonAncestor(T, p, q); visit(node); return 0; }
'''From Youtube channel 0612 TV w/ NERDfirst https://www.youtube.com/watch?v=y1ahOBeyM40 January 17, 2019''' import copy import time start = time.time() hard = '.........5.3.67...9..3421.......4.....1...72...2.1.....3......9.8.1..2.....75.8.6' expert = '....7..6....185..945.9........8...1.62.........3.....7...4.6...3.........48.5.19.' evil = '85..7.4...7.2......6...9...9...6....3.8...7.1....2...5...8...2......1.9...7.3..58' easy1 = "..3.2.6..9..3.5..1..18.64....81.29..7.......8..67.82....26.95..8..2.3..9..5.1.3.." easy2= '6..874.1...9.36......19.8..7946.......1.894.....41..69.7..5..9..539.76..9.2.61.47' #board = [] total = 0 def printBoard(board): #global board for row in board: print(row) def solve(b): global total #board,total try: fillAllObvious(b) except: return False if isComplete(b): return True i,j = 0,0 #look for blank squares for rowIdx,row in enumerate(b): for colIdx,col in enumerate(row): if col != '.': continue else: i,j = rowIdx,colIdx #get possibilities for that square possibilities = getPossibilities(b,i,j) for value in possibilities: #save the board before changing snapshot = copy.deepcopy(b) #place the value in that square b[i][j] = value #solve with that value result = solve(b) #if it solves it, we're done if result: total += int(b[0][0])+int(b[0][1])+int(b[0][2]) return True #otherwise, return to saved board else: b = copy.deepcopy(snapshot) return False def fillAllObvious(board): #if there are any obvious moves, fill them #global board while True: somethingChanged = False #go through all squares, filling if you can #if there are no changes, return for i in range(9): for j in range(9): possibilities = getPossibilities(board,i,j) #no possibilities for that square if possibilities == False: continue if len(possibilities) == 0: raise RuntimeError("No Moves Left") #if there's only one possibility, fill it if len(possibilities) == 1: board[i][j] = possibilities[0] somethingChanged = True if not somethingChanged: return def getPossibilities(board,i,j): #global board #if square isn't empty, no possibilities if board[i][j] != '.': return False possibilities = {str(n) for n in range(1,10)} #take away values in row for val in board[i]: possibilities -= set(val) #take away values in column for idx in range(9): possibilities -= set(board[idx][j]) #take away values in block iStart = (i // 3) * 3 jStart = (j // 3) * 3 block = board[iStart:iStart + 3] for idx, row in enumerate(block): block[idx] = row[jStart:jStart+3] for row in block: for col in row: possibilities -= set(col) return list(possibilities) def isComplete(board): #global board for row in board: for col in row: if col == '.': return False return True def displayBoard(board): '''displays Sudoku board''' sz = 50 for r,row in enumerate(board): for c,col in enumerate(row): y,x = r*sz+sz/2.0, c*sz+sz/2.0 noFill() strokeWeight(1) rect(x,y,sz,sz) fill(0) text(col,x-sz/6.0,y+sz/6.0) strokeWeight(2) line(3*sz,0,3*sz,9*sz) line(6*sz,0,6*sz,9*sz) line(0,3*sz,9*sz,3*sz) line(0,6*sz,9*sz,6*sz) def main(): #global board with open('p096_sudoku.txt','r') as f: data = f.read().split() print(data[:10]) #list of strings total = 0 #this many games for i in range(2): strboard = '' for j in range(2,11): strboard += data[11*i+j] #printBoard(strboard) #strboard = sum(strboard) board = [] for i in range(9): board.append([]) for j in range(9): num = strboard[9*i+j] if num == '0': board[i].append('.') else: board[i].append(num) printBoard(board) solve(board) #displayBoard(board) printBoard(board) print("total",total) #elapsed = time.time() - start #print(elapsed)''' if __name__ == '__main__': main()
import { DataTypes, Model } from 'sequelize' import sequelize from '../instance' class User extends Model { } User.init({ id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true, unique: true }, firstname: { type: DataTypes.STRING(45), allowNull: false, }, lastname: { type: DataTypes.STRING(45), allowNull: false, }, password: { type: DataTypes.TEXT, allowNull: false, }, email: { type: DataTypes.STRING(120), allowNull: false, unique: true }, username: { type: DataTypes.STRING(45), allowNull: false, unique: true }, created_at: { type: 'TIMESTAMP', defaultValue: sequelize.literal('CURRENT_TIMESTAMP'), allowNull: true, }, updated_at: { type: 'TIMESTAMP', defaultValue: sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), allowNull: true, }, }, { sequelize, // We need to pass the connection instance modelName: 'user', tableName: 'users', timestamps: false, underscored: true, defaultScope: { attributes: { exclude: ['password'] } } }); export default User;
import * as chalk from 'chalk' import { readTextFile } from '../../lib' const data = readTextFile(__dirname + '/input.txt') enum Opponent { Rock = 'A', Paper = 'B', Scissors = 'C', } export enum Me { Rock = 'X', Paper = 'Y', Scissors = 'Z', } enum ShapeScore { Rock = 1, Paper = 2, Scissors = 3, } enum RoundScore { Win = 6, Draw = 3, } export type RoundInput<T extends string> = `${Opponent} ${T}` type Round<T> = [Opponent, T] const getRound = <T extends string>(input: RoundInput<T>) => input.split(' ') as Round<T> export const getRounds = (data: string) => data.split('\n') const isRoundDraw = (round: Round<Me>) => { const [opponent, me] = round const isRock = opponent === Opponent.Rock && me === Me.Rock const isPaper = opponent === Opponent.Paper && me === Me.Paper const isScissors = opponent === Opponent.Scissors && me === Me.Scissors return isRock || isPaper || isScissors } const isRoundWin = (round: Round<Me>) => { const [opponent, me] = round const isScissorsToPaper = me === Me.Scissors && opponent === Opponent.Paper const isPaperToRock = me === Me.Paper && opponent === Opponent.Rock const isRockToScissors = me === Me.Rock && opponent === Opponent.Scissors return isScissorsToPaper || isPaperToRock || isRockToScissors } const getShapeScore = (round: Round<Me>) => { let result = 0 const [, me] = round switch (me) { case Me.Rock: result += ShapeScore.Rock break case Me.Paper: result += ShapeScore.Paper break case Me.Scissors: result += ShapeScore.Scissors break } return result } const getRoundScore = (round: Round<Me>) => { let result = 0 if (isRoundWin(round)) { result += RoundScore.Win } if (isRoundDraw(round)) { result += RoundScore.Draw } return result } const getScore = (round: Round<Me>) => { const roundScore = getRoundScore(round) const shapeScore = getShapeScore(round) return roundScore + shapeScore } export const getPart1 = (rounds: RoundInput<Me>[]) => { return rounds.reduce((acc, curr) => { const round = getRound<Me>(curr) const score = getScore(round) return acc + score }, 0) } export enum Result { Loss = 'X', Draw = 'Y', Win = 'Z', } const getLossResult = (opponent: Opponent) => { switch (opponent) { case Opponent.Paper: return Me.Rock case Opponent.Rock: return Me.Scissors case Opponent.Scissors: return Me.Paper } } const getDrawResult = (opponent: Opponent) => { switch (opponent) { case Opponent.Paper: return Me.Paper case Opponent.Rock: return Me.Rock case Opponent.Scissors: return Me.Scissors } } const getWinResult = (opponent: Opponent) => { switch (opponent) { case Opponent.Paper: return Me.Scissors case Opponent.Rock: return Me.Paper case Opponent.Scissors: return Me.Rock } } const getShape = (round: Round<Result>) => { const [opponent, result] = round switch (result) { case Result.Loss: return getLossResult(opponent) case Result.Draw: return getDrawResult(opponent) case Result.Win: return getWinResult(opponent) } } export const getPart2 = (rounds: RoundInput<Result>[]) => { return rounds.reduce((acc, curr) => { const round = getRound<Result>(curr) const me = getShape(round) const [opponent] = round const score = getScore([opponent, me]) return acc + score }, 0) } function main() { const rounds = getRounds(data) const part1 = getPart1(rounds as RoundInput<Me>[]) const part2 = getPart2(rounds as RoundInput<Result>[]) console.log(`Day 02 [Part 1]: ${chalk.yellow(part1)}`) console.log(`Day 02 [Part 2]: ${chalk.yellow(part2)}`) } main()
<?php namespace App\Http\Controllers\Admin\Market; use Illuminate\Http\Request; use App\Models\Market\Product; use App\Http\Controllers\Controller; use App\Http\Requests\Admin\Market\StoreRequest; use App\Http\Requests\Admin\Market\StoreUpdateRequest; use Illuminate\Support\Facades\Log; class StoreController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $products = Product::all(); return view('admin.market.store.index' , compact('products')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function addToStore(Product $product) { return view('admin.market.store.add-to-store', compact('product')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(StoreRequest $request, Product $product) { $product->marketable_number += $request->marketable_number; $product->save(); Log::info("deliverer => {$request->deliverer}, receiver => {$request->receiver}, description => {$request->description}, added => {$request->marketable_number}"); return redirect()->route('admin.market.store.index')->with('swal-success', 'موجودی جدید با موفقیت ثبت شد'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit(Product $product) { return view('admin.market.store.edit' , compact('product')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(StoreUpdateRequest $request, Product $product) { $product->marketable_number = $request->marketable_number; $product->frozen_number = $request->frozen_number; $product->sold_number = $request->sold_number; $product->update(); return redirect()->route('admin.market.store.index')->with('swal-success', 'موجودی با موفقیت اصلاح شد'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ }
import React, { useEffect, useState } from 'react'; import { Message } from './Message'; export const SimpleForm = () => { const [formState, setFormState] = useState({ username: 'marco', email: '[email protected]', }); const { username, email } = formState; const onInputChange = ({ target }) => { const { name, value } = target; setFormState({ ...formState, // Propiedad computada [name]: value, }); }; // NO se recomienda que se usen useEffect sin dependencias. // Es recomendable dividir las responsabilidades en varios useEffect useEffect(() => () => { // console.log('useEffect called once.'); }, []); useEffect(() => () => { // console.log('formState changed!'); }, [formState]); // Tambien se puede usar en propiedades destructuradas, por ejemplo // para que este efecto vaya y compruebe en una peticion asincrona si el email es valido // (Solo se estaria ejecutando cuando el email cambia) useEffect(() => () => { // console.log('email changed!'); }, [email]); return ( <> <h1>Formulario Simple</h1> <hr /> <input type="text" className="form-control" placeholder="Username" name="username" value={username} onChange={onInputChange} /> <input type="text" className="form-control" placeholder="[email protected]" name="email" value={email} onChange={onInputChange} /> {/* Solo para demostrar rapidamente el unmount con el useEffect */} {username === 'marco' && <Message />} </> ); };
import os from datetime import datetime from django.conf import settings import requests import json import random from cdt_newsletter.utils import generate_page_content, create_qmd_file from repository.utils import create_push_request from repository.models import Publication, Conference from cdt_newsletter.models import Newsletter def schedule_api(): """ Retrieve the latest newsletter and filter posts and conferences updated since then. Generate a QMD file with the filtered content and create a push request for it. Returns: None """ newsletter_objects = Newsletter.objects.all() latest_newsletter = newsletter_objects.latest("modified_at") latest_date = latest_newsletter.modified_at posts = Publication.objects.filter( updated_at__range=(latest_date, datetime.now()) ) posts = list(posts.values()) conferences = Conference.objects.filter( updated_at__range=(latest_date, datetime.now()) ) conferences = list(conferences.values()) content = {"posts": posts, "conferences": conferences} current_path = os.getcwd() filepath = current_path + f"/newsletter_frontend/index.qmd" create_qmd_file(filepath) generate_page_content(filepath, content) repo = "newsletter_frontend" path = "index.qmd" print("creating push request") create_push_request( file_path=filepath, folder_name="", repo=repo, path=path )
import {Op} from "sequelize"; export interface Pagination { currentPage?: number; numOfItemsPerPage?: number; numOfPages?: number; nextPage?: number; previousPage?: number; } export const filterQuery = (query: any) => { const queryObject = {...query}; // EXCLUDE To Use Them For Filtering, Sorting, Limit_Fields, Pagination const excludesFields = ["sort", "page", "limit", "fields"]; excludesFields.forEach((field) => delete queryObject[field]); // Build the filter query const filterQuery: any = {}; Object.keys(queryObject).forEach((key) => { const value = queryObject[key]; // Check if the filter value uses a special operator("gt", "lt", "gte", "lte") // For Example : if this endpoint >> {{URL}}/users?role=ADMIN&age_gt=18&age_lt=30 // I Need To reach to this {where: { role: 'ADMIN', age: { [Op.gt]: '18', [Op.lt]: '30' }}} const operator = ["gt", "lt", "gte", "lte"].find((op) => key.includes(`_${op}`) ); if (operator) { const realKey = key.split(`_${operator}`)[0]; const opType = operator === "gt" ? Op.gt : operator === "lt" ? Op.lt : operator === "gte" ? Op.gte : Op.lte; filterQuery[realKey] = { ...filterQuery[realKey], [opType]: value, }; } else { filterQuery[key] = value; } }); // console.log(filterQuery); return filterQuery; }; export default class APIFeatures { public paginationStatus!: Pagination; constructor(private query: any) {} // 1) Filtering filter() { return filterQuery(this.query); } // 2) Sorting sort(): [string, string][] { if (!this.query.sort) { // Default sort by -createdAt return [["createdAt", "DESC"]]; } else { let sortArr: [string, string][] = []; const sortFields = this.query.sort.split(","); sortFields.forEach((sortField: string) => { const direction = sortField.startsWith("-") ? "DESC" : "ASC"; const field = sortField.substring(1); sortArr.push([field, direction]); }); return sortArr; } } // 3) Limit Fields limitFields() { return this.query.fields ? (this.query.fields as string).split(",") : undefined; } // 4) Pagination paginate(totalNumOfDocs: number) { const page = this.query.page * 1 || 1; const limit = this.query.limit * 1 || 10; const offset = (page - 1) * limit; let pagination: Pagination = {}; pagination.currentPage = page; pagination.numOfItemsPerPage = limit; pagination.numOfPages = Math.ceil(totalNumOfDocs / limit); // Q: when nextPage is exist? const lastItemIdxInPage = page * limit; if (lastItemIdxInPage < totalNumOfDocs) { pagination.nextPage = page + 1; } // Q: when previousPage is exist? if (offset > 0) { pagination.previousPage = page - 1; } this.paginationStatus = pagination; return {limit, offset}; } }
package com.chen.graduation.filters; import lombok.Data; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * 耗时过滤器 * * @author CHEN * @date 2023/01/31 */ @WebFilter("/") @Slf4j @Setter @Component @ConditionalOnProperty(value = "timing.enable", havingValue = "true") @ConfigurationProperties(prefix = "timing") public class TimeingFilter implements Filter { /** * 警告时间 * 接口响应超过该时间,打印警告日志 */ private int warningTime = 300; /** * 启用该过滤器 */ private boolean enable = false; @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //获取当前时间 long start = System.currentTimeMillis(); //放行 filterChain.doFilter(servletRequest, servletResponse); //计算耗时 long total = System.currentTimeMillis() - start; //获取请求路径 String requestUri = ((HttpServletRequest) servletRequest).getRequestURI(); //判断时候超过警告时间 if (total > warningTime) { log.warn(requestUri + "接口耗时:{}ms", total); return; } log.info(requestUri + "接口耗时:{}ms", total); } }
# Generate random variates from a theoretical distribution. # distr = name of function, follow conventional R methods. E.g. "norm", "pois", "lnorm", "exp", etc. # The function uses the random generation function for each distribution (if it exists), e.g. for distr="norm", "rnorm" is used. # para = named list with parameters, must match arguments of the specified distribution. # E.g. for distr="norm", see get("rnorm",mode="function") or args("rnorm") # Allows sampling from groups, specified with the argument g. # If a vector g is not supplied, the function uses g and prob to generate a random sample. # Also possible with weighted sampling, argument prob (length of vector must equal number of categories in g). # Output options: print=TRUE (prints data frame with grouping variable and random variates), print=FALSE (only random variates). # Example: # .x <- genRandom(distr="norm", para=list(n=10000, mean=c(1,10,20), sd=c(2,2,2)), catgs=3, print=TRUE) # hist(.x$x, col="lightgrey", breaks=60) # A lot of the code is borrowed from the package fitdistrplus #' @export genRandom <- function(distr, para, catgs=3, g=NULL, prob=NULL, print=FALSE, ...) { # Evaluate input arguments if(class(para) != "list") stop("'para' must be a named list") if (is.null(names(para))) stop("'para' must be a named list") if ((missing(distr) & !missing(para)) || (missing(distr) & !missing(para))) stop("'distr' and 'para' must defined") if (missing(catgs)) stop("'catgs', number of categories must be entered") if (!is.null(g)) if((class(g) %in% c("factor","integer")==FALSE)) stop("Grouping variable 'g' must be numeric") # Random generation from the distribution specified in 'distr' # & Check that the specified function exists. rdistname <- paste("r",distr,sep="") if (distr != "trunc") { if (!exists(rdistname, mode = "function")) stop(paste("The ", rdistname, " function must be defined")) # Check that the input parameters in the list 'para' matches the internal arguments of the function specified. # If not, stop and return error message. densfun <- get(rdistname, mode = "function") nm <- names(para) f <- formals(densfun) args <- names(f) m <- match(nm, args) if (any(is.na(m))) stop(paste("'para' specifies names which are not arguments to ", rdistname)) } # If vector with probabilities is supplied, check that the number of categories matches length of prob. vector if (!missing(prob)) { if (length(prob) != catgs) stop("Length of 'prob' vector must equal number of categories") } # Create grouping variable, if a grouping variable is not supplied by the user: if (is.null(g)) { g <- sample(1:catgs, para[["n"]], replace=TRUE, prob=prob) } # For truncated distributions if (distr == "trunc" | distr == "t3tr") { # Add code for case when spec is missing in rt3tr #if (distr == "t3tr") ... insert(para, 2, c(spec="t")) para.names <- names(para) para.temp <- lapply(3:length(para), function(i) para[[i]][g]) para.temp <- insert(para.temp, ats=1, values=c(para$n), useNames=FALSE) para.temp <- insert(para.temp, ats=2, values=c(para$spec), useNames=FALSE) names(para.temp) <- para.names para <- para.temp x <- do.call(paste("r",distr,sep=""), para) } # For non-truncated distributions else if (distr != "trunc" | distr != "t3tr") { para.names <- names(para) para <- lapply(1:length(para), function(i) para[[i]][g]) names(para) <- para.names x <- do.call(rdistname, para) } else stop("Not a valid distribution") # If print=TRUE, return a data frame with the grouping variable and not only the random variates if (print==TRUE) x <- data.frame(g,x) # Print x }
// // PostDetailsVC.swift // Final Project // // Created by Omar Tharwat on 4/8/22. // Copyright © 2022 Omar Tharwat. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import NVActivityIndicatorView class PostDetailsVC: UIViewController { var post : Post! var comments : [Comment] = [] // Mark : OUTLETS @IBOutlet weak var loaderView: NVActivityIndicatorView! @IBOutlet weak var commentsTableView: UITableView! @IBOutlet weak var userImageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var postTextLabel: UILabel! @IBOutlet weak var postImageView: UIImageView! @IBOutlet weak var numberOfLikesLabel: UILabel! @IBOutlet weak var exitButton: UIButton! @IBOutlet weak var commentTextField: UITextField! @IBOutlet weak var newCommentSV: UIStackView! // Mark : LIFE CYCLE METHODS override func viewDidLoad() { super.viewDidLoad() if UserManger.loggedInUser == nil { newCommentSV.isHidden = true } commentsTableView.delegate = self commentsTableView.dataSource = self exitButton.layer.cornerRadius = exitButton.frame.width / 2 userNameLabel.text = post.owner.firstName + " " + post.owner.lastName postTextLabel.text = post.text numberOfLikesLabel.text = String(post.likes) if let image = post.owner.picture { userImageView.setImageFromStringUrl(stringUrl: image) } userImageView.makeCircularImage() let postImageStringUrl = post.image postImageView.setImageFromStringUrl(stringUrl: postImageStringUrl) // API REQUEST getPostComment() } func getPostComment(){ loaderView.startAnimating() PostAPI.getPostComment(id: post.id) { (commentsResponse) in self.comments = commentsResponse self.commentsTableView.reloadData() self.loaderView.stopAnimating() } } // Mark : ACTIONS @IBAction func closeButtonClick(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func sendButtonClicked(_ sender: Any) { let message = commentTextField.text! if let user = UserManger.loggedInUser { PostAPI.addNewCommentToPost(postId: post.id, userId: user.id, message: message) { self.getPostComment() self.commentTextField.text = "" } } } } extension PostDetailsVC : UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell") as!CommentCell let currentComment = comments[indexPath.row] cell.commentMessageLabel.text = currentComment.message cell.userNameLabel.text = currentComment.owner.firstName + " " + currentComment.owner.lastName if let userImage = currentComment.owner.picture { cell.userImageView.setImageFromStringUrl(stringUrl: userImage) } cell.userImageView.makeCircularImage() return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 101 } }
//Contract based on [https://docs.openzeppelin.com/contracts/3.x/erc721](https://docs.openzeppelin.com/contracts/3.x/erc721) // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma experimental ABIEncoderV2; import "./Rachel.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; contract RachelV2 is Rachel, ERC721EnumerableUpgradeable { bool initializedV2; using CountersUpgradeable for CountersUpgradeable.Counter; function initializeV2() public initializer { require(!initializedV2); initializedV2 = true; __ERC721Enumerable_init(); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { ERC721EnumerableUpgradeable._beforeTokenTransfer(from, to, tokenId); } function _burn(uint256 tokenId) internal virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) { ERC721Upgradeable._burn(tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) returns (bool) { return ERC721Upgradeable.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) { return ERC721URIStorageUpgradeable.tokenURI(tokenId); } struct NFT { uint32 token; string uri; } function getMyNFTs() public view returns (NFT[] memory) { address sender = msg.sender; uint256 numberOfNFTs = balanceOf(sender); NFT[] memory nfts = new NFT[](numberOfNFTs); for (uint256 index = 0; index < numberOfNFTs; index++) { uint256 token = tokenOfOwnerByIndex(sender, index); nfts[index].uri = tokenURI(token); nfts[index].token = uint32(token); } return nfts; } function mintNFTFromUser(string memory uri) public { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(msg.sender, newItemId); _setTokenURI(newItemId, uri); } function getCountOfAllNFTs() public view returns (uint256) { return _tokenIds.current(); } }
import React from 'react'; import { Public_Sans } from 'next/font/google'; import AnswerInput from '@/components/AnswerInput/AnswerInput'; import useRaindrops from '@/hooks/useRaindrops'; import RainDrop from '@/types/RainDrop'; import useAudio from '@/hooks/useAudio'; import ScoreDisplay from '@/components/ScoreDisplay/ScoreDisplay'; import GameControl from '@/components/GameControl/GameControl'; import Raindrop from '@/components/Raindrop/Raindrop'; import useTabVisibility from '@/hooks/useTabVisibility'; const publicSans = Public_Sans({ subsets: ['latin'] }); export default function Home() { const [score, setScore] = React.useState(0); const [gameActive, setGameActive] = React.useState(false); const [raindrops, setRaindrops] = useRaindrops(gameActive); const scoreAudio = useAudio('/ca.mp3'); useTabVisibility({ onHidden: () => setGameActive(false), onVisible: () => setGameActive(true), }); const handleAnswer = (userInput: string) => { const input = parseInt(userInput); const currentTime = Date.now(); const newRainDrops = raindrops.filter((drop: RainDrop) => { // Calculate the animation progress const timeElapsed = currentTime - drop.createdAt; const animationDuration = 8000; // 8 seconds const animationProgress = timeElapsed / animationDuration; // Only consider drops where the animation is not yet complete if (animationProgress < 1) { const isCorrect = input === drop.answer; if (isCorrect) { if (scoreAudio) { scoreAudio.play(); } setScore(score + 500); } return !isCorrect; } return true; // Keep drops that have completed animation }); setRaindrops(newRainDrops); }; return ( <main className={publicSans.className}> <div className=' w-[60%] max-w-[960px] mx-auto mt-12'> <div className='text-[#254052] flex justify-between items-center'> <h1 className='font-semibold mb-4 text-2xl'>Raindrops</h1> <ScoreDisplay score={score} /> </div> <div className='bg-white p-4 border-[#e2e2e2] h-[660px] overflow-hidden relative rounded-md border'> <GameControl gameActive={gameActive} onGameStart={() => setGameActive(true)} /> <div className='bg-[#56b1c5] h-[540px] p-3 w-full overflow-hidden relative rounded-md rounded-b-none'> {raindrops.map((drop: RainDrop) => ( <Raindrop key={drop.id} drop={drop} /> ))} </div> <div className='bg-[#254052] h-[90px] flex items-center justify-center rounded-md rounded-t-none'> <AnswerInput onSubmit={handleAnswer} /> </div> </div> </div> </main> ); }
import copy import matplotlib.pyplot as plt import numpy as np import pandas as pd from src.jguides_2024.utils.array_helpers import min_positive_val_arr from src.jguides_2024.utils.interval_helpers import check_intervals_list from src.jguides_2024.utils.plot_helpers import plot_intervals from src.jguides_2024.utils.stats_helpers import mean_squared_error def event_times_in_intervals_bool(event_times, valid_time_intervals): """ Filter event times for those within valid_intervals :param event_times: array-like with times of events :param valid_time_intervals: nested list with intervals for valid times :return: boolean indicating indices in event_times within valid_time_intervals """ # If no valid_time_intervals, return boolean of False same length as event_times if len(valid_time_intervals) == 0: return np.asarray([False]*len(event_times)) # Otherwise, return boolean indicating which event times are within valid time intervals # (note that in case of empty valid_time_intervals, this returns False which is not what we # want) return np.sum(np.asarray([np.logical_and(event_times >= t1, event_times <= t2) for t1, t2 in valid_time_intervals]), axis=0) > 0 def event_times_in_intervals(event_times, valid_time_intervals): """ Filter event times for those within valid_intervals :param event_times: array-like with times of events :param valid_time_intervals: nested list with intervals for valid times :return: array with indices (from np.where) in original event_times of valid event times :return: array with valid event times """ event_times = np.asarray(event_times) valid_bool = event_times_in_intervals_bool(event_times, valid_time_intervals) return np.where(valid_bool)[0], event_times[valid_bool] def bins_in_intervals_bool(valid_intervals, bin_centers, bin_edges=None): bin_starts, bin_ends = copy.deepcopy(bin_centers), copy.deepcopy(bin_centers) # default if bin_edges is not None: bin_starts, bin_ends = list(map(np.asarray, list(zip(*bin_edges)))) return np.sum(np.vstack([event_times_in_intervals_bool(x, valid_intervals) for x in [bin_centers, bin_starts, bin_ends]]), axis=0) == 3 def bins_in_intervals(valid_intervals, bin_centers, bin_edges=None, verbose=False): valid_bool = bins_in_intervals_bool(valid_intervals, bin_centers, bin_edges) valid_bin_centers = bin_centers[valid_bool] # Plot if indicated if verbose: fig, ax = plt.subplots(figsize=(12, 2)) plot_intervals(valid_intervals, label="valid_intervals", ax=ax) ax.plot(valid_bin_centers, [1]*len(valid_bin_centers), 'x', color="red", label="valid_bin_centers") return valid_bin_centers def calculate_average_event_rate(event_times, valid_time_intervals): """ Calculate average event rate during a time interval :param event_times: array-like with times of events :param valid_time_intervals: nested list with intervals for valid times :return: """ if len(np.shape(valid_time_intervals)) != 2 or np.shape(valid_time_intervals)[1] != 2: raise Exception(f"valid_intervals must be n by 2 array, but has shape {np.shape(valid_time_intervals)}") _, valid_event_times = event_times_in_intervals(event_times, valid_time_intervals) return len(valid_event_times)/np.sum(np.diff(valid_time_intervals)) def ideal_poisson_error(observed_counts, num_ideal_trials=100): observed_counts_arr = np.tile(observed_counts, (num_ideal_trials, 1)) return mean_squared_error(np.random.poisson(observed_counts_arr), observed_counts_arr) def not_small_diff_bool(x, diff_threshold): if len(x) == 0: return np.asarray([]) x_diff = np.diff(x) valid_bool = x_diff > diff_threshold return (np.concatenate(([True], valid_bool)) * np.concatenate((valid_bool, [True]))) # True if x value is NOT part of small gap pair def get_event_times_relative_to_trial_start(event_times, trial_intervals, trial_start_time_shift=0): """ Get time of each event from start of trial in which event occurs, and express relative to unshifted trials. For example, if interested in spike times (these are the event times) during well arrival trials (these provide the trial times) with minus/plus one second shift, express spike times on domain: -1 to 1 second around well arrival :param event_times: list of event times (e.g. spike times) :param trial_intervals: list of trial start/end times ([[trial start, trial end], ...]) :param trial_start_time_shift: how much the start times of trials was shifted relative to an event of interest. We add this to event times relative to trials to express these in terms of the time of the event of interest :return: event times relative to trial start """ # Check trial intervals well defined check_intervals_list(trial_intervals) # Get event times within trial intervals (reduces size of computation below) event_times_in_trials_idxs, event_times_trials = event_times_in_intervals(event_times, trial_intervals) # Get time of each event from start of each trial. In array below, event times vary along columns # and trial start times vary along rows event_times_rel_all_trials_start = np.tile(event_times_trials, (len(trial_intervals), 1)) - \ np.tile(trial_intervals[:, 0], (len(event_times_trials), 1)).T # For each spike time, take the smallest positive (positive -> after trial start) relative time event_times_rel_trial_start = min_positive_val_arr(event_times_rel_all_trials_start, axis=0) + \ trial_start_time_shift return event_times_rel_trial_start, event_times_in_trials_idxs def get_full_event_times_relative_to_trial_start(event_times, trial_intervals, trial_start_time_shift=0): # Ensure trial intervals ias array trial_intervals = np.asarray(trial_intervals) # Initialize vector same length as event times relative_times = np.asarray([np.nan]*len(event_times)) # Get event times relative to trial start, for event times within trials valid_relative_times, valid_idxs = get_event_times_relative_to_trial_start(event_times, trial_intervals, trial_start_time_shift) relative_times[valid_idxs] = valid_relative_times return pd.Series(relative_times, index=event_times)
import { UserAlreadyExistsError } from "@/services/errors/user-already-exists-error" import { MakeUserRegisterService } from "@/services/factories/make-userRegister-service" import { FastifyRequest, FastifyReply } from "fastify" import { z } from "zod" export async function userRegister(req: FastifyRequest, res: FastifyReply) { const registerBodySchema = z.object({ name: z.string(), email: z.string().email(), password: z.string().min(6), }) const {name, email, password} = registerBodySchema.parse(req.body) try { const userRegisterService = MakeUserRegisterService() await userRegisterService.execute({name, email, password}) } catch (error) { if(error instanceof UserAlreadyExistsError){ return res.status(409).send({error: error.message}) } throw error } return res.status(201).send() }
import React, { ChangeEvent, useState, ChangeEventHandler, FormEvent } from 'react'; import Box from '@mui/material/Box'; import TextField from '@mui/material/TextField'; import Button from '@mui/material/Button'; import Stack from '@mui/material/Stack'; import { Typography } from '@mui/material'; import { IUserModel } from '../../store/slices/authSlice'; import AuthService from "../../services/auth.service"; import { ILoginProps } from '../../models/login.model'; import {Link } from 'react-router-dom'; import {useDispatch, useSelector} from 'react-redux'; import { tryLogin} from '../../store/store'; type Props = {}; type State = { redirect: string | null, username: string, password: string, loading: boolean, message: string }; export const BasicForm = (loginProps: ILoginProps) => { const dispatch = useDispatch(); const [loginInfo, setLoginInfo] = useState<IUserModel>(); const handleLogin = (event: FormEvent<HTMLFormElement>) => { console.log("HandleLogin", loginInfo) event.preventDefault(); if (loginInfo?.username && loginInfo?.password){ console.log("Does this get hit?") // AuthService.login(loginInfo.username, loginInfo.password) const loginActionInfo: IUserModel = { username: loginInfo.username, password: loginInfo.password } dispatch(tryLogin(loginActionInfo)) } } const handleUserNameInput = (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>{ setLoginInfo({ username: event.target.value, password: loginInfo?.password }) console.log("LOGIN INFO",loginInfo) } const handlePasswordInput = (event: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) =>{ setLoginInfo({ username: loginInfo?.username, password: event.target.value }) } return ( <form onSubmit={handleLogin} action=""> <Typography> <TextField id="username" name="username" label="Username" variant="filled" onChange={handleUserNameInput}/> </Typography> <Typography> <TextField id="filled-password-input" label="Password" type="password" autoComplete="current-password" variant="filled" name="password" onChange={handlePasswordInput} /> </Typography> <Button type="submit" variant="outlined">{loginProps.formName}</Button> </form> ) }
var provider = require("/demandables/provider"); var serviceFactory = require("/demandables/services/servicefactory"); var util = require("/demandables/util"); var log = require("log"); log.setLevel("info"); var document = require("document"); const MIN_CAPACITY = 8; /** * This class implements the behavior of a basic waste bi provider, i.e. it can be invoked by trucks * to find an empty bin that is closer to them and obtain the route to that bin. * "Reassignable" workers will obtain an updated waste bin location/route everytime their run() method is executed * based on their current location * @class WasteBinProvider * @extends Provider */ function WasteBinProvider(dto) { provider.Provider.call(this); this.wastemgtservice = serviceFactory.getService("wastemgtservice"); this.directionService = serviceFactory.getService("directionservice"); } WasteBinProvider.prototype = new provider.Provider(); WasteBinProvider.prototype.constructor = WasteBinProvider; /** * Return the closer available waste bin to the worker and the route to that bin. * Distance is used, not traffic conditions. * @method getPurpose * @param {Object} mobileWorker: an instance of MobileWorker or any of its subclasses * @param {Object} params: optional. Additional parameters needed to customize the method * @return {Object} { * {String}id: binId, * {Number}latitude, * {Number}longitude, * {Number}capacity, * {Object} route { {Number} duration: time to reach bin in seconds, {Array}points where point is {Array}(lat,long)} */ WasteBinProvider.prototype.getPurpose = function(mobileWorker, params) { var currentLocation = mobileWorker.getCurrentLocation(); var point = util.toPoint(currentLocation); var bin = this._findWasteBinCloserToLocation(point.latitude, point.longitude); if (bin && bin.id) { var route = this.directionService.getRoute(currentLocation, bin.latitude + "," + bin.longitude); var purpose = { id: bin.id, targetLocation: bin.latitude + "," + bin.longitude, route:route }; log.info("Purpose target location " + JSON.stringify(purpose.targetLocation)); return purpose; } return {}; }; /** * Find a full bin with the shortest distance to the worker. Although this is not optimal (as it does not take into account * traffic conditions and traffic directions), it is very fast to execute * @method _findWasteBinCloserToLocation */ WasteBinProvider.prototype._findWasteBinCloserToLocation = function(lat, lon) { log.info("WasteBinProvider --> WasteMgtService is " + JSON.stringify(this.wastemgtservice)); var shortest = {}; var minDistance = 1000000000000000; try { var transaction = apsdb.beginTransaction(); var bins = this.wastemgtservice.listBins(lat + "," + lon, 200, {lock:true}); for (var i = 0; i < bins.length; i++) { var distanceToBin = util.getDistanceFromLatLon(lat, lon, bins[i].latitude, bins[i].longitude); log.info("WasteBinProvider --> checking " + JSON.stringify(bins[i])); if (distanceToBin < minDistance && bins[i].capacity <= MIN_CAPACITY && !bins[i].assigned) { minDistance = distanceToBin; shortest = bins[i]; } } // if bin found specify that it was assigned to a truck if (shortest.id){ log.info("WasteBinProvider found Bin " + JSON.stringify(shortest)); this.wastemgtservice.assignBin(shortest.id); transaction.commit(); }else { transaction.rollback(); } }catch(exception) { log.error("WasteBinProvider._findWasteBinCloserToLocation: error occurred while searching for bin. " + JSON.stringify(exception)); if (transaction) { transaction.rollback(); } } return shortest; };
package slogtest import ( "log/slog" "regexp" "slices" "github.com/stretchr/testify/assert" ) type Matcher struct { inplaceAssertF []func(t assert.TestingT, record slog.Record) afterAssertF []func(t assert.TestingT, records []slog.Record) t assert.TestingT handlerAssertF []func() } func NewMatcher(t assert.TestingT) *Matcher { return &Matcher{t: t} } func (m Matcher) WithNoLevel(level slog.Level) *Matcher { m.inplaceAssertF = append(m.inplaceAssertF, func(t assert.TestingT, record slog.Record) { assert.NotEqual(m.t, level, record.Level) }) return &m } func (m Matcher) WithNoMsg(msg string) *Matcher { m.inplaceAssertF = append(m.inplaceAssertF, func(t assert.TestingT, record slog.Record) { assert.NotEqual(m.t, msg, record.Message) }) return &m } func (m Matcher) WithNoMsgRegExp(msg *regexp.Regexp) *Matcher { m.inplaceAssertF = append(m.inplaceAssertF, func(t assert.TestingT, record slog.Record) { ok := msg.MatchString(record.Message) if ok { m.t.Errorf("Expect \"%s\" to NOT match \"%s\"", record.Message, msg.String()) } }) return &m } func (m Matcher) WithMsg(msg string) *Matcher { m.afterAssertF = append(m.afterAssertF, func(t assert.TestingT, records []slog.Record) { ok := slices.ContainsFunc(records, func(r slog.Record) bool { return r.Message == msg }) if !ok { m.t.Errorf("Can't find msg \"%s\" in logs", msg) } }) return &m } func (m Matcher) WithMsgRegExp(msg *regexp.Regexp) *Matcher { m.afterAssertF = append(m.afterAssertF, func(t assert.TestingT, records []slog.Record) { ok := slices.ContainsFunc(records, func(r slog.Record) bool { return msg.MatchString(r.Message) }) if !ok { m.t.Errorf("Can't find regexp \"%s\" in logs", msg.String()) } }) return &m } func (m *Matcher) Handler() *Handler { h := NewHandler(m.t, func(record slog.Record) { for _, f := range m.inplaceAssertF { f(m.t, record) } }) m.handlerAssertF = append(m.handlerAssertF, func() { records := h.Records() for _, f := range m.afterAssertF { f(m.t, records) } }) return h } func (m *Matcher) Finish() { for _, f := range m.handlerAssertF { f() } }
<x-app-layout> <link href="{{ asset('assets/css/bootstrap.min.css')}}" rel="stylesheet" /> <div class="modal fade" tabindex="-1" id="deleteModal"> <div class="modal-dialog"> <div class="modal-content"> <form action="{{ route('player.delete') }}" method="post"> @csrf <div class="modal-header"> <h5 class="modal-title">Delete Player</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <input type="hidden" name="player_delete_id" id="player_delete_id"/> <h3>Are you sure want to delete this Player</h3> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-danger">Yes Delete</button> </div> </form> </div> </div> </div> <div class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex py-10" > <h1 style="color: red">All Players</h1><br/><br/> <table class="table"> <thead> <tr style="color: yellow"> <th>Player Name</th> <th>Cap number</th> <th>Matches Played</th> <th>Player Age</th> <th>Action</th> </tr> </thead> <tbody> @foreach ($players as $player) <tr style="color: blue"> <td>{{$player->player_name}}</td> <td>{{$player->cap_number}}</td> <td>{{$player->matches_played}}</td> <td>{{$player->player_age}}</td> <td> <a href="{{ route('player.edit',$player->id) }}" class="btn btn-success">Edit</a> <button type="button" value="{{ $player->id }}" class="btn btn-danger deletePlayerBtn">Delete</button> </td> </tr> @endforeach </tbody> </table> </div> </x-app-layout> <script src="{{ asset('assets/js/jquery-3.6.0.min.js') }}"></script> <script src="{{ asset('assets/js/bootstrap.bundle.min.js') }}"></script> <script> $(document).ready(function() { // $('.deleteCategoryBtn').click(function() { $(document).on('click','.deletePlayerBtn',function() { let player_id = $(this).val(); $('#player_delete_id').val(player_id); $('#deleteModal').modal('show'); }); }); </script>
package gui.dashboard.trainer_dashboard.training_management; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import utils.CustomLogger; import utils.Message; import utils.ValidateData; public class UpdateTrainingWindow extends JFrame { private JPanel mainPanel; private JButton updateButton; private JButton loadGymButton; private JTable reportTable; private DefaultTableModel reportTableModel; public UpdateTrainingWindow(Message message, BufferedReader ReadFromServer, PrintWriter SendToServer, int employeeID) { // Create the main window this.setSize(1024, 768); this.setVisible(true); this.setTitle("Gym Management System | Update Training Window"); // Create the main panel mainPanel = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.insets = new Insets(5, 5, 5, 5); // Create the Update gym panel JPanel updateEmployee = new JPanel(); updateEmployee.setBorder(javax.swing.BorderFactory.createTitledBorder("Update Training")); // Create the update button updateButton = new JButton("Update"); // Add the load gym button to the main panel loadGymButton = new JButton("Load"); updateEmployee.add(loadGymButton); updateEmployee.add(updateButton); mainPanel.add(updateEmployee); // Add the report table reportTableModel = new DefaultTableModel(new String[]{"ID", "Name", "Date", "Start Hour", "End Hour", "Capacity", "Room", "Gym ID", "Gym"}, 0) { @Override public boolean isCellEditable(int row, int column) { // Make the ID column unmodifiable return column != 0; } }; reportTable = new JTable(reportTableModel); JScrollPane scrollPane = new JScrollPane(reportTable); constraints.gridx = 0; constraints.gridy = 4; constraints.gridwidth = 2; constraints.fill = GridBagConstraints.BOTH; constraints.weightx = 1.0; constraints.weighty = 1.0; mainPanel.add(scrollPane, constraints); // Add the report panel to the main window this.add(mainPanel); // Add action listener to the "Load" button loadGymButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Send the message to the server message.sendLoadEmployeeTrainingsMessage(SendToServer, employeeID + ""); // Clear the table reportTableModel.setRowCount(0); // Read the report from the server try { String report = ReadFromServer.readLine(); String[] reportLines = report.split("///"); // Add the report to the report table for (String reportLine : reportLines) { String[] reportLineParts = reportLine.split(","); reportTableModel.addRow(reportLineParts); } } catch (IOException ex) { CustomLogger.logError("Error reading from server: " + ex.getMessage()); } } }); // Add action listener to the update button updateButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Get the selected row int selectedRow = reportTable.getSelectedRow(); // Check if a row is selected if (selectedRow == -1) { JOptionPane.showMessageDialog(null, "Please select a row", "Success", JOptionPane.ERROR_MESSAGE); return; } // check if fields aren't edited if (reportTable.isEditing()) { JOptionPane.showMessageDialog(null, "Please finish editing the table", "Success", JOptionPane.ERROR_MESSAGE); return; } // Get the ID int trainingID = Integer.parseInt(reportTable.getValueAt(selectedRow, 0).toString()); String name = reportTable.getValueAt(selectedRow, 1).toString(); String date = reportTable.getValueAt(selectedRow, 2).toString(); String startHour = reportTable.getValueAt(selectedRow, 3).toString(); String endHour = reportTable.getValueAt(selectedRow, 4).toString(); int capacity = Integer.parseInt(reportTable.getValueAt(selectedRow,5).toString()); String room = reportTable.getValueAt(selectedRow,6).toString(); String gymID = reportTable.getValueAt(selectedRow, 7).toString(); String trainer = employeeID + ""; // if empty fields if (name.isEmpty() || date.isEmpty() || startHour.isEmpty() || endHour.isEmpty() || room.isEmpty() || gymID.isEmpty()) { JOptionPane.showMessageDialog(null, "Please fill all the fields!", "Error", JOptionPane.ERROR_MESSAGE); return; } // Validate the data if (!ValidateData.validateName(name) || !ValidateData.ValidateDate(date) || !ValidateData.ValidateHourRange(startHour, endHour)|| !ValidateData.ValidateCapacity(capacity + "") || !ValidateData.ValidateRoom(room) || !ValidateData.ValidateGymID(gymID)) { return; } // Send the ID to the server message.sendUpdateTrainingMessage(SendToServer, trainingID + "," + name + "," + date + "," + startHour + "," + endHour + "," + capacity + "," + room + "," + trainer + "," + gymID); try { // Get the response from the server String response = ReadFromServer.readLine(); if (response.equals("True")) { JOptionPane.showMessageDialog(null, "Training updated successfully!", "Success", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Training update failed! Trainer is busy or the room is occupied!", "Error", JOptionPane.ERROR_MESSAGE); } } catch (IOException e1) { CustomLogger.logError("Error reading from server: " + e1.getMessage()); } } }); } }
<template> <q-btn icon="logout" :label="$t('components.internal.auth.logout.buttonLabel')" class="btnAuth" @click="onLogout" /> </template> <script setup lang="ts"> import { Notify } from 'quasar'; import { useRouter } from 'vue-router'; import { logoutUser } from 'src/services/AuthServices/login-service'; import { useI18n } from 'vue-i18n'; const { t } = useI18n({ useScope: 'global' }); const router = useRouter() async function onLogout() { try { const sucess = await logoutUser(); if (sucess) { Notify.create({ progress: true, color: 'positive', textColor: 'white', icon: 'fa-solid fa-circle-check', message: t('components.internal.auth.logout.notificationMessage'), }); router.push({ name: 'login' }) } } catch (error) { console.log(error) } } </script> <style lang="scss"> .btnAuth { background-image: linear-gradient(92.88deg, #455EB5 9.16%, #5643CC 43.89%, #673FD7 64.72%); color: $white; border-radius: 8px; border-style: none; box-sizing: border-box; flex-shrink: 0; text-shadow: rgba(0, 0, 0, 0.25) 0 3px 8px; transition: all .5s; user-select: none; -webkit-user-select: none; touch-action: manipulation; &:hover { box-shadow: rgba(80, 63, 205, 0.5) 0 1px 30px; transition-duration: .1s; } } @media (min-width: $breakpoint-md-max) { .btnAuth { padding: 0 2.6rem; } } </style>
// // Network.swift // MovieAppCase // // Created by Toygun Çil on 21.09.2022. // import Foundation import Alamofire let apiKey = "9c61371b" let baseUrl = "https://www.omdbapi.com/?" struct Endpoint { static let searchTitle = "s=" static let detailId = "i=" static let searchType = "&type=movie" static let apiKey = "&apikey=" } class Network { static let sharedNetwork = Network() private init() {} func getSearchData(with movieTitle: String?, completion: @escaping (Result<MovieListResponse, AFError>) -> Void) { if let movieTitle = movieTitle{ let searchUrl = "\(baseUrl)\(Endpoint.searchTitle)\(String(describing: movieTitle ))\(Endpoint.searchType)\(Endpoint.apiKey)\(apiKey)" AF.request(searchUrl, method: .get).responseDecodable(of: MovieListResponse.self) { movieResponse in completion(movieResponse.result) } } } func getDetailData(with movieId: String?, completion: @escaping (Result<MovieDetailResponse,AFError>) -> Void) { if let movieId = movieId { let detailUrl = "\(baseUrl)\(Endpoint.detailId)\(movieId)\(Endpoint.apiKey)\(apiKey)" AF.request(detailUrl, method: .get).responseDecodable(of: MovieDetailResponse.self) { detailResponse in completion(detailResponse.result) } } } }
import { HttpClientModule } from '@angular/common/http'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BrowserModule } from '@angular/platform-browser'; import { NgModule, LOCALE_ID } from '@angular/core'; import { TableModule } from 'primeng/table'; import { AppComponent } from './app.component'; import { CoreModule } from './core/core.module'; import localeFr from '@angular/common/locales/pt'; import { registerLocaleData } from '@angular/common'; import { ToastyModule } from 'ng2-toasty'; import { AppRoutingModule } from './app-routing.module'; import { LoginFormComponent } from './seguranca/login-form/login-form.component'; import { SegurancaModule } from './seguranca/seguranca.module'; registerLocaleData(localeFr); @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, BrowserAnimationsModule, HttpClientModule, TableModule, CoreModule, SegurancaModule, AppRoutingModule, ToastyModule.forRoot() ], providers: [ ], bootstrap: [AppComponent] }) export class AppModule { }
# TODO List That's a simples CRUD of a Todo card. The main purpose is to exercise somethings and also learn others. ## What you'll find here? * Go * Docker * Rest API * Postgres * OpenTelemetry * Prometheus (soon..) * Grafana (soon..) * Kubernetes (soon..) * Kong API Gateway (soon..) ## How to run in Docker You must have docker and docker compose installed on your machine To start the database and application run, if running in a linux with make installed run: `make start` and to shut down server `make stop` If you don't have make on your system then run from the root folder: `docker compose up -f build/docker-compose.yaml` to start the database and application and `docker compose down -f build/docker-compose.yaml` to stop. ## How to run in K8S with Kind You'll also need to have docker installed on your machine. Further information soon. ## Tips Before the following code it's necessary to configure the TextMapPropagator just like this: ```go otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator(propagation.TraceContext{}, propagation.Baggage{})) ``` Here's a reference link to link for [b3](https://opentelemetry.io/docs/instrumentation/go/manual/#propagators-and-context). Now, if needed to pass the open telemetry headers (w3c,b3,..) you can use the following code, i'm using resty to do the http call, but the relevant part is related to otel. ```go url := "your_url" client := resty.New() req := client. R(). SetContext(ctx). EnableTrace() // the magic happens here otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(req.Header)) resp, err := req.Get(url) ``` ## Observability | Name | Url | |------------|-------------------------| | Jaeger | http://localhost:16686/ | | Prometheus | http://localhost:9090/ | | Grafana | http://localhost:3000/ |
<?php /** * The admin-specific functionality of the plugin. * * @link https://www.maciejziemichod.com * @since 1.0.0 * * @package Graph_Widget * @subpackage Graph_Widget/admin */ /** * The admin-specific functionality of the plugin. * * Defines the plugin name, version, and two examples hooks for how to * enqueue the admin-specific stylesheet and JavaScript. * * @package Graph_Widget * @subpackage Graph_Widget/admin * @author Maciej Ziemichód <[email protected]> */ class Graph_Widget_Admin { /** * The ID of this plugin. * * @since 1.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private string $plugin_name; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private string $version; /** * ID of the dashboard widget. * * @since 1.0.0 * @access private * @var string $widget_id ID of the dashboard widget. */ private string $widget_id; /** * Initialize the class and set its properties. * * @param string $plugin_name The name of this plugin. * @param string $version The version of this plugin. * @param string $widget_id ID of the dashboard widget. * * @since 1.0.0 */ public function __construct( string $plugin_name, string $version, string $widget_id ) { $this->plugin_name = $plugin_name; $this->version = $version; $this->widget_id = $widget_id; } /** * Register the stylesheets for the admin area. * * @param string $hook_suffix Current admin page hook. * * @return void * @since 1.0.0 */ public function enqueue_styles( string $hook_suffix ): void { /** * This function is provided for demonstration purposes only. * * An instance of this class should be passed to the run() function * defined in Graph_Widget_Loader as all of the hooks are defined * in that particular class. * * The Graph_Widget_Loader will then create the relationship * between the defined hooks and the functions defined in this * class. */ if ( ! $this->is_admin_dashboard_page( $hook_suffix ) ) { return; } wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'build/index.css', array(), $this->version ); } /** * Checks if page hook is for admin dashboard page. * * @param string $hook Admin page hook. * * @return bool */ private function is_admin_dashboard_page( string $hook ): bool { return 'index.php' === $hook; } /** * Register the JavaScript for the admin area. * * @param string $hook_suffix Current admin page hook. * * @return void * @since 1.0.0 */ public function enqueue_scripts( string $hook_suffix ): void { /** * This function is provided for demonstration purposes only. * * An instance of this class should be passed to the run() function * defined in Graph_Widget_Loader as all of the hooks are defined * in that particular class. * * The Graph_Widget_Loader will then create the relationship * between the defined hooks and the functions defined in this * class. */ if ( ! $this->is_admin_dashboard_page( $hook_suffix ) ) { return; } wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'build/index.js', array(), $this->version, array( 'strategy' => 'defer' ) ); } /** * Registers plugin REST route. * * @return void */ public function register_rest_route(): void { register_rest_route( "{$this->plugin_name}/v1", '/data', array( 'methods' => 'GET', 'callback' => array( $this, 'get_data' ), 'args' => array( 'count' => array( 'validate_callback' => fn( mixed $param ): bool => is_numeric( $param ), ), ), ) ); } /** * Controller for /data endpoint. * * @param WP_REST_Request $request REST request object. * * @return WP_REST_Response */ public function get_data( WP_REST_Request $request ): WP_REST_Response { $data = get_option( GRAPH_WIDGET_OPTION_KEY ); if ( false === $data ) { return $this->get_error_rest_response( 'Failed to retrieve data', 502 ); } $requested_range = $request->get_param( 'count' ); if ( null === $requested_range ) { return $this->get_error_rest_response( 'Missing required "count" parameter' . $requested_range, 400 ); } $length = count( $data ); if ( $length < $requested_range ) { return $this->get_error_rest_response( "Don't have enough data", 500 ); } $requested_data = array_slice( $data, $length - $requested_range ); return new WP_REST_Response( $requested_data ); } /** * Used to retrieve uniformed error REST response. * * @param string $message Error message. * @param int $status Response status code. * * @return WP_REST_Response */ private function get_error_rest_response( string $message, int $status ): WP_REST_Response { return new WP_REST_Response( array( 'message' => $message ), $status ); } /** * Register plugin dashboard widget. * * @return void */ public function add_dashboard_widget(): void { wp_add_dashboard_widget( $this->widget_id, 'Graph Widget', array( $this, 'render_widget' ) ); } /** * Renders widget container. * * @return void */ public function render_widget(): void { echo '<div class="root"></div>'; } }
<!DOCTYPE html> <html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"> <head> <th:block th:include="include :: header('卡片分组信息列表')" /> </head> <body class="gray-bg"> <div class="container-div"> <div class="row"> <div class="col-sm-12 search-collapse"> <form id="formId"> <div class="select-list"> <ul> <li> <label>分组名称:</label> <input type="text" name="terminalGroupName"/> </li> <li> <label>分组层级</label> <input type="text" name="terminalGroupLevel"/> </li> <li> 启用禁用: <select name="enableFlag" > <option value="">所有</option> <option value="1">启用</option> <option value="0">禁用</option> </select> </li> <li> <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a> <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a> </li> </ul> </div> </form> </div> <div class="btn-group-sm" id="toolbar" role="group"> <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="terminal:group:add"> <i class="fa fa-plus"></i> 添加 </a> <a class="btn btn-primary single disabled" onclick="$.operate.edit()" shiro:hasPermission="terminal:group:edit"> <i class="fa fa-edit"></i> 修改 </a> <a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="terminal:group:remove"> <i class="fa fa-remove"></i> 删除 </a> <a class="btn btn-warning" onclick="$.table.exportExcel()" shiro:hasPermission="terminal:group:export"> <i class="fa fa-download"></i> 导出 </a> </div> <div class="col-sm-12 select-table table-striped"> <table id="bootstrap-table"></table> </div> </div> </div> <th:block th:include="include :: footer" /> <script th:inline="javascript"> var editFlag = [[${@permission.hasPermi('terminal:group:edit')}]]; var removeFlag = [[${@permission.hasPermi('terminal:group:remove')}]]; var prefix = ctx + "terminal/group"; $(function() { var options = { url: prefix + "/list", createUrl: prefix + "/add", updateUrl: prefix + "/edit/{id}", removeUrl: prefix + "/remove", exportUrl: prefix + "/export", modalName: "卡片分组", columns: [{ checkbox: true }, { field : 'terminalGroupId', title : '分组主键id', align: "center", visible: false }, { field : 'terminalGroupName', align: "center", title : '分组名称' }, { field : 'terminalGroupLevel', title : '分组层级', align: "center" }, { field : 'parentTerminalGroupId', title : '上级分组id', align: "center" }, { field : 'parentTerminalGroupName', title : '上级分组名称', align: "center" }, { field: 'enableFlag', title: '启用禁用', align: "center", formatter: function(value, row, index) { if (row.enableFlag == 0) { return '禁用'; }else if(row.enableFlag == 1) { return '启用'; }else{ return '-'; } } }, { field : 'createTime', title : '创建时间', align: "center" }, { title: '操作', align: 'center', formatter: function(value, row, index) { var actions = []; actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.terminalGroupId + '\')"><i class="fa fa-edit"></i>编辑</a> '); actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.terminalGroupId + '\')"><i class="fa fa-remove"></i>删除</a>'); return actions.join(''); } }] }; $.table.init(options); }); </script> </body> </html>
from __future__ import annotations from typing import Optional import os import aiosqlite from .embed import Embed from config import Guild_id, DB_NAME, PASSWORD, PORT, USER, HOST from logging import getLogger; log = getLogger("Bot") from discord.ext import commands import discord __all__ = ( "Bot", ) class Bot(commands.AutoShardedBot): def __init__(self): super().__init__( command_prefix= "!", intents= discord.Intents.all(), chunk_guild_at_startup = False ) self.synced = False self.anti_spam = commands.CooldownMapping.from_cooldown(10, 10, commands.BucketType.member) async def setup_hook(self): log.info("Running setup...") for file in os.listdir("cogs"): if not file.startswith("__"): await self.load_extension(f"cogs.{file}.plugin") async def on_ready(self): game = discord.Game("難道你良心不會痛嗎?") await self.change_presence(status= discord.Status.online, activity= game) await self.wait_until_ready() if not self.synced: sync_commands = await self.tree.sync(guild = discord.Object(id= Guild_id)) self.synced = True log.info(f"Successfully synced {len(sync_commands)} commands.") setattr(Bot, "db", await aiosqlite.connect("databases/level.db")) async with Bot.db.cursor() as cursor: await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)") log.info(f"Logged in as {self.user} (ID: {self.user.id})") log.info("Bot ready.") async def on_connected(self): log.info(f"Connected to Discord (latency: {self.latency * 1000:,.0f} ms).") async def on_message(self, msg: discord.Message): if type(msg.channel) is not discord.TextChannel or msg.author.bot: return if not msg.author.bot: await self.process_commands(msg) bucket = self.anti_spam.get_bucket(msg) retry_after = bucket.update_rate_limit() if retry_after: await msg.channel.send(f"馬的智障{msg.author.mention}\n不要洗頻!!!") async def success( self, message: str, interaction: discord.Interaction, *, ephemeral: bool = False, embed: Optional[bool] = True ) -> Optional[discord.WebhookMessage]: if embed: if interaction.response.is_done(): return await interaction.followup.send( embed= Embed(description= message, color= discord.Colour.green(), ephemeral= ephemeral) ) return await interaction.response.send_message( embed= Embed(description= message, color= discord.Colour.green()), ephemeral= ephemeral ) else: if interaction.response.is_done(): return await interaction.followup.send(content= f"✔️ | {message}", ephemeral= ephemeral) return await interaction.response.send_message(content= f"✔️ | {message}", ephemeral= ephemeral) async def error( self, message: str, interaction: discord.Interaction, *, ephemeral: bool = False, embed: Optional[bool] = True ) -> Optional[discord.WebhookMessage]: if embed: if interaction.response.is_done(): return await interaction.followup.send( embed= Embed(description= message, color= discord.Colour.red(), ephemeral= ephemeral) ) return await interaction.response.send_message( embed= Embed(description= message, color= discord.Colour.red()), ephemeral= ephemeral ) else: if interaction.response.is_done(): return await interaction.followup.send(content= f"❌ | {message}", ephemeral= ephemeral) return await interaction.response.send_message(content= f"❌ | {message}", ephemeral= ephemeral)
import { mocked } from 'jest-mock' import { contactDB } from '../database' import formatNumber from './formatNumber' jest.mock('../database') const mockedContactDB = mocked(contactDB, true) beforeEach(() => { jest.clearAllMocks() }) it('Formats an number into the expected shape', () => { return expect(formatNumber('01234567890', 'GB')).resolves.toEqual({ country: 'GB', international: '+44 1234 567890', name: undefined, national: '01234 567890', number: '+441234567890', }) }) it('Returns a basic shape when number is phoney', () => { return expect(formatNumber('12345', 'GB')).resolves.toEqual({ country: undefined, international: undefined, name: undefined, national: undefined, number: '12345', }) }) it('Returns a number with a contact name when provided', async () => { mockedContactDB.asyncFindOne.mockResolvedValue({ name: 'Joseph Bloggs', number: '01234567890', }) return expect(formatNumber('01234567890', 'GB')).resolves.toEqual({ country: 'GB', international: '+44 1234 567890', name: 'Joseph Bloggs', national: '01234 567890', number: '+441234567890', }) })
import express from 'express'; import cors from 'cors'; import { Celulares } from './lista.js'; //objeto// let Listacelulares = [ new Celulares(24, "samsung", 2500, 2022), new Celulares(54, "Iphone", 2500, 2021), new Celulares(92, "Motorola", 2500, 2023), new Celulares(18, "Lg", 2500, 2018) ] const celular = express(); celular.use(express.json()); celular.use(cors()); celular.use(express.urlencoded({extended: true})); celular.get("/", (req, res)=>{ return res.status(200).json(Listacelulares) }) celular.post("/novo", (req, res)=>{ const { codigo, modelo, preco, ano_lancamento } = req.body; Listacelulares.push(new Celulares(Listacelulares.length + 1, codigo, modelo, preco, ano_lancamento)); return res.status(200).json("cadastrado com sucesso!"); }) celular.put("/produtos/alterar/:codigo", (req,res)=>{ const { codigo } = req.params; const {modelo, preco, ano_lancamento} = req.body; let produtos = Listacelulares.find(obj => obj.codigo == codigo); produtos.modelo = modelo; produtos.preco = preco; produtos.ano_lancamento = ano_lancamento; return res.status(200).json("Alterado com sucesso!"); }) celular.delete("/produtos/excluir/:codigo",(req,res)=>{ const { codigo } = req.params; Listacelulares = Listacelulares.filter(p => p.codigo != codigo); return res.status(200).json("Deletado"); }) celular.listen(4000, ()=>{ console.log("Api no ar!"); })
'use client'; import React from 'react'; import clsx from 'clsx'; // hooks & utils import useSearch from './useSearch'; import { filterData, isValueInFilter } from '@utils/filterUtils'; // components import MotionContainer from '@components/Layout/MotionContainer'; import Message from '@components/Message/Message'; import Page from '@components/Layout/Page/Page'; import GroupedEntries from '@components/Entry/Entries/GroupedEntries'; import SelectPill from '@components/Elements/SelectPill/SelectPill'; import CloseSearchButton from './CloseSearchButton'; import { Flex } from '@styles/styles'; import { FiltersSection, FiltersSectionItem, FiltersSectionTitle, SearchInput, SearchInputWrapper, } from './Styles'; // icons import { SearchIcon, XIcon } from '@heroicons/react/outline'; // local data import emotionContent from '@data/content.json'; import { DEFAULT_ENTRY_MESSAGES } from '@config/messages'; interface SearchProps { setIsOpen?: React.Dispatch<React.SetStateAction<boolean>>; data: any[]; tags: string[]; } const Search = ({ setIsOpen, data: propsData, tags }: SearchProps) => { // manages filter state const { searchFilterState, handelSetFilter, handelAddFilter, handleQuery, handleResetQuery, } = useSearch(); // filters data const { data: filteredData, filter } = filterData({ data: propsData, filter: searchFilterState, }); const data = filter ? filteredData : []; const isNotFound = filter && filteredData?.length === 0; const getPillVariant = (value: string, key: keyof IEntry) => isValueInFilter(searchFilterState, value, key) ? 'selected' : 'default'; return ( <MotionContainer> <Page.Layout> <Flex className='justify-between'> <Page.Title>Search</Page.Title> <CloseSearchButton onClick={() => setIsOpen?.(false)} /> </Flex> <SearchInputWrapper> <SearchIcon className='h-7 w-7 text-zinc-400' /> <SearchInput autoFocus value={searchFilterState.content} onChange={handleQuery} placeholder='Search...' /> {/* if input has text display delete all text icon*/} <XIcon onClick={handleResetQuery} className={clsx( 'h-6 w-6 cursor-pointer text-zinc-700', searchFilterState.content ? 'block' : 'hidden' )} /> </SearchInputWrapper> <FiltersSection> <FiltersSectionItem> <FiltersSectionTitle>Search by emotion</FiltersSectionTitle> <Flex className='flex-wrap'> {emotionContent.emotions.map(({ text }: { text: string }) => { return ( <SelectPill variant={getPillVariant(text, 'emotion')} onClick={() => handelSetFilter({ key: 'emotion', payload: text }) } key={text}> {text} </SelectPill> ); })} </Flex> </FiltersSectionItem> <FiltersSectionItem> <FiltersSectionTitle>Search by tag</FiltersSectionTitle> <Flex className='flex-wrap'> {tags.map((tag: string) => { return ( <SelectPill variant={getPillVariant(tag, 'tags')} onClick={() => handelAddFilter({ key: 'tags', payload: tag }) } key={tag}> {tag} </SelectPill> ); })} </Flex> </FiltersSectionItem> </FiltersSection> <GroupedEntries entries={data} /> <Message hidden={!isNotFound} message={DEFAULT_ENTRY_MESSAGES.NO_SEARCH_RESULTS} /> </Page.Layout> </MotionContainer> ); }; export default Search;
import React from "react"; import { FcApproval } from "react-icons/fc"; import { RxCross2 } from "react-icons/rx"; import BookingTour from "./BookingTour"; import RatingForm from "./RatingForm"; const AboutTour = ({ tour }) => { return ( <div> <div className="pt-12 bbg-gray-800 btext-gray-100 container grid gap-6 mx-auto text-center lg:grid-cols-2 xl:grid-cols-5 " > {/* tour details */} <div className="flex flex-col max-w-3xl mx-auto overflow-hidden rounded w-full xl:col-span-3 italic" > <div className="flex"> {/* about tour */} <div className="text-start leading-8 "> <p className="inline-block text-2xl font-semibold sm:text-xl text-primary"> Explore Tours </p> <p className="text-justify mr-3"> {tour?.description} </p> </div> <img src={tour?.imageCover} alt="" className="opacity-100 w-1/2 p-3 float-right text-end h-60 sm:h-96" /> </div> </div> {/* tour booking */} <div className="w-full rounded-md sm:px-12 md:px-16 xl:col-span-2 "> <div className="shadow-lg py-12 mb-10 px-5"> <h1 className="text-3xl font-extrabold btext-gray-50"> Booking for {tour?.title} </h1> <p className="my-8"> <span className="font-medium btext-gray-50"> You ar booking for {tour?.title} </span> To conferm the tour booking please see the user profile for your tour status. </p> {/* form tour booking */} <BookingTour id={tour?._id} title={tour?.title} price={tour?.price} /> </div> {/* rating */} <RatingForm /> </div> </div> {/* fqa section */} {/* <div className="w-3/4 flex flex-col justify-center pb-5 "> <h2 className="text-2xl font-semibold sm:text-4xl py-3">Tour Plan</h2> <div className="space-y-4"> <details className="w-full border rounded-lg"> <summary className="px-4 py-6 focus:outline-none focus-visible:ring-violet-400"> Day 1st </summary> <p className="px-4 py-6 pt-0 ml-4 -mt-4 btext-gray-400"> Lectus iaculis orci metus vitae ligula dictum per. Nisl per nullam taciti at adipiscing est.{" "} </p> </details> <details className="w-full border rounded-lg"> <summary className="px-4 py-6 focus:outline-none focus-visible:ring-violet-400"> Day 3rd </summary> <p className="px-4 py-6 pt-0 ml-4 -mt-4 btext-gray-400"> Lectus iaculis orci metus vitae ligula dictum per. Nisl per nullam taciti at adipiscing est.{" "} </p> </details> <details className="w-full border rounded-lg"> <summary className="px-4 py-6 focus:outline-none focus-visible:ring-violet-400"> Day 2nd </summary> <p className="px-4 py-6 pt-0 ml-4 -mt-4 btext-gray-400"> Lectus iaculis orci metus vitae ligula dictum per. Nisl per nullam taciti at adipiscing est.{" "} </p> </details> </div> </div> */} </div> ); }; export default AboutTour;
import { configureStore, ReducersMapObject } from '@reduxjs/toolkit'; import { currencyReducer } from 'entities/currency'; import { StateSchema } from './stateSchema'; export function createRootStore(initialState?: StateSchema) { const rootReducer: ReducersMapObject<StateSchema> = { currency: currencyReducer, }; return configureStore<StateSchema>({ reducer: rootReducer, preloadedState: initialState, }); } export type AppDispatch = ReturnType<typeof createRootStore>['dispatch']
// import React, { useState, useContext } from 'react' // import { Redirect } from 'react-router-dom' // import { Alert, AlertTitle } from '@material-ui/lab' // import { CardContent, Card } from '@material-ui/core' // import CryptoJS from 'crypto-js' // import Header from './header' // import LoginForm from './login-form' // import { Box, BoxTitle } from '../../box-card' // import { LoaderContext } from '../../../lib/context/loader-context' // import { AuthContext } from '../../../lib/context/auth-context' // import AuthAPI from '../../../lib/api/auth' // import './form-login.css' // eslint-disable-next-line no-use-before-define import React, { useState, useContext } from 'react' import { Redirect } from 'react-router-dom' import { Alert, AlertTitle } from '@material-ui/lab' import CryptoJS from 'crypto-js' import Header from './header' import LoginForm from './login-form' import { Box, BoxTitle } from '../../box-card' import { LoaderContext } from '../../../lib/context/loader-context' import { AuthContext } from '../../../lib/context/auth-context' import AuthAPI from '../../../lib/api/auth' import './form-login.css' const initialState = { username: '', password: '' } const Layout = () => { const [loginData, setLoginData] = useState(initialState) const [successLogin, setSuccessLogin] = useState(false) const [errorLogin, setErrorLogin] = useState({}) const { setIsLoading, setEstaAutenticado } = useContext(LoaderContext) const { setDadosUser } = useContext(AuthContext) const submitForm = async (values) => { setIsLoading(true) const senhaMd5 = CryptoJS.MD5(`{uni${values.password}med}`).toString() const obj = { ...values } obj.password = senhaMd5 const result = await AuthAPI.autenticate(obj) setLoginData(values) setSuccessLogin(result.success) setDadosUser(result.data?.user) if (result.success === false) { setErrorLogin(result) } setEstaAutenticado(result.success) setIsLoading(false) } return ( <> {successLogin ? ( <Redirect to="/" /> ) : ( <> <div className="container"> <div className="h-100 d-flex justify-content-center align-items-center"> <Box className="form-login"> <BoxTitle className="text-center text-uppercase"> Acesso Restrito </BoxTitle> <LoginForm submitForm={submitForm} loginData={loginData} /> </Box> </div> <div className="d-flex justify-content-center align-items-center"> {errorLogin.success === false && ( <Box className="form-login mt-0"> <Alert severity="error"> <AlertTitle>{errorLogin.error}</AlertTitle> </Alert> </Box> )} </div> </div> </> )} </> ) } export default Layout
import ArrowForwardIcon from '@mui/icons-material/ArrowForward' import CalendarMonthIcon from '@mui/icons-material/CalendarMonth' import { CardContent, Typography, CardActions, Grid, CardHeader } from '@mui/material' import React from 'react' import { Link } from 'react-router-dom' import * as S from 'pages/Article/styles' interface I_ArticleCardProps { articleId: string title: string imageUrl: string description: string date: string } export const ArticleCard: React.FC<I_ArticleCardProps> = ({ articleId, title, imageUrl, description, date, }) => { return ( <Grid item md={4}> <S.CardContainer> <S.CardMediaFile image={imageUrl} /> <CardHeader avatar={<CalendarMonthIcon color='disabled' />} subheader={date} /> <CardContent> <Link to={`/article/${articleId}`} key={articleId}> <Typography gutterBottom variant='h5' component='div' height={60} dangerouslySetInnerHTML={{ __html: title }} /> </Link> <Typography variant='body2' color='text.secondary' dangerouslySetInnerHTML={{ __html: description.substring(0, 100) + '...', }} /> </CardContent> <CardActions> <Link to={`/article/${articleId}`} key={articleId}> <S.ButtonIcon endIcon={<ArrowForwardIcon />} size='small'> <Typography textTransform='none' variant='button'> Read more </Typography> </S.ButtonIcon> </Link> </CardActions> </S.CardContainer> </Grid> ) }
import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'adicionar_evento_tela.dart'; import 'adicionar_fornecedor_tela.dart'; import 'adicionar_orcamento_tela.dart'; import 'adicionar_servico_avulso_tela.dart'; class BemVindoFornecedorTela extends StatelessWidget { Future<Map<String, dynamic>> _fetchUserData() async { User? user = FirebaseAuth.instance.currentUser; if (user != null) { try { DocumentSnapshot userDoc = await FirebaseFirestore.instance.collection('fornecedores').doc(user.uid).get(); if (userDoc.exists) { return userDoc.data() as Map<String, dynamic>; } else { print("Documento não encontrado"); return {}; } } catch (e) { print("Erro ao buscar dados do Firestore: $e"); return {}; } } else { print("Usuário não está autenticado"); return {}; } } @override Widget build(BuildContext context) { return Scaffold( body: FutureBuilder<Map<String, dynamic>>( future: _fetchUserData(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } if (snapshot.hasError) { return Center(child: Text('Erro ao carregar dados: ${snapshot.error}')); } if (!snapshot.hasData || snapshot.data == null || snapshot.data!.isEmpty) { return Center(child: Text('Nenhum dado encontrado')); } var userData = snapshot.data!; var nome = userData['nome']; return Padding( padding: EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Bem-vindo, $nome!', style: TextStyle(fontSize: 25), ), SizedBox(height: 20), Expanded( child: GridView.count( crossAxisCount: 2, crossAxisSpacing: 10, mainAxisSpacing: 10, children: [ _buildButton(context, 'Eventos', Icons.event, const Color.fromARGB(255, 135, 196, 247)), _buildButton(context, 'Indicações', Icons.business, const Color.fromARGB(255, 146, 243, 149)), _buildButton(context, 'Orçamentos', Icons.receipt, const Color.fromARGB(255, 247, 208, 149)), _buildButton(context, 'Serviços', Icons.miscellaneous_services, const Color.fromARGB(255, 232, 167, 243)), ], ), ), ], ), ); }, ), bottomNavigationBar: BottomAppBar( shape: CircularNotchedRectangle(), notchMargin: 6.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ IconButton( icon: Icon(Icons.home), onPressed: () { Navigator.pushNamed(context, '/bem_vindo_fornecedor'); }, ), IconButton( icon: Icon(Icons.receipt), onPressed: () { Navigator.pushNamed(context, '/orcamento'); }, ), IconButton( icon: Icon(Icons.menu), onPressed: () { showModalBottomSheet( context: context, builder: (BuildContext context) { return Container( padding: EdgeInsets.all(16.0), child: Wrap( children: <Widget>[ ListTile( leading: Icon(Icons.person), title: Text('Dados Pessoais'), onTap: () { Navigator.pushNamed(context, '/dados_pessoais'); }, ), ListTile( leading: Icon(Icons.child_care), title: Text('Dados da Criança'), onTap: () { Navigator.pushNamed(context, '/dados_crianca'); }, ), ListTile( leading: Icon(Icons.info), title: Text('Sobre'), onTap: () { Navigator.pushNamed(context, '/sobre'); }, ), ], ), ); }, ); }, ), ], ), ), ); } Widget _buildButton(BuildContext context, String label, IconData icon, Color color) { return ElevatedButton( onPressed: () { switch (label) { case 'Eventos': Navigator.push(context, MaterialPageRoute(builder: (context) => AdicionarEventoTela())); break; case 'Indicações': Navigator.push(context, MaterialPageRoute(builder: (context) => AdicionarFornecedorTela())); break; case 'Orçamentos': Navigator.push(context, MaterialPageRoute(builder: (context) => AdicionarOrcamentoTela())); break; case 'Serviços': Navigator.push(context, MaterialPageRoute(builder: (context) => AdicionarServicoAvulsoTela())); break; } }, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(icon, size: 50), SizedBox(height: 10), Text(label, textAlign: TextAlign.center), ], ), style: ElevatedButton.styleFrom( backgroundColor: color, padding: EdgeInsets.all(16), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ); } }
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common'; import { UnitsService } from './units.service'; import { Prisma } from '@prisma/client'; @Controller('units') export class UnitsController { constructor(private readonly unitsService: UnitsService) { } @Post() create(@Body() createUnitDto: Prisma.UnitsCreateInput) { return this.unitsService.create(createUnitDto); } @Get() findAll() { return this.unitsService.findAll(); } @Get(':id') findOne(@Param('id') id: string) { return this.unitsService.findOne(+id); } @Patch(':id') update(@Param('id') id: string, @Body() updateUnitDto: Prisma.UnitsUpdateInput) { return this.unitsService.update(+id, updateUnitDto); } @Delete(':id') remove(@Param('id') id: string) { return this.unitsService.remove(+id); } }
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { AbstractControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { from, of, Subject, throwError } from 'rxjs'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import Swal from 'sweetalert2'; import { ProductService } from '../../services/product/product.service'; import { ProductListComponent } from './product-list.component'; import { Product } from 'src/app/shared/interfaces/product.interface'; import { brandMock, brandsMock } from 'src/app/testing/product-mock'; import { formControlHasErrors, setFormControlValue } from 'src/app/testing/functions/form-validator'; class FakeActivatedRoute { private subject = new Subject(); push(value: any){ this.subject.next( value ); } get params(){ return this.subject.asObservable(); } } describe('ProductListComponent', () => { let component: ProductListComponent; let fixture: ComponentFixture<ProductListComponent>; let productServiceSpy: jasmine.SpyObj<ProductService>; let ngBModalSpy: jasmine.SpyObj<NgbModal>; let activatedRoute: ActivatedRoute; beforeEach(async () => { productServiceSpy = jasmine.createSpyObj<ProductService>('ProductService',['getProducts','saveProduct','getBrands']); ngBModalSpy = jasmine.createSpyObj<NgbModal>('NgbModal',['dismissAll']); await TestBed.configureTestingModule({ declarations: [ ProductListComponent ], schemas: [ NO_ERRORS_SCHEMA ], providers: [ { provide: ActivatedRoute, useClass: FakeActivatedRoute }, { provide: ProductService, useValue: productServiceSpy }, { provide: NgbModal, useValue: ngBModalSpy }, ], imports: [ ReactiveFormsModule ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(ProductListComponent); component = fixture.componentInstance; // fixture.detectChanges(); activatedRoute = TestBed.inject(ActivatedRoute); (<FakeActivatedRoute>(<any>activatedRoute)).push(of({searchTerm: 'nuevo'})); }); it('should create', () => { expect(component).toBeTruthy(); }); it('ngOnInit() method', waitForAsync(() => { productServiceSpy.getBrands.and.returnValue( from([brandsMock]) ); component.ngOnInit(); expect(component).toBeTruthy(); expect(productServiceSpy.getBrands).toHaveBeenCalled(); expect(component.brands.length).toBe(2); })); it('Check validation fields errors', () => { let priceControl = setFormControlValue(component.productForm,'price',123); let hasErrors = formControlHasErrors(priceControl!); expect(hasErrors).toBeFalsy(); priceControl?.setValue(""); hasErrors = formControlHasErrors(priceControl!); expect(hasErrors).toBeTruthy(); priceControl = setFormControlValue(component.productForm,'brand.id',brandMock.id) hasErrors = formControlHasErrors(priceControl!); expect(hasErrors).toBeFalsy(); priceControl = setFormControlValue(component.productForm,'brand.id',null) hasErrors = formControlHasErrors(priceControl!); expect(hasErrors).toBeTruthy(); }); it('saveProduct() with invalid form', () => { const spy = spyOn(component.productForm,'markAllAsTouched'); component.saveProduct(); expect(spy).toHaveBeenCalled(); }); it('saveProduct() with invalid form', () => { const spy = spyOn(component.productForm,'markAllAsTouched'); component.saveProduct(); expect(spy).toHaveBeenCalled(); }); it('saveProduct() with valid form', (done:DoneFn) => { let product:Product = {} as Product; setFormFieldValues(component.productForm); productServiceSpy.saveProduct.and.returnValue(of(product)); component.saveProduct(); setTimeout(() => { expect(Swal.isVisible()).toBeTruthy(); Swal.clickConfirm(); done(); }); expect(component.productForm.valid).toBeTruthy(); expect(productServiceSpy.saveProduct).toHaveBeenCalled(); expect(ngBModalSpy.dismissAll).toHaveBeenCalled(); }); it('Test error in saveProduct()', () => { setFormFieldValues(component.productForm); let spy = spyOn(console,'log'); productServiceSpy.saveProduct.and.returnValue(throwError(() => '')); component.saveProduct(); expect(spy).toHaveBeenCalledWith('Ha ocurrido un error al tratar de guardar el producto'); }); function setFormFieldValues(productForm: FormGroup): void { productForm.get('name')?.setValue('Apple TV'); productForm.get('description')?.setValue('Apple TV, the most recent TV in the market'); productForm.get('price')?.setValue(125); productForm.get('brand.id')?.setValue(brandMock.id); } });
#include <stdio.h> #include<stdlib.h> // Node definition struct Node{ int data ; struct Node *left ; struct Node *right; / }; struct Node* makeTree(){ int inputData ; struct Node *p ; printf("Enter the data or -1 to terminate\n") ; scanf("%d", &inputData) ; if(inputData == -1) return NULL; p = (struct Node*) malloc(sizeof(struct Node)) ; p->data = inputData ; printf("Enter the left child of %d or -1 if no left child\n",inputData) ; p->left = makeTree(); printf("Enter the right child of %d or -1 if no left child\n",inputData) ; p->right = makeTree(); return p ; } void mpreorder(struct Node *t){ if(t!=NULL){ printf("%d->", t->data) ; // R, L, R mpreorder(t->left) ; mpreorder(t->right) ; } } void mpostorder(struct Node *t){ if(t!=NULL){ mpostorder(t->left) ; mpostorder(t->right) ; printf("%d->", t->data) ; } } void inorder(struct Node *t){ if(t!=NULL) { inorder(t->left); printf("%d->", t->data); inorder(t->right); } } int main() { struct Node *root; root = makeTree(); printf("Preorder Traversal \n"); mpreorder(root); printf("\n"); printf("Postorder Traversal \n"); mpostorder(root); printf("\n"); printf("Inorder Traversal \n"); inorder(root); return 0; }
import { mnemonicToWalletKey, mnemonicNew } from "ton-crypto"; import { compileFunc } from '@ton-community/func-js'; import fs from 'fs'; // we use fs for reading content of files import { Cell } from "ton-core"; import { beginCell } from "ton-core"; import { Address } from "ton-core"; import { sign } from "ton-crypto"; import { toNano } from "ton-core"; import { TonClient } from "ton"; import { getHttpEndpoint } from "@orbs-network/ton-access"; async function main() { const mnemonicArray = 'ENTER YOUR SEED-CODE HERE(WORD_1, WORD_2...)'.split(' ') const keyPair = await mnemonicToWalletKey(mnemonicArray); // extract private and public keys from mnemonic console.log(mnemonicArray) // if we want, we can print our mnemonic const subWallet = 698983191; const result = await compileFunc({ targets: ['wallet_v3.fc'], // targets of your project sources: { "stdlib.fc": fs.readFileSync('./src/stdlib.fc', { encoding: 'utf-8' }), "wallet_v3.fc": fs.readFileSync('./src/wallet_v3.fc', { encoding: 'utf-8' }), } }); if (result.status === 'error') { console.error(result.message) return; } const codeCell = Cell.fromBoc(Buffer.from(result.codeBoc, "base64"))[0]; // get buffer from base64 encoded BOC and get cell from this buffer // now we have base64 encoded BOC with compiled code in result.codeBoc console.log('Code BOC: ' + result.codeBoc); console.log('\nHash: ' + codeCell.hash().toString('base64')); // get the hash of cell and convert in to base64 encoded string. We will need it further const dataCell = beginCell(). storeUint(0, 32). // Seqno storeUint(698983191, 32). // Subwallet ID storeBuffer(keyPair.publicKey). // Public Key endCell(); const stateInit = beginCell(). storeBit(0). // No split_depth storeBit(0). // No special storeBit(1). // We have code storeRef(codeCell). storeBit(1). // We have data storeRef(dataCell). storeBit(0). // No library endCell(); const contractAddress = new Address(0, stateInit.hash()); // get the hash of stateInit to get the address of our smart contract in workchain with ID 0 console.log(`Contract address: ${contractAddress.toString()}`); // Output contract address to console const internalMessageBody = beginCell(). storeUint(0, 32). storeStringTail("Hello, TON!"). endCell(); const internalMessage = beginCell(). storeUint(0x10, 6). // no bounce storeAddress(Address.parse("ENTER YOUR WALLET ADDRESS HERE")). storeCoins(toNano("0.03")). storeUint(1, 1 + 4 + 4 + 64 + 32 + 1 + 1). // We store 1 that means we have body as a reference storeRef(internalMessageBody). endCell(); // transaction for our wallet const toSign = beginCell(). storeUint(subWallet, 32). storeUint(Math.floor(Date.now() / 1e3) + 60, 32). storeUint(0, 32). // We put seqno = 0, because after deploying wallet will store 0 as seqno storeUint(3, 8). storeRef(internalMessage); const signature = sign(toSign.endCell().hash(), keyPair.secretKey); const body = beginCell(). storeBuffer(signature). storeBuilder(toSign). endCell(); const externalMessage = beginCell(). storeUint(0b10, 2). // indicate that it is an incoming external transaction storeUint(0, 2). // src -> addr_none storeAddress(contractAddress). storeCoins(0). // Import fee storeBit(1). // We have State Init storeBit(1). // We store State Init as a reference storeRef(stateInit). // Store State Init as a reference storeBit(1). // We store Message Body as a reference storeRef(body). // Store Message Body as a reference endCell(); // get the decentralized RPC endpoint const endpoint = await getHttpEndpoint({ network: "testnet", }); // initialize ton library const client = new TonClient({ endpoint }); client.sendFile(externalMessage.toBoc()); } main().finally(() => console.log("Exiting..."));
import { error } from "./error.js"; import { IToken, TokenType, Literal, NULL, getBinPrec } from "./lexer.ts"; export class Parser { private index = 0; private tokens = new Array<IToken>(); private consume(amount = 1): IToken { const token = this.tokens[this.index]; this.index += amount; return token; } private peek(amount = 1): IToken { if (amount > this.tokens.length - this.index) error(203, [], this.current().lineNum); return this.tokens[this.index + amount] } private current(): IToken { return this.tokens[this.index]; } private tryConsume(type: TokenType) { if (this.current().type === type) this.consume(); else error(202, [type], this.current().lineNum); } private parseTerm(): INodeTerm { if (this.current().type === Literal.INT) return this.consume(); else if (this.current().type === TokenType.IDENTIFIER) { if (this.peek().type === TokenType.OPENPAREN) return this.parseFunctionCall(); else return this.consume(); } else if (this.current().type === TokenType.OPENPAREN) { this.consume() // Consume the '(' const paren: INodeParen = { innerExpr: this.parseExpression(), _type: "paren" }; this.tryConsume(TokenType.CLOSEPAREN); return paren; } else return NULL; } private parseExpression(min_prec = 0): INodeExpr { const term_lhs: INodeExpr = { value: this.parseTerm(), _type: "expr" }; if (term_lhs.value === NULL) return NullExpr; const expr: INodeExpr = NullExpr; while (true) { const op = this.current(); const prec = getBinPrec(this.current().type); if (!op || prec === null || prec < min_prec) break; this.consume(); // Consume the operator const next_min_prec = prec + 1; const term_rhs = this.parseExpression(next_min_prec); if (term_rhs.value === NULL) error(201, [], this.current().lineNum); if (op.type === TokenType.PLUS) { const add: INodeBinAdd = { lhs: { value: term_lhs.value, _type: "expr" }, rhs: term_rhs, _type: "add" }; expr.value = add; } else if (op.type === TokenType.MINUS) { const mult: INodeBinSub = { lhs: { value: term_lhs.value, _type: "expr" }, rhs: term_rhs, _type: "sub" }; expr.value = mult; } else if (op.type === TokenType.STAR) { const mult: INodeBinMult = { lhs: { value: term_lhs.value, _type: "expr" }, rhs: term_rhs, _type: "mult" }; expr.value = mult; } else if (op.type === TokenType.FSLASH) { const mult: INodeBinDiv = { lhs: { value: term_lhs.value, _type: "expr" }, rhs: term_rhs, _type: "div" }; expr.value = mult; } else error(205, [], this.current().lineNum); term_lhs.value = expr.value; } return term_lhs; } private parseScope(): INodeScope { this.consume(); // Consume the '{' const scope: INodeScope = { statements: [], _type: "scope" }; // Parse the scope while (this.current().type !== TokenType.CLOSECURLY) scope.statements.push(this.parseStatement()); this.consume(); // Consume the '}' return scope; } private parseIf(): INodeIf { this.tryConsume(TokenType.IF); this.tryConsume(TokenType.OPENPAREN); const expr = this.parseExpression(); this.tryConsume(TokenType.CLOSEPAREN); if (expr.value === NULL) error(206, [], this.current().lineNum); let scope: INodeScope; if (this.current().type !== TokenType.OPENCURLY) { const stmt = this.parseStatement(); scope = { statements: [stmt], _type: "scope" }; } else scope = this.parseScope(); if (this.current().type === TokenType.ELSE) { this.consume(); // Consume the 'else' let elseScope: INodeScope; if (this.current().type !== TokenType.OPENCURLY) { const stmt = this.parseStatement(); elseScope = { statements: [stmt], _type: "scope" }; } else elseScope = this.parseScope(); return { conditionExpr: expr, scope, else: elseScope, _type: "if" }; } return { conditionExpr: expr, scope, _type: "if" }; } private parseWhile(): INodeWhile { this.tryConsume(TokenType.WHILE); this.tryConsume(TokenType.OPENPAREN); const expr = this.parseExpression(); this.tryConsume(TokenType.CLOSEPAREN); if (expr.value === NULL) error(206, [], this.current().lineNum); let scope: INodeScope; if (this.current().type !== TokenType.OPENCURLY) { const stmt = this.parseStatement(); scope = { statements: [stmt], _type: "scope" }; } else scope = this.parseScope(); return { conditionExpr: expr, scope, _type: "while" }; } private parseDeclaration(): INodeDeclare | INodeFunctionDeclare { const type = this.consume(); const identifier = this.consume(); if (this.current().type === TokenType.EOL) { // Declaration without a value this.consume(); // Consume the ';' return { type, identifier, expression: NullExpr, _type: "declare" }; } else if (this.current().type === TokenType.EQUALS) { this.consume(); // Consume the '=' const statement: INodeDeclare = { type, identifier, expression: this.parseExpression(), _type: "declare" }; this.tryConsume(TokenType.EOL); if (statement.expression === NullExpr) error(206, [], this.current().lineNum); return statement; } else if (this.current().type === TokenType.OPENPAREN) { this.tryConsume(TokenType.OPENPAREN); const params: INodeParameter[] = []; if (this.current().type === TokenType.TYPE) { params.push({ type: this.consume(), identifier: this.consume(), _type: "parameter" }); while (this.current().type === TokenType.COMMA) { this.tryConsume(TokenType.COMMA); params.push({ type: this.consume(), identifier: this.consume(), _type: "parameter" }); } } this.tryConsume(TokenType.CLOSEPAREN); const functionScope = this.parseScope(); return { identifier, returnType: type, functionScope, parameters: params, _type: "declareFun" }; } else return error(206, [], this.current().lineNum); } private parseFunctionCall(): INodeFunctionCall { const identifier = this.consume(); this.tryConsume(TokenType.OPENPAREN); const args: INodeExpr[] = []; if (this.current().type !== TokenType.CLOSEPAREN) { args.push(this.parseExpression()); while (this.current().type === TokenType.COMMA) { this.tryConsume(TokenType.COMMA); args.push(this.parseExpression()); } } this.tryConsume(TokenType.CLOSEPAREN); return { identifier, args, _type: "funcCall" }; } private parseAssignment(): INodeAssign { const identifier = this.consume(); const op = this.consume(); let expression: INodeExpr; if (op.type === TokenType.EQUALS) { expression = this.parseExpression(); if (expression === NullExpr) error(206, [], this.current().lineNum); } else if (op.type === TokenType.DPLUS) { expression = { value: { lhs: { value: identifier, _type: "expr" }, rhs: { value: { type: Literal.INT, value: 1, _type: "token" }, _type: "expr" }, _type: "add" }, _type: "expr" }; } else if (op.type === TokenType.DMINUS) { expression = { value: { lhs: { value: identifier, _type: "expr" }, rhs: { value: { type: Literal.INT, value: 1, _type: "token" }, _type: "expr" }, _type: "sub" }, _type: "expr" }; } else if (op.type === TokenType.PEQUALS) { const added = this.parseExpression(); expression = { value: { lhs: { value: identifier, _type: "expr" }, rhs: added, _type: "add" }, _type: "expr" }; } else if (op.type === TokenType.MEQUALS) { const subbed = this.parseExpression(); expression = { value: { lhs: { value: identifier, _type: "expr" }, rhs: subbed, _type: "sub" }, _type: "expr" }; } else return error(200, [], this.current().lineNum); this.tryConsume(TokenType.EOL); return { identifier, expression, _type: "assign" }; } private parseStatement(): INodeStatement { if (this.current().type === TokenType.RETURN) { this.consume(); // Consume the return const statement: INodeReturn = { returnExpr: this.parseExpression(), _type: "return" }; this.tryConsume(TokenType.EOL); return statement; } else if (this.current().type === TokenType.TYPE && this.peek().type === TokenType.IDENTIFIER) return this.parseDeclaration(); else if (this.current().type === TokenType.IDENTIFIER && ( this.peek().type === TokenType.EQUALS || this.peek().type === TokenType.DPLUS || this.peek().type === TokenType.DMINUS || this.peek().type === TokenType.PEQUALS || this.peek().type === TokenType.MEQUALS )) return this.parseAssignment(); else if (this.current().type === TokenType.OPENCURLY) return this.parseScope(); else if (this.current().type === TokenType.IF) return this.parseIf(); else if (this.current().type === TokenType.WHILE) return this.parseWhile(); else return error(204, [this.current().type], this.current().lineNum); } parse(tokens: IToken[]): INodeProgram { this.index = 0; this.tokens = tokens; const programNode: INodeProgram = { statements: [], _type: "program" }; while (this.current().type !== TokenType.EOF) programNode.statements.push(this.parseStatement()); return programNode; } } /* --- Node interfaces --- */ export interface INodeExpr { _type: "expr", value: INodeTerm | INodeBinExpr; } export interface INodeParen { _type: "paren"; innerExpr: INodeExpr; } export type INodeTerm = IToken | INodeParen | INodeFunctionCall; export interface INodeBinAdd { _type: "add"; lhs: INodeExpr; rhs: INodeExpr; } export interface INodeBinSub { _type: "sub"; lhs: INodeExpr; rhs: INodeExpr; } export interface INodeBinMult { _type: "mult"; lhs: INodeExpr; rhs: INodeExpr; } export interface INodeBinDiv { _type: "div"; lhs: INodeExpr; rhs: INodeExpr; } export type INodeBinExpr = INodeBinAdd | INodeBinSub | INodeBinMult | INodeBinDiv; export interface INodeIf { _type: "if"; conditionExpr: INodeExpr; scope: INodeScope; else?: INodeScope; } export interface INodeWhile { _type: "while"; conditionExpr: INodeExpr; scope: INodeScope; } export interface INodeReturn { _type: "return"; returnExpr: INodeExpr; } export interface INodeDeclare { _type: "declare"; identifier: IToken; expression: INodeExpr; type: IToken; } export interface INodeFunctionCall { _type: "funcCall"; identifier: IToken; args: INodeExpr[]; } export interface INodeParameter { _type: "parameter"; identifier: IToken; type: IToken; } export interface INodeFunctionDeclare { _type: "declareFun"; identifier: IToken; parameters: INodeParameter[]; functionScope: INodeScope; returnType: IToken; } export interface INodeAssign { _type: "assign"; identifier: IToken; expression: INodeExpr; } export interface INodeScope { _type: "scope"; statements: INodeStatement[]; } export type INodeStatement = INodeReturn | INodeDeclare | INodeFunctionDeclare | INodeAssign | INodeScope | INodeIf | INodeWhile | INodeFunctionCall; export interface INodeProgram { _type: "program"; statements: INodeStatement[]; } const NullExpr: INodeExpr = { value: NULL, _type: "expr" };
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/mman.h> #include <errno.h> #include <string.h> #include <time.h> #include <fcntl.h> #include <unistd.h> #include <sys/resource.h> #include <sys/time.h> double cpu_load(double start, double end, double used) { return used / (end - start) * 100; } double cpu_time_used_s(void) { struct rusage usage; getrusage(RUSAGE_SELF, &usage); // RUSAGE_SELF // 返回调用进程的资源使用统计信息, // 这是所有线程使用的资源的总和 // 过程。 return (double)usage.ru_stime.tv_sec + (double)usage.ru_stime.tv_usec / (double)1000000 + (double)usage.ru_utime.tv_sec + (double)usage.ru_utime.tv_usec / (double)1000000; } double get_time_s() { struct timeval tv; gettimeofday(&tv, NULL); return (double)tv.tv_sec + (double)tv.tv_usec / (double)1000000; } int main(int argc, char *argv[]) { unsigned long x, i; double start = get_time_s(); printf(">>>>>>>my pid is %d\n", getpid()); sleep(5); srand(time(NULL)); x = rand(); for (i = 0; i < 1000000000; i++) { x ^= rand(); x |= rand(); x &= ~rand(); } double end = get_time_s(); double real_time_used = end - start; double cpu_time_used = cpu_time_used_s(); printf("start: %.3fs, end: %.3fs\n" "real_time_used: %.3f\n" "cpu_time_used: %.3fs, cpu_load: %.3f%%\n", start, end, real_time_used, cpu_time_used, cpu_load(start, end, cpu_time_used)); return 0; }
--- description: "Cara Gampang mengolah Sayur bumbu kuning santan (Telor,Tahu,ayam dan kacang panjang) yang mudah" title: "Cara Gampang mengolah Sayur bumbu kuning santan (Telor,Tahu,ayam dan kacang panjang) yang mudah" slug: 2053-cara-gampang-mengolah-sayur-bumbu-kuning-santan-telor-tahu-ayam-dan-kacang-panjang-yang-mudah date: 2020-08-27T02:02:07.908Z image: https://img-global.cpcdn.com/recipes/9762ff36eeccd6ad/751x532cq70/sayur-bumbu-kuning-santan-telortahuayam-dan-kacang-panjang-foto-resep-utama.jpg thumbnail: https://img-global.cpcdn.com/recipes/9762ff36eeccd6ad/751x532cq70/sayur-bumbu-kuning-santan-telortahuayam-dan-kacang-panjang-foto-resep-utama.jpg cover: https://img-global.cpcdn.com/recipes/9762ff36eeccd6ad/751x532cq70/sayur-bumbu-kuning-santan-telortahuayam-dan-kacang-panjang-foto-resep-utama.jpg author: Dennis Massey ratingvalue: 3.7 reviewcount: 6 recipeingredient: - "Bagian Paha ayam potong kecilkecil" - "5 buah Telor Ayam" - "Secukupnya Kacang Panjang" - "2 buah Tahu" - "1 santan kara kecil" - " Bumbu kuning diuleg" - "2 siung bawang merah" - "2 siung bawang putih" - "2 pc kemiri" - "Secukupnya merica" - "1 ruas kunyit" - " Garam" - " Roico" recipeinstructions: - "Rebus dlu ayam lalu buang airnya, tiriskan." - "Rebus/kukus telor -/+10 menit lalu kupas tiriskan" - "Bahan bumbu kuningnya di ulek Lalu tumis hingga harum baru masukan ayam oseng2 sebentar lalu masukan kacang panjang beri air secukupnya lalu masukan telornya setelah mendidih masukan garam,roico lalu cek rasa setelah dirasa sudah matang baru masukan santan aduk2 sebentar lalu angkat dan sajikan boleh kasih taburan bawang goreng." categories: - Resep tags: - sayur - bumbu - kuning katakunci: sayur bumbu kuning nutrition: 293 calories recipecuisine: Indonesian preptime: "PT26M" cooktime: "PT56M" recipeyield: "2" recipecategory: Lunch --- ![Sayur bumbu kuning santan (Telor,Tahu,ayam dan kacang panjang)](https://img-global.cpcdn.com/recipes/9762ff36eeccd6ad/751x532cq70/sayur-bumbu-kuning-santan-telortahuayam-dan-kacang-panjang-foto-resep-utama.jpg) <b><i>sayur bumbu kuning santan (telor,tahu,ayam dan kacang panjang)</i></b>, Memasak merupakan suatu hobi yang menggembirakan dilakukan oleh bermacam kalangan. bukan hanya para bunda, sebagian pria juga banyak yang tertarik dengan kegemaran ini. walaupun hanya untuk sekedar seru seruan dengan teman atau memang sudah menjadi passion dalam dirinya. maka dari itu dalam dunia masakan sekarang sedikit banyak ditemukan pria dengan kemampuan memasak yang sempurna, dan banyak sekali juga kita lihat di bermacam kedai dan cafe yang menggunakan chef laki laki sebagai juru masak andalan nya. Baik, kita mulai ke pembahasan resep resep menu <i>sayur bumbu kuning santan (telor,tahu,ayam dan kacang panjang)</i>. di tengah tengah kegiatan kita, mungkin akan terasa menggembirakan bila sejenak anda menyempatkan sebagian waktu untuk mengolah sayur bumbu kuning santan (telor,tahu,ayam dan kacang panjang) ini. dengan keberhasilan kalian dalam mengolah masakan tersebut, akan menjadikan diri anda bangga akan hasil masakan anda sendiri. apalagi disini dengan situs ini kalian akan dapat pedoman untuk membuat masakan <u>sayur bumbu kuning santan (telor,tahu,ayam dan kacang panjang)</u> tersebut menjadi olahan yang yummy dan sempurna, oleh sebab itu catat alamat situs ini di gadget anda sebagai sebagian rujukan kalian dalam memasak olahan baru yang endes. Sayur tahu bumbu kuning ini akan sangat pas jika disajikan di tengah-tengah keluarga tercinta. Perpaduan tahu serta bumbu Di bawah ini akan kami sajikan resep masakan serta cara membuat sayur tahu bumbu kuning tanpa santan yang gurih dan sederhana. Jika sebelumnya sayur tahu bumbu kuning tidak menggunakan santan, namun berbeda halnya dengan sayur tahu ini. Saat ini langsung saja kita awali untuk menyiapkan alat alat yang diperuntuk kan dalam meracik masakan <u><i>sayur bumbu kuning santan (telor,tahu,ayam dan kacang panjang)</i></u> ini. setidak tidaknya diperlukan <b>13</b> bahan bahan yang diperlukan di menu ini. biar nanti dapat tercapai rasa yang lezat dan menggugah selera. dan juga sisihkan waktu anda sejenak, karena kita akan mengolahnya sedikit banyak dengan <b>3</b> langkah mudah. saya berharap segala yang dibutuhkan sudah kalian punya disini, Baiklah mari kita awali dengan merinci dulu bahan perlengkapan selanjutnya ini. <!--inarticleads1--> ##### Bahan pokok dan bumbu yang dibutuhkan dalam pembuatan Sayur bumbu kuning santan (Telor,Tahu,ayam dan kacang panjang): 1. Siapkan Bagian Paha ayam potong kecil-kecil 1. Gunakan 5 buah Telor Ayam 1. Siapkan Secukupnya Kacang Panjang 1. Siapkan 2 buah Tahu 1. Gunakan 1 santan kara kecil 1. Ambil Bumbu kuning diuleg 1. Ambil 2 siung bawang merah 1. Sediakan 2 siung bawang putih 1. Gunakan 2 pc kemiri 1. Gunakan Secukupnya merica 1. Sediakan 1 ruas kunyit 1. Gunakan Garam 1. Gunakan Roico Tumis ayam kacang panjang kecap. - Tumis bumbu halus hingga matang dan harum, masukkan kacang panjang tumis sebentar. - Masukkan kacang panjang, tahu, dan tomat. - Campur lagi dan ulek dengan kuah santan kuning kental. Tambah jeruk limau untuk menambah kenikmatan rasa. bumbu: garam, gula pasir, merica dan penyedap secukupnya - Masukan telur, tahu dan tempe yang sudah di goreng tadi lalu tes rasa terlebih dahulu - Masak sampai mendidih dan air santan aga menyusut Sayur Bening Bayam, Goreng Tempe dan Sambal. Telor ayam atau telor bebek merupakan bahan lauk pauk yg mudah. Gurih dan Pedasnya Kuah Telur Tahu Santan Pedas, Ini Resep dan Cara Membuatnya Gurih Resep Sayur Kuning Kacang Panjang, Enak Banget Masak Seperti ini. <!--inarticleads2--> ##### Langkah-langkah menyiapkan Sayur bumbu kuning santan (Telor,Tahu,ayam dan kacang panjang): 1. Rebus dlu ayam lalu buang airnya, tiriskan. 1. Rebus/kukus telor -/+10 menit lalu kupas tiriskan 1. Bahan bumbu kuningnya di ulek Lalu tumis hingga harum baru masukan ayam oseng2 sebentar lalu masukan kacang panjang beri air secukupnya lalu masukan telornya setelah mendidih masukan garam,roico lalu cek rasa setelah dirasa sudah matang baru masukan santan aduk2 sebentar lalu angkat dan sajikan boleh kasih taburan bawang goreng. Resep Sayur Santan Kacang Panjang Super Enak Dan Praktis dapat anda lihat pada video slide berikut ini dan untuk lebih. Penjelasan lengkap seputar Resep Ayam Bumbu Rujak yang Enak, Lezat, Mudah, Simple. Dibuat dari Bumbu dan Rempah Pilihan Khas Jawa Ala Masukkan santan dan gula merah setelah ayamnya terlihat cukup matang. Bumbu tinggal diiris-iris, siapkan santan dan dalam sekejap sayur siap dihidangkan. Tambahkan santan kemudian masukkan irisan tahu. Berikut sedikit pengulasan hidangan tentang resep <u>sayur bumbu kuning santan (telor,tahu,ayam dan kacang panjang)</u> yang lezat. kami harap kalian dapat mengerti dengan tulisan diatas, dan kalian dapat mengolah lagi di acara lain untuk di sajikan dalam saat saat kegiatan family atau sahabat kalian. kita bs menambahkan resep resep yang ditampilkan diatas sesuai dengan keinginan anda, sehingga masakan <b>sayur bumbu kuning santan (telor,tahu,ayam dan kacang panjang)</b> ini bs menjadi lebih enak dan sempurna lagi. demikianlah penjabaran singkat ini, sampai berjumpa kembali di lain kesempatan. kami harap hari anda menyenangkan.
package nextcp.domainmodel.device.mediaserver.search; import java.util.ArrayList; import java.util.List; import org.jupnp.support.model.DIDLContent; import org.jupnp.support.model.container.Container; import org.jupnp.support.model.item.Item; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import nextcp.dto.ContainerDto; import nextcp.dto.MusicItemDto; import nextcp.dto.SearchRequestDto; import nextcp.dto.SearchResultDto; import nextcp.upnp.GenActionException; import nextcp.upnp.device.mediaserver.MediaServerDevice; import nextcp.upnp.modelGen.schemasupnporg.contentDirectory1.ContentDirectoryService; import nextcp.upnp.modelGen.schemasupnporg.contentDirectory1.actions.SearchInput; import nextcp.upnp.modelGen.schemasupnporg.contentDirectory1.actions.SearchOutput; import nextcp.util.DidlContent; /** * Content Directory Service - Search Support Class */ public class SearchSupport { private static final Logger log = LoggerFactory.getLogger(SearchSupport.class.getName()); private ContentDirectoryService contentDirectoryService = null; private DidlContent didlContent = new DidlContent(); private MediaServerDevice mediaServerDevice = null; private String searchCaps = ""; public SearchSupport(ContentDirectoryService contentDirectoryService, MediaServerDevice mediaServerDevice) { this.contentDirectoryService = contentDirectoryService; this.mediaServerDevice = mediaServerDevice; try { searchCaps = contentDirectoryService.getSearchCapabilities().SearchCaps; } catch (GenActionException e) { log.warn(String.format("%s -> %s", "No search capability for device", e.description)); } catch (Exception e) { log.info("no search capability available ... ", e); } } public String getSearchCaps() { return searchCaps; } /** * Quick Search delivers first elements of Songs, Albums, Artists and Playlists. Sorting is optimized to deliver liked or better rated music * * @param searchRequest * @return */ public SearchResultDto quickSearch(SearchRequestDto searchRequest) { String quickSearch = searchRequest.searchRequest; long requestCount = adjustRequestCount(searchRequest.requestCount); SearchResultDto container = initEmptySearchResultContainer(); searchAndAddMusicItems(quickSearch, "-upnp:rating, +dc:title", container, requestCount); searchAndAddArtistContainer(quickSearch, searchRequest.sortCriteria, container, requestCount); searchAndAddAlbumContainer(quickSearch, "-ums:likedAlbum, +dc:title", container, requestCount); searchAndAddPlaylistContainer(quickSearch, searchRequest.sortCriteria, container, requestCount); return container; } private long adjustRequestCount(Long givenRequestCount) { if (givenRequestCount == null) { return 3; } givenRequestCount = Math.min(999, givenRequestCount); givenRequestCount = Math.max(2, givenRequestCount); return givenRequestCount; } private void searchAndAddPlaylistContainer(String quickSearch, String sortCriteria, SearchResultDto container, long requestCount) { searchAndAddArtistContainer(quickSearch, sortCriteria, container.playlistItems, "object.container.playlistContainer", requestCount); } private void searchAndAddAlbumContainer(String quickSearch, String sortCriteria, SearchResultDto container, long requestCount) { searchAndAddArtistContainer(quickSearch, sortCriteria, container.albumItems, "object.container.album", requestCount); } private void searchAndAddArtistContainer(String quickSearch, String sortCriteria, SearchResultDto container, long requestCount) { searchAndAddArtistContainer(quickSearch, sortCriteria, container.artistItems, "object.container.person", requestCount); } private void searchAndAddArtistContainer(String quickSearch, String sortCriteria, List<ContainerDto> container, String upnpClass, long requestCount) { SearchInput searchInput = new SearchInput(); searchInput.ContainerID = "0"; searchInput.SearchCriteria = String.format("( upnp:class derivedfrom \"%s\" and dc:title contains \"%s\")", upnpClass, quickSearch); searchInput.StartingIndex = 0L; searchInput.Filter = "*"; searchInput.RequestedCount = requestCount; searchInput.SortCriteria = sortCriteria; SearchOutput out = contentDirectoryService.search(searchInput); DIDLContent didl; try { didl = didlContent.generateDidlContent(out.Result); if (didl != null) { addContainerObjects(container, didl); } } catch (Exception e) { log.warn("search error", e); } } private void searchAndAddMusicItems(String quickSearch, String sortCriteria, SearchResultDto container, Long requestCount) { StringBuilder sb = new StringBuilder(); sb.append("( upnp:class = \"object.item.audioItem.musicTrack\""); // upnp:class derivedfrom “object.container.person” sb.append(String.format(" and dc:title contains \"%s\")", quickSearch)); SearchInput searchInput = new SearchInput(); searchInput.ContainerID = "0"; searchInput.SearchCriteria = sb.toString(); searchInput.StartingIndex = 0L; searchInput.Filter = "*"; searchInput.RequestedCount = requestCount; searchInput.SortCriteria = sortCriteria; DIDLContent didl; try { SearchOutput out = contentDirectoryService.search(searchInput); didl = didlContent.generateDidlContent(out.Result); if (didl != null) { addItemObjects(container.musicItems, didl); } } catch (Exception e) { log.warn("search error", e); } } private SearchResultDto initEmptySearchResultContainer() { SearchResultDto dto = new SearchResultDto(); dto.albumItems = new ArrayList<ContainerDto>(); dto.artistItems = new ArrayList<ContainerDto>(); dto.musicItems = new ArrayList<>(); dto.playlistItems = new ArrayList<>(); return dto; } private void addContainerObjects(List<ContainerDto> container, DIDLContent didl) { for (Container didlObject : didl.getContainers()) { ContainerDto containerDto = mediaServerDevice.getDtoBuilder().buildContainerDto(didlObject); containerDto.mediaServerUDN = mediaServerDevice.getUDN().getIdentifierString(); container.add(containerDto); } } private void addItemObjects(List<MusicItemDto> result, DIDLContent didl) { for (Item item : didl.getItems()) { MusicItemDto itemDto = mediaServerDevice.getDtoBuilder().buildItemDto(item, mediaServerDevice.getUDN().getIdentifierString()); result.add(itemDto); } } // // search all from one type // public SearchResultDto searchAllItems(SearchRequestDto searchRequest) { SearchResultDto container = initEmptySearchResultContainer(); searchAndAddMusicItems(searchRequest.searchRequest, searchRequest.sortCriteria, container, adjustRequestCount(searchRequest.requestCount)); return container; } public SearchResultDto searchAllArtists(SearchRequestDto searchRequest) { SearchResultDto container = initEmptySearchResultContainer(); searchAndAddArtistContainer(searchRequest.searchRequest, searchRequest.sortCriteria, container, adjustRequestCount(searchRequest.requestCount)); return container; } public SearchResultDto searchAllAlbum(SearchRequestDto searchRequest) { SearchResultDto container = initEmptySearchResultContainer(); searchAndAddAlbumContainer(searchRequest.searchRequest, searchRequest.sortCriteria, container, adjustRequestCount(searchRequest.requestCount)); return container; } public SearchResultDto searchAllPlaylist(SearchRequestDto searchRequest) { SearchResultDto container = initEmptySearchResultContainer(); searchAndAddPlaylistContainer(searchRequest.searchRequest, searchRequest.sortCriteria, container, adjustRequestCount(searchRequest.requestCount)); return container; } }
(ns status-im2.contexts.wallet.create-account.view (:require [quo.core :as quo] [quo.theme :as quo.theme] [react-native.core :as rn] [react-native.safe-area :as safe-area] [reagent.core :as reagent] [status-im2.common.standard-authentication.standard-auth.view :as standard-auth] [status-im2.contexts.wallet.common.utils :as utils] [status-im2.contexts.wallet.create-account.style :as style] [utils.i18n :as i18n] [utils.re-frame :as rf])) (def diamond-emoji "\uD83D\uDC8E") (defn keypair-string [full-name] (let [first-name (utils/get-first-name full-name)] (i18n/label :t/keypair-title {:name first-name}))) (defn get-keypair-data [name derivation-path] [{:title (keypair-string name) :button-props {:title (i18n/label :t/edit)} :left-icon :i/placeholder :description :text :description-props {:text (i18n/label :t/on-device)}} {:title (i18n/label :t/derivation-path) :button-props {:title (i18n/label :t/edit)} :left-icon :i/derivated-path :description :text :description-props {:text derivation-path}}]) (defn- view-internal [] (let [top (safe-area/get-top) bottom (safe-area/get-bottom) account-color (reagent/atom :blue) emoji (reagent/atom diamond-emoji) number-of-accounts (count (rf/sub [:profile/wallet-accounts])) account-name (reagent/atom (i18n/label :t/default-account-name {:number (inc number-of-accounts)})) derivation-path (reagent/atom (utils/get-derivation-path number-of-accounts)) {:keys [public-key]} (rf/sub [:profile/profile]) on-change-text #(reset! account-name %) display-name (first (rf/sub [:contacts/contact-two-names-by-identity public-key]))] (fn [{:keys [theme]}] [rn/view {:style {:flex 1 :margin-top top}} [quo/page-nav {:type :no-title :background :blur :right-side [{:icon-name :i/info}] :icon-name :i/close :on-press #(rf/dispatch [:navigate-back])}] [quo/gradient-cover {:customization-color @account-color :container-style (style/gradient-cover-container top)}] [rn/view {:style style/account-avatar-container} [quo/account-avatar {:customization-color @account-color :size 80 :emoji @emoji :type :default}] [quo/button {:size 32 :type :grey :background :photo :icon-only? true :on-press #(rf/dispatch [:emoji-picker/open {:on-select (fn [selected-emoji] (reset! emoji selected-emoji))}]) :container-style style/reaction-button-container} :i/reaction]] [quo/title-input {:customization-color @account-color :placeholder "Type something here" :on-change-text on-change-text :max-length 24 :blur? true :disabled? false :default-value @account-name :container-style style/title-input-container}] [quo/divider-line] [rn/view {:style style/color-picker-container} [quo/text {:size :paragraph-2 :weight :medium :style (style/color-label theme)} (i18n/label :t/colour)] [quo/color-picker {:default-selected @account-color :on-change #(reset! account-color %) :container-style {:padding-horizontal 12 :padding-vertical 12}}]] [quo/divider-line] [quo/category {:list-type :settings :label (i18n/label :t/origin) :data (get-keypair-data display-name @derivation-path)}] [standard-auth/view {:size :size-48 :track-text (i18n/label :t/slide-to-create-account) :customization-color @account-color :on-enter-password (fn [entered-password] (rf/dispatch [:wallet/derive-address-and-add-account entered-password {:emoji @emoji :color @account-color :path @derivation-path :account-name @account-name}])) :biometric-auth? false :auth-button-label (i18n/label :t/confirm) :container-style (style/slide-button-container bottom)}]]))) (def view (quo.theme/with-theme view-internal))
// // LessonCollectionViewCell.swift // α // // Created by Sola on 2021/1/14. // Copyright © 2021 Sola. All rights reserved. // import UIKit class LessonCollectionViewCell: UICollectionViewCell { // MARK: - Models var lesson: Lesson! // MARK: - Controllers // TODO: protocol var delegate: LessonViewController! // MARK: - Views lazy var view: UIView = { let view = UIView() return view }() lazy var lessonButton: UIButton = { let button = UIButton() view.addSubview(button) button.setTitleColor(.white, for: .normal) button.layer.cornerRadius = 8 button.backgroundColor = .black button.titleLabel?.font = UIFont(name: "Chalkduster", size: LessonCollectionViewCell.fontSize) button.addTarget(self, action: #selector(lessonButtonTapped), for: .touchUpInside) return button }() // MARK: - Init override init(frame: CGRect) { super.init(frame: frame) updateViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) fatalError("init(coder:) has not been implemented") } func updateViews() { contentView.addSubview(view) view.snp.makeConstraints { (make) in make.width.equalToSuperview().multipliedBy(LessonCollectionViewCell.sizeRatio) make.height.equalToSuperview().multipliedBy(LessonCollectionViewCell.sizeRatio) make.centerX.equalToSuperview() make.centerY.equalToSuperview() } lessonButton.snp.makeConstraints { (make) in make.height.equalToSuperview() make.width.equalToSuperview() make.centerX.equalToSuperview() make.centerY.equalToSuperview() } } func updateValues(lesson: Lesson?, delegate: LessonViewController) { self.lesson = lesson self.delegate = delegate if let lesson = lesson { lessonButton.setTitle(String(lesson.id), for: .normal) } else { lessonButton.setTitle("", for: .normal) } } // MARK: - Actions @objc func lessonButtonTapped() { if let lesson = lesson { let functionSelectionViewController = FunctionsViewController() functionSelectionViewController.updateValues(lesson: lesson, delegate: delegate) delegate.navigationController?.pushViewController(functionSelectionViewController, animated: true) } } } extension LessonCollectionViewCell { static let sizeRatio: CGFloat = 0.9 static let fontSize: CGFloat = UIScreen.main.bounds.width * 0.05 }
--- title: Testare i tuoi provider --- import { AutoSnippet, When } from "../../../../../src/components/CodeSnippet"; import createContainer from "!!raw-loader!/docs/essentials/testing/create_container.dart"; import unitTest from "!!raw-loader!/docs/essentials/testing/unit_test.dart"; import widgetTest from "!!raw-loader!/docs/essentials/testing/widget_test.dart"; import fullWidgetTest from "!!raw-loader!/docs/essentials/testing/full_widget_test.dart"; import widgetContainerOf from "!!raw-loader!/docs/essentials/testing/widget_container_of.dart"; import providerToMock from "/docs/essentials/testing/provider_to_mock"; import mockProvider from "!!raw-loader!/docs/essentials/testing/mock_provider.dart"; import autoDisposeListen from "!!raw-loader!/docs/essentials/testing/auto_dispose_listen.dart"; import listenProvider from "!!raw-loader!/docs/essentials/testing/listen_provider.dart"; import awaitFuture from "!!raw-loader!/docs/essentials/testing/await_future.dart"; import notifierMock from "/docs/essentials/testing/notifier_mock"; Una parte fondamentale delle API di Riverpod è l'abilità di testare i tuoi provider in modo isolato. Per una suite di test adeguata, ci sono alcune sfide da superare: - I test non dovrebbero condividere lo stato. Ciò significa che nuovi test non dovrebbero essere influenzati dai test precedenti. - I test dovrebbero darci l'abilità di emulare certe funzionalità per ottenere lo stato desiderato. - L'ambiente di test dovrebbe essere il più vicino possibile all'ambiente reale. Fortunatamente, Riverpod semplifica il raggiungimento di tutti questi obiettivi. ## Impostare un test Quando si definisce un test con Riverpod, ci sono due scenari principali: - Test unitari, di solito senza dipendenze di Flutter. Possono essere utili per testare il comportamento di un provider isolamente. - Test di widget, di solito con dipendenze di Flutter. Possono essere utili per testare il comportamento di un widget che utilizza un provider. ### Test unitari I test unitari sono definit usando la funzione `test` da [package:test](https://pub.dev/packages/test) La differenza principale con qualsiasi altro test è che creeremo un oggetto `ProviderContainer`. Questo oggetto permetterà al nostro test di interagire con i provider Si consiglia di creare un'utilità di test sia per la creazione che per l'eliminazione di un oggetto `ProviderContainer`: <AutoSnippet raw={createContainer} /> Successivamente, possiamo definire un `test` utilizzando questa utilità: <AutoSnippet raw={unitTest} /> Ora che abbiamo un ProviderContainer possiamo utilizzarlo per leggere i provider usando: - `container.read`, per leggere il valore corrente di un provider. - `container.listen`, per restare in ascolto di un provider ed essere notificato dei suoi cambiamenti. :::caution Fai attenzione quando usi `container.read` quando i provider sono distrutti automaticamente. Se il tuo provider non è ascoltato, ci sono chances che il suo stato verrà distrutto nel mezzo del nostro test. In quel caso, considera utilizzare `container.listen`. Il suo valore di ritorno permette comunque di leggere il valore corrente del provider, ma si assicurerà anche che il provider non venga distrutto nel mezzo del tuo test: <AutoSnippet raw={autoDisposeListen} /> ::: ### Test di widget I test dei widget sono definiti usando la funzione `testWidgets` da [package:flutter_test](https://pub.dev/packages/flutter_test). In questo caso, la differenza principale con i normali test di widget è che dobbiamo aggiungere un widget `ProviderScope` alla radice di `tester.pumpWidget`. <AutoSnippet raw={widgetTest} /> Questo è simile a quello che facciamo quando abilitiamo Riverpod nella nostra app Flutter. Successivamente, possiamo usare `tester` per interagire col nostro widget. In alternativa, se vuoi interagire coi tuoi provider, puoi ottenere un `ProviderContainer`. Un oggetto `ProviderContainer` può essere ottenuto usando `ProviderScope.containerOf(buildContext)`. Usando `tester` possiamo quindi scrivere quanto segue: <AutoSnippet raw={widgetContainerOf} /> Possiamo quindi usarlo per leggere i provider. Di seguito un esempio completo: <AutoSnippet raw={fullWidgetTest} /> ## Mock/Imitare provider Fino ad ora abbiamo visto come impostare un test ed interagire in modo semplice con i provider. Tuttavia, in alcuni casi, potremmo voler imitare un provider. La parte interessante: tutti i provider possono essere imitati di default, senza nessun impostazione aggiuntiva. Questo è possibile specificando il parametro `overrides` su `ProviderScope` o `ProviderContainer`. Consideriamo il provider seguente: <AutoSnippet {...providerToMock} /> Possiamo imitarlo usando: <AutoSnippet raw={mockProvider} /> ## Spiare i cambiamenti in un provider Dato che abbiamo ottenuto un `ProviderContainer` nei nostri test, è possibile usarlo per "ascoltare" un provider: <AutoSnippet raw={listenProvider} /> Puoi combinare questo con pacchetti come [mockito](https://pub.dev/packages/mockito) o [mocktail](https://pub.dev/packages/mocktail) per usare la loro API `verify`. O più semplicemente, puoi aggiungere tutti i cambiamenti in una lista e controllarli tramite 'assert'. ## Aspettare provider asincroni In Riverpod è molto comune per i provider restituire un Future/Stream. In questo caso, ci sono chances che i nostri test abbiano bisogno di aspettare che quelle operazioni asincrone siano completate. Un modo per farlo è leggere il `.future` di un provider: <AutoSnippet raw={awaitFuture} /> ## Imitare i Notifier È generalmente sconsigliato imitare i Notifier. Invece, dovresti probabilmente introdurre un livello di astrazione nella logica del tuo Notifier, in modo tale da poter imitare tale astrazione. Per esempio, al posto di imitare un Notifier, potresti imitare un "repository" che il Notifier usa per ottenere i dati. Se vuoi insistere nell'imitare un Notifier, esiste una considerazione speciale per creare un mock di questo tipo: il tuo mock deve essere una subclass della classe base del Notifier: non puoi implementare (via "implements") un Notifier, poichè romperebbe l'interfaccia. Pertanto, quando si imita un Notifier, invece di scrivere il codice mockito seguente: ```dart class MyNotifierMock with Mock implements MyNotifier {} ``` Dovresti invece scrivere: <AutoSnippet {...notifierMock} /> <When codegen={true}> Per far sì che funzioni, il tuo mock deve essere posto nello stesso file del Notifier che stai imitando. Altrimenti, non avresti accesso alla classe `_$MyNotifier`. </When>
<div class="row"> <h2>Modifier les structures</h2> <div class="col-md"> <h4>Structure status : En ligne</h4> <ul class="list-group" *ngFor="let structure of structures"> <li class="list-group-item" *ngIf="structure.status === 'online'"> <h4>{{ structure.name }}</h4> <p>{{ structure._id }}</p> <p>Email : {{ structure.email }}</p> <p>Adresse : {{ structure.address }}</p> <p>Type de structure : {{ structure.type }}</p> <p>Statut : {{ structure.status }}</p> <div> <button class="btn btn-primary" (click)="onUpdate([structure._id])" style="margin-right: 10px;" > Modifier </button> </div> <div class="form-group"> <select class="custom-select" style=" width: 250px; height: 38px; border-radius: 10; margin-top: 10px; " placeholder="{{ structure.moderation }}" value="{{ structure.moderation }}" (change)="editModeration($event, structure._id)" > <option value="incomplete">Manque d'informations</option> <option value="validate">Valider</option> </select> </div> </li> </ul> </div> <div class="col-md"> <h4>Structure status : Brouillon</h4> <ul class="list-group" *ngFor="let structure of structures"> <li class="list-group-item" *ngIf="structure.status === 'draft'"> <h4>{{ structure.name }}</h4> <p>{{ structure._id }}</p> <p>Email : {{ structure.email }}</p> <p>Adresse : {{ structure.address }}</p> <p>Type de structure : {{ structure.type }}</p> <p>Statut : {{ structure.status }}</p> <div> <button class="btn btn-primary" (click)="onUpdate([structure._id])" style="margin-right: 10px;" > Modifier </button> </div> <div class="form-group"> <select class="custom-select" style=" width: 250px; height: 38px; border-radius: 10; margin-top: 10px; " placeholder="{{ structure.moderation }}" value="{{ structure.moderation }}" (change)="editModeration($event, structure._id)" > <option value="incomplete">Manque d'informations</option> <option value="validate">Valider</option> </select> </div> </li> </ul> </div> </div> <!-- <input type="text" value="{{ structure.email }}" /> <input type="text" value="{{ structure.address }}" /> <select id="status" class="form-control" name="{{ structure.type }}" value="{{ structure.type }}" ngModel > <option value="distribution">Distribution</option> <option value="douche">Douche</option> <option value="wifi">Wifi</option> </select> <select id="status" class="form-control" value="{{ structure.status }}" ngModel > <option value="brouillon">Brouillon</option> <option value="enligne">En ligne</option> </select> -->
package com.yjkj.chainup.new_version.fragment import android.os.Handler import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.View import com.google.gson.Gson import com.yjkj.chainup.R import com.yjkj.chainup.base.NBaseFragment import com.yjkj.chainup.db.constant.ParamConstant import com.yjkj.chainup.extra_service.arouter.ArouterUtil import com.yjkj.chainup.extra_service.eventbus.EventBusUtil import com.yjkj.chainup.extra_service.eventbus.MessageEvent import com.yjkj.chainup.util.LanguageUtil import com.yjkj.chainup.manager.NCoinManager import com.yjkj.chainup.new_version.adapter.MarketDetailAdapter import com.yjkj.chainup.new_version.home.callback.MarketTabDiffCallback import com.yjkj.chainup.new_version.view.EmptyForAdapterView import com.yjkj.chainup.util.ContextUtil import com.yjkj.chainup.util.LogUtil import com.yjkj.chainup.util.Utils import com.yjkj.chainup.util.getSymbolChannel import com.yjkj.chainup.ws.WsAgentManager import kotlinx.android.synthetic.main.fragment_market_detail.rv_market_detail import kotlinx.android.synthetic.main.fragment_market_detail.swipe_refresh import kotlinx.android.synthetic.main.include_market_sort.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.imageResource import org.json.JSONObject /** * @Author: Bertking * @Date:2019-06-15-15:26 * @Description: */ class MarketTrendFragment : NBaseFragment() { override fun setContentView() = R.layout.fragment_market_detail override fun initView() { tv_name?.text = LanguageUtil.getString(context, "home_action_coinNameTitle") tv_new_price?.text = LanguageUtil.getString(context, "home_text_dealLatestPrice") tv_limit?.text = LanguageUtil.getString(context, "common_text_priceLimit") swipe_refresh.setColorSchemeColors(ContextUtil.getColor(R.color.colorPrimary)) initAdapter() setOnclick() setOnScrowListener() } override fun loadData() { super.loadData() marketName = arguments?.getString(MARKET_NAME) ?: "" curIndex = arguments?.getInt(CUR_INDEX) ?: 1 if (null == marketName || marketName.isEmpty()) return symbols = NCoinManager.getMarketByName(marketName) if (null == symbols || symbols.isEmpty()) return oriSymbols.addAll(symbols) normalTickList.clear() normalTickList.addAll(oriSymbols) normalTickList?.sortBy { it?.optInt("sort") } normalTickList.sortBy { it.optInt("newcoinFlag") } } var adapterScroll = true private fun setOnScrowListener() { rv_market_detail?.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) adapterScroll = ParamConstant.ONSCROLLSTATECHANGED == newState } }) } private fun initAdapter() { if (null == adapter) { adapter = MarketDetailAdapter() rv_market_detail?.layoutManager = LinearLayoutManager(mActivity) rv_market_detail?.adapter = adapter adapter?.notifyDataSetChanged() rv_market_detail?.isNestedScrollingEnabled = false rv_market_detail?.setHasFixedSize(true) ll_item_titles?.visibility = View.VISIBLE adapter?.setEmptyView(EmptyForAdapterView(context ?: return)) } adapter?.setList(normalTickList) initReq() adapter?.setOnItemClickListener { adapter, _, position -> adapter.apply { val model = (data.get(position) as JSONObject) ArouterUtil.forwardKLine(model.optString("symbol")) } } } /** * 原始 */ private var oriSymbols = arrayListOf<JSONObject>() private var normalTickList = arrayListOf<JSONObject>() var adapter: MarketDetailAdapter? = null private var marketName = "" private var curIndex = 1 private var symbols = arrayListOf<JSONObject>() var nameIndex = 0 var newPriceIndex = 0 var limitIndex = 0 var isScrollStatus = false /** * 点击事件 */ fun setOnclick() { /** * 点击名称 */ ll_name.setOnClickListener { refreshTransferImageView(0) adapter?.isMarketSort = false val normalTickList = adapter?.data if (normalTickList.isNullOrEmpty()) return@setOnClickListener when (nameIndex) { /** * 正常 */ 0 -> { normalTickList.sortBy { NCoinManager.showAnoterName(it) } normalTickList.sortBy { it.optInt("newcoinFlag") } nameIndex = 1 iv_name_up?.imageResource = R.drawable.quotes_up_daytime } /** * 正序 */ 1 -> { normalTickList.sortByDescending { NCoinManager.showAnoterName(it) } normalTickList.sortBy { it.optInt("newcoinFlag") } nameIndex = 2 iv_name_up?.imageResource = R.drawable.quotes_under_daytime } /** * 倒序 */ 2 -> { normalTickList.sortBy { it.optInt("sort") } normalTickList.sortBy { it.optInt("newcoinFlag") } nameIndex = 0 iv_name_up?.imageResource = R.drawable.quotes_upanddown_default_daytime } } refreshAdapter(normalTickList as ArrayList<JSONObject>) } /** * 点击最新价 */ ll_new_price.setOnClickListener { refreshTransferImageView(1) val normalTickList = adapter?.data if (normalTickList.isNullOrEmpty()) return@setOnClickListener when (newPriceIndex) { /** * 正常 */ 0 -> { normalTickList.sortBy { it.optDouble("close") } newPriceIndex = 1 iv_new_price?.imageResource = R.drawable.quotes_up_daytime } /** * 正序 */ 1 -> { normalTickList.sortByDescending { it.optDouble("close") } newPriceIndex = 2 iv_new_price?.imageResource = R.drawable.quotes_under_daytime } /** * 倒序 */ 2 -> { normalTickList.sortBy { it.optInt("sort") } normalTickList.sortBy { it.optInt("newcoinFlag") } newPriceIndex = 0 iv_new_price?.imageResource = R.drawable.quotes_upanddown_default_daytime } } adapter?.isMarketSort = newPriceIndex != 0 refreshAdapter(normalTickList as ArrayList<JSONObject>) } /** * 点击24小时涨幅 */ ll_limit.setOnClickListener { refreshTransferImageView(2) val normalTickList = adapter?.data if (normalTickList.isNullOrEmpty()) return@setOnClickListener when (limitIndex) { /** * 正常 */ 0 -> { normalTickList.sortBy { it.optDouble("rose", 0.0) } limitIndex = 1 iv_new_limit?.imageResource = R.drawable.quotes_up_daytime } /** * 正序 */ 1 -> { normalTickList.sortByDescending { it.optDouble("rose", 0.0) } limitIndex = 2 iv_new_limit?.imageResource = R.drawable.quotes_under_daytime } /** * 倒序 */ 2 -> { normalTickList.sortBy { it.optInt("sort") } normalTickList.sortBy { it.optInt("newcoinFlag") } limitIndex = 0 iv_new_limit?.imageResource = R.drawable.quotes_upanddown_default_daytime } } adapter?.isMarketSort = limitIndex != 0 refreshAdapter(normalTickList as ArrayList<JSONObject>) } /** * 此处刷新 */ swipe_refresh?.setOnRefreshListener { isScrollStatus = true /** * 刷新数据操作 */ loadData() swipe_refresh?.isRefreshing =false } } fun handleData(data: String) { try { val json = JSONObject(data) if (!json.isNull("tick")) { doAsync { val quotesData = json showWsData(quotesData) } } else { if (!json.isNull("data")) { doAsync { val array = json.optJSONObject("data") if (null != array && array.length() > 0) { val it = array.keys() val wsArrayMap = hashMapOf<String, JSONObject>() normalTickList.forEach { val key = it.getString("symbol") val tick = array.optJSONObject(key) if (tick != null) { val itemObj = JSONObject() itemObj.put("tick", tick) itemObj.put("channel", "market_${key}_ticker") wsArrayMap.put(itemObj.optString("channel", ""), itemObj) } } LogUtil.e(TAG, "dropListsAdapter req ${marketName} list ${normalTickList.size} ${wsArrayMap.size}") dropListsAdapter(wsArrayMap) } } } } } catch (e: Exception) { e.printStackTrace() } } @Synchronized private fun showWsData(jsonObject: JSONObject) { if (normalTickList.isEmpty()) return val dataDiff = callDataDiff(jsonObject) if (dataDiff != null) { val items = dataDiff.second dropListsAdapter(items) wsArrayTempList.clear() wsArrayMap.clear() } } fun startInit() { Handler().postDelayed({ pageEventSymbol() }, 200) } private fun refreshTransferImageView(status: Int) { when (status) { 0 -> { iv_new_price?.imageResource = R.drawable.quotes_upanddown_default_daytime iv_new_limit?.imageResource = R.drawable.quotes_upanddown_default_daytime newPriceIndex = 0 limitIndex = 0 } 1 -> { iv_name_up?.imageResource = R.drawable.quotes_upanddown_default_daytime iv_new_limit?.imageResource = R.drawable.quotes_upanddown_default_daytime nameIndex = 0 limitIndex = 0 } 2 -> { iv_name_up?.imageResource = R.drawable.quotes_upanddown_default_daytime iv_new_price?.imageResource = R.drawable.quotes_upanddown_default_daytime nameIndex = 0 newPriceIndex = 0 } } } private fun refreshAdapter(list: ArrayList<JSONObject>) { adapter?.replaceData(list) } private fun pageEventSymbol() { if (normalTickList.size == 0) { return } val arrays = arrayOfNulls<String>(normalTickList.size) for ((index, item) in normalTickList.withIndex()) { arrays.set(index, item.getString("symbol")) } forwardMarketTab(arrays) } private fun forwardMarketTab(coin: Array<String?>, isBind: Boolean = true) { val messageEvent = MessageEvent(MessageEvent.market_event_page_symbol_type) messageEvent.msg_content = hashMapOf("symbols" to coin, "bind" to isBind, "curIndex" to 1) EventBusUtil.post(messageEvent) } private val wsArrayTempList: ArrayList<JSONObject> = arrayListOf() private val wsArrayMap = hashMapOf<String, JSONObject>() private var wsTimeFirst: Long = 0L @Synchronized private fun callDataDiff(jsonObject: JSONObject): Pair<ArrayList<JSONObject>, HashMap<String, JSONObject>>? { if (System.currentTimeMillis() - wsTimeFirst >= 2000L && wsTimeFirst != 0L) { // 大于一秒 wsTimeFirst = 0L if (wsArrayMap.size != 0) { return Pair(wsArrayTempList, wsArrayMap) } } else { if (wsTimeFirst == 0L) { wsTimeFirst = System.currentTimeMillis() } wsArrayTempList.add(jsonObject) wsArrayMap.put(jsonObject.optString("channel", ""), jsonObject) } return null } @Synchronized fun dropListsAdapter(items: HashMap<String, JSONObject>) { val data = adapter?.data if (data?.isEmpty()!!) { return } val message = Gson().toJson(data) val jsonCopy = Utils.jsonToArrayList(message, JSONObject::class.java) val tempNew = jsonCopy for ((index, item) in items.entries) { val jsonObject = item val channel = jsonObject.optString("channel") var tempData = -1 for ((coinIndex, coinItem) in data.withIndex()) { if (channel == coinItem.optString("symbol").getSymbolChannel()) { tempData = coinIndex break } } if (tempData != -1) { val tick = jsonObject.optJSONObject("tick") val model = tempNew.get(tempData) model.put("rose", tick?.optString("rose")) model.put("close", tick?.optString("close")) model.put("vol", tick?.optString("vol")) tempNew.set(tempData, model) } } if (newPriceIndex != 0 || limitIndex != 0) { if (newPriceIndex != 0) { when (newPriceIndex) { 1 -> { tempNew.sortBy { it.optDouble("close", 0.0) } } 2 -> { tempNew.sortByDescending { it.optDouble("close", 0.0) } } } } else if (limitIndex != 0) { when (limitIndex) { 1 -> { tempNew.sortBy { it.optDouble("rose", 0.0) } } 2 -> { tempNew.sortByDescending { it.optDouble("rose", 0.0) } } } } } val diffCallback = MarketTabDiffCallback(data, tempNew) activity?.runOnUiThread { adapter?.setDiffData(diffCallback) } } private fun initReq() { val data = WsAgentManager.instance.reqJson if (data != null) { doAsync { normalTickList.forEach { val key = it.getString("symbol") val tick = data.get(key) if (tick != null) { it.put("rose", tick.get("rose")) it.put("close", tick.get("close")) it.put("vol", tick.get("vol")) } } activity?.runOnUiThread { adapter?.setList(normalTickList) } } } } }
rm(list = ls()) library(Matrix) # for sparse matrix library(tidyverse) T = 601 T.eff = T - 1 # effective T, due to one lag N = 15 time.marker = rep(1:T, N) # to hand the diff between y and its lag # dependent variable and regressors Y.raw <- rnorm(N*T) Y <- matrix( Y.raw[time.marker != 1], ncol = 1 ) # remove the start of each state. (T.eff*N)-vector X <- matrix( Y.raw[time.marker != T], ncol = N ) # lagged variables in matrix. T.eff-by-N matrix XX <- kronecker( diag(N), X ) %>% Matrix() # regressors into a big matrix ## dummy variables state.index = rep(1:N, each = T.eff) state.D <- fastDummies::dummy_cols(state.index, remove_first_dummy = TRUE) %>% data.matrix( ) %>% Matrix( ) hour.index <- rep( c( rep(1:24, length.out = T) ), N) hour.index <- hour.index[time.marker != 1 ] # similar to (Y.raw -> Y) hour.D <- fastDummies::dummy_cols(hour.index, remove_first_dummy = TRUE) %>% data.matrix( ) %>% Matrix( ) # dummies and regressors together DX <- cbind(state.D, hour.D, XX) ## OLS bhat <- solve( t(DX)%*% DX, t(DX)%*% Y )
<!DOCTYPE html> <html lang="en-US"><head> <meta charset="UTF-8" /> <title>Sudoku Game</title> <!-- CS 3312, spring 2017 Final Project YOUR NAME(s): Anna Porter and Michael McCarver --> <!-- GOALS: Create basic sudoku layout without pencil marks Save previous input Clear previous input for all and for each puzzle Have multiple puzzles of different difficulties Must have interactive elements Must be organized using model view controller (studio 8) model seperate from view seperate from controller Written proposal due next week --> <!-- Import a CSS stylesheet to style the page. --> <link href="style.css" rel="stylesheet" /> </head><body> <h1> Sudoku Puzzles </h1> <h2 class="timer"><time>00:00:00</time></h2> <!-- Puzzle Selectors --> <div class = "dropdown" id="easy"> <button class = "dropbtn">Easy</button> <div id="my-dropdown" class = "dropdown-content"> <button class="puzzle-select" id="easy-1">Easy 1</button> <button class="puzzle-select" id="easy-2">Easy 2</button> <button class="puzzle-select" id="easy-3">Easy 3</button> </div> </div> <div class = "dropdown" id="medium"> <button class = "dropbtn">Medium</button> <div id="my-dropdown" class = "dropdown-content"> <button class="puzzle-select" id="medium-1">Medium 1</button> <button class="puzzle-select" id="medium-2">Medium 2</button> <button class="puzzle-select" id="medium-3">Medium 3</button> </div> </div> <div class = "dropdown" id="hard"> <button class = "dropbtn">Hard</button> <div id="my-dropdown" class = "dropdown-content"> <button class="puzzle-select" id="hard-1">Hard 1</button> <button class="puzzle-select" id="hard-2">Hard 2</button> <button class="puzzle-select" id="hard-3">Hard 3</button> </div> </div> <div class = "dropdown" id="fiendish"> <button class = "dropbtn">Fiendish</button> <div id="my-dropdown" class = "dropdown-content"> <button class="puzzle-select" id="fiendish-1">Fiendish 1</button> <button class="puzzle-select" id="fiendish-2">Fiendish 2</button> <button class="puzzle-select" id="fiendish-3">Fiendish 3</button> </div> </div> <div class = "dropdown" id="nightmare"> <button class = "dropbtn">Nightmare</button> <div id="my-dropdown" class = "dropdown-content"> <button class="puzzle-select" id="nightmare-1">Nightmare 1</button> <button class="puzzle-select" id="nightmare-2">Nightmare 2</button> <button class="puzzle-select" id="nightmare-3">Nightmare 3</button> </div> </div> <div class = "dropdown" id="userPuzzle"> <button class = "dropbtn">Input Your Own!</button> <div id="my-dropdown" class = "dropdown-content"> <button class="puzzle-select" id="userPuzzle-1">Create Puzzle</button> </div> </div> <h2>Displaying Puzzle <span id="which-puzzle"><span></h2> <div class = "ghetto-padding"></div> <div class = "neat"> <div class = "maybe"> <div class = "puzzleHere" id="currentPuzzle"></div> </div> <!-- <div class = "ghetto-padding"></div> --> <div class = "sidebar"> <div class = "freak"> <div class = "top"> <button class = "utility" id="clear">Clear Puzzle</button> <button class = "utility" id="save">Save Puzzle</button> </div> <div class = "middle"> </div> <div class = "bottom"> <button class = "utility puzzle-select" id="validate-always">Validate as You Go</button> <button class = "utility puzzle-select" id="validate-once">Validate</button> </div> </div> <!-- Manual Entry Buttons --> <table id="input-buttons"> <tr class="noborder"> <td class="noborder"><button class="input" id="1b">1</button></td> <td class="noborder"><button class="input" id="2b">2</button></td> <td class="noborder"><button class="input" id="3b">3</button></td> </tr> <tr class="noborder"> <td class="noborder"><button class="input" id="4b">4</button></td> <td class="noborder"><button class="input" id="5b">5</button></td> <td class="noborder"><button class="input" id="6b">6</button></td> </tr> <tr class="noborder"> <td class="noborder"><button class="input" id="7b">7</button></td> <td class="noborder"><button class="input" id="8b">8</button></td> <td class="noborder"><button class="input" id="9b">9</button></td> </tr> </table> </div> </div> </body></html> <!-- Import a JavaScript script to add interactivity to the page. --> <script src="script.js"></script>
<?php declare(strict_types=1); namespace Laser\Core\Framework\Test\DataAbstractionLayer\Event; use PHPUnit\Framework\TestCase; use Laser\Core\Content\Product\ProductDefinition; use Laser\Core\Defaults; use Laser\Core\Framework\Context; use Laser\Core\Framework\DataAbstractionLayer\EntityRepository; use Laser\Core\Framework\DataAbstractionLayer\Event\EntityWrittenContainerEvent; use Laser\Core\Framework\Test\TestCaseBase\IntegrationTestBehaviour; use Laser\Core\Framework\Uuid\Uuid; /** * @internal */ class EntityWrittenEventSerializationTest extends TestCase { use IntegrationTestBehaviour; public function testEventCanBeSerialized(): void { $container = $this->writeTestProduct(); $event = $container->getEventByEntityName(ProductDefinition::ENTITY_NAME); $encoded = json_encode($event, \JSON_THROW_ON_ERROR); static::assertNotFalse($encoded); static::assertJson($encoded); $encoded = json_encode($container, \JSON_THROW_ON_ERROR); static::assertNotFalse($encoded); static::assertJson($encoded); } private function writeTestProduct(): EntityWrittenContainerEvent { /** @var EntityRepository $productRepository */ $productRepository = $this->getContainer()->get('product.repository'); return $productRepository->create( [[ 'id' => Uuid::randomHex(), 'manufacturer' => [ 'id' => Uuid::randomHex(), 'name' => 'amazing brand', ], 'name' => 'wusel', 'productNumber' => Uuid::randomHex(), 'tax' => ['id' => Uuid::randomHex(), 'taxRate' => 19, 'name' => 'tax'], 'price' => [['currencyId' => Defaults::CURRENCY, 'gross' => 10, 'net' => 12, 'linked' => false]], 'stock' => 0, ]], Context::createDefaultContext() ); } }
package com.openclassrooms.tourguide.service; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.Comparator; import java.util.HashMap; import org.springframework.stereotype.Service; import gpsUtil.GpsUtil; import gpsUtil.location.Attraction; import gpsUtil.location.Location; import gpsUtil.location.VisitedLocation; import rewardCentral.RewardCentral; import com.openclassrooms.tourguide.attraction.ContactAttractionDTO; import com.openclassrooms.tourguide.user.User; import com.openclassrooms.tourguide.user.UserReward; @Service public class RewardsService { private static final double STATUTE_MILES_PER_NAUTICAL_MILE = 1.15077945; //convertir les miles nautiques en miles terrestre // proximity in miles private int defaultProximityBuffer = 10; //proximiter d'un user proche d'une attraction private int proximityBuffer = defaultProximityBuffer; private int attractionProximityRange = 200; //proximiter d'un user n'est plus proche d'une attraction private final GpsUtil gpsUtil; private final RewardCentral rewardsCentral; private final ExecutorService executorService = Executors.newFixedThreadPool(100); /** * On prend l'emplacement d'un user avec GpsUtil * On récupére les 5 attractions les plus proche */ public RewardsService(GpsUtil gpsUtil, RewardCentral rewardCentral) { this.gpsUtil = gpsUtil; this.rewardsCentral = rewardCentral; } public void setProximityBuffer(int proximityBuffer) { this.proximityBuffer = proximityBuffer; } public void setDefaultProximityBuffer() { proximityBuffer = defaultProximityBuffer; } /* * calcule récompense pour un user * si il n'a pas deja la recompense, et si il est proche la récompense est ajouter à l'user */ public void calculateRewards(User user) { List<VisitedLocation> userLocations = user.getVisitedLocations(); List<Attraction> attractions = gpsUtil.getAttractions(); List<CompletableFuture<Void>> futures = new ArrayList<>(); for(VisitedLocation visitedLocation : userLocations) { CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { for(Attraction attraction : attractions) { if(user.getUserRewards().stream().filter(r -> r.attraction.attractionName.equals(attraction.attractionName)).count() == 0) { if(nearAttraction(visitedLocation, attraction)) { user.addUserReward(new UserReward(visitedLocation, attraction, getRewardPoints(attraction, user))); } } } },executorService); futures.add(future); } CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join(); } public List<ContactAttractionDTO> sortAttractionsAndRewards (VisitedLocation visitedLocation, List<Attraction> attractionsList,User user ){ List<ContactAttractionDTO> contactAttractionDTO = new ArrayList<>(); Map<Attraction, Double> distancesMap = new HashMap<>(); for(Attraction attraction : attractionsList) { double distance = getDistance(visitedLocation.location,attraction); distancesMap.put(attraction, distance); } attractionsList.sort(Comparator.comparingDouble(distancesMap::get)); List<Attraction> fiveFirstAttractions = attractionsList.subList(0, 5); for (Attraction attractionReward : fiveFirstAttractions) { ContactAttractionDTO attractionWithRewardDTO = new ContactAttractionDTO(); int rewardPointByAttraction = getRewardPoints(attractionReward, user); attractionWithRewardDTO.setLatAttraction(attractionReward.latitude); attractionWithRewardDTO.setLonAttraction(attractionReward.longitude); attractionWithRewardDTO.setNameAttraction(attractionReward.attractionName); attractionWithRewardDTO.setRewardAttraction(rewardPointByAttraction); attractionWithRewardDTO.setDistance(getDistance(visitedLocation.location, attractionReward)); contactAttractionDTO.add(attractionWithRewardDTO); } return contactAttractionDTO; } // Collections.sort(attraction, new Comparator<Attraction>() { // public int compare(Attraction a1, Attraction a2) { // double distance1 = getDistance(visitedLocation.location, attraction); // double distance2 = getDistance(visitedLocation.location, attraction); // return Double.compare(distance1, distance2); // } //}); public boolean isWithinAttractionProximity(Attraction attraction, Location location) { return getDistance(attraction, location) > attractionProximityRange ? false : true; } private boolean nearAttraction(VisitedLocation visitedLocation, Attraction attraction) { return getDistance(attraction, visitedLocation.location) > proximityBuffer ? false : true; } private int getRewardPoints(Attraction attraction, User user) { return rewardsCentral.getAttractionRewardPoints(attraction.attractionId, user.getUserId()); } /* * calcule en miles la distance entre deux points donnée par des longitude et latitude */ public double getDistance(Location loc1, Location loc2) { double lat1 = Math.toRadians(loc1.latitude); double lon1 = Math.toRadians(loc1.longitude); double lat2 = Math.toRadians(loc2.latitude); double lon2 = Math.toRadians(loc2.longitude); double angle = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon1 - lon2)); double nauticalMiles = 60 * Math.toDegrees(angle); double statuteMiles = STATUTE_MILES_PER_NAUTICAL_MILE * nauticalMiles; return statuteMiles; } }
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateEstacionBombeoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('estacion_bombeo', function (Blueprint $table) { $table->id("estacion_id"); $table->string("estacion_nombre"); $table->text("estacion_ubicacion"); $table->double("estacion_estado")->default(1); $table->bigInteger('camaronera_id'); $table->foreign('camaronera_id')->references('camaronera_id')->on('camaronera'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('estacion_bombeo'); } }
package pl.elgrandeproject.elgrande.entities.user; import jakarta.persistence.*; import jakarta.validation.constraints.Email; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.Size; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import pl.elgrandeproject.elgrande.entities.role.Role; import java.util.HashSet; import java.util.Set; import java.util.UUID; @Entity @Table(name = "users") @NoArgsConstructor @Setter @Getter @EqualsAndHashCode(onlyExplicitlyIncluded = true) public class UserClass { @Id private UUID id = UUID.randomUUID(); @NotBlank(message = "The field can not be empty.") private String firstName; @NotBlank(message = "The field can not be empty.") private String lastName; @Email @NotBlank(message = "The field can not be empty.") @EqualsAndHashCode.Include @Column(unique = true) private String email; @NotBlank(message = "The field can not be empty.") @Size(min = 8, message = "The password must be 8 characters minimum") private String password; @NotBlank(message = "The field can not be empty.") private String repeatedPassword; @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles = new HashSet<>(); public UserClass(String firstName, String lastName, String email, String password, String repeatedPassword) { this.firstName = firstName; this.lastName = lastName; this.email = email; this.password = password; this.repeatedPassword = repeatedPassword; } public void addRole(Role role) { roles.add(role); } public void clearAssignRole() { getRoles().clear(); } }
class Solution { public: int helper(int idx1, int idx2, string &s1, string &s2, vector<vector<int>> &dp) { if (idx1 < 0 || idx2 < 0) return 0; // longest length if one string becomes 0 is 0 if (dp[idx1][idx2] != -1) return dp[idx1][idx2]; if (s1[idx1] == s2[idx2]) return dp[idx1][idx2] = 1 + helper(idx1 - 1, idx2 - 1, s1, s2, dp); else return dp[idx1][idx2] = 0 + max(helper(idx1 - 1, idx2, s1, s2, dp), helper(idx1, idx2 - 1, s1, s2, dp)); } int longestCommonSubsequence(string text1, string text2) { int n = text1.length(); int m = text2.length(); vector<vector<int>> dp(n, vector<int>(m, -1)); return helper(n - 1, m - 1, text1, text2, dp); } }; // TABULATION class Solution { public: // shifting of index coz for the base case we want idx<0 i.e -1 but we can't store so we shift the index by 1 // -1 0 1 2 3 . . . n-1 // 0 1 2 3 4 . . . n we do right shifting of index // so base case becomes // if (idx1 == 0 || idx2 == 0) return 0; int longestCommonSubsequence(string s1, string s2) { int n = s1.length(); int m = s2.length(); vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)); // base case for (int idx1 = 0; idx1 <= n; idx1++) { dp[idx1][0] = 0; } for (int idx2 = 0; idx2 <= m; idx2++) { dp[0][idx2] = 0; } for (int idx1 = 1; idx1 <= n; idx1++) { for (int idx2 = 1; idx2 <= m; idx2++) { if (s1[idx1 - 1] == s2[idx2 - 1]) dp[idx1][idx2] = 1 + dp[idx1 - 1][idx2 - 1]; else dp[idx1][idx2] = 0 + max(dp[idx1 - 1][idx2], dp[idx1][idx2 - 1]); } } return dp[n][m]; } };
<?php namespace App\Http\Requests\Category; use Illuminate\Foundation\Http\FormRequest; class CategoryCreateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * @return bool */ public function authorize(): bool { return auth()->user()->is_admin; } /** * Get the validation rules that apply to the request. * @return array */ public function rules(): array { return [ 'name' => 'required|min:2|max:20', 'slug' => 'required|unique:categories,slug|min:2|max:20' ]; } }
import React, { useState, useEffect, useContext } from 'react'; import SidebarLayout from 'src/layouts/SidebarLayout'; import MYS from '../../../Styles/mystyle.module.css' import Badge from '@mui/material/Badge'; import Select from '@mui/material/Select'; import InputLabel from '@mui/material/InputLabel'; import MenuItem from '@mui/material/MenuItem'; import LoadingButton from '@mui/lab/LoadingButton'; import { LuChevronRight } from "react-icons/lu"; const ReactQuill = typeof window === 'object' ? require('react-quill') : () => false; import 'react-quill/dist/quill.snow.css'; import TitleNav from '../../../src/components/Parts/TitleNav' import CircularProgress from '@mui/material/CircularProgress'; import TextField from '@mui/material/TextField'; import { IconButton, styled, FormControl, } from '@mui/material'; import Image from 'next/image' import { useRouter, useParams } from 'next/router' import { MediaFilesFolder, MediaFilesUrl } from '/Data/config' function DashboardCrypto() { const router = useRouter() const [isLoading, setIsLoading] = useState(true); const [isActive, setIsActive] = useState(3); const [Btnloading, setBtnloading] = useState(false); const [PageData, setPageData] = useState(''); const [PageTitle, setPageTitle] = useState(''); const handleEditorChange = (content) => { setPageData(content); }; const SavePage = async (e) => { e.preventDefault(); // Check if both fields are filled if (PageTitle !== '' && PageData !== '') { setBtnloading(true) try { console.log(PageTitle); // Prepare the payload to send to the server const payload = { PageTitle: PageTitle, PageData: PageData, isActive: isActive }; // Make the API request to add the page const response = await fetch("/api/V3/Admin/WebPage/Add_page", { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); // Check if the request was successful if (!response.ok) { throw new Error('Failed to fetch data'); } // Parse the response const result = await response.json(); console.log(result); // Check if the operation was successful if (result.ReqD && result.ReqD.done) { alert('Page saved successfully!'); router.push(`/admin/pages/edit/${result.ReqD.PageSlug}`) } else { alert(result.ReqD.error) setBtnloading(false) } } catch (error) { setBtnloading(false) // Log the error and inform the user console.error('Error fetching data:', error); alert('An error occurred while saving the page. Please try again later.'); } } else { // Inform the user if any field is empty alert('All fields are required!'); } }; useEffect(() => { setTimeout(function () { setIsLoading(false) }, 2000); }, [router.query]) const StyledBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { right: -3, top: 13, border: `2px solid ${theme.palette.background.paper}`, padding: '0 4px', }, })); const handleChangeTSStatus = (event) => { setIsActive(event.target.value); }; return ( <> <TitleNav Title={`Create New Page : ${PageTitle}`} /> <div className={MYS.Pagebox}> <form onSubmit={SavePage}> {!isLoading && <div className={MYS.PostTextBox}> <div className={MYS.inputlogin}> <TextField required label="Page Title" fullWidth value={PageTitle} onInput={e => setPageTitle(e.target.value)} /> </div> <div className={MYS.inputlogin}> <ReactQuill theme="snow" // You can change the theme as per your preference value={PageData} placeholder='write your post here ...' onChange={handleEditorChange} /> </div> <div className={MYS.inputlogin}> <FormControl fullWidth> <InputLabel id="demo-simple-select-label">Status</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" value={isActive} label="Status" onChange={handleChangeTSStatus} > <MenuItem value={3}>Public</MenuItem> <MenuItem value={2}>Upcoming</MenuItem> <MenuItem value={1}>Private</MenuItem> </Select> </FormControl> </div> <div style={{ height: '20px' }}></div> <div className={MYS.Loginbtnbox}> <LoadingButton type='submit' onClick={SavePage} endIcon={<LuChevronRight />} loading={Btnloading} desabled={Btnloading} loadingPosition="end" variant='contained' > <span>Publish Page</span> </LoadingButton> <div style={{ height: '20px' }}></div> </div> </div> } </form> </div> </> ); } DashboardCrypto.getLayout = (page) => <SidebarLayout>{page}</SidebarLayout>; export default DashboardCrypto;
import React from "react"; import { Col, Container, Row } from "react-bootstrap"; import { useSelector } from "react-redux"; import CategoryCard from "./CategoryCard"; import "./CategoryCard.css"; function AllCategories() { const { categories } = useSelector((state) => state.categories); return ( <Container className="all-categoris"> <h3>Browse By Catrgories</h3> <Row> {categories && categories.map((c, index) => { let columnClasses; let categoryCardClass; if (index === 0) { columnClasses = "col-12 col-sm-12 col-md-4"; categoryCardClass = "category-card-4-cols"; } else if (index === 1 || index === 2) { columnClasses = "col-12 col-sm-12 col-md-8"; categoryCardClass = "category-card-8-cols"; } else if (index === 3) { columnClasses = "col-12 col-sm-12 col-md-4"; categoryCardClass = "category-card-4-cols"; } return ( <Col className={`mb-2 p-2 ${columnClasses} ${categoryCardClass}`} key={index} > <CategoryCard category={c} /> <img src={c.imageSrc} alt={c.name} className="category-image" /> </Col> ); })} </Row> </Container> ); } export default AllCategories;
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSuppliersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('suppliers', function (Blueprint $table) { $table->increments('id'); $table->string('title')->nullable(); $table->string('link')->nullable(); $table->string('exchange')->default('off')->nullable(); $table->string('add_new_products')->default('off')->nullable(); $table->string('update_new_products')->default('off')->nullable(); $table->string('overwrite_products')->default('off')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('suppliers'); } }
import 'package:ecommerce_application/core/service/database/cart_database_helper.dart'; import 'package:ecommerce_application/model/cart_product_model.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class CartViewModel extends GetxController { ValueNotifier<bool> get loading => _loading; final ValueNotifier<bool> _loading = ValueNotifier(false); List<CartProductModel> _cartProductModel = []; List<CartProductModel> get cartProductModel => _cartProductModel; late double _totalPrice = 0.0; double get totalPrice => _totalPrice; var dbHelper = CartDatabaseHelper.db; CartViewModel() { getAllProducts(); } getAllProducts() async { _loading.value = true; _cartProductModel = await dbHelper.getAllProducts(); _loading.value = false; getTotalPrice(); update(); } getTotalPrice() { for (var i = 0; i < _cartProductModel.length; i++) { _totalPrice += (double.parse(_cartProductModel[i].price!) * _cartProductModel[i].quantity!); } update(); } void addProduct(CartProductModel cartProductModel) async { for (var i = 0; i < _cartProductModel.length; i++) { if (_cartProductModel[i].productId == cartProductModel.productId) { return; } } await dbHelper.insert(cartProductModel); _cartProductModel.add(cartProductModel); _totalPrice += (double.parse(cartProductModel.price!) * cartProductModel.quantity!); update(); } void increaseQuantity(int index) async { _cartProductModel[index].quantity = _cartProductModel[index].quantity! + 1; _totalPrice += double.parse(_cartProductModel[index].price!); await dbHelper.updateProduct(_cartProductModel[index]); update(); } void decreaseQuantity(int index) async { _cartProductModel[index].quantity = _cartProductModel[index].quantity! - 1; _totalPrice -= double.parse(_cartProductModel[index].price!); await dbHelper.updateProduct(_cartProductModel[index]); update(); } }