Snippets Collections
1
2
3
4
5
6
a = [[1, 2, 3, 4], [5, 6], [7, 8, 9]]
for i in range(len(a)):
    for j in range(len(a[i])):
        print(a[i][j], end=' ')
    print()
// opens a new u_error_reporting record from an sc_task record
function openOverlay(overlayID, overlayTitle, iframeURI, height, width) {
	// Instantiate the GlideOverlay
	// Note: GlideOverlay extends GlideBox, which contains the close() method
	var overlayWindow = new GlideOverlay({
		                                     id:             overlayID,
		                                     title:          overlayTitle,
		                                     iframe:         iframeURI,
		                                     allowOverflowX: true,
		                                     closeOnEscape:  true,
		                                     height:         height,
		                                     width:          width
	                                     });
	overlayWindow.render();
	// Get the element containing the iframe document.
	var overlayDocument = overlayWindow._box.getElementsByClassName('gb_iframe')[0];
	// Add a listener for when the document in the iframe finishes loading, and run some code when it does.
	// Without this, our code would not have a "document" in which to execute, and wouldn't do anything.
	overlayDocument.onload = function() {
		// Get all of the "buttons" (button UI actions) in the document in the iframe -- that is, on the form in the GlideOverlay.
		var overlayG_form = overlayDocument.contentWindow.g_form;
		var buttonsInOverlayWindow = overlayDocument.contentWindow.document.getElementsByClassName('form_action_button');
		// Iterate over each UI action button on the form.
		for (var i in buttonsInOverlayWindow) {
			// Standard check to make sure that the element (still) exists.
			if (buttonsInOverlayWindow.hasOwnProperty(i)) {
				// Adding an event listener to each UI action button. This executes a function when the button is clicked.
				buttonsInOverlayWindow[i].addEventListener('click', function() {
					// When a UI action button is clicked, we first call setTimeout. We pass in only a very small timeout timer, since
					// even a timeout of 0 will cause the code passed into the setTimeout function to execute after all other scripts
					// have finished running as a result of that click (such as the form being submitted).
					setTimeout(function() {
						// Finally, after all other code has executed as a result of the user clicking the UI action button, we call
						// a function to check if any mandatory fields have not been filled out. If we're good, then we close the overlay.
						if (!(overlayG_form.getMissingFields().length > 0)) {
							overlayWindow.close();
							console.warn(!(overlayG_form.getMissingFields().length > 0) + 'CLOSING');
						} else {
							console.warn(!(overlayG_form.getMissingFields().length > 0) + 'NOT CLOSING');
						}
					}, 500);
				});
			}
		}
	};
}
function pow(x, n) {
  return (n == 1) ? x : (x * pow(x, n - 1));
}
---------------------
Number.isNaN(24);
// False.
--------------------
<?php
	session_start();
	
	$errorsArr = array();
	
	if(isset($_POST['submittedLogin'])){
		$username = $_POST['usernameLogin'];
		$password = $_POST['passwordLogin'];
		
		//ensure form fields are filled properly
		if(empty($username)){
			array_push($errorsArr, "Username is required! Please try again!");
		}
		if(empty($password)){
			array_push($errorsArr, "Password is required! Please try again!");
		}
		if((!empty($username)) && (!empty($password)) && ($username != 'admin') && ($password != 'admin')){
			array_push($errorsArr, "Incorrect username or password! Please try again!");
		}
		
		//no errors
		if(count($errorsArr) == 0){
			$_SESSION['username'] = $username;
			$_SESSION['success'] = "You are now logged in!";
			header('Location: /205CDE/Assignment/manageNews.php');
		}
	}
	
	//logout
	if(isset($_GET['logout'])){
		session_destroy();
		unset($_SESSION['username']);
		header('Location: /205CDE/Assignment/home.php');
	}
?>
<div class="container-fluid" style="background: #1f52a3;">
	<div class="row">
		<div class="col-2"></div>
		<div class="col-8">
			<a href="/205CDE/Assignment/home.php"><h1 style="text-align: center; color: #e6e8eb; margin: 20px 0;">U Chen Daily</h1></a>
		</div>
		<div class="col-2 d-flex justify-content-center align-items-center">
			<?php if(isset($_SESSION['username'])){ ?>
				<a href="/205CDE/Assignment/home.php?logout='1'" class="btn btn-outline-light">LOGOUT</a>
				<?php }else{ 
				?>
				<button type="button" class="btn btn-outline-light" data-toggle="modal" data-target="#loginFormModal">
					LOGIN AS ADMIN
				</button>
			<?php } ?>
			<!--<a href="/205CDE/Assignment/manageNews.php" target="_blank" class="btn btn-outline-light">LOGIN</a>-->
		</div>
	</div>
</div>
<!--login form modal START-->
<!-- Modal -->
<div class="modal fade" id="loginFormModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered" role="document">
		<div class="modal-content">
			<div class="modal-header">
				<h5 class="modal-title" id="exampleModalCenterTitle">Login</h5>
				<button type="button" class="close" data-dismiss="modal" aria-label="Close">
					<span aria-hidden="true">&times;</span>
				</button>
			</div>
			<form action="/205CDE/Assignment/home.php" method="post" id="loginModalForm">
				<div class="modal-body">
					<?php
						if(count($errorsArr) > 0){?>
						<div class="form-group">
							<?php
								foreach($errorsArr as $errorMsg){
									//echo "<p class=\"text-danger\">$errorMsg</p>";
									echo "<script>alert(\"$errorMsg\")</script>";
								}
							?>
						</div>
						<?php }
					?>
					<div class="form-group">
						<label for="exampleInputEmail1">Username</label>
						<input type="text" class="form-control" name="usernameLogin" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter username" value="<?php if(isset($username)){echo $username;} ?>">
					</div>
					<div class="form-group">
						<label for="exampleInputPassword1">Password</label>
						<input type="password" class="form-control" name="passwordLogin" id="exampleInputPassword1" placeholder="Enter password">
					</div>
					<br>
					<div class="form-group">
						<button type="submit" class="btn btn-lg btn-block text-light" style="background: #1f52a3;">LOGIN</button>
						<input type="hidden" name="submittedLogin">
					</div>
				</div>
				<!--<div class="modal-footer">
					<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
					<button type="button" class="btn btn-primary">Login</button>
				</div>-->
			</form>
		</div>
	</div>
</div>
<!--login form modal END-->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
	<a class="navbar-brand" href="/205CDE/Assignment/home.php"><i class="fas fa-home" style="font-size: 30px; color: #1f52a3;"></i></a>
	<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
		<span class="navbar-toggler-icon"></span>
	</button>
	
	<div class="collapse navbar-collapse" id="navbarSupportedContent">
		<ul class="navbar-nav mr-auto">
			<li class="nav-item dropdown" style="margin: 0 15px;">
				<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">News</a>
				<div class="dropdown-menu" aria-labelledby="navbarDropdown">
					<?php
						$newsCategoryArr = array(
						'All', 'Nation', 'World',
						'Sport', 'Entertainment',
						);
						foreach($newsCategoryArr as $newsType){
							echo "<a class=\"dropdown-item\" href=\"/205CDE/Assignment/news$newsType.php\" target=\"_blank\">$newsType</a>";
						}
					?>
				</div>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/aboutUs.php" target="_blank">About Us</a>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/contactUs.php" target="_blank">Contact Us</a>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/faqs.php" target="_blank">FAQs</a>
			</li>
			<!-- <li class="nav-item"> -->
			<!-- <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> -->
			<!-- </li> -->
		</ul>
		<!-- <form class="form-inline my-2 my-lg-0"> -->
		<!-- <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> -->
		<!-- <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> -->
		<!-- </form> -->
	</div>
</nav>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | News</title>
	</head>
	<body>
		<!--using external files-->
		<?php require('header.php'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">News</h3></div>
			</div>
		</div>
		<?php
			$dbc = mysqli_connect('localhost', 'root', '');
			mysqli_select_db($dbc, 'news');
			
			if(isset($_GET['id']) && is_numeric($_GET['id'])){
				$query = "SELECT * FROM news WHERE news_id={$_GET['id']}";
				
				if($r = mysqli_query($dbc, $query)){
					$row = mysqli_fetch_array($r);
				?>
				<div class="container-fluid bg-light" style="padding: 50px 20px">
					<div class="row d-flex justify-content-between" style="margin: 0 50px;">
						<div class="col-lg-8 col-md-12">
							<div class="row mb-3">
								<h2 style="color: #1f52a3;"><?php echo $row['news_title'] ?></h2>
							</div>
							<div class="row">
								<div class="col mb-3" style="font-size: 18px; color:#1f52a3;">
									<i class="far fa-clock"></i>&nbsp
									<?php echo date('d-M-Y', strtotime($row['news_datetime'])); ?>&nbsp&nbsp&nbsp
									<i class="fas fa-tag"></i>&nbsp
									<?php echo strtoupper($row['news_category']); ?>
								</div>
							</div>
							<div class="row">
								<div class="col-12"  style="margin-bottom: 10px;">
									<img class="card-img-top" src="<?php 
										if(empty($row['news_image'])){
											echo 'https://via.placeholder.com/350x250';
											}else{
											echo $row['news_image'];
										}
									?>" alt="Card image cap" style="width:80%;">
								</div>
								
							</div>
							<div class="row" style="margin: 10px 0; font-size: 20px;">
								<p class="font-weight-normal"><?php echo $row['news_details'] ?></p>
							</div>
						</div>
						<?php
						}
					}
					mysqli_close($dbc);
				?>
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news ORDER BY news_datetime DESC LIMIT 5';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<div class="col-lg-4 col-md-12">
					<div class="list-group list-group-flush" style="border: 2px solid #1f52a3; border-top: 0;">
						<h4 class="list-group-item text-light text-center" style="background: #1f52a3;">Top 5 Latest News</h4>
						<?php
							if($runQuery){
								foreach($runQuery as $row){?>
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>" class="list-group-item list-group-item-action" target="_blank">
									<div class="row">
										<div class="col-3">
											<img src="<?php 
												if(empty($row['news_image'])){
													echo 'https://via.placeholder.com/200x200';
													}else{
													echo $row['news_image'];
												}?>" alt="Thumbnail News Image" class="img-thumbnail">
											</div>
											<div class="col-8" style="font-size: 15px;">
												<?php echo $row['news_title']; ?>
											</div>
										</div>
									</a>	
									<?php }
									}else{
									echo "ERROR! No record found!";
								}
								mysqli_close($dbc);
							?>
						</div>
					</div>
					<!--<div class="col-3" style="">
						<img class="card-img-top" src="https://via.placeholder.com/350x200" alt="Card image cap">
					</div>-->
				</div>
			</div>
			
			
			<!--using external files-->
			<?php require('footer.html'); ?>
		</body>
	</html>	
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | FAQs</title>
	</head>
	<style>
		.card-header{
		background: #1f52a3;
		}
		.card-body{
		color: #1f52a3;
		}
		h3{
		color: #1f52a3;
		margin: 20px 0;
		}
	</style>
	<body>
		<!--using external files-->
		<?php require('header.php'); ?>
		<div class="container" style="margin: 5px 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">FAQs</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 10px 10px 50px;">
			<div class="row bg-light" style="margin: 10px 35px; font-size: 18px;">
				<div class="col-lg-6">
					<h3>General</h3>
					<div class="accordion" id="accordionExample">
						<!--first faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingOne">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
										There is something wrong with TheUChen.com.my and/or app. What should I do? (example: broken link, error page, spotted some issues)
									</button>
								</h2>
							</div>
							<div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
								<div class="card-body bg-white">
									We are sorry for the inconvenience caused. Please report your issue to us and include as much information as possible.
								</div>
							</div>
						</div>
						<!--first faq END-->
						<!--second faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingTwo">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
										I want to publish articles or pictures from U Chen Daily. How do I get copyright permission?
									</button>
								</h2>
							</div>
							<div id="collapseTwo" class="collapse" aria-labelledby="headingTwo" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Write to us and get permission. Granting or refusal of permission is at our sole and absolute discretion.
								</div>
							</div>
						</div>
						<!--second faq END-->
						<!--third faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingThree">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
										Why can I only read a limited number of articles on TheUChen.com.my and app?
									</button>
								</h2>
							</div>
							<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Effective Feb 24, 2020, we will be offering a paid digital membership for unlimited access to TheUChen.com.my and app (“Digital Access”). This will ensure that we continue to provide reliable, relevant, and compelling content while maintaining the quality of journalism that readers trust us to uphold. The membership, called U Chen Daily Digital Access, also includes personalisation features to improve your reading experience.
								</div>
							</div>
						</div>
						<!--third faq END-->
						<!--4th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingFour">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseFour">
										How can I keep track of how many articles I have read?
									</button>
								</h2>
							</div>
							<div id="collapseFour" class="collapse" aria-labelledby="headingFour" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Sorry, you can't track your article limit at the moment. We're still developing this part of the system so do bear with us while we continue to improve.
								</div>
							</div>
						</div>
						<!--4th faq END-->
						<!--5th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingFive">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseFive" aria-expanded="false" aria-controls="collapseFive">
										If I don’t want to register as a member, can I still read articles for free?
									</button>
								</h2>
							</div>
							<div id="collapseFive" class="collapse" aria-labelledby="headingFive" data-parent="#accordionExample">
								<div class="card-body bg-white">
									As a guest user without an active paid membership, you can access a limited number of articles for free each month. This limit resets every 30 days. This excludes premium content (marked as ‘PREMIUM’), which are exclusive to paid members, and content hosted on a separate subscription-based service, e.g. dimsum e-tuition videos.
								</div>
							</div>
						</div>
						<!--5th faq END-->
						<!--6th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingSix">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseSix" aria-expanded="false" aria-controls="collapseSix">
										Do I need to log in with a MyUChen account if I just want to read articles for free as a guest user?
									</button>
								</h2>
							</div>
							<div id="collapseSix" class="collapse" aria-labelledby="headingSix" data-parent="#accordionExample">
								<div class="card-body bg-white">
									While it’s not compulsory, we do recommend that you sign up for a MyUChen account. As a member, you can UChent your 1-month free trial to U Chen Daily Digital Access and enjoy personalisation features to improve your reading experience.
								</div>
							</div>
						</div>
						<!--6th faq END-->
						<!--7th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingSeven">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseSeven" aria-expanded="false" aria-controls="collapseSeven">
										What does the paid U Chen Daily Digital Access membership entail?
									</button>
								</h2>
							</div>
							<div id="collapseSeven" class="collapse" aria-labelledby="headingSeven" data-parent="#accordionExample">
								<div class="card-body bg-white">
									With U Chen Daily Digital Access membership, you will be able to access all articles on TheUChen.com.my and app, including premium content which are exclusive to paid members, excluding content hosted on a separate subscription-based services, e.g. dimsum e-tuition videos. Members can also access all personalisation features.
								</div>
							</div>
						</div>
						<!--7th faq END-->
						<!--8th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingEight">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseEight" aria-expanded="false" aria-controls="collapseEight">
										I'm currently subscribed to ePaper. Do I still need to subscribe to U Chen Daily?
									</button>
								</h2>
							</div>
							<div id="collapseEight" class="collapse" aria-labelledby="headingEight" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Yes. At the moment U Chen Daily Digital Access and ePaper subscription are on two separate platforms.
								</div>
							</div>
						</div>
						<!--8th faq END-->
					</div>
				</div>
				<div class="col-lg-6">
					<h3>About Account</h3>
					<div class="accordion" id="accordionExample">
						<!--9th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingNine">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light" type="button" data-toggle="collapse" data-target="#collapseNine" aria-expanded="true" aria-controls="collapseNine">
										I can’t sign up/register from Internet Explorer?
									</button>
								</h2>
							</div>
							<div id="collapseNine" class="collapse show" aria-labelledby="headingNine" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Internet Explorer is not supported at the moment. Best view from Chrome browsers.
								</div>
							</div>
						</div>
						<!--9th faq END-->
						<!--10th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingTen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseTen" aria-expanded="false" aria-controls="collapseTen">
										I signed up for a free MyUChen account before Feb 10, 2020 and was prompted to update my password. What should I do?
									</button>
								</h2>
							</div>
							<div id="collapseTen" class="collapse" aria-labelledby="headingTen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Please log in with your username/email and change your password with a minimum of eight characters. It must contain at least one upper case letter, one number, and one special character except '+' and '='. Please use your new password for future logins.
								</div>
							</div>
						</div>
						<!--10th faq END-->
						<!--11th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingEleven">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseEleven" aria-expanded="false" aria-controls="collapseEleven">
										Why do I have to change my password?
									</button>
								</h2>
							</div>
							<div id="collapseEleven" class="collapse" aria-labelledby="headingEleven" data-parent="#accordionExample">
								<div class="card-body bg-white">
									We've made some enhancements to the TheUChen.com.my and app to improve your reading experience and for web security. This includes migrating all MyUChen accounts to a new system. Members who signed up before Feb 10, 2020, are required to update their password.
								</div>
							</div>
						</div>
						<!--11th faq END-->
						<!--12th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingTwelve">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseTwelve" aria-expanded="false" aria-controls="collapseTwelve">
										I forgot my password, what should I do?
									</button>
								</h2>
							</div>
							<div id="collapseTwelve" class="collapse" aria-labelledby="headingTwelve" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Click ‘Forgot Password?’ and you will be emailed a temporary password that you can log in with. Please proceed to change your password as soon as possible.
								</div>
							</div>
						</div>
						<!--12th faq END-->
						<!--13th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingThirteen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseThirteen" aria-expanded="false" aria-controls="collapseThirteen">
										I’ve updated my password, but I can’t log in with MyUChen account’s username?
									</button>
								</h2>
							</div>
							<div id="collapseThirteen" class="collapse" aria-labelledby="headingThirteen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Please use the new password with your MyUChen email.
								</div>
							</div>
						</div>
						<!--13th faq END-->
						<!--14th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingFourteen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseFourteen" aria-expanded="false" aria-controls="collapseFourteen">
										I registered for a MyUChen account but did not receive any verification email. What should I do?
									</button>
								</h2>
							</div>
							<div id="collapseFourteen" class="collapse" aria-labelledby="headingFourteen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									lease check both your Inbox and/or Spam folders. Click ‘Resend verification email’ and try again. If you have closed the page or have been logged out, please log in again to click ‘Resend verification email’.
									<br>
									If you are using a corporate email, kindly inform your tech department to whitelist @theUChen.com.my.
								</div>
							</div>
						</div>
						<!--14th faq END-->
						<!--15th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingFifteen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseFifteen" aria-expanded="false" aria-controls="collapseFifteen">
										The email verification link/code provided is invalid. What should I do?
									</button>
								</h2>
							</div>
							<div id="collapseFifteen" class="collapse" aria-labelledby="headingFifteen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									Click ‘Resend verification email’ and try again. If you have closed the page or have been logged out, please log in again to click ‘Resend verification email’.
								</div>
							</div>
						</div>
						<!--15th faq END-->
						<!--16th faq UChenT-->
						<div class="card">
							<div class="card-header" id="headingSixteen">
								<h2 class="mb-0">
									<button class="btn btn-block text-left text-light collapsed" type="button" data-toggle="collapse" data-target="#collapseSixteen" aria-expanded="false" aria-controls="collapseSixteen">
										I can’t seem to register. It says email address previously registered. What do I do?
									</button>
								</h2>
							</div>
							<div id="collapseSixteen" class="collapse" aria-labelledby="headingSixteen" data-parent="#accordionExample">
								<div class="card-body bg-white">
									If you have forgotten your password, click ‘Forgot Password?’ to reset it. If you are certain that you did not sign up with your email address before, kindly contact our Customer Service.
								</div>
							</div>
						</div>
						<!--16th faq END-->
					</div>
				</div>
			</div>
		</div>
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef long double ld;
ll cs=0;
struct duo
{
    ld x,F,S;
};
bool sim(duo a,duo b)
{
    if(a.F==b.F||a.F==b.S||a.S==b.F||a.S==b.S)
        return 1;
    return 0;
}
void sol()
{
    cout.precision(11);
    cout<<fixed;
    ll n,i,k;
    cin>>n;
    ld a[n],vl,ans=0;
    duo low[3],h[3];
    for(i=0; i<3; i++)
        low[i].x=INT_MAX;
    for(i=0; i<n; i++)
        cin>>a[i];
    sort(a,a+n);
    for(i=0; i<3; i++)
    {
        h[i].F=a[n-1-i];
        h[i].S=a[n-2-i];
    }
    for(i=0; i<n-1; i++)
    {
        vl=abs(a[i]-a[i+1]);
        for(k=0; k<3; k++)
        {
            if(vl<low[k].x)
            {
                ll j=k;
                for(j=2; j>=k+1; j--)
                {
                    low[j].x=low[j-1].x;
                    low[j].F=low[j-1].F;
                    low[j].S=low[j-1].S;
                }
                low[k].x=vl;
                low[k].F=a[i];
                low[k].S=a[i+1];
                break;
            }
        }
    }
    for(i=0;i<3;i++)
    {
        for(k=0;k<3;k++)
        {
            if(!sim(h[i],low[k]))
                ans=fmax(ans,(h[i].F+h[i].S)/low[k].x);
        }
    }
    cout<<ans;

}
int main()
{
    //ios_base::sync_with_stdio(false);
    //cin.tie(NULL);
    //ll t;
    //cin>>t;
    //while(t--)
    sol();
    return 0;
}
      {arr.map(({ what ever you want to get from map }) => (
        <div>
			code goes here to display through html elements
        </div>
      ))}
//Perfect Square without finding square root

function perfectSquare(number) {
  for (let i = 0; i * i <= number; i++) {
    if (number % i === 0 && number / i === i) return true;
  }
  return false;
}

let num = 12;
console.log(perfectSquare(num));
//Square Root of a number without using Math.sqrt() function

function square(num, left, right) {
  let mid = (left + right) / 2,
    sq = mid * mid;
  if (sq === num || Math.abs(sq - num) < 0.00001) return mid;
  else if (sq < num) return square(num, mid, right);
  else return square(num, left, mid);
}

function findSquareRoot(num) {
  let i = 1,
    found = false;
  while (!found) {
    //If num is a perfect square, if condition will return the value
    if (i * i === num) return i;
    else if (i * i > num) {
      let result = square(num, i - 1, i);
      return result;
    }
    i++;
  }
}

let number = 3;
console.log(findSquareRoot(number));
const myObject= {
  'Age': '25',
  'Gender': 'Male',
  'Nationality': 'Australian'
};

const myMap = new Map(Object.entries(myObject)); //object to map
const anotherObject = Object.fromEntries(myMap) // map to object
library(readr)
cereal <- read_csv("C:/Users/pierewan77/Downloads/Cereal/cereal.csv")
View(cereal)
 // Redirect the user back to the login page after the login failed, and add a $_GET parameter to let us know. Courtesy of WordPressFlow.com
add_action( 'wp_login_failed', 'elementor_form_login_fail', 9999999 );
function elementor_form_login_fail( $username ) {
    $referrer = $_SERVER['HTTP_REFERER'];  // where did the post submission come from?
    // if there's a valid referrer, and it's not the default log-in screen
    if ((!empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') )) {
        //redirect back to the referrer page, appending the login=failed parameter and removing any previous query strings
        //maybe could be smarter here and parse/rebuild the query strings from the referrer if they are important
        wp_redirect(preg_replace('/\?.*/', '', $referrer) . '/?login=failed' );
        exit;
    }
}

// This is also important. Make sure that the redirect still runs if the username and/or password are empty.
add_action( 'wp_authenticate', 'elementor_form_login_empty', 1, 2 );
function elementor_form_login_empty( $username, $pwd ) {
    $referrer = $_SERVER['HTTP_REFERER'];  // where did the post submission come from?
 if ( empty( $username ) || empty( $pwd ) ) {
    if ((!strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') )) {
        //redirect back to the referrer page, appending the login=failed parameter and removing any previous query strings
        //maybe could be smarter here and parse/rebuild the query strings from the referrer if they are important
        wp_redirect(preg_replace('/\?.*/', '', $referrer) . '/?login=failed' );
        exit;
    }
   exit();
 }
}

function generate_login_fail_messaging(){
    ob_start();
    if($_GET['login'] == 'failed'){
    echo '<div class="message_login_fail" style="background-color: #ca5151;color: #ffffff;display: block;margin-bottom: 20px;text-align: center;padding: 9px 15px; width: fit-content;margin: 0 auto;"><span style="color: #ca5151;background-color: #fff;width: 20px;height: 20px;display: inline-flex;align-items: center;justify-content: center;font-weight: 900;border-radius: 50%;margin-right: 10px;">!</span>Oops! Looks like you have entered the wrong username or password. Please check your login details and try again.</div>';
    }
    $return_string = ob_get_contents();
    ob_end_clean();
    return $return_string;
}
add_shortcode('login_fail_messaging', 'generate_login_fail_messaging');
pip list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1  | xargs -n1 pip install -U
package com.javacodegeeks.snippets.basics;

public class SumArrayWithForLoop {
	
	public static void main(String[] args) {
		
		// array to sum
		int[] numbers = new int[]{ 10, 10, 10, 10};
		 
		int sum = 0;
		 
		for (int i=0; i < numbers.length ; i++) {
			sum = sum + numbers[i];
		}
		 
		System.out.println("Sum value of array elements is : " + sum);
		
	}

}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PageController : MonoBehaviour
{
    CharacterController controller;

    public float speed = 15.0f;
    public float jumpSpeed = 20.0f;
    public float gravity = 6.0f;
    public float life = 1f;

    public GameObject player;
    public GameObject page;

    public PlayerMovement playerScript;

    public bool canFloat = false;

    public Transform exitPoint;

    Vector3 velocity;

    public AudioSource musicSource;
    public AudioClip pageAudio;

    void Start()
    {
        controller = GetComponent<CharacterController>();
        musicSource = GetComponent<AudioSource>();
    }

    void Update()
    {
        if (controller.isGrounded)
        {
            speed = 0;
        }

        if (Input.GetKeyDown(KeyCode.E) && playerScript.inPage == false && life == 1 && playerScript.distToPage < 8f)
        {
            playerScript.inPage = true;
            playerScript.transform.position = exitPoint.position;
            playerScript.transform.rotation = Quaternion.Euler(0, 0, 0);
            playerScript.canMove = false;
            //rend.enabled = false;
        }

        if (playerScript.inPage)
        {
            canFloat = true;
        }

        if (canFloat)
        {
            if (Input.GetKeyDown(KeyCode.Space) && life == 1)
            {
                velocity.y = jumpSpeed;
                Invoke("lifeloss", 1);
                speed = 20;
                musicSource.clip = pageAudio;
                musicSource.Play();
            }

            if (controller.isGrounded && life <= 0)
            {

                playerScript.inPage = false;
                playerScript.canMove = true;
                canFloat = false;
                musicSource.Stop();

            }

            float x = Input.GetAxis("Horizontal");
            float z = Input.GetAxis("Vertical");

            Vector3 move = transform.right * x + transform.forward * z;

            controller.Move(move * speed * Time.deltaTime);

            controller.Move(velocity * Time.deltaTime);

            velocity.y -= gravity * Time.deltaTime;

            page.transform.rotation = player.transform.rotation;
        }

        else
        {
            controller.Move(velocity * Time.deltaTime);
            velocity.y = -6;
        }

    }

    void lifeloss()
    {
        life -= 1;
    }
}
		echo '<pre>';
			var_dump($post);
		echo '</pre>';
const port = process.env.PORT || 3000;

import express from "express";
import path from "path";
import bodyParser from "body-parser";
import cors from "cors";
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cors());

//* Root Handler
app.get("/", (req, res) =>
  res.sendFile(path.join(__dirname + "/public/index.html"))
);

app.get('api/v1', (req,res) => res.json())

// Set static folder
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api/v1', require('./routes/api/v1'))

app.listen(port, () => {
  console.log(`Server at: http://localhost:${port}`);
});
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen  Daily | Contact Us</title>
	</head>
	<style>
		.google-maps {
        position: relative;
        padding-bottom: 50%;
        height: 0;
        overflow: hidden;
		}
		.google-maps iframe {
        position: absolute;
        top: 0;
        left: 0;
        width: 100% !important;
        height: 100% !important;
		}
		i {
		font-size: 50px; 
		color: #1f52a3;
		}
		h5 {
		color: #1f52a3;
		margin-top: 35px;
		}
	</style>
	<body>
		<!--using external files-->
		<?php require('header.html'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">Contact Us</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 30px 10px;">
			<div class="row bg-light" style="margin: 0px 35px;">
				<div class="col-12 google-maps">
					<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3972.4919887247825!2d100.2796820147649!3d5.341603796125226!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x304ac048a161f277%3A0x881c46d428b3162c!2sINTI%20International%20College%20Penang!5e0!3m2!1sen!2smy!4v1606047317819!5m2!1sen!2smy" width="600" height="450" frameborder="0" style="border: 2px solid #1f52a3;" allowfullscreen="" aria-hidden="false" tabindex="0"></iframe>
				</div>
			</div>
			<div class="row bg-light" style="margin: 35px 35px 0;">
				<div class="col-4">
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<i class="far fa-envelope"></i>
					</div>
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<h5>info@uchendaily.com</h5>
					</div>
				</div>
				<div class="col-4">
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<i class="fas fa-phone-alt"></i>
					</div>
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<h5>+604-577 9999</h5>
					</div>
				</div>
				<div class="col-4">
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<i class="fas fa-map-marker-alt"></i>
					</div>
					<div class="row bg-light d-flex justify-content-center align-items-center">
						<h5>1-Z, Lebuh Bukit Jambul,<br>Bukit Jambul,<br>11900 Bayan Lepas,Pulau Pinang.</h5>
					</div>
				</div>
			</div>
		</div>
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen  Daily | About Us</title>
	</head>
	<body>
		<!--using external files-->
		<?php require('header.html'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">About Us</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 30px 10px;">
			<div class="row bg-light" style="margin: 0 35px;">
				<div class="col">
					<h4>U Chen  Daily</h4>
				</div>
			</div>
			<div class="row bg-light" style="margin: 10px 35px;">
				<div class="col-6">
					<p>Since its launch on June 23, 1995, as Malaysia's first news website, U Chen  Daily has always striven to provide readers with up to date breaking news, compelling content and insightful opinions.</p>
					<p>Evolving with the times, our content includes current news, business, sports, community, tech, lifestyle and world news, as well as expert analysis and dynamic videos.</p>
					<p>The website was recognised in 2014 as one of the best in Asia by the World Association of Newspapers and News Publishers (WAN-IFRA).</p>
					<p>It serves as the foundation of an online community that has a million strong following on both Twitter and Facebook.</p>
					<p>As the digital companion to U Chen  Daily newspaper, U Chen  Daily is part of a portfolio that offers content through print, U Chen  Daily ePaper and a mobile app.</p>
					<p>Readers on-the-go who want breaking news and business updates delivered to them can opt for our SMS services available via Maxis and DiGi.</p>
				</div>
				<div class="col-6">
					<p>U Chen  Daily (daily) and Sunday U Chen  are published in five editions. Two editions cover the northern peninsular states of Penang, Kedah, Perlis, Kelantan and northern Perak, while another two editions cover the rest of the country. As of March 2010, the newspaper has a separate Sarawak edition priced at RM1.20.</p>
					<p>There are two main printing plants that publish four editions of U Chen  Daily on a daily basis. The northern editions are printed at U Chen  Daily Northern Hub in Bayan Lepas, Penang, while the other two editions are printed at U Chen  Daily Media Hub in Bukit Jelutong, Shah Alam, Selangor.</p>
					<p>U Chen  Daily weekday paper is packaged as a 4-in-1 paper, comprising the Main Paper, U Chen Biz, U Chen 2 and U Chen  Metro. Naturally, this newspaper also contains classifieds.</p>
					<p>The Main Paper covers the latest in both local and international news while U Chen Biz offers a comprehensive coverage of business developments, market trends, financial reports and updates in the stock market. U Chen 2 features articles on lifestyle, entertainment, health, parenting, social etiquette, science, environment, fashion, food, comics and many more. The contents published on U Chen  Daily Metro varies by edition, covering news and events in a particular region covered by each edition.</p>
				</div>
			</div>
		</div>
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>
<footer>
	<div class="container-fluid" style="background: #1f52a3; margin-top: 50px; padding: 30px;">
		<div class="row">
			<div class="col-1"></div>
			<div class="col-10 d-flex justify-content-start" style="color: #e6e8eb;">&#169; Copyright 2020 U Chen Daily. All rights reserved.</div>
			<div class="col-1"></div>
		</div>
	</div>
</footer>
 console.log($("#pending-incidents-table tbody tr td").first().html())
const collectionName = 'databases' // this is my collection name
const ref = firebase.firestore().collection(collectionName);
ref.onSnapshot((snapshot) => {
  snapshot.forEach((doc) => {
    const data = doc.data();
    // ...
  });
});
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	res, err := http.Get("https://raw.githubusercontent.com/asos-craigmorten/opine/0.12.0/examples/hello-world/index.ts")
	if err != nil {
		log.Fatal(err)
	}
	deno, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
		if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%s", deno)

}
package adapter

import android.content.Context
import android.view.ViewGroup
import androidx.collection.SparseArrayCompat
import androidx.recyclerview.widget.RecyclerView
import domain.ViewType
import domain.movie.ListaItemFilme
import pessoaspopulares.adapter.LoadingDelegateAdapter
import pessoaspopulares.adapter.ViewTypeDelegateAdapter
import utils.Constant

/**
 * Created by icaro on 14/08/16.
 */
class ListUserAdapter(private val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val listaResult = ArrayList<ViewType>()
    private val delegateAdapters = SparseArrayCompat<ViewTypeDelegateAdapter>()

    init {
        delegateAdapters.put(Constant.ViewTypesIds.LOADING, LoadingDelegateAdapter())
        delegateAdapters.put(Constant.ViewTypesIds.NEWS, ListasDelegateAdapter())
        listaResult.add(loading)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return delegateAdapters.get(viewType)!!.onCreateViewHolder(parent)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        delegateAdapters.get(getItemViewType(position))?.onBindViewHolder(holder, listaResult[position], context)
    }

    override fun getItemViewType(position: Int): Int {
        return listaResult[position].getViewType()
    }

    fun addItens(listaMedia: List<ListaItemFilme?>?, totalResults: Int) {
        if (listaMedia?.isNotEmpty()!!) {
            val initPosition = listaResult.size - 1
            this.listaResult.removeAt(initPosition)
            notifyItemRemoved(initPosition)
            for (result in listaMedia) {
                this.listaResult.add(result!!)
            }
            this.listaResult.sortedBy { (it as ListaItemFilme).releaseDate }
                .reversed()
            notifyItemRangeChanged(initPosition, this.listaResult.size + 1 /* plus loading item */)
            if (listaResult.size < totalResults)
                this.listaResult.add(loading)
        }
    }

    override fun getItemCount(): Int = listaResult.size

    companion object {

        private val loading = object : ViewType {
            override fun getViewType(): Int {
                return Constant.ViewTypesIds.LOADING
            }
        }
    }
}





@Keep
interface ViewType {
    fun getViewType(): Int
}

interface ViewTypeDelegateAdapter {

    fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder

    fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType?, context: Context?)
}



class LoadingDelegateAdapter : ViewTypeDelegateAdapter {

    override fun onCreateViewHolder(parent: ViewGroup) = LoadingViewHolder(parent)

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, item: ViewType?, context: Context?) {
    }

    class LoadingViewHolder(parent: ViewGroup) : RecyclerView.ViewHolder(
            LayoutInflater.from(parent.context)
                .inflate(R.layout.new_item_loading, parent, false))
}


class ListasDelegateAdapter : ViewTypeDelegateAdapter {

	override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder =
		ListViewHolder(parent)

	override fun onBindViewHolder(
		holder: RecyclerView.ViewHolder,
		item: ViewType?,
		context: Context?
	) {
		(holder as ListViewHolder).bind(item as ListaItemFilme)
	}

	inner class ListViewHolder(parent: ViewGroup) :
		RecyclerView.ViewHolder(
			LayoutInflater.from(parent.context).inflate(R.layout.lista, parent, false)
		) {

		fun bind(item: ListaItemFilme) = with(itemView) {

			img_lista.setPicassoWithCache(item.posterPath, 3)
			when (item.mediaType) {
				"tv" -> date_oscar.text =
					if (!item.first_air_date.isNullOrEmpty() && item.first_air_date.length > 3)
						item.first_air_date.subSequence(0, 4) else "-"
				"movie" -> date_oscar.text =
					if (!item.releaseDate.isNullOrEmpty() && item.releaseDate.length > 3)
						item.releaseDate.subSequence(0, 4) else "-"
			}

			progress.visibility = View.GONE
			itemView.setOnClickListener {
				when (item.mediaType) {
					"tv" -> {
						val intent = Intent(context, TvShowActivity::class.java).apply {
							putExtra(Constant.TVSHOW_ID, item.id)
							putExtra(Constant.COLOR_TOP, UtilsApp.loadPalette(img_lista))
						}
						context.startActivity(intent)
					}
					"movie" -> {
						val intent = Intent(context, MovieDetailsActivity::class.java).apply {
							putExtra(Constant.FILME_ID, item.id)
							putExtra(Constant.COLOR_TOP, UtilsApp.loadPalette(img_lista))
						}
						context.startActivity(intent)
					}
				}
			}
		}
	}
}

  
package utils

import android.animation.Animator
import android.animation.Animator.*
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.util.Log
import android.view.View
import android.view.ViewGroup.*
import android.widget.ImageView
import android.widget.Toast
import androidx.core.view.marginTop
import androidx.fragment.app.FragmentActivity
import androidx.palette.graphics.Palette
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import applicaton.BaseViewModel.*
import applicaton.BaseViewModel.BaseRequest.*
import br.com.icaro.filme.R
import com.github.clans.fab.FloatingActionMenu
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.gson.Gson
import com.squareup.picasso.Callback
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.NetworkPolicy
import com.squareup.picasso.Picasso
import domain.reelgood.movie.Availability
import domain.tvshow.Tvshow
import error.BottomSheetError
import error.CallBackError
import java.text.DateFormat
import java.text.Normalizer
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * Created by icaro on 03/09/17.
 */
/**
 * IMAGEVIEW
 */
fun ImageView.setPicasso(
	stillPath: String?,
	patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
): ImageView {
	Picasso.get()
		.load(
			UtilsApp
				.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath
		)
		.error(img_erro)
		.memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_CACHE)
		.networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setPicassoWithCache(
	stillPath: String?, patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
): ImageView {
	Picasso.get()
		.load(
			UtilsApp
				.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath
		)
		.error(img_erro)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setPicassoWithCacheAndHolder(
	stillPath: String?, patten: Int = 4,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.poster_empty,
	holder: Int,
): ImageView {
	Picasso.get()
		.load(UtilsApp.getBaseUrlImagem(UtilsApp.getTamanhoDaImagem(context, patten)) + stillPath)
		.placeholder(holder)
		.error(img_erro)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.loadPallet(): Int? {
	val color = (drawable as? BitmapDrawable)?.run {
		Palette.Builder(this.bitmap).generate().swatches.first().rgb
	}
	return color ?: 0
}

fun loadPalette(view: ImageView): Int { // Todo Usar ext
	val imageView = view as ImageView
	val drawable = imageView.drawable as? BitmapDrawable
	if (drawable != null) {
		return Palette.Builder(drawable.bitmap).generate().swatches.last().rgb
	}
	return 0
}

/**
 * ACTIVITY
 */
fun Activity.makeToast(restText: Int, time: Int = Toast.LENGTH_SHORT) {
	this.makeToast(this.getString(restText), time)
}

fun Activity.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(this, text, time).show()
}

/**
 * Context
 */
fun Context.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(this, text, time).show()
}

/**
 * VIEW
 */
fun View.gone() {
	this.visibility = View.GONE
}

fun View.visible() {
	this.visibility = View.VISIBLE
}

fun View.invisible() {
	this.visibility = View.INVISIBLE
}

fun View.animeRotation(
	end: () -> Unit = {},
	cancel: () -> Unit = {},
	start: () -> Unit = {},
	repeat: () -> Unit = {},
) {
	ObjectAnimator
		.ofPropertyValuesHolder(
			this,
			PropertyValuesHolder.ofFloat(View.SCALE_X, 1.0f, 0.2f),
			PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.0f, 0.2f),
			PropertyValuesHolder.ofFloat(View.SCALE_X, 0.0f, 1.0f),
			PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.0f, 1.0f)
		)
		.apply {
			duration = 790
			addListener(object : AnimatorListener {
				override fun onAnimationRepeat(animation: Animator?) {
					repeat()
				}

				override fun onAnimationEnd(animation: Animator?) {
					end()
				}

				override fun onAnimationCancel(animation: Animator?) {
					cancel()
				}

				override fun onAnimationStart(animation: Animator?) {
					start()
				}
			})
		}.start()
}

/**
 * Any
 */
fun Any.putString(cxt: Context): String = when (this) {
	is String -> this
	is Int -> cxt.getString(this)
	else -> {
		require(false) { "Need R.string.id or string" }
		""
	}
}

/**
 * STRING
 */
fun String.removerAcentos(): String {
	this.replace(".", "")
	this.replace(":", "")
	this.replace("/", "")
	this.replace(";", "")
	return Normalizer.normalize(this, Normalizer.Form.NFD).replace("[^\\p{ASCII}]".toRegex(), "")
}

fun String.parseDate(): String {
	return try {
		val sim = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
		val data = sim.parse(this)
		DateFormat.getDateInstance(DateFormat.SHORT).format(data)
	} catch (ex: Exception) {
		"-/-"
	}
}

fun String.parseDateShot(): String {
	return try {
		val sim = SimpleDateFormat("yyyy-MM-dd")
		val data = sim.parse(this)
		DateFormat.getDateInstance(DateFormat.SHORT).format(data)
	} catch (ex: Exception) {
		"-/-"
	}
}

fun verifyLaunch(air_date: Date?): Boolean {
	if (air_date == null) return false
	val now = Calendar.getInstance().time
	return if (air_date.before(now)) {
		true
	} else !air_date.after(now)
}

fun String.getDate(format: String = "yyyy-MM-dd"): Date? {
	return try {
		let {
			val sdf = SimpleDateFormat(format, Locale.getDefault())
			sdf.parse(it)
		}
	} catch (e: ParseException) {
		e.printStackTrace()
		null
	}
}

fun String.released(): Boolean {
	val data = getDate()
	return verifyLaunch(data)
}

@Throws(Exception::class)
fun String.yearDate(): String {
	return if (this.length >= 4) this.substring(0, 4) else ""
}

fun String.periodLaunch(): Boolean {
	val oneWeekBack = Calendar.getInstance().apply { add(Calendar.DAY_OF_YEAR, -7) }.time
	return getDate() != null && getDate()!!.after(oneWeekBack) //valida data
}

fun String.getNameTypeReel(): String {
	return replace(":", "-")
		.replace(" ", "-")
		.replace("&", "and")
		.replace(".", "")
		.replace("é", "e")
		.replace("ẽ", "e")
		.replace("è", "e")
		.replace("ë", "e")
		.replace("ç", "c")
		.replace("â", "a")
		.replace("ã", "a")
		.replace("á", "a")
		.replace("à", "a")
		.replace("ä", "a")
		.replace("ä", "a")
		.replace("'", "")
		.replace("\"", "")
		.replace("´", "")
		.replace("~", "")
		.replace("^", "")
		.replace("---", "-")
		.replace("----", "-")
		.replace("--", "-")
		.toLowerCase()
}

fun String?.notNullOrEmpty() = !this.isNullOrEmpty()
fun <T> Gson.fromJsonWithLog(json: String?, classOfT: Class<T>): T {
	return this.fromJson<T>(json, classOfT).apply {
		this.toString().log(classOfT.name)
	}
}

fun String.log(tag: String = "") = Log.i(tag, this)

fun Tvshow.createIdReal() = createIdReal(this.originalName ?: "", this.firstAirDate ?: "")
private fun createIdReal(originalName: String, data: String) =
	"${originalName.getNameTypeReel()}-${data.yearDate()}"

/**
 * RECYCLER
 */
fun RecyclerView.setScrollInvisibleFloatMenu(floatButton: FloatingActionMenu) {
	addOnScrollListener(object : RecyclerView.OnScrollListener() {
		override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
			when (newState) {
				RecyclerView.SCROLL_STATE_IDLE -> floatButton.visible()
				RecyclerView.SCROLL_STATE_DRAGGING -> floatButton.invisible()
				RecyclerView.SCROLL_STATE_SETTLING -> floatButton.invisible()
			}
		}
	})
}

@SuppressLint("WrongConstant")
fun RecyclerView.patternRecyler(horizont: Boolean = true): RecyclerView {
	val typeOrient = if (horizont) LinearLayoutManager.HORIZONTAL else LinearLayoutManager.VERTICAL
	layoutManager = LinearLayoutManager(context, typeOrient, false)
	itemAnimator = DefaultItemAnimator()
	setHasFixedSize(true)
	return this
}

fun RecyclerView.patternRecyclerGrid(quant: Int = 2): RecyclerView {
	layoutManager = GridLayoutManager(context, quant)
	setHasFixedSize(true)
	itemAnimator = DefaultItemAnimator()
	return this
}

fun RecyclerView.minHeight(): RecyclerView {
	layoutParams.height = 1
	importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
	isFocusable = false
	return this
}

/**
 * AVAILABILITY
 */
fun Availability.getPricePurchase(): String {
	val less = purchaseCostSd?.let { purchaseCostHd?.coerceAtMost(it) }
	val biggest = purchaseCostSd?.let { purchaseCostHd?.coerceAtLeast(it) }
	if (less == biggest) return less.toString()
	return "${if (less != 0.0) less.toString() else "--"} - ${if (biggest != 0.0) biggest.toString() else "--"}"
}

fun Availability.getPriceRental(): String {
	val less = rentalCostSd?.let { rentalCostHd?.coerceAtMost(it) }
	val biggest = rentalCostSd?.let { rentalCostHd?.coerceAtLeast(it) }
	if (less == biggest) return less.toString()
	return "${if (less != 0.0) less.toString() else "--"} - ${if (biggest != 0.0) biggest.toString() else "--"}"
}

/**
 * BottomSheetBehavior
 */
fun BottomSheetBehavior<View>.setAnimation(container: View, viewHeight: View) {
	ValueAnimator.ofInt(container.measuredHeight, viewHeight.marginTop).apply {
		addUpdateListener {
			peekHeight = it.animatedValue as Int
		}
		duration = 500
	}.start()

	container.post {
		val newLayoutParams = (container.layoutParams as? MarginLayoutParams)
		newLayoutParams?.setMargins(0, 0, 0, viewHeight.marginTop + 1)
		container.layoutParams = newLayoutParams
	}
}

/**
 * MutableList
 */
fun <T> MutableList<T>.replaceItemList(item: T, predicate: (T) -> Boolean): MutableList<T> {
	return this.map {
		if (predicate(it)) item else it
	}.toMutableList()
}

fun <T> Any.listSize(item: T, size: Int): ArrayList<T> {
	return if (size <= 0) {
		arrayListOf()
	} else {
		arrayListOf<T>().apply {
			for (i in 0 until size) {
				add(item)
			}
		}
	}
}

/**
 * BaseRequest
 */
fun <T> BaseRequest<T>.success() = (this as Success<T>).result
fun <T> BaseRequest<T>.resolver(
	activity: FragmentActivity,
	successBlock: (data: T) -> Unit,
	failureBlock: (error: Exception) -> Unit = {},
	loadingBlock: (loading: Boolean) -> Unit = {},
	genericError: CallBackError? = null,
) {
	when (this) {
		is Success -> successBlock(result)
		is Loading -> loadingBlock(loading)
		is Failure -> {
			error.toString().log()
			if (genericError != null) {
				BottomSheetError().newInstance(callBackError = genericError)
					.show(activity.supportFragmentManager, "")
			} else {
				failureBlock(error)
			}
		}
	}
}


import android.animation.Animator
import android.animation.Animator.*
import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
import android.animation.ValueAnimator
import android.app.Activity
import android.content.Context
import android.graphics.PorterDuff
import android.util.Log
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.*
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.ColorRes
import androidx.appcompat.widget.AppCompatSpinner
import androidx.core.content.ContextCompat
import androidx.core.view.children
import androidx.core.view.marginTop
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import br.gov.sp.educacao.diariodeclassesp.BaseActivity
import br.gov.sp.educacao.diariodeclassesp.BaseViewModel.*
import br.gov.sp.educacao.diariodeclassesp.BaseViewModel.BaseRequest.*
import br.gov.sp.educacao.diariodeclassesp.R
import br.gov.sp.educacao.diariodeclassesp.models.ResponseDiario
import br.gov.sp.educacao.diariodeclassesp.utils.ToastDiario
import br.gov.sp.educacao.diariodeclassesp.utils.ToastDiario.Type.*
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.navigation.NavigationView
import com.google.gson.Gson
import com.squareup.picasso.Callback
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.NetworkPolicy
import com.squareup.picasso.Picasso
import okhttp3.Response
import org.json.JSONObject
import java.text.DateFormat
import java.text.Normalizer
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Calendar
import java.util.Date
import java.util.Locale

/**
 * Created by icaro on 03/09/17.
 */
/**
 * IMAGEVIEW
 */
fun ImageView.setPicasso(
	stillPath: String?,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.apagar_snape
): ImageView {
	Picasso.get()
		.load(stillPath)
		.error(img_erro)
		.memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_CACHE)
		.networkPolicy(NetworkPolicy.NO_CACHE, NetworkPolicy.NO_STORE)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setPicassoWithCache(
	stillPath: String?,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.apagar_snape
): ImageView {
	Picasso.get()
		.load(stillPath)
		.error(img_erro)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setPicassoWithCacheAndHolder(
	stillPath: String?,
	sucesso: () -> Unit = {},
	error: () -> Unit = {},
	img_erro: Int = R.drawable.apagar_snape,
	holder: Int
): ImageView {
	Picasso.get()
		.load(stillPath)
		.placeholder(holder)
		.error(img_erro)
		.into(this, object : Callback {
			override fun onSuccess() {
				sucesso()
			}

			override fun onError(e: java.lang.Exception?) {
				error()
			}
		})
	return this
}

fun ImageView.setSvgColor(@ColorRes color: Int) =
	setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_IN)
/**
 * CONTEXT
 */

fun Context.makeToast(restText: Int, time: Int = Toast.LENGTH_SHORT) {
	this.makeToast(this.getString(restText), time)
}

fun Context.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(this, text, time).show()
}

/**
 * ACTIVITY
 */
fun Activity.makeToast(restText: Int, time: Int = Toast.LENGTH_SHORT) {
	this.makeToast(this.getString(restText), time)
}

fun Activity.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(this, text, time).show()
}

fun Activity.hideSoftKeyboard() {
	window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
	val imm: InputMethodManager =
		getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
	currentFocus.ifValid {
		imm.hideSoftInputFromWindow(currentFocus!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
	}
}

/**
 * FRAGMENT
 */
fun Fragment.makeToast(restText: Int, time: Int = Toast.LENGTH_SHORT) {
	this.makeToast(this.getString(restText), time)
}

fun Fragment.makeToast(text: String?, time: Int = Toast.LENGTH_SHORT) {
	Toast.makeText(requireContext(), text, time).show()
}

fun Fragment.hideSoftKeyboard() {
	requireActivity().window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}

/**
 * VIEW
 */
fun View.gone() {
	this.visibility = View.GONE
}

fun View.visible() {
	this.visibility = View.VISIBLE
}

fun View.invisible() {
	this.visibility = View.INVISIBLE
}

fun View.onClick(func: () -> Unit) = this.apply { setOnClickListener { func.invoke() } }

fun View.animeRotation(
	end: () -> Unit = {},
	cancel: () -> Unit = {},
	start: () -> Unit = {},
	repeat: () -> Unit = {}
) {
	ObjectAnimator
		.ofPropertyValuesHolder(
			this,
			PropertyValuesHolder.ofFloat(View.SCALE_X, 1.0f, 0.2f),
			PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.0f, 0.2f),
			PropertyValuesHolder.ofFloat(View.SCALE_X, 0.0f, 1.0f),
			PropertyValuesHolder.ofFloat(View.SCALE_Y, 0.0f, 1.0f)
		)
		.apply {
			duration = 790
			addListener(object : AnimatorListener {
				override fun onAnimationRepeat(animation: Animator?) {
					repeat()
				}

				override fun onAnimationEnd(animation: Animator?) {
					end()
				}

				override fun onAnimationCancel(animation: Animator?) {
					cancel()
				}

				override fun onAnimationStart(animation: Animator?) {
					start()
				}
			})
		}.start()
}

/**
 * Any
 */
fun Any.putString(cxt: Context): String = when (this) {
	is String -> this
	is Int -> cxt.getString(this)
	else -> {
		require(false) { "Need R.string.id or string" }
		""
	}
}

fun <T> Any.listSize(item: T, size: Int): ArrayList<T> {
	return if (size <= 0) {
		arrayListOf()
	} else {
		arrayListOf<T>().apply {
			for (i in 0 until size) {
				add(item)
			}
		}
	}
}

/**
 * STRING
 */
fun String.removerAcentos(): String {
	this.replace(".", "")
	this.replace(":", "")
	this.replace("/", "")
	this.replace(";", "")
	return Normalizer.normalize(this, Normalizer.Form.NFD).replace("[^\\p{ASCII}]".toRegex(), "")
}

fun String.parseDate(): String {
	return try {
		val sim = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ROOT)
		val data = sim.parse(this)
		DateFormat.getDateInstance(DateFormat.SHORT).format(data!!)
	} catch (ex: Exception) {
		"-/-"
	}
}

fun String.parseDateShot(): String {
	return try {
		val sim = SimpleDateFormat("yyyy-MM-dd", Locale.ROOT)
		val data = sim.parse(this)
		DateFormat.getDateInstance(DateFormat.SHORT).format(data!!)
	} catch (ex: Exception) {
		"-/-"
	}
}

fun String.getDate(format: String = "yyyy-MM-dd"): Date? {
	return try {
		let {
			val sdf = SimpleDateFormat(format, Locale.getDefault())
			sdf.parse(it)
		}
	} catch (e: ParseException) {
		e.printStackTrace()
		null
	}
}

fun String.log(tag: String = "tag"): String {
	Log.d(tag, this)
	return this
}

fun <T> Gson.fromJsonWithLog(json: String?, classOfT: Class<T>): T {
	return this.fromJson<T>(json, classOfT).apply {
		json?.log()
		this.toString().log(classOfT.name)
	}
}

fun String?.notNullOrEmpty() = !this.isNullOrEmpty()

fun String.toPatternName(): CharSequence? {
	return this.toLowerCase().split(" ").reduceRight { s, acc ->
		"${s.capitalize()} ${acc.capitalize()}"
	}
}

/**
 * RECYCLER
 */
fun RecyclerView.patternRecycler(horizont: Boolean = true, divider: Int = 0): RecyclerView {
	layoutManager = LinearLayoutManager(
		context,
		if (horizont) LinearLayoutManager.HORIZONTAL else LinearLayoutManager.VERTICAL,
		false
	)
	if (divider != 0) addCustomDivider(divider)
	itemAnimator = DefaultItemAnimator()
	setHasFixedSize(true)
	return this
}

fun RecyclerView.patternRecyclerGrid(quant: Int = 2): RecyclerView {
	layoutManager = GridLayoutManager(context, quant)
	setHasFixedSize(true)
	itemAnimator = DefaultItemAnimator()
	return this
}

fun RecyclerView.minHeight(): RecyclerView {
	layoutParams.height = 1
	importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
	isFocusable = false
	return this
}

fun RecyclerView.addCustomDivider(divider: Int) {
	DividerItemDecoration(context, DividerItemDecoration.VERTICAL).apply {
		setDrawable(ContextCompat.getDrawable(context, divider)!!)
		addItemDecoration(this)
	}
}

fun RecyclerView.setScrollInvisibleFloatMenu(view: View) {
	addOnScrollListener(object : RecyclerView.OnScrollListener() {
		override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
			when (newState) {
				RecyclerView.SCROLL_STATE_IDLE -> {
					view.visible()
				}
				RecyclerView.SCROLL_STATE_DRAGGING -> {
					view.gone()
				}
				RecyclerView.SCROLL_STATE_SETTLING -> {
					view.gone()
				}
			}
		}
	})
}


/**
 * BottomSheetBehavior
 */
fun BottomSheetBehavior<View>.setAnimation(container: View, viewHeight: View) {
	ValueAnimator.ofInt(container.measuredHeight, viewHeight.marginTop).apply {
		addUpdateListener {
			peekHeight = it.animatedValue as Int
		}
		duration = 500
	}.start()

	container.post {
		val newLayoutParams = (container.layoutParams as? MarginLayoutParams)
		newLayoutParams?.setMargins(0, 0, 0, viewHeight.marginTop + 1)
		container.layoutParams = newLayoutParams
	}
}

/**
 * MutableList
 */
fun <T> MutableList<T>.replaceItemList(item: T, predicate: (T) -> Boolean): MutableList<T> {
	return this.map {
		if (predicate(it)) item else it
	}.toMutableList()
}

/**
 * Array
 */
inline fun <reified T> Array<T>.addHint(filter: T): Array<T> {
	return arrayOf(filter, *this)
}

/**
 * NavigationView
 */
fun <T> NavigationView.findViewOnHeader(id: Int): T? {
	return (getHeaderView(0) as? ViewGroup)
		?.children?.find {
			it.id == id
			// todo por id
		} as? T
}

/**
 * Response - Htttp3
 */
fun Response.contaisErro(json: String?) = json.ifValid { JSONObject(json!!).has("Erro") } ?: false
fun Response.createError(json: String?) =
	if (contaisErro(json)) JSONObject(json!!).getString("Erro") else ""

/**
 * Response - Retrofit
 */
fun <T> retrofit2.Response<T>.contaisErro(json: String?): Boolean =
	json.ifValid { JSONObject(json!!).has("Erro") } ?: false

fun <T> retrofit2.Response<T>.createError(json: String?) =
	if (contaisErro(json)) JSONObject(json!!).getString("Erro") else ""

/**
 * BaseRequest
 */
fun <T> BaseRequest<T>.success() = (this as? Success<T>)?.result
fun <T> BaseRequest<T>.successArray() = (this as? Success<ResponseDiario<Array<T>>>)?.result
fun <T> BaseRequest<ResponseDiario<Array<T>>>.resolverArray(
	activity: Activity,
	successBlock: (data: Array<T>) -> Unit,
	toastSuccess: Boolean = false,
	failure: () -> Unit = {},
	alert: Boolean = true,
	genericError: Boolean = true
) {
	this.resolver(activity, successBlock, toastSuccess, failure, alert, genericError)
}

// val result = (_classes.value as? Success)?.result
// val list = (result as? )?.data ?: arrayOf()
fun <T> BaseRequest<ResponseDiario<T>>.resolver(
	activity: Activity,
	successBlock: (data: T) -> Unit,
	toastSuccess: Boolean = false,
	failure: () -> Unit = {},
	alert: Boolean = true,
	genericError: Boolean = true
) {
	if (alert)
		when (this) {
			is Success -> {
				@Suppress("UNCHECKED_CAST")
				val result = result
				result.let { response ->
					when (response.code) {
						200 -> {
							if (toastSuccess) {
								ToastDiario(activity, result.message ?: "")
									.show(type = SUCCESS)
							}
							successBlock(result.data)
						}
						202 -> ToastDiario(activity, result.message ?: "").show(type = ERRO)
						201, in 203..299 -> ToastDiario(activity,
							result.message ?: "").show(type = ALERT)
					}
				}
			}
			is Failure -> {
				error.toString().log()
				if (genericError) {
					(activity as? BaseActivity)?.error { failure() }
				} else {
					failure()
				}
			}
		}
	else {
		when (this) {
			is Success -> {
				@Suppress("UNCHECKED_CAST")
				val result = result
				result.let { response ->
					if (toastSuccess) ToastDiario(activity,
						response.message ?: "").show(type = SUCCESS)
					successBlock(response.data)
				}
			}
			is Failure -> {
				error.toString().log()
				if (genericError) {
					(activity as? BaseActivity)?.error { failure() }
				} else {
					failure()
				}
			}
		}
	}
}
/**
 * AppCompatSpinner
 */

fun AppCompatSpinner.selectedOneChoose(list: Array<*>) {
	if (list.size == 2) setSelection(list.size - 1)
}
/**
 * Int
 */
fun Int.toDp(context: Context) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
	this.toFloat(), context.resources.displayMetrics).toInt()
/**
 * Float
 */
fun Float.toDp(context: Context) = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
	this, context.resources.displayMetrics).toInt()

/**
 * Boolean
 */
fun Boolean.invert() = !this

/**
 * Calendar
 */
fun Calendar.getFormetDateBr(): String {
	return "${this[Calendar.DAY_OF_MONTH]}/${this[Calendar.MONTH]}/${this[Calendar.YEAR]}"
}

fun Calendar.formatApi(): String {
	return time.formatApi()
}

/**
 * Date
 */

fun Date.getFormetDateBr(): String {
	return "${this.day}/${this.month}/${this.year}"
}

fun Date.formatApi(): String {
	// Fri Nov 20 19:15:41 GMT-03:00 2020
	// "MM/dd/yyyy'T'HH:mm:ss"
	// 20/10/2020
	return try {
		return SimpleDateFormat("dd/MM/yyyy").parse(this.getFormetDateBr()).toString()
	} catch (ex: java.lang.Exception) {
		ex.toString()
	}
}

// you could use the invokable flag so you don't use the index

php artisan make:controller PagesController --invokable

// and then use this route:
Route::get('/{any?}', App\Http\Controllers\PagesController::class)->where('any', '.*');

// it tells Laravel routing to respond to any route provided or nothing with the question mark "?" and responds with an invokable controller

    public function __invoke()
    {
        return view('welcome');
    }
"[go]": {

        "editor.formatOnSave": false,
        "editor.codeActionsOnSave": {
            "source.organizeImports": false
        },
    },
    "go.formatTool": "gofmt",
// Bubble sorting using most of the important features in TypeScript

//* index.ts
import { Sorter } from './Sorter';
import { NumbersCollection } from './NumbersCollecton';

// Passing object into helper function to prepare variable for sorter when data is an array
const numbersCollection = new NumbersCollection([10, 3, -5, 0])
// Passing in object now instead of raw data
const sorter = new Sorter(numbersCollection)

sorter.sort()

console.log(numbersCollection.data)



//* Sorter.ts
import { NumbersCollection } from './NumbersCollecton';


export class Sorter {
  constructor(public collection: NumbersCollection)  {}

  sort(): void {
    const { length } = this.collection

    for (let i = 0; i < length; i++) {
      for (let j = 0; j < length - i - 1; j++) {
        if (this.collection.compare(j, j + 1)) {
          this.collection.swap(j, j+1)
        }
        // Only going to work if collecton is a string
        // If collection is a string, do this instead
        // ~~~logic to compare and swap characters in a string
      }
    }
  }
}



//* NumbersCollection.ts

/* Class Structure: */

// File: NumbersCollection.ts
// Class: NumbersCollection {
// Constructor: constructor(permissions, vars: types) {}
// Function(s) function(): type {
  // function body
// } //close function
// } // Close Class




export class NumbersCollection {
  // Require an array of numbers to be passed in and instantiated
  constructor(public data: number[]) {}
  // Need to get length of array
  get length(): number {
    return this.data.length
  }
  // decide if we need to swap 2 elements in a pair (bubble sort)
  /* is -1 > 0 ? If so, swap them
    /       |
  /        |
  [-1] [0] [5] [10] */
  compare(leftIndex: number, rightIndex: number): boolean {
    return this.data[leftIndex] > this.data[rightIndex]
  }

  swap(leftIndex: number, rightIndex: number): void {
    const leftHand = this.data[leftIndex]
    this.data[leftIndex] = this.data[rightIndex]
    this.data[rightIndex] = leftHand

  }

}

// const collection = new NumbersCollection([1,2,3])
// // since 'get' was used, length doesn't need to be called as a function (ex: collection.length())
// collection.length
@foreach($estados as $estado)
                                                        <td> <small><b>{{$estado->DOCUMENTO}}</b></small> <br> <small>{{$estado->NOMBRES}}</small></td>
                                                        <td>{{$estado->EDAD}}</td>
                                                        <td><small>{{$estado->CENTRO_ATENCION}}</small><br><cite style="font-size: 10px">{{$estado->ESPECIALIDAD}}</cite></td>
                                                        <td><small> {{Carbon\Carbon::parse($estado->FEC_INGRESO)->isoFormat('H:mm:ss A')}}</small></td>
                                                        @if(!empty($estado->FEC_INIC_ATENC))
                                                        <td><small>{{Carbon\Carbon::parse($estado->FEC_INIC_ATENC)->isoFormat('H:mm:ss A')}}</small></td>
                                                        @else
                                                        <td>{{$estado->FEC_INIC_ATENC}}</td>
                                                        @endif
                                                        <td>
                                                            @if(empty($estado->FEC_INIC_ATENC))
                                                            <div class="progress-group">
                                                                <i class="fas fa-hourglass-end"></i> paciente en espera de atención 
                                                                <span class="float-right"><b></b></span>
                                                                {{-- <div class="progress progress-sm">
                                                                    <div class="progress-bar bg-danger" style="width: 100%"></div>
                                                                </div> --}}
                                                                <hr>
                                                            </div>
                                                            @include('clasificacion')
                                                            @else
                                                            <div class="progress-group">
                                                                <i class="fas fa-check"></i> Paciente atendido 
                                                                <span class="float-right"><b>{{ $diff = Carbon\Carbon::parse($estado->FEC_INIC_ATENC)->diffInMinutes(Carbon\Carbon::parse($estado->FECHA_FIN_ATENCION)) }}</b> Minutos</span>
                                                                {{-- <div class="progress progress-sm">
                                                                    <div class="progress-bar bg-primary" style="width: 100%"></div>
                                                                </div> --}}
                                                                <hr>
                                                            </div>
                                                            @include('clasificacion')
                                                            @endif
                                                        </td>
                                                        @if(!empty($estado->FECHA_FIN_ATENCION))
                                                        <td><small>{{Carbon\Carbon::parse($estado->FECHA_FIN_ATENCION)->isoFormat('H:mm:ss A')}}</small></td>
                                                        @else
                                                        <td><small>{{$estado->FEC_INIC_ATENC}}</small></td>
                                                        @endif

                                                    </tr>
                                                    @endforeach
data_train = pd.read_csv('/content/train.csv')
data_test = pd.read_csv('/content/test.csv')
data_train.head()
data_train = pd.read_csv('/content/train.csv')
data_test = pd.read_csv('/content/test.csv')
data_train.head()
<?php
	$dbc = mysqli_connect('localhost', 'root', '');	//connect database
	mysqli_select_db($dbc, 'news');	//select database
	
	if(isset($_POST['addNewsData'])){
		$newsTitle = $_POST['txtNewsTitle'];
		$newsDetails = $_POST['txtNewsDetails'];
		$newsCategory = $_POST['selectNewsCategory'];
		
		$query = "INSERT INTO news (news_title, news_details, news_category, news_datetime) 
		VALUES ('$newsTitle', '$newsDetails', '$newsCategory', NOW())";
		
		$runQuery = mysqli_query($dbc, $query);
		
		if($runQuery){
			echo '<script> alert("Data saved!"); </script>';
			header('Location: /205CDE/Assignment/manageNews.php');
		}else{
			echo '<script> alert("Data not save yet!"); </script>';
		}
	}
	mysqli_close($dbc);
?>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | Admin</title>
		<script type="text/javascript">
			setTimeout(function(){ 
				document.querySelector('.close').click();
			}, 2500);
		</script>
		<!--show news info for editing START-->
		<script type="text/javascript">
			$(document).ready(function(){
				$('.btnEdit').on('click', function(){
					$('#updNewsModal').modal('show');
					
					$tr = $(this).closest('tr');
					
					var data = $tr.children("td").map(function(){
						return $(this).text();
					}).get();
					
					console.log(data);
					
					$('#update_id').val(data[0]);
					$('#news_datetime').val(data[1]);
					$('#news_title').val(data[2]);
					$('#news_details').val(data[3]);
					$('#news_category').val(data[4]);
					$('#news_image').val(data[5]);
				});
			});
		</script>
		<!--show news info for editing END-->
		
		<!--show confirmation message for deleting START-->
		<script type="text/javascript">
			$(document).ready(function(){
				$('.btnDel').on('click', function(){
					$('#delNewsModal').modal('show');
					
					$tr = $(this).closest('tr');
					
					var data = $tr.children("td").map(function(){
						return $(this).text();
					}).get();
					
					console.log(data);
					
					$('#delete_id').val(data[0]);
				});
			});
		</script>
		<!--show confirmation message for deleting END-->
		
		<!--show file name after uploading image START-->
		<script type="text/javascript">
            $(document).ready(function() {
                bsCustomFileInput.init();
			});
		</script>
		<!--show file name after uploading image END-->
		<body>
			<!--using external files-->
			<?php
				if(empty($_SESSION['username'])){
					header('Location: /205CDE/Assignment/home.php');
				}
			?>
			<?php require('header.php'); ?>
			
			<div class="container" style="margin: 20px;">
				<div class="row">
					<div class="col-sm"><h3 style="color: #1f52a3;">Manage News</h3></div>
				</div>
			</div>
			<!--add news modal START-->
			<!-- Modal -->
			<div class="modal fade bd-example-modal-lg" id="addNewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog modal-lg" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" id="exampleModalLabel">Add News</h5>
							<!--<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>-->
						</div>
						<form action="/205CDE/Assignment/insertData.php" method="post" enctype="multipart/form-data">
							<div class="modal-body">
								<div class="form-group">
									<label for="inputNewsTitle">News Title:</label>
									<input type="text" class="form-control" name="txtNewsTitle" id="inputNewsTitle" aria-describedby="emailHelp" placeholder="Enter news title">
								</div>
								<div class="form-group">
									<label for="selectNewsCategory">News Category:</label>
									<select class="form-control" name="selectNewsCategory" id="selectNewsCategory">
										<?php
											$newsCategoryArr = array(
											'--Select news category--' => "",
											'Nation' => 1,	'World' => 2,
											'Sport' => 3,	'Entertainment' => 4
											);
											foreach($newsCategoryArr as $newsType => $newsNum){
												echo "<option value=\"$newsType\">$newsType</option>";
											}
										?>
									</select>
								</div>
								<div class="form-group mb-3">
									<label for="inputNewsImage" class="col-form-label">News Image:</label>
									<div class="custom-file">
										<input type="file" class="custom-file-input" name="uploadNewsImg" id="customFile">
										<label class="custom-file-label" for="customFile">Choose file</label>
									</div>
								</div>
								<div class="form-group">
									<label for="inputNewsDetails" class="col-form-label">News Details:</label>
									<textarea class="form-control" name="txtNewsDetails" id="inputNewsDetails" rows="10"></textarea>
								</div>
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
								<button type="submit" class="btn btn-primary" name="addNewsData" style="background: #1f52a3;">Add</button>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!--add news modal END-->
			
			<!--edit news modal START-->
			<!-- Modal -->
			<div class="modal fade bd-example-modal-lg" id="updNewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog modal-lg" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" id="exampleModalLabel">Edit News</h5>
							<!--<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>-->
						</div>
						<form action="/205CDE/Assignment/updateData.php" method="post" enctype="multipart/form-data">
							<div class="modal-body">
								<input type="hidden" name="update_id" id="update_id">
								<div class="form-group">
									<label for="txtNewsDatetime">News Created Datetime:</label>
									<input type="text" class="form-control" name="txtNewsDatetime" id="news_datetime" aria-describedby="emailHelp" placeholder="Enter news datetime" disabled>
								</div>
								<div class="form-group">
									<label for="inputNewsTitle">News Title:</label>
									<input type="text" class="form-control" name="txtNewsTitle" id="news_title" aria-describedby="emailHelp" placeholder="Enter news title">
								</div>
								<div class="form-group">
									<label for="selectNewsCategory">News Category:</label>
									<select class="form-control" name="selectNewsCategory" id="news_category">
										<?php
											$newsCategoryArr = array(
											'--Select news category--' => "",
											'Nation' => 1,	'World' => 2,
											'Sport' => 3,	'Entertainment' => 4
											);
											foreach($newsCategoryArr as $newsType => $newsNum){
												echo "<option value=\"$newsType\">$newsType</option>";
											}
										?>
									</select>
								</div>
								<div class="form-group mb-3">
									<label for="inputNewsImage" class="col-form-label">News Image:</label>
									<div class="custom-file">
										<input type="file" class="custom-file-input" name="uploadNewsImg" id="news_image">
										<label class="custom-file-label" for="news_image"></label>
									</div>
								</div>
								<div class="form-group">
									<label for="inputNewsDetails" class="col-form-label">News Details:</label>
									<textarea class="form-control" name="txtNewsDetails" id="news_details" rows="10"></textarea>
								</div>
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
								<button type="submit" class="btn btn-primary" name="updNewsData" style="background: #1f52a3;">Edit</button>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!--edit news modal END-->
			
			<!--delete news modal START-->
			<!-- Modal -->
			<div class="modal fade" id="delNewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog modal-dialog-centered" role="document">
					<div class="modal-content">
						<form action="/205CDE/Assignment/deleteData.php" method="post">
							<div class="modal-body">
								<input type="hidden" name="delete_id" id="delete_id">
								<div class="d-flex justify-content-center" style="margin: 25px 0;">
									<i class="fas fa-times-circle text-danger" style="font-size: 100px;"></i>
								</div>
								<div class="d-flex justify-content-center">
									<h4>Are you sure?</h4>
								</div>
								<div class="d-flex justify-content-center">
									<p class="col-1"></p>
									<p class="col-10" style="text-align: center;">Do you really want to delete this record?<br>This process cannot be undone.</p>
									<p class="col-1"></p>
								</div>
								<div class="row justify-content-around" style="margin: 15px 0;">
									<div class="col-6 d-flex justify-content-end">
										<button type="button" class="btn btn-secondary btn-lg" data-dismiss="modal">Cancel</button>
									</div>
									<div class="col-6 d-flex justify-content-start">
										<button type="submit" class="btn btn-danger btn-lg" name="delNewsData">Delete</button>
									</div>
									<input type="hidden" name="delSubmitted" value="true"/>
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!--delete news modal END-->
			
			<div class="container-fluid bg-light" style="padding: 30px 10px;">
				<div class="row bg-light" style="margin: 0 35px;">
					<div class="col-6">
						<h5>All News</h5>
					</div>
					<div class="col-6 d-flex justify-content-end">
						<button type="button" class="btn btn-primary" style="background: #1f52a3;" data-toggle="modal" data-target="#addNewsModal"><i class="fas fa-plus" style="font-size: 20px;"></i> Add News</button>
					</div>
				</div>
				<!--add news alert START-->
				<div class="row bg-light" style="margin: 15px 35px;" id="addNewsAlert">
					<div class="col-12">
						<div class="alert alert-success alert-dismissible fade show" role="alert" >
							<strong>Success!</strong> The news is added successfully!
							<button type="button" class="close" data-dismiss="alert" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>
						</div>
					</div>
				</div>
				<!--add news alert END-->
				
				<!--news table START-->
				<div class="card-deck" style="margin: 15px 50px;">
					<?php
						$dbc = mysqli_connect('localhost', 'root', '');	//connect database
						mysqli_select_db($dbc, 'news');	//select database
						
						$query = 'SELECT * FROM news ORDER BY news_datetime DESC';
						$runQuery = mysqli_query($dbc, $query);
					?>
					<table class="table table-hover bg-light" id="manageNewsTable">
						<thead class="thead-light">
							<tr>
								<th scope="col">News ID</th>
								<th scope="col">News Created Datetime</th>
								<th scope="col">News Title</th>
								<th scope="col">News Details</th>
								<th scope="col">News Category</th>
								<th scope="col">News Image</th>
								<th scope="col">Edit/Delete</th>
							</tr>
						</thead>
						<?php
							if($runQuery){
								foreach($runQuery as $row){
								?>
								<tbody>
									<tr>
										<td><?php echo $row['news_id']; ?></td>
										<td><small><?php echo $row['news_datetime'];?></small></td>
										<td><?php echo $row['news_title']; ?></td>
										<td><?php echo $row['news_details']; ?></td>
										<td><?php echo $row['news_category']; ?></td>
										<td>
											<a href="<?php 
												if(empty($row['news_image'])){
													echo 'https://via.placeholder.com/200x200';
													}else{
													echo '/205CDE/Assignment/'.$row['news_image'];
												} ?>" target="_blank">
												<img src="<?php 
													if(empty($row['news_image'])){
														echo 'https://via.placeholder.com/200x200';
														}else{
														echo $row['news_image'];
													}?>" alt="Thumbnail News Image" class="img-thumbnail">
											</a>
										</td>
										<td>
											<button type="button" class="btn btn-info btnEdit"><i class="fas fa-edit" style="font-size: 14px;"></i></button>
											<button type="button" class="btn btn-danger btnDel"><i class="fas fa-trash" style="font-size: 14px;"></i></button>
										</td>
									</tr>
								</tbody>
								<?php
								}
								}else{
								echo "ERROR! No record found!";
							}
							mysqli_close($dbc);
						?>
					</table>
				</div>
				<!--news table END-->
			</div>
			<!--using external files-->
			<?php require('footer.html'); ?>
		</body>
	</html>																				
action_my_profile: function(event) {
          var self = this;
          event.stopPropagation();
          event.preventDefault();
          self._rpc({
                    model: 'ir.model.data',
                    method: 'xmlid_to_res_id',
                    kwargs: {xmlid: 'youre_form_id'},
                }).then(function (res_id) {
                      self.do_action({
                            name: _t("My Profile"),
                            type: 'ir.actions.act_window',
                            res_model: 'hr.employee',
                            res_id: self.employee_data.id,
                            view_mode: 'form',
                            view_type: 'form',
                            views: [[res_id, 'form']],
                            context: {'edit': true},
                            domain: [],
                            target: 'current'
                          },{on_reverse_breadcrumb: function(){ return self.reload();}})

                },
            },
function refreshPendingIncidents() {
  return $.ajax({
    type: 'GET',
    url: '/pending-incidents/refresh/' + "{{ $reports[0]->id }}"
  });
}

refreshPendingIncidents().done(function(result) {
  console.log(result)
  console.log('res')
  }).fail(function() {
  	console.log('fail')
});
(function refreshPendingIncidents() {
  $.ajax({
    url: '/pending-incidents/refresh/' + "{{ $reports[0]->id }}",
    success: function(data) {
      console.log(data)
      console.log('test')
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(refreshPendingIncidents, 3000);
    }
  });
})();
window.addEventListener('load', (event) => {
    console.log('The page has fully loaded');
});
PSA: How to View Variables in Lists
by 
Bradford Shelley
 Forum Level 2
created 4y ago (edited 3y ago ) in Developer Community
After having to play around with variables quite a bit in a recent project, I thought I'd share how to display variables on a list of Requested Items / Catalog Tasks. This applies to lists and related lists, as reports have their own method of displaying variables. Important note: This was performed on Fuji. Your experience may differ on older versions of ServiceNow.

Step 1 Identify the variables you'd like to display on your list, then copy the sys_id for each variable. This is as simple as heading to the Catalog Item, and jumping into the variable(s) in question. We'll need the sys_id to add the column into the list.

Step 2 Head over to System UI -> Lists

Step 3 Identify the list you'd like to display the variable(s) on. We're looking for one of two things here. Either the name of the view of the list you'd like to include the variable(s) on (I highly recommend creating a new view instead of using the Default view for this, as most likely the variables will apply to certain catalog items instead of every single one), or for a related list look at the Parent and Relationship columns for the table and name of the tab for the related list. Head into the list when you've found it.



Step 4 Create a new List Element(s) from the related list at, using "variables.sys_id" (no quotes) in the actual Element field on the List Element form. Create a new List Element for each variable you wish to add.



Step 5 Head over to the list where variables were just added. They won't show up immediately, so don't panic. Edit the list layout, and move around the variables to the spots you'd like them in the list (even if the position is already how you'd like it, move a variable one position up/down, then move it back and save). At this point, the variables should be visible!

Hope this helps at least one person out there. Take care!
alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
<div class="container-fluid" style="background: #1f52a3;">
	<div class="row">
		<div class="col-2"></div>
		<div class="col-8">
			<a href="/205CDE/Assignment/home.php"><h1 style="text-align: center; color: #e6e8eb; margin: 20px 0;">U Chen Daily</h1></a>
		</div>
		<div class="col-2 d-flex justify-content-center align-items-center"><a href="/205CDE/Assignment/manageNews.php" target="_blank" class="btn btn-outline-light">LOGIN</a></div>
	</div>
</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
	<a class="navbar-brand" href="/205CDE/Assignment/home.php"><i class="fas fa-home" style="font-size: 30px; color: #1f52a3;"></i></a>
	<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
		<span class="navbar-toggler-icon"></span>
	</button>
	
	<div class="collapse navbar-collapse" id="navbarSupportedContent">
		<ul class="navbar-nav mr-auto">
			<li class="nav-item dropdown" style="margin: 0 15px;">
				<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">News</a>
				<div class="dropdown-menu" aria-labelledby="navbarDropdown">
					<?php
						$newsCategoryArr = array(
						'All', 'Nation', 'World',
						'Sport', 'Entertainment',
						);
						foreach($newsCategoryArr as $newsType){
							echo "<a class=\"dropdown-item\" href=\"/205CDE/Assignment/news$newsType.php\" target=\"_blank\">$newsType</a>";
						}
					?>
				</div>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/aboutUs.php" target="_blank">About Us</a>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/contactUs.php" target="_blank">Contact Us</a>
			</li>
			<li class="nav-item" style="margin: 0 15px;">
				<a class="nav-link" href="/205CDE/Assignment/faqs.php" target="_blank">FAQs</a>
			</li>
			<!-- <li class="nav-item"> -->
			<!-- <a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> -->
			<!-- </li> -->
		</ul>
		<!-- <form class="form-inline my-2 my-lg-0"> -->
		<!-- <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search"> -->
		<!-- <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> -->
		<!-- </form> -->
	</div>
</nav>
<!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
	
    <!-- U Chen CSS -->
	<link rel="stylesheet" href="homeStyle.css">
	
	<!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
	
	<!-- Font Awesome Icons -->
	<script src="https://kit.fontawesome.com/a076d05399.js"></script>
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | Admin</title>
		<script>
			
		</script>
	</head>
	<body>
		<!--using external files-->
		<?php require('header.html'); ?>
		<div class="container" style="margin: 20px;">
			<div class="row">
				<div class="col-sm"><h3 style="color: #1f52a3;">Manage News</h3></div>
			</div>
		</div>
		<div class="container-fluid bg-light" style="padding: 30px 10px;">
			<div class="row bg-light" style="margin: 0 35px;">
				<div class="col-6">
					<h5>All News</h5>
				</div>
				<div class="col-6 d-flex justify-content-end">
					<button type="button" class="btn btn-primary" style="background: #1f52a3;" data-toggle="modal" data-target="#addNewsModal"><i class="fas fa-plus" style="font-size: 20px;"></i> Add News</button>
				</div>
			</div>
			
			<!--add news modal START-->
			<!-- Modal -->
			<div class="modal fade bd-example-modal-lg" id="addNewsModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
				<div class="modal-dialog modal-lg" role="document">
					<div class="modal-content">
						<div class="modal-header">
							<h5 class="modal-title" id="exampleModalLabel">Add News</h5>
							<!--<button type="button" class="close" data-dismiss="modal" aria-label="Close">
								<span aria-hidden="true">&times;</span>
							</button>-->
						</div>
						<form action="/205CDE/Assignment/admin.php" method="post">
							<div class="modal-body">
								<div class="form-group">
									<label for="inputNewsTitle">News Title:</label>
									<input type="text" class="form-control" name="txtNewsTitle" id="inputNewsTitle" aria-describedby="emailHelp" placeholder="Enter news title">
								</div>
								<div class="form-group">
									<label for="selectNewsCategory">News Category:</label>
									<select class="form-control" name="selectNewsCategory" id="selectNewsCategory">
										<?php
											$newsCategoryArr = array(
											'--Select news category--' => "",
											'Nation' => 1,	'World' => 2,
											'Sport' => 3,	'Lifestyle' => 4,
											'Food' => 5,	'Tech' => 6,
											'Education' => 7
											);
											foreach($newsCategoryArr as $newsType => $newsNum){
												echo "<option value=\"$newsType\">$newsType</option>";
											}
										?>
									</select>
								</div>
								<div class="form-group">
									<label for="inputNewsDetails" class="col-form-label">News Details:</label>
									<textarea class="form-control" name="txtNewsDetails" id="inputNewsDetails" rows="10"></textarea>
								</div>
								
							</div>
							<div class="modal-footer">
								<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
								<button type="submit" class="btn btn-primary" name="btnAddNews" style="background: #1f52a3;">Add</button>
								<input type="hidden" name="submitted" value="true"/>
							</div>
						</form>
					</div>
				</div>
			</div>
			<!--add news modal END-->
			<!--connect & insert news into database START-->
			<?php			
				if (isset($_POST['submitted'])){
					//connect database
					$dbc = mysqli_connect('localhost', 'root', '');
					//select database
					mysqli_select_db($dbc, 'news');
					
					$problem = FALSE;
					
					if(!empty($_POST['txtNewsTitle']) && !empty($_POST['selectNewsCategory']) && !empty($_POST['txtNewsDetails'])){
						$newsTitle = trim($_POST['txtNewsTitle']);
						$newsDetails = trim($_POST['txtNewsDetails']);
						$newsCategory = trim($_POST['selectNewsCategory']);
						}else{
						echo '<p>Error! Please enter title and details select category!</p>';
						$problem = TRUE;
					}
					
					if(!$problem){
						$query = "INSERT INTO news (news_title, news_details, news_category, news_datetime) 
						VALUES ('$newsTitle', '$newsDetails', '$newsCategory', NOW())";
						if(mysqli_query($dbc, $query)){
							echo '<p>Added successfully!</p>';
							}else{
							echo '<p>Error! '.mysqli_error($dbc).'</p>';
							echo '<p>Query: '.$query.'</p>';
						}
					}
					mysqli_close($dbc);
				}
			?>
			<!--connect & insert news into database END-->
			<!--news table START-->
			<div class="card-deck" style="margin: 15px 50px;">
				<table class="table table-hover bg-light">
					<thead class="thead-light">
						<tr>
							<th scope="col">News ID</th>
							<th scope="col">News Datetime</th>
							<th scope="col">News Title</th>
							<th scope="col">News Details</th>
							<th scope="col">News Category</th>
							<th scope="col">Edit/Delete</th>
						</tr>
					</thead>
					<tbody>
						<!--select news from database START-->
						<?php
							$dbc = mysqli_connect('localhost', 'root', '');
							mysqli_select_db($dbc, 'news');
							
							$query = 'SELECT * FROM news ORDER BY news_id ASC';
							
							if($r = mysqli_query($dbc, $query)){
								while($row = mysqli_fetch_array($r)){
									echo "<tr>
									<th scope=\"row\">{$row['news_id']}</th>
									<td>{$row['news_datetime']}</td>
									<td>{$row['news_title']}</td>
									<td>{$row['news_details']}</td>
									<td>{$row['news_category']}</td>
									<td>
									<button type=\"button\" class=\"btn btn-info\"><i class=\"fas fa-edit\" style=\"font-size: 20px;\"></i></button>
									<button type=\"button\" class=\"btn btn-danger\"><i class=\"fas fa-trash\" style=\"font-size: 20px;\"></i></button>
									</td>
									</tr>";
								}
								}else{
								echo '<p>Error! '.mysqli_error($dbc).'</p>';
							}
							
							mysqli_close($dbc);
						?>
						<!--select news from database END-->
					</tbody>
				</table>
			</div>
			<!--news table END-->
		</div>
	</body>
</html>
bookmark
dashboard

Wed Nov 25 2020 22:07:24 GMT+0000 (UTC) https://pythontutor.ru/lessons/2d_arrays/

By @jora535 #python

bookmark
dashboard

Wed Nov 25 2020 21:05:50 GMT+0000 (UTC) https://gist.github.com/thisnameissoclever/cd621a5e04254b278c83307efaeb6102

By @nhord2007@yahoo.com

bookmark
dashboard

Wed Nov 25 2020 21:03:04 GMT+0000 (UTC) https://javascript.info/recursion

By @ryan #javascript

bookmark
dashboard

Wed Nov 25 2020 19:35:55 GMT+0000 (UTC)

By @jpannu

bookmark
dashboard

Wed Nov 25 2020 14:39:33 GMT+0000 (UTC)

By @uchenliew #php

bookmark
dashboard

Wed Nov 25 2020 14:38:59 GMT+0000 (UTC)

By @uchenliew #php

bookmark
dashboard

Wed Nov 25 2020 14:36:11 GMT+0000 (UTC)

By @uchenliew #php

bookmark
dashboard

Wed Nov 25 2020 08:53:13 GMT+0000 (UTC) https://stackoverflow.com/questions/44027873/how-to-create-a-new-docker-image-from-a-running-container-on-amazon

By @ramshankerg #python

bookmark
dashboard

Wed Nov 25 2020 01:54:07 GMT+0000 (UTC)

By @Shami_Al #c++

bookmark
dashboard

Tue Nov 24 2020 19:39:37 GMT+0000 (UTC) https://confva.com/

By @VictorDronov #typescript #javascript #html #css

bookmark
dashboard

Tue Nov 24 2020 19:16:56 GMT+0000 (UTC)

By @VictorDronov #javascript #typescript #react.js #next.js

bookmark
dashboard

Tue Nov 24 2020 16:21:44 GMT+0000 (UTC)

By @snigdhakhurana10

bookmark
dashboard

Tue Nov 24 2020 16:15:30 GMT+0000 (UTC)

By @snigdhakhurana10

bookmark
dashboard

Tue Nov 24 2020 12:48:26 GMT+0000 (UTC) https://medium.com/javascript-in-plain-english/stop-using-objects-and-arrays-to-store-data-289c3edaaa33

By @Jota #javascript #object #map

bookmark
dashboard

Mon Nov 23 2020 18:24:44 GMT+0000 (UTC)

By @jpannu

bookmark
dashboard

Mon Nov 23 2020 11:10:54 GMT+0000 (UTC)

By @tubagus.dat@gmail.com

bookmark
dashboard

Mon Nov 23 2020 09:40:12 GMT+0000 (UTC) https://wordpressflow.com/elementor-on-failed-logins-on-the-login-form-redirect-back-to-the-login-page-and-add-a-failed-message/

By @performmarketing

bookmark
dashboard

Mon Nov 23 2020 04:03:12 GMT+0000 (UTC) https://stackoverflow.com/questions/2720014/how-to-upgrade-all-python-packages-with-pip

By @Ohad #python #pip

bookmark
dashboard

Sun Nov 22 2020 22:53:58 GMT+0000 (UTC) https://examples.javacodegeeks.com/java-basics/for-loop/sum-array-of-numbers-with-for-loop/

By @rainxx

bookmark
dashboard

Sun Nov 22 2020 21:32:19 GMT+0000 (UTC)

By @huntercoad

bookmark
dashboard

Sun Nov 22 2020 19:42:59 GMT+0000 (UTC)

By @rstringa

bookmark
dashboard

Sun Nov 22 2020 16:49:47 GMT+0000 (UTC) debtcollect.io

By @narro #typescript #nodejs

bookmark
dashboard

Sun Nov 22 2020 14:36:28 GMT+0000 (UTC)

By @uchenliew #php

bookmark
dashboard

Sun Nov 22 2020 14:36:11 GMT+0000 (UTC)

By @uchenliew #php

bookmark
dashboard

Sun Nov 22 2020 14:35:24 GMT+0000 (UTC)

By @uchenliew #php

bookmark
dashboard

Sun Nov 22 2020 10:55:38 GMT+0000 (UTC)

By @eneki

bookmark
dashboard

Sat Nov 21 2020 22:19:05 GMT+0000 (UTC)

By @narro #javascript

bookmark
dashboard

Sat Nov 21 2020 21:55:13 GMT+0000 (UTC) https://golang.org/pkg/net/http/

By @narro #go

bookmark
dashboard

Sat Nov 21 2020 21:03:31 GMT+0000 (UTC)

By @icaronunes #kotlin

bookmark
dashboard

Sat Nov 21 2020 20:59:49 GMT+0000 (UTC)

By @icaronunes #kotlin

bookmark
dashboard

Sat Nov 21 2020 20:56:37 GMT+0000 (UTC)

By @icaronunes #kotlin

bookmark
dashboard

Sat Nov 21 2020 19:51:19 GMT+0000 (UTC) https://dev.to/37shadesofgrey/setting-up-vue-in-laravel-8-580m

By @eneki

bookmark
dashboard

Sat Nov 21 2020 02:28:05 GMT+0000 (UTC) https://stackoverflow.com/questions/48124565/why-does-vscode-delete-golang-source-on-save

By @narro #go

bookmark
dashboard

Sat Nov 21 2020 00:37:48 GMT+0000 (UTC) https://www.udemy.com/course/typescript-the-complete-developers-guide/learn/lecture/15066674#questions/13040850/

By @narro #typescript

bookmark
dashboard

Fri Nov 20 2020 18:34:42 GMT+0000 (UTC)

By @fadas

bookmark
dashboard

Fri Nov 20 2020 14:35:38 GMT+0000 (UTC)

By @anandahange@gmail.com

bookmark
dashboard

Fri Nov 20 2020 14:35:38 GMT+0000 (UTC)

By @anandahange@gmail.com

bookmark
dashboard

Fri Nov 20 2020 12:52:23 GMT+0000 (UTC)

By @uchenliew #php

bookmark
dashboard

Fri Nov 20 2020 12:51:43 GMT+0000 (UTC)

By @uchenliew #php

bookmark
dashboard

Fri Nov 20 2020 10:55:34 GMT+0000 (UTC) https://blog.csdn.net/xkwy100/article/details/80297968

By @natsumi88

bookmark
dashboard

Fri Nov 20 2020 07:54:57 GMT+0000 (UTC) https://stackoverflow.com/questions/56827361/call-a-specific-form-view-of-model-in-odoo-js-building-dashboard

By @don_moses

bookmark
dashboard

Fri Nov 20 2020 06:20:59 GMT+0000 (UTC)

By @eneki

bookmark
dashboard

Fri Nov 20 2020 06:17:14 GMT+0000 (UTC)

By @eneki

bookmark
dashboard

Fri Nov 20 2020 06:06:10 GMT+0000 (UTC) https://www.javascripttutorial.net/javascript-dom/javascript-onload/

By @eneki

bookmark
dashboard

Thu Nov 19 2020 16:19:10 GMT+0000 (UTC) https://javascript.info/type-conversions

By @ryan #javascript

bookmark
dashboard

Thu Nov 19 2020 14:16:21 GMT+0000 (UTC)

By @uchenliew #html

bookmark
dashboard

Thu Nov 19 2020 14:14:42 GMT+0000 (UTC)

By @uchenliew #html #javascript

bookmark
dashboard

Thu Nov 19 2020 14:12:09 GMT+0000 (UTC)

By @uchenliew #html #php

bookmark
dashboard

Thu Nov 19 2020 12:04:58 GMT+0000 (UTC) https://stackoverflow.com/questions/309424/how-do-i-read-convert-an-inputstream-into-a-string-in-java

By @torebal #inputstream #string #java

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension