text
stringlengths 184
4.48M
|
---|
import { Router } from 'express';
import orderController from '../controllers/orderController';
const orderRoutes = Router();
/**
* @swagger
* tags:
* name: Orders
* description: API endpoints for managing orders
*/
/**
* @swagger
* /api/orders:
* get:
* summary: Retrieve all orders
* tags: [Orders]
* responses:
* '200':
* description: A list of orders
*/
orderRoutes.get('/orders', orderController.getAllOrders);
/**
* @swagger
* /api/orders/{id}:
* get:
* summary: Retrieve an order by ID
* tags: [Orders]
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: ID of the order to retrieve
* responses:
* '200':
* description: A single order
*/
orderRoutes.get('/orders/:id', orderController.getOrderById);
/**
* @swagger
* /api/orders:
* post:
* summary: Create a new order
* tags: [Orders]
* responses:
* '201':
* description: Created
*/
orderRoutes.post('/orders', orderController.createOrder);
/**
* @swagger
* /api/orders/{id}:
* put:
* summary: Update an order by ID
* tags: [Orders]
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: ID of the order to update
* responses:
* '200':
* description: Updated
*/
orderRoutes.put('/orders/:id', orderController.updateOrder);
/**
* @swagger
* /api/orders/{id}:
* delete:
* summary: Delete an order by ID
* tags: [Orders]
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: string
* description: ID of the order to delete
* responses:
* '204':
* description: No content
*/
orderRoutes.delete('/orders/:id', orderController.deleteOrder);
/**
* @swagger
* /api/orders/search:
* get:
* summary: Search orders
* tags: [Orders]
* responses:
* '200':
* description: A list of orders matching the search criteria
*/
orderRoutes.get('/orders/search', orderController.searchOrders);
export default orderRoutes;
|
//
// Loopable.swift
//
//
// Created by Benjamin Cáceres on 28-07-22.
//
import Foundation
// MARK: - Loopable
protocol Loopable {
func allProperties() throws -> [String: Any]
}
// MARK: - Loopable allProperties()
extension Loopable {
func allProperties() throws -> [String: Any] {
var result: [String: Any] = [:]
let mirror = Mirror(reflecting: self)
guard let style = mirror.displayStyle, style == .struct || style == .class else { throw NSError() }
for (property, value) in mirror.children {
guard let property = property else { continue }
result[property] = value
}
return result
}
}
|
import { useState } from "react";
// Package Imports
// import { RiMenu3Line, RiCloseLine } from "react-icons/ri";
import { MdArrowDropDown, MdArrowDropUp } from "react-icons/md";
import { RxRocket } from "react-icons/rx";
import { CiMenuBurger } from "react-icons/ci";
import { HiOutlineUserGroup, HiOutlineCheckBadge } from "react-icons/hi2";
import finalLogo from "../../../assets/final logoHeader.png";
import { Link, NavLink } from "react-router-dom";
// CSS File
import Style from "../style.module.css";
import { useSelector } from "react-redux";
function Navbar() {
const [toggle, settoggle] = useState(false);
const [toggleBar, settoggleBar] = useState(false);
const { user, isAuthenticated } = useSelector((state) => state.user);
return (
<>
<nav
className={`flex flex-row justify-around items-center md:py-2 xl:py-3 md:justify-normal md:px-16`}
>
<div
onClick={() => settoggleBar(!toggleBar)}
className={`${
toggleBar
? "absolute top-0 left-0 w-full h-screen bg-slate-900 opacity-20 z-0"
: null
}`}
></div>
<div className="w-full md:w-2/12 flex justify-around md:justify-between items-center">
<img src={finalLogo} alt="pic" className="w-[100px] h-[60px] ml-4" />
<NavLink
to="/user/register"
className={`px-[2rem] ml-[6rem] md:hidden h-9 text-white flex items-center rounded bg-slate-800 hover:bg-slate-700 font-medium my-3`}
>
Sign up
</NavLink>
<span
className="flex md:hidden mr-4 z-50"
onClick={() => settoggleBar(!toggleBar)}
>
<CiMenuBurger size={25} />
</span>
</div>
<div className="w-5/12 hidden md:flex flex-row gap-6 justify-center">
<NavLink
to="/"
className="text-black font-medium hover:text-green-400"
>
Home
</NavLink>
<NavLink
to="/"
className="text-black font-medium hover:text-green-400"
>
About us
</NavLink>
<NavLink
to="/"
className="text-black font-medium hover:text-green-400"
>
Contact us
</NavLink>
<NavLink className="text-black flex font-medium hover:text-green-400">
Community
{toggle ? (
<MdArrowDropUp
color="green"
size={27}
onClick={() => settoggle(false)}
/>
) : (
<MdArrowDropDown
color="green"
size={27}
onClick={() => settoggle(true)}
/>
)}
{toggle && (
<div className="flex flex-col absolute top-[4rem] rounded bg-white p-2">
<div className="flex flex-row border-2 border-solid bg-green-400 border-gray-200 rounded-md justify-start p-2 px-4">
<RxRocket color="#fff" size={22} />
<Link
to="https://tally.so/r/3EKgA2"
className="text-white font-bold hover:text-white"
>
StartUp Community
</Link>
</div>
<div className="flex flex-row border-2 border-solid bg-green-400 border-gray-200 rounded-md justify-start p-2 px-4">
<HiOutlineUserGroup color="#fff" size={22} />
<Link
to="https://tally.so/r/3EKgA2"
className="text-white font-bold hover:text-white"
>
Bangalorean Community
</Link>
</div>
<div className="flex flex-row border-2 border-solid bg-green-400 border-gray-200 rounded-md justify-start p-2 px-4">
<HiOutlineUserGroup color="#fff" size={22} />
<Link
to="https://tally.so/r/3EKgA2"
className="text-white font-bold hover:text-white"
>
Bangalorean Community
</Link>
</div>
</div>
)}
</NavLink>
</div>
<div className="w-5/12 hidden md:flex flex-row gap-4 justify-end items-center">
{user?.role === "seller" ? (
<NavLink
to={isAuthenticated ? "/seller" : "/user/login"}
className="text-white bg-purple-500 hover:bg-purple-600 p-1 xl:px-3 rounded font-medium flex items-center h-9"
>
<HiOutlineCheckBadge /> Seller Dashboard
</NavLink>
) : (
<NavLink
to={isAuthenticated ? "/sellerhomepage" : "/user/login"}
className="text-white bg-green-500 hover:bg-green-600 p-1 xl:px-3 rounded font-medium flex items-center h-9"
>
<HiOutlineCheckBadge /> Become a Seller
</NavLink>
)}
{!isAuthenticated ? (
<>
<NavLink
to="/user/login"
className={` px-[1.5rem] py-1 text-black ${Style.login_btn} flex items-center bg-slate-100 h-9 border-2 border-blue-500 my-3`}
>
Login
</NavLink>
<NavLink
to="/user/register"
className={`px-[1.5rem] h-9 text-white flex items-center rounded bg-slate-800 hover:bg-slate-700 font-medium my-3`}
>
Sign up
</NavLink>
</>
) : (
<Link
to={"/main"}
className="bg-purple-600 h-9 flex items-center px-3 text-white rounded"
>
Dashboard
</Link>
// <span>Hello, {user?.firstName}</span>
)}
</div>
<div
className={`md:hidden p-3 ${
toggleBar ? "flex" : "hidden"
} flex-col justify-between flex-wrap w-[50%] fixed z-[99] top-0 left-0 h-screen bg-[#eefff7] transition-all duration-[1000ms] ease-in-out`}
>
<div className="w-full flex flex-col">
<NavLink
to="/"
className="text-black font-medium hover:text-green-400 my-2"
>
Home
</NavLink>
<NavLink
to="/"
className="text-black font-medium hover:text-green-400 my-2"
>
About us
</NavLink>
<NavLink
to="/"
className="text-black font-medium hover:text-green-400 my-2"
>
Contact us
</NavLink>
<NavLink
className="text-black flex font-medium hover:text-green-400 my-2 relative"
onClick={() => settoggle(!toggle)}
>
Community
{toggle ? (
<MdArrowDropUp color="green" size={27} />
) : (
<MdArrowDropDown color="green" size={27} />
)}
{toggle && (
<div className="flex flex-col w-full absolute top-[100%] left-0">
<div className="flex flex-row border-2 border-solid bg-green-400 my-1 border-green-400 rounded-md justify-start p-2">
<RxRocket color="#fff" size={22} />
<Link
to="https://tally.so/r/3EKgA2"
className="text-white font-bold hover:text-white"
>
StartUp Community
</Link>
</div>
<div className="flex flex-row border-2 border-solid bg-green-400 my-1 border-green-400 rounded-md justify-start p-2">
<HiOutlineUserGroup color="#fff" size={22} />
<Link
to="https://tally.so/r/3EKgA2"
className="text-white font-bold hover:text-white"
>
Bangalorean Community
</Link>
</div>
<div className="flex flex-row border-2 border-solid bg-green-400 my-1 border-green-400 rounded-md justify-start p-2">
<HiOutlineUserGroup color="#fff" size={22} />
<Link
to="https://tally.so/r/3EKgA2"
className="text-white font-bold hover:text-white"
>
Bangalorean Community
</Link>
</div>
</div>
)}
</NavLink>
</div>
<div className="w-full">
<NavLink
to={isAuthenticated ? "/sellerhomepage" : "/user/login"}
className="text-white bg-green-500 hover:bg-green-600 p-1 px-3 rounded font-medium flex items-center h-9 my-3"
>
<HiOutlineCheckBadge /> Become a Seller
</NavLink>
{!isAuthenticated ? (
<>
<NavLink
to="/user/login"
className={` px-[1.5rem] py-1 text-black ${Style.login_btn} flex items-center bg-slate-100 h-9 border-2 border-blue-500 my-3`}
>
Login
</NavLink>
<NavLink
to="/user/register"
className={`px-[1.5rem] h-9 text-white flex items-center rounded bg-slate-800 hover:bg-slate-700 font-medium my-3`}
>
Sign up
</NavLink>
</>
) : (
<Link
to={"/main"}
className="bg-purple-700 h-9 flex items-center px-3 text-white rounded"
>
Dashboard
</Link>
)}
</div>
</div>
</nav>
</>
);
}
export default Navbar;
|
function Y = inv_chol(L)
% Matrix Inversion using Cholesky Decomposition
% Finds the inverse of the matrix X, given its (lower triangular) Cholesky
% Decomposition; i.e. X = LL', according to the paper 'Matrix Inversion
% Using Cholesky Decomposition'
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Initializations
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
N = size(L, 1) ;
Y = zeros(N, N) ;
% Work with the upper triangular matrix
R = L' ;
% Construct the auxillary diagonal matrix S = 1/rii
S = inv(diag(diag(R))) ;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Algorithm
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
for j=N:-1:1
for i=j:-1:1
Y(i,j) = S(i,j) - R(i,i+1:end)*Y(i+1:end,j) ;
Y(i,j) = Y(i,j)/R(i,i) ;
% Write out the symmetric element
Y(j,i) = conj(Y(i,j)) ;
end
end
|
package net.meetsky.step_definitions;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import net.meetsky.pages.ContactsPage;
import net.meetsky.pages.LoginPage;
import net.meetsky.pages.MainPage;
import net.meetsky.utilities.ConfigurationReader;
import net.meetsky.utilities.SkyDriver;
import net.meetsky.utilities.SkyUtils;
import org.junit.Assert;
import org.openqa.selenium.Keys;
import java.util.List;
public class ContactsStepDefs {
String fullname;
String email;
@Given("the user accesses the Log in page")
public void the_user_accesses_the_Log_in_page() {
SkyDriver.get().get(ConfigurationReader.get("url"));
}
@Given("the user login with valid credential {string} {string}")
public void the_user_login_with_valid_credential(String username, String password) {
String url = ConfigurationReader.get("url");
SkyDriver.get().get(url);
SkyUtils.waitForPageToLoad(5);
LoginPage loginPage = new LoginPage();
loginPage.login(username, password);
}
@When("Navigate to {string} module")
public void navigate_to_module(String moduleName) {
switch (moduleName){
case "Contacts":
new MainPage().contacts.click();
break;
case "Talk":
new MainPage().talk.click();
break;
}
}
@When("Click {string} button")
public void click_button(String newContact) {
new ContactsPage().newContactButton.click();
}
@When("Enter a {string} into fullname inbox")
public void enter_a_into_fullname_inbox(String fullname) {
this.fullname=fullname;
ContactsPage contactsPage=new ContactsPage();
SkyUtils.waitForClickablility(contactsPage.fullnamebox,5);
contactsPage.fullnamebox.clear();
contactsPage.fullnamebox.sendKeys(fullname+ Keys.ENTER);
}
@When("Enter an {string} into Email inbox")
public void enter_an_into_Email_inbox(String email) {
this.email=email;
ContactsPage contactsPage=new ContactsPage();
contactsPage.emailbox.clear();
SkyUtils.waitFor(3);
contactsPage.emailbox.sendKeys(email);
SkyUtils.waitForPageToLoad(2);
System.out.println("email = " + contactsPage.emailbox.getText());
SkyUtils.waitFor(5);
}
@When("Click any empty area")
public void click_any_empty_area() {
new ContactsPage().emptyArea.click();
}
@Then("Verify new contact is shown in contact list")
public void verify_new_contact_is_shown_in_contact_list() {
ContactsPage contactsPage = new ContactsPage();
List<String> contacts = SkyUtils.getElementsText(contactsPage.contactList);
SkyUtils.waitFor(2);
System.out.println("fullname = " + fullname);
Assert.assertTrue(contacts.contains(fullname));
}
}
|
<?php
declare( strict_types=1 );
namespace MediaWiki\Skins\Citizen\Tests\Partials;
use MediaWiki\Skins\Citizen\Partials\Drawer;
use MediaWiki\Skins\Citizen\SkinCitizen;
/**
* @group Citizen
* @group Database
*/
class DrawerTest extends \MediaWikiIntegrationTestCase {
/**
* @covers \MediaWiki\Skins\Citizen\Partials\Drawer::decorateSidebarData
* @return void
*/
public function testDecorateSidebarDataEmpty() {
$partial = new Drawer( new SkinCitizen() );
$this->assertEmpty( $partial->decorateSidebarData( [
'array-portlets-rest' => [],
] )['array-portlets-rest'] );
}
/**
* @covers \MediaWiki\Skins\Citizen\Partials\Drawer::decorateSidebarData
* @return void
*/
public function testDecorateSidebarRemovePageTools() {
$partial = new Drawer( new SkinCitizen() );
$sidebarData = [
'array-portlets-rest' => [
[ 'id' => 'foo' ],
[ 'id' => 'p-tb' ],
],
];
$this->assertNotEmpty( $partial->decorateSidebarData( $sidebarData ) );
$this->assertArrayHasKey( 'array-portlets-rest', $partial->decorateSidebarData( $sidebarData ) );
$this->assertNotContains( [ 'id' => 'pt-tb' ], $partial->decorateSidebarData( $sidebarData )['array-portlets-rest'] );
}
/**
* @covers \MediaWiki\Skins\Citizen\Partials\Drawer::getSiteStatsData
* @return void
*/
public function testGetSiteStatsDataDisabled() {
$this->overrideConfigValues( [
'CitizenEnableDrawerSiteStats' => false,
] );
$partial = new Drawer( new SkinCitizen() );
$this->assertEmpty( $partial->getSiteStatsData() );
}
/**
* @covers \MediaWiki\Skins\Citizen\Partials\Drawer::getSiteStatsData
* @covers \MediaWiki\Skins\Citizen\Partials\Drawer::getSiteStatValue
* @return void
*/
public function testGetSiteStatsDataNoFormat() {
$this->overrideConfigValues( [
'CitizenEnableDrawerSiteStats' => true,
'CitizenUseNumberFormatter' => false,
] );
$partial = new Drawer( new SkinCitizen() );
$data = $partial->getSiteStatsData();
$this->assertArrayHasKey( 'array-drawer-sitestats-item', $data );
$this->assertCount( 4, $data['array-drawer-sitestats-item'] );
foreach ( $data['array-drawer-sitestats-item'] as $stat ) {
$this->assertArrayHasKey( 'id', $stat );
$this->assertArrayHasKey( 'icon', $stat );
$this->assertArrayHasKey( 'value', $stat );
$this->assertArrayHasKey( 'label', $stat );
$this->assertContains( $stat['id'], [ 'articles', 'images', 'users', 'edits' ] );
}
}
}
|
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './shared/component/header/header.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { ToastrModule } from 'ngx-toastr';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AuthInterceptor } from './shared/helpers/authconfig.interceptor';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [AppComponent, HeaderComponent],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
ReactiveFormsModule,
FontAwesomeModule,
BrowserAnimationsModule,
AppRoutingModule,
ToastrModule.forRoot({
positionClass: 'toast-bottom-right',
}),
NgbModule,
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: AuthInterceptor,
multi: true,
},
],
bootstrap: [AppComponent],
})
export class AppModule {}
|
import React from "react";
import { useSelector } from "react-redux";
import { referendumVoteFinishedStatusArray } from "../../../utils/democracy/referendum";
import { useEstimateBlocksTime } from "../../../utils/hooks";
import CountDown from "../../_CountDown";
import { bigNumber2Locale } from "../../../utils";
import chainOrScanHeightSelector from "next-common/store/reducers/selectors/height";
function getMeta(onchain) {
if (onchain.meta) {
return onchain.meta;
}
if (onchain.status) {
return onchain.status;
}
if (onchain.info?.ongoing) {
return onchain.info.ongoing;
}
throw new Error(`Can not get meta of referendum ${onchain.referendumIndex}`);
}
export default function ReferendumElapse({ detail }) {
const blockHeight = useSelector(chainOrScanHeightSelector);
const onchain = detail?.onchainData;
const timeline = onchain.timeline || [];
const isFinished = (timeline || []).some((item) =>
referendumVoteFinishedStatusArray.includes(item.method),
);
const startHeight = onchain.indexer?.blockHeight;
const meta = getMeta(onchain);
const estimatedBlocksTime = useEstimateBlocksTime(meta.end - blockHeight);
if (isFinished || !blockHeight || !estimatedBlocksTime) {
return null;
}
if (blockHeight > meta.end) {
return null;
}
return (
<CountDown
numerator={blockHeight - startHeight}
denominator={meta.end - startHeight}
tooltipContent={`End in ${estimatedBlocksTime}, #${bigNumber2Locale(
meta.end.toString(),
)}`}
/>
);
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- --------- UNICONS ---------- -->
<link rel="stylesheet" href="https://unicons.iconscout.com/release/v4.0.8/css/line.css">
<!-- --------- CSS ---------- -->
<link rel="stylesheet" href="src/style.css">
<!-- --------- FAVICON ---------- -->
<link rel="shortcut icon" href="assets/images/favicon.png" type="image/x-icon">
<title>Portfolio | Antonin Royer</title>
</head>
<body>
<div>
<!-- --------------- HEADER --------------- -->
<nav id="header">
<div class="nav-logo">
<p class="nav-name">Antonin Royer</p>
<span>.</span>
</div>
<div class="nav-menu" id="myNavMenu">
<ul class="nav_menu_list">
<li class="nav_list">
<a href="#home" class="nav-link active-link">Home</a>
<div class="circle"></div>
</li>
<li class="nav_list">
<a href="#about" class="nav-link">About</a>
<div class="circle"></div>
</li>
<li class="nav_list">
<a href="#projects" class="nav-link">Projects</a>
<div class="circle"></div>
</li>
<li class="nav_list">
<a href="#contact" class="nav-link">Contact</a>
<div class="circle"></div>
</li>
</ul>
</div>
<div class="nav-button">
<a href="assets/files/antonin-royer-cv.pdf" download class="btn cv-text">Download CV <i class="uil uil-file-alt"></i></a>
</div>
<div class="nav-menu-btn">
<i class="uil uil-bars" onclick="myMenuFunction()"></i>
</div>
</nav>
<!-- -------------- MAIN ---------------- -->
<main class="wrapper">
<!-- -------------- FEATURED BOX ---------------- -->
<section class="featured-box" id="home">
<div class="featured-text">
<div class="featured-text-card">
<span>Antonin Royer </span>
</div>
<div class="featured-name">
<p>I'm <span class="typedText"></span></p>
</div>
<div class="featured-text-info">
<p>An experienced developer with a passion for creating visually stunning and user-friendly websites.
</p>
</div>
<div class="featured-text-btn">
<a href="#contact" class="btn blue-btn shadow-link">Hire Me</a>
<a href="assets/files/antonin-royer-cv.pdf" download class="btn cv-text">Download CV <i class="uil uil-file-alt"></i></a>
</div>
<div class="social_icons">
<a target="_blank" href="https://www.instagram.com/shpirtdj/" class="icon"><i class="uil uil-instagram"></i></a>
<a target="_blank" href="https://www.linkedin.com/in/antonin-royer-458a14155/" class="icon"><i class="uil uil-linkedin-alt"></i></a>
<a target="_blank" href="https://www.facebook.com/antonin.royer.355/" class="icon"><i class="uil uil-facebook"></i></a>
<a target="_blank" href="https://github.com/AntoninRoyer" class="icon"><i class="uil uil-github-alt"></i></a>
</div>
</div>
<div class="featured-image">
<div class="image">
<img src="assets/images/avatar.png" alt="avatar">
</div>
</div>
<div class="scroll-icon-box">
<a href="#about" class="scroll-btn">
<i class="uil uil-mouse-alt"></i>
<p>Scroll Down</p>
</a>
</div>
</section>
<!-- -------------- ABOUT BOX ---------------- -->
<section class="section" id="about">
<div class="top-header">
<h1>About Me</h1>
</div>
<div class="row columns">
<div class="column">
<div class="about-info">
<h3>Hello, I'm Royer Antonin, Web Developer and System Administrator</h3>
<p>
With a passion for IT and solid experience in web development and system administration, I'm dedicated to creating innovative, high-performance digital solutions. With a bachelor's degree in computer science and certification in Microsoft technologies, I've acquired invaluable expertise working on a variety of dynamic projects.<br><br>
My specialization in web development goes hand in hand with in-depth skills in system administration, enabling me to offer complete solutions ranging from intuitive website design to efficient IT infrastructure management. I'm particularly proud of my ability to integrate the latest technologies to create secure, robust systems tailored to specific business needs.<br><br>
I invite you to browse through my portfolio to discover how my technical skills and creativity have contributed to the success of various projects. Please do not hesitate to contact me for any collaboration or professional opportunity.
</p>
<div class="about-btn">
<a href="assets/files/antonin-royer-cv.pdf" download class="btn cv-text">Download CV <i class="uil uil-import"></i></a>
</div>
</div>
</div>
<div class="column">
<div class="skills-box">
<div class="skills-header">
<h3>Frontend</h3>
</div>
<div class="skills-list">
<span>HTML</span>
<span>CSS</span>
<span>Bootstrap</span>
<span>Bulma</span>
<span>JavaScript</span>
<span>Twig</span>
</div>
</div>
<div class="skills-box">
<div class="skills-header">
<h3>Backend</h3>
</div>
<div class="skills-list">
<span>PHP</span>
<span>Node.js</span>
<span>Symfony</span>
<span>Laravel</span>
<span>Docker</span>
</div>
</div>
<div class="skills-box">
<div class="skills-header">
<h3>Database</h3>
</div>
<div class="skills-list">
<span>MySQL</span>
<span>PostgresSQL</span>
<span>SQLite</span>
</div>
</div>
<div style="margin-top: 30px!important;" class="about-info">
<h3>Chinese portrait</h3>
<p>
"If I were to be a superhero, I would be Batman."
"If I were a fruit, I would be a pineapple."
</p>
</div>
</div>
</div>
</section>
<!-- -------------- PROJECT BOX ---------------- -->
<section class="section" id="projects">
<div class="top-header">
<h1>Projects</h1>
</div>
<div class="project-container">
<div class="project-box" id="project-btn">
<i class="uil uil-briefcase-alt"></i>
<h3>Completed</h3>
<label>15+ Finished Projects</label>
</div>
<div class="project-box" id="client-btn">
<i class="uil uil-envelope"></i>
<h3>Letter to me</h3>
<label>A letter to me 10 years later</label>
</div>
<div class="project-box" id="experience-btn">
<i class="uil uil-award"></i>
<h3>Experience</h3>
<label>2+ Years in the field</label>
</div>
</div>
</section>
<hr>
<section style="display: none;" class="section project-container" id="experience">
<div style="color: var(--text-color-second)!important;" class="columns">
<div class="column">
<div class="box">
<h5 class="title">IT Assistant</h5>
<h5 class="subtitle">Plug In Digital</h5>
<p>2022 - 2024</p>
</div>
</div>
<div class="column">
<div class="box">
<h5 class="title">Informatic Bachelor</h5>
<h5 class="subtitle">OPEN IT</h5>
<p>2021 - 2024</p>
</div>
</div>
<div class="column">
<div class="box">
<h5 class="title">BTS Audiovisual</h5>
<h5 class="subtitle">ACFA Multimédia</h5>
<p>2018 - 2020</p>
</div>
</div>
</div>
</section>
<section style="display: none;" class="section project-container" id="client">
<div style="text-align: left; align-items: flex-start;" class="box">
<h1 style="color: var(--text-color-second)" class="title">Letter to me 10 years later</h1>
<p style="color: var(--text-color-second)" class="subtitle">Dear Antonin,</p><br>
<p style="color: var(--text-color-second)">It's been a decade since you penned this letter. I trust life has treated you kindly. May you have realized your aspirations and found contentment. May love fill your days and your home be a sanctuary of beauty. May your career flourish, bringing prosperity. May you have explored the globe, beholding its wonders. May your circle be rich with friendship and affection. May health grace you, nurtured with care. May joy permeate your existence, as you embrace your journey. May pride swell within you for all you've achieved. May you be living the dream you've long envisioned.</p>
<p style="color: var(--text-color-second)">Love,</p>
<p style="color: var(--text-color-second)">Antonin</p>
</div>
</section>
<section style="display: none;" class="section project-container columns is-multiline" id="project">
</section>
<!-- -------------- CONTACT BOX ---------------- -->
<section class="section" id="contact">
<div class="top-header">
<h1>Get in touch</h1>
<span>Do you have a project in your mind, contact me here</span>
</div>
<div class="row">
<div class="col">
<div class="contact-info">
<h2>Find Me <i class="uil uil-corner-right-down"></i></h2>
<p><i class="uil uil-envelope"></i> Email: <a class="shadow-link" href="mailto:antonin.royer84@gmail.com">antonin.royer84@gmail.com</a></p>
<p><i class="uil uil-phone"></i> Tel: <a class="shadow-link" href="tel:+330750425149">+33 750 425 149</a></p>
</div>
</div>
<div class="col">
<div class="form-control">
<div class="form-inputs">
<input type="text" class="input-field" placeholder="Name">
<input type="text" class="input-field" placeholder="Email">
</div>
<div class="text-area">
<label>
<textarea placeholder="Message"></textarea>
</label>
</div>
<div class="form-button">
<button class="btn">Send <i class="uil uil-message"></i></button>
</div>
</div>
</div>
</div>
</section>
</main>
<!-- --------------- FOOTER --------------- -->
<footer>
<div class="top-footer">
<p style="color:var(--text-color-second);">Antonin Royer .</p>
</div>
<div class="middle-footer">
<ul class="footer-menu">
<li class="footer_menu_list">
<a href="#home">Home</a>
</li>
<li class="footer_menu_list">
<a href="#about">About</a>
</li>
<li class="footer_menu_list">
<a href="#projects">Projects</a>
</li>
<li class="footer_menu_list">
<a href="#contact">Contact</a>
</li>
</ul>
</div>
<div class="footer-social-icons">
<a target="_blank" href="https://www.instagram.com/shpirtdj/" class="icon"><i class="uil uil-instagram"></i></a>
<a target="_blank" href="https://www.linkedin.com/in/antonin-royer-458a14155/" class="icon"><i class="uil uil-linkedin-alt"></i></a>
<a target="_blank" href="https://www.facebook.com/antonin.royer.355/" class="icon"><i class="uil uil-facebook"></i></a>
<a target="_blank" href="https://github.com/AntoninRoyer" class="icon"><i class="uil uil-github-alt"></i></a>
</div>
<div class="bottom-footer">
<p>Copyright © <a href="#home" style="text-decoration: none;">Antonin Royer</a> - All rights reserved</p>
</div>
</footer>
</div>
<!-- ----- TYPING JS Link ----- -->
<script src="https://unpkg.com/typed.js@2.0.16/dist/typed.umd.js"></script>
<!-- ----- SCROLL REVEAL JS Link----- -->
<script src="https://unpkg.com/scrollreveal"></script>
<!-- ----- MAIN JS ----- -->
<script src="assets/js/main.js"></script>
<script src="assets/js/modal.js"></script>
</body>
</html>
|
#include <iostream>
#include <fstream>
#include <filesystem>
#include <string>
#include <ctime>
#include <stdexcept>
#include <chrono>
#include <thread>
#include <conio.h>
#include <Windows.h>
namespace fs = std::filesystem;
enum ConsoleColor {
COLOR_DEFAULT = 7,
COLOR_RED = 12,
COLOR_GREEN = 10,
};
const char* kLogFileName = "log.txt";
const char* kDirectoryPath = "txt";
const std::size_t kMaxFileSize = 10 * 1024 * 1024; // 10 MB
// Class to manage log file
class LogFile {
public:
LogFile(const std::string& fileName) : fileName_(fileName) {
logFile_.open(fileName_, std::ios::app);
if (!logFile_.is_open()) {
throw std::runtime_error("Error opening file: " + fileName_);
}
}
~LogFile() {
if (logFile_.is_open()) {
logFile_.close();
}
}
void Write(const std::string& message) {
logFile_ << message << "\n";
}
private:
std::string fileName_;
std::ofstream logFile_;
};
// Function to log a message with a timestamp
void LogMessage(const std::string& message, LogFile& logFile) {
std::time_t now = std::time(nullptr);
char timestamp[50];
std::tm time_info;
localtime_s(&time_info, &now);
std::strftime(timestamp, sizeof(timestamp), "[%Y-%m-%d %H:%M:%S] ", &time_info);
logFile.Write(timestamp + message);
}
// Function to count characters in a text file
std::size_t CountCharacters(const fs::path& file_path) {
try {
std::ifstream file(file_path, std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("Error opening file: " + file_path.string());
}
std::size_t character_count = 0;
char c;
while (file.get(c)) {
character_count++;
if (character_count > kMaxFileSize) {
throw std::runtime_error("File size exceeds the limit (10 MB): " + file_path.string());
}
}
return character_count;
}
catch (const std::exception& ex) {
throw; // Re-throw the exception
}
}
// Function to display a message in the console with color
void DisplayInfo(const std::string& message, ConsoleColor color) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
std::cout << message << std::endl;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), COLOR_DEFAULT);
}
int main() {
char choice;
bool restart = false;
do {
try {
// Check if the directory exists and create it if it doesn't
if (!fs::exists(kDirectoryPath)) {
fs::create_directory(kDirectoryPath);
}
// Check if the path is a valid directory
if (!fs::is_directory(kDirectoryPath)) {
throw std::runtime_error("'txt' is not a valid directory.");
}
std::size_t total_character_count = 0;
bool found_text_files = false;
LogFile logFile(kLogFileName);
// Iterate through files in the directory
for (const auto& entry : fs::directory_iterator(kDirectoryPath)) {
if (entry.is_regular_file() && entry.path().has_extension() && entry.path().extension() == ".txt") {
found_text_files = true;
std::size_t character_count = CountCharacters(entry.path());
total_character_count += character_count;
// Display information about the file in the console
char message[256];
sprintf_s(message, sizeof(message), "File: %s | Characters: %zu", entry.path().string().c_str(), character_count);
DisplayInfo(message, COLOR_GREEN);
// Log the message with timestamp
LogMessage(message, logFile);
}
}
// Handle case where no text files were found
if (!found_text_files) {
throw std::runtime_error("No text files found in the 'txt' directory.");
}
// Display the total character count in the console
char total_message[256];
sprintf_s(total_message, sizeof(total_message), "Total characters: %zu", total_character_count);
DisplayInfo(total_message, COLOR_DEFAULT);
// Log the total character count with timestamp
LogMessage(total_message, logFile);
}
catch (const std::exception& ex) {
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), COLOR_RED);
std::cerr << "Exception: " << ex.what() << std::endl;
// Log the exception with timestamp
LogFile logFile(kLogFileName);
LogMessage("Exception: " + std::string(ex.what()), logFile);
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), COLOR_DEFAULT);
}
std::cout << "Press 'R' to restart or 'Q' to quit: \n";
choice = _getch();
if (choice == 'R' || choice == 'r') {
restart = true;
}
else {
restart = false;
}
} while (restart);
return 0;
}
|
{% extends "blog/base.html" %}
{% block content %}
<div class="flex items-center justify-between space-y-4 mt-7">
<div class="space-y-4">
<h1
class="text-3xl font-extrabold leading-9 tracking-tight text-gray-900 dark:text-gray-100 sm:text-4xl sm:leading-10 md:text-6xl md:leading-14">
<span class="wave">👋🏻</span>, <span> I'm </span><span class="text-sky-500 dark:text-teal-400">{{ author }}</span>
</h1>
<p>Welcome to my blog - here I share everything that I love.</p>
</div>
<div class="rounded-full md:hidden shadow-lg">
<img alt="avatar" loading="lazy" width="100" height="100" decoding="async" data-nimg="1" src="{{ avatar }}"
class="h-50 w-50 rounded-full shadow-gray-300" style="color: transparent" />
</div>
<img alt="avatar" loading="lazy" width="150" height="150" decoding="async" data-nimg="1"
class="h-30 w-30 rounded-full hidden md:block shadow-lg shadow-gray-400" style="color: transparent"
src="{{ avatar }}" />
</div>
<main class="mb-auto">
<div class="divide-y divide-gray-200 dark:divide-gray-700">
<div class="space-y-2 pb-8 pt-6 md:space-y-5">
<h1
class="text-3xl font-extrabold leading-9 tracking-tight text-gray-900 dark:text-gray-100 sm:text-4xl sm:leading-10 md:text-6xl md:leading-14">
{% if category %}
<span>
Category:
</span>
<span class="text-sky-500 dark:text-teal-400 bg-sky-100 dark:bg-teal-900 rounded-md px-2 py-1 m-2">
{{ category }}
</span>
{% elif query %}
<span>
Search:
</span>
<span class="text-sky-500 dark:text-teal-400">{{ query }}</span>
{% else %}
Latest posts
{% endif %}
</h1>
<div class="flex items-left justify-left pt-4">
<div>
<div class="pb-1 text-sm font-semibold text-gray-800 dark:text-gray-100">search for posts
</div>
<form class="flex flex-col sm:flex-row" action="/search" method="GET">
<div><input autocomplete="query"
class="bg-white focus:ring-primary-600 w-72 rounded-md px-4 focus:border-transparent focus:outline-none focus:ring-2 border-gray-300 dark:border-gray-700 border-2 py-2"
style="color: black" id="query-input" placeholder="Enter your query" required=""
type="search" name="query"></label></div>
<div class="mt-2 flex w-full rounded-md shadow-sm sm:mt-0 sm:ml-3">
<button
class="bg-primary-500 w-full rounded-md py-2 px-4 font-medium text-white sm:py-0 hover:bg-primary-700 dark:hover:bg-primary-400 focus:ring-primary-600 focus:outline-none focus:ring-2 focus:ring-offset-2 dark:ring-offset-black"
type="submit">Search</button>
</div>
</form>
</div>
</div>
</div>
<ul class="divide-y divide-gray-200 dark:divide-gray-700">
{% for post in posts %}
<li class="py-6">
<article>
<div class="space-y-2 xl:grid xl:grid-cols-4 xl:items-baseline xl:space-y-0">
<dl>
<dt class="sr-only">Published on</dt>
<dd class="text-base font-medium leading-6 text-gray-500 dark:text-gray-400">
<time datetime="2023-10-30T00:00:00.000Z">
{{ post.create_time }}
</time>
<div class="py-2 pr-3">
{% if post.cover %}
<img alt="ReactJS vs NextJS" loading="lazy" width="215" height="150"
decoding="async" data-nimg="1" class="object-cover object-center"
style="color: transparent" src="{{ post.cover.0 }}" />
{% endif %}
</div>
</dd>
</dl>
<div class="space-y-5 xl:col-span-3">
<div class="space-y-6">
<div>
<h2 class="text-2xl font-bold leading-8 tracking-tight">
<a class="text-gray-900 dark:text-gray-100" href="/post/{{ post.id }}">{{ post.title }}</a>
</h2>
<div class="flex flex-wrap">
{% for category in post.category %}
<a class="mr-3 text-sm font-medium uppercase text-primary-500 hover:text-primary-600 dark:hover:text-primary-400"
href="/category/{{ category }}">{{ category }}</a>
{% endfor %}
</div>
</div>
<div class="prose max-w-none text-gray-500 dark:text-gray-400">
<p>{{ post.summary }}</p>
</div>
</div>
<div class="text-base font-medium leading-6">
<a class="text-primary-500 hover:text-primary-600 dark:hover:text-primary-400"
href="/post/{{ post.id }}">Read more →</a>
</div>
</div>
</div>
</article>
</li>
{% endfor %}
</ul>
</div>
{% endblock %}
|
import 'dart:math';
import 'package:flutter/material.dart';
class NameAvatar extends StatelessWidget {
final String? fullName;
NameAvatar({this.fullName});
@override
Widget build(BuildContext context) {
String? initials = _getInitials(fullName);
Color color = _getColor(fullName);
return CircleAvatar(
backgroundColor: color,
child: Text(
initials!,
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
),
),
);
}
String? _getInitials(String? fullName) {
if (fullName == null || fullName.isEmpty) return null;
List<String> nameParts = fullName.split(' ');
String initials = '';
for (var part in nameParts) {
if (part.isNotEmpty) {
initials += part[0].toUpperCase();
}
}
return initials;
}
Color _getColor(String? fullName) {
if (fullName == null) return Colors.grey;
final random = Random(fullName.hashCode);
return Color.fromARGB(
255,
random.nextInt(256),
random.nextInt(256),
random.nextInt(256),
);
}
}
|
import React, { useState, useEffect } from 'react';
import GeneralLayout from '../../components/general/GeneralLayout';
import { useParams, useNavigate } from 'react-router-dom';
import { formatDistanceToNow } from 'date-fns';
function HomeFaculty() {
const { faculty } = useParams();
const [articles, setArticles] = useState([]);
const [searchTerm, setSearchTerm] = useState('');
const navigate = useNavigate();
const [currentPage, setCurrentPage] = useState(0);
const formatTimeAgo = (date) => formatDistanceToNow(new Date(date), { addSuffix: true });
const articlesPerPage = 10; // Number of articles per page
const truncateDescription = (text, maxLength) => {
if (text.length > maxLength) {
return `${text.slice(0, maxLength)}..`;
} else {
return text;
}
};
const handleArticleClick = (title) => {
navigate(`/student/readingPage/${encodeURIComponent(title)}`); // Navigate to reading page with the title as a parameter
};
useEffect(() => {
fetch(`https://localhost:7002/api/Contributions/faculty/${faculty}`, {
headers: {
'accept': 'application/json'
},
})
.then(response => response.json())
.then(data => {
// Filter articles by status "Selected" right after fetching them
const selectedArticles = data.filter(article => article.status === 'Selected');
setArticles(selectedArticles.reverse());
})
.catch(error => console.error('Error fetching articles:', error));
}, [faculty]);
// Filter articles based on search term
const filteredArticles = articles.filter(article =>
article.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
article.description.toLowerCase().includes(searchTerm.toLowerCase())
);
// Get current articles for the current page
const indexOfLastArticle = (currentPage + 1) * articlesPerPage;
const indexOfFirstArticle = indexOfLastArticle - articlesPerPage;
const currentArticles = filteredArticles.slice(indexOfFirstArticle, indexOfLastArticle);
const changePage = (page) => {
setCurrentPage(page);
};
return (
<GeneralLayout>
<div className="container mx-auto p-4">
<h2 className="text-2xl font-bold mb-6">{faculty} faculty articles</h2>
<input
type="text"
placeholder="Search articles"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="mb-4 p-2 border rounded"
/>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
{currentArticles.map((article, index) => (
<div key={index} className="bg-white shadow-lg rounded-lg overflow-hidden" >
<img
src={`https://localhost:7002/api/Contributions/DownloadImageFile?title=${encodeURIComponent(article.title)}`}
alt={article.title}
className="w-full h-48 object-cover object-center"
loading="lazy"
onClick={() => handleArticleClick(article.title)}
/>
<div className="p-4">
<h3 className="text-lg font-semibold truncate">{article.title}</h3>
<p className="text-sm text-gray-600 overflow-ellipsis overflow-hidden h-12">{truncateDescription(article.description, 70)}</p>
<div className=" pt-4 pb-2">
<span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">{formatTimeAgo(article.submissionDate)}</span>
</div>
</div>
</div>
))}
</div>
<div className="pagination flex justify-center mt-6">
{Array.from({ length: Math.ceil(filteredArticles.length / articlesPerPage) }, (_, i) => (
<button
key={i}
onClick={() => changePage(i)}
className={`px-4 py-2 m-1 ${currentPage === i ? 'bg-blue-500 text-white' : 'bg-white border'}`}
>
{i + 1}
</button>
))}
</div>
</div>
</GeneralLayout>
);
}
export default HomeFaculty;
|
---
title: Prestanda
slug: Tools/Prestanda
translation_of: Tools/Performance
---
<div><section class="Quick_links" id="Quick_Links">
<ol>
<li><a href="/sv-SE/docs/Tools/Page_Inspector">Sidinspektör</a></li>
<li><a href="/sv-SE/docs/Tools/Web_Console">Webbkonsol</a></li>
<li><a href="/sv-SE/docs/Tools/Debugger">Avlusare</a></li>
<li><a href="/sv-SE/docs/Tools/Network_Monitor">Nätverksövervakare</a></li>
<li><a href="/sv-SE/docs/Tools/Performance">Performance</a></li>
<li><a href="/sv-SE/docs/Tools/Application">Application</a></li>
<li><a href="/sv-SE/docs/Tools/Responsive_Design_Mode">Responsive Design Mode</a></li>
<li><a href="/sv-SE/docs/Tools/Accessibility_inspector">Accessibility Inspector</a></li>
<li class="toggle">
<details>
<summary>More Tools</summary>
<ol>
<li><a href="/sv-SE/docs/Tools/Memory">Memory</a></li>
<li><a href="/sv-SE/docs/Tools/Storage_Inspector">Lagringsinspektör</a></li>
<li><a href="/sv-SE/docs/Tools/DOM_Property_Viewer">DOM Property Viewer</a></li>
<li><a href="/sv-SE/docs/Tools/Eyedropper">Eyedropper</a></li>
<li><a href="/sv-SE/docs/Tools/Taking_screenshots">Screenshot</a></li>
<li><a href="/sv-SE/docs/Tools/Style_Editor">Stilredigerare</a></li>
<li><a href="/sv-SE/docs/Tools/Rulers">Rulers</a></li>
<li><a href="/sv-SE/docs/Tools/Measure_a_portion_of_the_page">Measure a portion of the page</a></li>
<li><a href="/sv-SE/docs/Tools/View_source">Visa källa</a></li>
</ol>
</details>
</li>
<li class="toggle">
<details>
<summary>Connecting the devtools</summary>
<ol>
<li><a href="/sv-SE/docs/Tools/about:debugging">about:debugging</a></li>
<li><a href="/sv-SE/docs/Tools/Remote_Debugging/Debugging_Firefox_for_Android_over_Wifi">Connecting to Firefox for Android</a></li>
<li><a href="/sv-SE/docs/Tools/Working_with_iframes">Connecting to iframes</a></li>
<li><a href="/sv-SE/docs/Tools/Valence">Connecting to other browsers</a></li>
</ol>
</details>
</li>
<li class="toggle">
<details>
<summary>Debugging the browser</summary>
<ol>
<li><a href="/sv-SE/docs/Tools/Browser_Console">Browser Console</a></li>
<li><a href="/sv-SE/docs/Tools/Browser_Toolbox">Browser Toolbox</a></li>
</ol>
</details>
</li>
<li><a href="/sv-SE/docs/Mozilla/Add-ons/WebExtensions/Extending_the_developer_tools">Extending the devtools</a></li>
<li><a href="/sv-SE/docs/Tools/Settings">Inställningar</a></li>
<li><a href="/sv-SE/docs/Tools/Tips">Tips</a></li>
<li><a href="/sv-SE/docs/Tools/Release_notes">Anteckningar för utgåvan</a></li>
</ol>
</section></div><p>Prestandaverktyget ger dig insikt i din sidas allmäna tillgänglighet, JavaScript- och layoutprestanda. Med Prestandaverktyget kan du skapa en inspelning, eller profil, av din sida över en tidsperiod. Verktyget visar dig en <a href="https://developer.mozilla.org/en-US/docs/Tools/Performance/UI_Tour#Waterfall_overview">översikt</a> av de saker webbläsare gjorde för att rendera din sida över profilen, och en graf av <a href="/en-US/docs/Tools/Performance/Frame_rate">bildhastighet</a> över profilen.</p>
<p>Du får tre sidoverktyg för att undersöka olika lägen av profilen i mer detalj:</p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Tools/Performance/Waterfall">Vattenfall</a> visar de olika operationer webbläsaren utförde, som att köra layout, JavaScript, ommåla, och skräp insamling</li>
<li><a href="/en-US/docs/Tools/Performance/Call_Tree">Anropsträd</a> visar JavaScriptets funktion där webbläsaren tillbringar mest tid</li>
<li><a href="/en-US/docs/Tools/Performance/Flame_Chart">Eldtabellen</a> visar JavaScript <span class="gt-text"><font><font>anropsstacken</font></font></span> under tiden av inspelningen.</li>
</ul>
<div class="intrinsic-wrapper"><div class="intrinsic-container "><iframe src="https://www.youtube.com/embed/WBmttwfA_k8?rel=0&html5=1"></iframe></div></div>
<hr>
<h2 id="Komma_igång">Komma igång</h2>
<div class="column-container">
<div class="column-half">
<dl>
<dt><a href="/en-US/docs/Tools/Performance/UI_Tour">Användargränsnittsguide</a></dt>
<dd>
<p>En snabbguide av användargränsnittet för att hitta runt i Prestandaverktyget.</p>
</dd>
</dl>
</div>
<div class="column-half">
<dl>
<dt><a href="/en-US/docs/Tools/Performance/How_to">Hur man</a></dt>
<dd>Standarduppgifter: öppna verktyget, skapa, spara, ladda, och konfigurera inspelningar.</dd>
</dl>
</div>
</div>
<hr>
<h2 id="Prestandaverktygets_komponenter">Prestandaverktygets komponenter</h2>
<div class="column-container">
<div class="column-half">
<dl>
<dt><a href="/en-US/docs/Tools/Performance/Frame_rate">Bildhastighet</a></dt>
<dd>Förstå din sidas generella tillgänglighet.</dd>
<dt><a href="/en-US/docs/Tools/Performance/Call_Tree">Anropsträd</a></dt>
<dd>Hitta flaskhalsar i din sidas JavaScript.</dd>
</dl>
</div>
<div class="column-half">
<dl>
<dt><a href="/en-US/docs/Tools/Performance/Waterfall">Vattenfall</a></dt>
<dd>Förstå vad webbläsaren gör medan användaren interagerar med din sida.</dd>
<dt><a href="/en-US/docs/Tools/Performance/Flame_Chart">Eldtabellen</a></dt>
<dd>Se vilken JavaScripts-funktion som utförs, och när, under tiden för inspelningen.</dd>
<dd> </dd>
</dl>
</div>
</div>
<hr>
<h2 id="Scenarier">Scenarier</h2>
<div class="column-container">
<div class="column-half">
<dl>
<dt><a href="/en-US/docs/Tools/Performance/Scenarios/Animating_CSS_properties">Animera CSS-egenskaper</a></dt>
<dd>Använder Vattenfall för att förstå hur webbläsaren uppdaterar en sida, och hur animeringen av olika CSS-egenskaper kan påverka prestandan.</dd>
<dd> </dd>
</dl>
</div>
<div class="column-half">
<dl>
<dt><a href="/en-US/docs/Tools/Performance/Scenarios/Intensive_JavaScript">Intensiv JavaScript</a></dt>
<dd>Använder bildhastighet och Vattenfallsvertygen för att framhäva prestanda problem orsakade av långvarig JavaScript, och hur användning av arbetare kan hjälpa i denna situation.</dd>
</dl>
</div>
</div>
<p> </p>
<div class="column-half">
<dl>
<dd> </dd>
</dl>
</div>
<p> </p>
|
"""Utility functions for copying and archiving files and directory trees.
XXX The functions here don't copy the resource fork or other metadata on Mac.
"""
import os
import sys
import stat
from os.path import abspath
import fnmatch
import collections
import errno
try:
from pwd import getpwnam
except ImportError:
getpwnam = None
try:
from grp import getgrnam
except ImportError:
getgrnam = None
__all__ = ["copyfileobj", "copyfile", "copymode", "copystat", "copy", "copy2",
"copytree", "move", "rmtree", "Error", "SpecialFileError",
"ExecError", "make_archive", "get_archive_formats",
"register_archive_format", "unregister_archive_format",
"ignore_patterns"]
class Error(EnvironmentError):
pass
class SpecialFileError(EnvironmentError):
"""Raised when trying to do a kind of operation (e.g. copying) which is
not supported on a special file (e.g. a named pipe)"""
class ExecError(EnvironmentError):
"""Raised when a command could not be executed"""
try:
WindowsError
except NameError:
WindowsError = None
def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
def _samefile(src, dst):
# Macintosh, Unix.
if hasattr(os.path, 'samefile'):
try:
return os.path.samefile(src, dst)
except OSError:
return False
# All other platforms: check for same pathname.
return (os.path.normcase(os.path.abspath(src)) ==
os.path.normcase(os.path.abspath(dst)))
def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise Error("`%s` and `%s` are the same file" % (src, dst))
for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn)
with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
def copymode(src, dst):
"""Copy mode bits from src to dst"""
if hasattr(os, 'chmod'):
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
os.chmod(dst, mode)
def copystat(src, dst):
"""Copy all stat info (mode bits, atime, mtime, flags) from src to dst"""
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
if hasattr(os, 'utime'):
os.utime(dst, (st.st_atime, st.st_mtime))
if hasattr(os, 'chmod'):
os.chmod(dst, mode)
if hasattr(os, 'chflags') and hasattr(st, 'st_flags'):
try:
os.chflags(dst, st.st_flags)
except OSError, why:
for err in 'EOPNOTSUPP', 'ENOTSUP':
if hasattr(errno, err) and why.errno == getattr(errno, err):
break
else:
raise
def copy(src, dst):
"""Copy data and mode bits ("cp src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copymode(src, dst)
def copy2(src, dst):
"""Copy data and all stat info ("cp -p src dst").
The destination may be a directory.
"""
if os.path.isdir(dst):
dst = os.path.join(dst, os.path.basename(src))
copyfile(src, dst)
copystat(src, dst)
def ignore_patterns(*patterns):
"""Function that can be used as copytree() ignore parameter.
Patterns is a sequence of glob-style patterns
that are used to exclude files"""
def _ignore_patterns(path, names):
ignored_names = []
for pattern in patterns:
ignored_names.extend(fnmatch.filter(names, pattern))
return set(ignored_names)
return _ignore_patterns
def copytree(src, dst, symlinks=False, ignore=None):
"""Recursively copy a directory tree using copy2().
The destination directory must not already exist.
If exception(s) occur, an Error is raised with a list of reasons.
If the optional symlinks flag is true, symbolic links in the
source tree result in symbolic links in the destination tree; if
it is false, the contents of the files pointed to by symbolic
links are copied.
The optional ignore argument is a callable. If given, it
is called with the `src` parameter, which is the directory
being visited by copytree(), and `names` which is the list of
`src` contents, as returned by os.listdir():
callable(src, names) -> ignored_names
Since copytree() is called recursively, the callable will be
called once for each directory that is copied. It returns a
list of names relative to the `src` directory that should
not be copied.
XXX Consider this example code rather than the ultimate tool.
"""
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
except EnvironmentError, why:
errors.append((srcname, dstname, str(why)))
try:
copystat(src, dst)
except OSError, why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.append((src, dst, str(why)))
if errors:
raise Error, errors
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete a directory tree.
If ignore_errors is set, errors are ignored; otherwise, if onerror
is set, it is called to handle the error with arguments (func,
path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
path is the argument to that function that caused it to fail; and
exc_info is a tuple returned by sys.exc_info(). If ignore_errors
is false and onerror is None, an exception is raised.
"""
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
try:
if os.path.islink(path):
# symlinks to directories are forbidden, see bug #1669
raise OSError("Cannot call rmtree on a symbolic link")
except OSError:
onerror(os.path.islink, path, sys.exc_info())
# can't continue even if onerror hook returns
return
names = []
try:
names = os.listdir(path)
except os.error, err:
onerror(os.listdir, path, sys.exc_info())
for name in names:
fullname = os.path.join(path, name)
try:
mode = os.lstat(fullname).st_mode
except os.error:
mode = 0
if stat.S_ISDIR(mode):
rmtree(fullname, ignore_errors, onerror)
else:
try:
os.remove(fullname)
except os.error, err:
onerror(os.remove, fullname, sys.exc_info())
try:
os.rmdir(path)
except os.error:
onerror(os.rmdir, path, sys.exc_info())
def _basename(path):
# A basename() variant which first strips the trailing slash, if present.
# Thus we always get the last component of the path, even for directories.
sep = os.path.sep + (os.path.altsep or '')
return os.path.basename(path.rstrip(sep))
def move(src, dst):
"""Recursively move a file or directory to another location. This is
similar to the Unix "mv" command.
If the destination is a directory or a symlink to a directory, the source
is moved inside the directory. The destination path must not already
exist.
If the destination already exists but is not a directory, it may be
overwritten depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.
"""
real_dst = dst
if os.path.isdir(dst):
if _samefile(src, dst):
# We might be on a case insensitive filesystem,
# perform the rename anyway.
os.rename(src, dst)
return
real_dst = os.path.join(dst, _basename(src))
if os.path.exists(real_dst):
raise Error, "Destination path '%s' already exists" % real_dst
try:
os.rename(src, real_dst)
except OSError:
if os.path.isdir(src):
if _destinsrc(src, dst):
raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
copytree(src, real_dst, symlinks=True)
rmtree(src)
else:
copy2(src, real_dst)
os.unlink(src)
def _destinsrc(src, dst):
src = abspath(src)
dst = abspath(dst)
if not src.endswith(os.path.sep):
src += os.path.sep
if not dst.endswith(os.path.sep):
dst += os.path.sep
return dst.startswith(src)
def _get_gid(name):
"""Returns a gid, given a group name."""
if getgrnam is None or name is None:
return None
try:
result = getgrnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None
def _get_uid(name):
"""Returns an uid, given a user name."""
if getpwnam is None or name is None:
return None
try:
result = getpwnam(name)
except KeyError:
result = None
if result is not None:
return result[2]
return None
def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0,
owner=None, group=None, logger=None):
"""Create a (possibly compressed) tar file from all the files under
'base_dir'.
'compress' must be "gzip" (the default), "bzip2", or None.
'owner' and 'group' can be used to define an owner and a group for the
archive that is being built. If not provided, the current owner and group
will be used.
The output tar file will be named 'base_name' + ".tar", possibly plus
the appropriate compression extension (".gz", or ".bz2").
Returns the output filename.
"""
tar_compression = {'gzip': 'gz', 'bzip2': 'bz2', None: ''}
compress_ext = {'gzip': '.gz', 'bzip2': '.bz2'}
# flags for compression program, each element of list will be an argument
if compress is not None and compress not in compress_ext.keys():
raise ValueError, \
("bad value for 'compress': must be None, 'gzip' or 'bzip2'")
archive_name = base_name + '.tar' + compress_ext.get(compress, '')
archive_dir = os.path.dirname(archive_name)
if archive_dir and not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# creating the tarball
import tarfile # late import so Python build itself doesn't break
if logger is not None:
logger.info('Creating tar archive')
uid = _get_uid(owner)
gid = _get_gid(group)
def _set_uid_gid(tarinfo):
if gid is not None:
tarinfo.gid = gid
tarinfo.gname = group
if uid is not None:
tarinfo.uid = uid
tarinfo.uname = owner
return tarinfo
if not dry_run:
tar = tarfile.open(archive_name, 'w|%s' % tar_compression[compress])
try:
tar.add(base_dir, filter=_set_uid_gid)
finally:
tar.close()
return archive_name
def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
# XXX see if we want to keep an external call here
if verbose:
zipoptions = "-r"
else:
zipoptions = "-rq"
from distutils.errors import DistutilsExecError
from distutils.spawn import spawn
try:
spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
except DistutilsExecError:
# XXX really should distinguish between "couldn't find
# external 'zip' command" and "zip failed".
raise ExecError, \
("unable to create zip file '%s': "
"could neither import the 'zipfile' module nor "
"find a standalone zip utility") % zip_filename
def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
"""Create a zip file from all the files under 'base_dir'.
The output zip file will be named 'base_name' + ".zip". Uses either the
"zipfile" Python module (if available) or the InfoZIP "zip" utility
(if installed and found on the default search path). If neither tool is
available, raises ExecError. Returns the name of the output zip
file.
"""
zip_filename = base_name + ".zip"
archive_dir = os.path.dirname(base_name)
if archive_dir and not os.path.exists(archive_dir):
if logger is not None:
logger.info("creating %s", archive_dir)
if not dry_run:
os.makedirs(archive_dir)
# If zipfile module is not available, try spawning an external 'zip'
# command.
try:
import zipfile
except ImportError:
zipfile = None
if zipfile is None:
_call_external_zip(base_dir, zip_filename, verbose, dry_run)
else:
if logger is not None:
logger.info("creating '%s' and adding '%s' to it",
zip_filename, base_dir)
if not dry_run:
with zipfile.ZipFile(zip_filename, "w",
compression=zipfile.ZIP_DEFLATED) as zf:
for dirpath, dirnames, filenames in os.walk(base_dir):
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
zf.write(path, path)
if logger is not None:
logger.info("adding '%s'", path)
return zip_filename
_ARCHIVE_FORMATS = {
'gztar': (_make_tarball, [('compress', 'gzip')], "gzip'ed tar-file"),
'bztar': (_make_tarball, [('compress', 'bzip2')], "bzip2'ed tar-file"),
'tar': (_make_tarball, [('compress', None)], "uncompressed tar file"),
'zip': (_make_zipfile, [],"ZIP file")
}
def get_archive_formats():
"""Returns a list of supported formats for archiving and unarchiving.
Each element of the returned sequence is a tuple (name, description)
"""
formats = [(name, registry[2]) for name, registry in
_ARCHIVE_FORMATS.items()]
formats.sort()
return formats
def register_archive_format(name, function, extra_args=None, description=''):
"""Registers an archive format.
name is the name of the format. function is the callable that will be
used to create archives. If provided, extra_args is a sequence of
(name, value) tuples that will be passed as arguments to the callable.
description can be provided to describe the format, and will be returned
by the get_archive_formats() function.
"""
if extra_args is None:
extra_args = []
if not isinstance(function, collections.Callable):
raise TypeError('The %s object is not callable' % function)
if not isinstance(extra_args, (tuple, list)):
raise TypeError('extra_args needs to be a sequence')
for element in extra_args:
if not isinstance(element, (tuple, list)) or len(element) !=2 :
raise TypeError('extra_args elements are : (arg_name, value)')
_ARCHIVE_FORMATS[name] = (function, extra_args, description)
def unregister_archive_format(name):
del _ARCHIVE_FORMATS[name]
def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None, logger=None):
"""Create an archive file (eg. zip or tar).
'base_name' is the name of the file to create, minus any format-specific
extension; 'format' is the archive format: one of "zip", "tar", "bztar"
or "gztar".
'root_dir' is a directory that will be the root directory of the
archive; ie. we typically chdir into 'root_dir' before creating the
archive. 'base_dir' is the directory where we start archiving from;
ie. 'base_dir' will be the common prefix of all files and
directories in the archive. 'root_dir' and 'base_dir' both default
to the current directory. Returns the name of the archive file.
'owner' and 'group' are used when creating a tar archive. By default,
uses the current owner and group.
"""
save_cwd = os.getcwd()
if root_dir is not None:
if logger is not None:
logger.debug("changing into '%s'", root_dir)
base_name = os.path.abspath(base_name)
if not dry_run:
os.chdir(root_dir)
if base_dir is None:
base_dir = os.curdir
kwargs = {'dry_run': dry_run, 'logger': logger}
try:
format_info = _ARCHIVE_FORMATS[format]
except KeyError:
raise ValueError, "unknown archive format '%s'" % format
func = format_info[0]
for arg, val in format_info[1]:
kwargs[arg] = val
if format != 'zip':
kwargs['owner'] = owner
kwargs['group'] = group
try:
filename = func(base_name, base_dir, **kwargs)
finally:
if root_dir is not None:
if logger is not None:
logger.debug("changing back to '%s'", save_cwd)
os.chdir(save_cwd)
return filename
|
import Avatar from '@material-ui/core/Avatar';
import React,{useState} from 'react'
import './ChatScreen.css'
function ChatScreen() {
const [input,setInput] = useState("");
const [messages,setMessages] = useState([
{
name : 'Natasha Phiri',
image :"https://media.istockphoto.com/photos/beautiful-woman-soft-makeup-and-perfect-skin-picture-id1133213198?k=6&m=1133213198&s=612x612&w=0&h=MQGFE8-cfFi3YpfGwPA6KZoCdSPjsRgfwAgIGCmfZ3w=",
message: 'Whats up'
},
{
name : 'Natasha Phiri',
image :"https://media.istockphoto.com/photos/beautiful-woman-soft-makeup-and-perfect-skin-picture-id1133213198?k=6&m=1133213198&s=612x612&w=0&h=MQGFE8-cfFi3YpfGwPA6KZoCdSPjsRgfwAgIGCmfZ3w=",
message: 'How is it going'
},
{
message: 'Yes how are you'
}
]);
const handleSend = e => {
e.preventDefault();
setMessages([...messages,{message:input}]);
setInput("");
}
return (
<div className="chatScreen">
<p className="chatScreen__timestamp">YOU MATCHED WITH NATASHA PHIRI ON 10/08/20</p>
{messages.map(message => (
message.name ? (
<div className="chatScreen__message">
<Avatar className="chatScreen__image"
alt={message.name}
src = {message.image}
/>
<p className="chatScreen__text">{message.message}</p>
</div>
) :(
<div className="chatScreen__message">
<p className="chatScreen__textUser">{message.message}</p>
</div>
)
))}
<form className="chatScreen__input">
<input value={input} onChange={(e) => setInput(e.target.value)} className="chatScreen__inputField" type="text" placeholder="Type a message..." />
<button type="submit" onClick={handleSend} className="chatScreen__inputButton">SEND</button>
</form>
</div>
);
}
export default ChatScreen
|
package resources
import (
"context"
"fmt"
"log"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider"
"github.com/hashicorp/go-uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)
var unsafeExecuteSchema = map[string]*schema.Schema{
"execute": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "SQL statement to execute. Forces recreation of resource on change.",
},
"revert": {
Type: schema.TypeString,
Required: true,
Description: "SQL statement to revert the execute statement. Invoked when resource is being destroyed.",
},
"query": {
Type: schema.TypeString,
Optional: true,
Description: "Optional SQL statement to do a read. Invoked after creation and every time it is changed.",
},
"query_results": {
Type: schema.TypeList,
Computed: true,
Description: "List of key-value maps (text to text) retrieved after executing read query. Will be empty if the query results in an error.",
Elem: &schema.Schema{
Type: schema.TypeMap,
Elem: &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
},
},
}
func UnsafeExecute() *schema.Resource {
return &schema.Resource{
Create: CreateUnsafeExecute,
Read: ReadUnsafeExecute,
Delete: DeleteUnsafeExecute,
Update: UpdateUnsafeExecute,
Schema: unsafeExecuteSchema,
DeprecationMessage: "Experimental resource. Will be deleted in the upcoming versions. Use at your own risk.",
Description: "Experimental resource used for testing purposes only. Allows to execute ANY SQL statement.",
CustomizeDiff: func(_ context.Context, diff *schema.ResourceDiff, _ interface{}) error {
if diff.HasChange("query") {
err := diff.SetNewComputed("query_results")
if err != nil {
return err
}
}
return nil
},
}
}
func ReadUnsafeExecute(d *schema.ResourceData, meta interface{}) error {
client := meta.(*provider.Context).Client
ctx := context.Background()
readStatement := d.Get("query").(string)
setNilResults := func() error {
log.Printf(`[DEBUG] Clearing query_results`)
err := d.Set("query_results", nil)
if err != nil {
return err
}
return nil
}
if readStatement == "" {
return setNilResults()
} else {
rows, err := client.QueryUnsafe(ctx, readStatement)
if err != nil {
log.Printf(`[WARN] SQL query "%s" failed with err %v`, readStatement, err)
return setNilResults()
}
log.Printf(`[INFO] SQL query "%s" executed successfully, returned rows count: %d`, readStatement, len(rows))
rowsTransformed := make([]map[string]any, len(rows))
for i, row := range rows {
t := make(map[string]any)
for k, v := range row {
if *v == nil {
t[k] = nil
} else {
switch (*v).(type) {
case fmt.Stringer:
t[k] = fmt.Sprintf("%v", *v)
case string:
t[k] = *v
default:
return fmt.Errorf("currently only objects convertible to String are supported by query; got %v", *v)
}
}
}
rowsTransformed[i] = t
}
err = d.Set("query_results", rowsTransformed)
if err != nil {
return err
}
}
return nil
}
func CreateUnsafeExecute(d *schema.ResourceData, meta interface{}) error {
client := meta.(*provider.Context).Client
ctx := context.Background()
id, err := uuid.GenerateUUID()
if err != nil {
return err
}
executeStatement := d.Get("execute").(string)
_, err = client.ExecUnsafe(ctx, executeStatement)
if err != nil {
return err
}
d.SetId(id)
log.Printf(`[INFO] SQL "%s" applied successfully\n`, executeStatement)
return ReadUnsafeExecute(d, meta)
}
func DeleteUnsafeExecute(d *schema.ResourceData, meta interface{}) error {
client := meta.(*provider.Context).Client
ctx := context.Background()
revertStatement := d.Get("revert").(string)
_, err := client.ExecUnsafe(ctx, revertStatement)
if err != nil {
return err
}
d.SetId("")
log.Printf(`[INFO] SQL "%s" applied successfully\n`, revertStatement)
return nil
}
func UpdateUnsafeExecute(d *schema.ResourceData, meta interface{}) error {
if d.HasChange("query") {
return ReadUnsafeExecute(d, meta)
}
return nil
}
|
package jmri.jmrit;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nonnull;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
import jmri.util.FileUtil;
/**
* Provide simple way to load and play sounds in JMRI.
* <p>
* This is placed in the jmri.jmrit package by process of elimination. It
* doesn't belong in the base jmri package, as it's not a basic interface. Nor
* is it a specific implementation of a basic interface, which would put it in
* jmri.jmrix. It seems most like a "tool using JMRI", or perhaps a tool for use
* with JMRI, so it was placed in jmri.jmrit.
*
* @see jmri.jmrit.sound
*
* @author Bob Jacobsen Copyright (C) 2004, 2006
* @author Dave Duchamp Copyright (C) 2011 - add streaming play of large files
*/
public class Sound {
// files over this size will be streamed
public static final long LARGE_SIZE = 100000;
private final URL url;
private boolean streaming = false;
private boolean streamingStop = false;
private AtomicReference<Clip> clipRef = new AtomicReference<>();
private boolean autoClose = true;
/**
* Create a Sound object using the media file at path
*
* @param path path, portable or absolute, to the media
* @throws NullPointerException if path cannot be converted into a URL by
* {@link jmri.util.FileUtilSupport#findURL(java.lang.String)}
*/
public Sound(@Nonnull String path) throws NullPointerException {
this(FileUtil.findURL(path));
}
/**
* Create a Sound object using the media file
*
* @param file reference to the media
* @throws java.net.MalformedURLException if file cannot be converted into a
* valid URL
*/
public Sound(@Nonnull File file) throws MalformedURLException {
this(file.toURI().toURL());
}
/**
* Create a Sound object using the media URL
*
* @param url path to the media
* @throws NullPointerException if URL is null
*/
public Sound(@Nonnull URL url) throws NullPointerException {
if (url == null) {
throw new NullPointerException();
}
this.url = url;
try {
streaming = this.needStreaming();
if (!streaming) {
clipRef.updateAndGet(clip -> {
return openClip();
});
}
} catch (URISyntaxException ex) {
streaming = false;
} catch (IOException ex) {
log.error("Unable to open {}", url);
}
}
private Clip openClip() {
Clip newClip = null;
try {
newClip = AudioSystem.getClip(null);
newClip.addLineListener(event -> {
if (LineEvent.Type.STOP.equals(event.getType())) {
if (autoClose) {
clipRef.updateAndGet(clip -> {
if (clip != null) {
clip.close();
}
return null;
});
}
}
});
newClip.open(AudioSystem.getAudioInputStream(url));
} catch (IOException ex) {
log.error("Unable to open {}", url);
} catch (LineUnavailableException ex) {
log.error("Unable to provide audio playback", ex);
} catch (UnsupportedAudioFileException ex) {
log.error("{} is not a recognised audio format", url);
}
return newClip;
}
/**
* Set if the clip be closed automatically.
* @param autoClose true if closed automatically
*/
public void setAutoClose(boolean autoClose) {
this.autoClose = autoClose;
}
/**
* Get if the clip is closed automatically.
* @return true if closed automatically
*/
public boolean getAutoClose() {
return autoClose;
}
/**
* Closes the sound.
*/
public void close() {
if (streaming) {
streamingStop = true;
} else {
clipRef.updateAndGet(clip -> {
if (clip != null) {
clip.close();
}
return null;
});
}
}
/** {@inheritDoc} */
@Override
@SuppressWarnings("deprecation") // Object.finalize
protected void finalize() throws Throwable {
try {
if (!streaming) {
clipRef.updateAndGet(clip -> {
if (clip != null) {
clip.close();
}
return null;
});
}
} finally {
super.finalize();
}
}
/**
* Play the sound once.
*/
public void play() {
if (streaming) {
Runnable streamSound = new StreamingSound(this.url);
Thread tStream = jmri.util.ThreadingUtil.newThread(streamSound);
tStream.start();
} else {
clipRef.updateAndGet(clip -> {
if (clip == null) {
clip = openClip();
}
if (clip != null) {
clip.start();
}
return clip;
});
}
}
/**
* Play the sound as an endless loop
*/
public void loop() {
this.loop(Clip.LOOP_CONTINUOUSLY);
}
/**
* Play the sound in a loop count times. Use
* {@link javax.sound.sampled.Clip#LOOP_CONTINUOUSLY} to create an endless
* loop.
*
* @param count the number of times to loop
*/
public void loop(int count) {
if (streaming) {
Runnable streamSound = new StreamingSound(this.url, count);
Thread tStream = jmri.util.ThreadingUtil.newThread(streamSound);
tStream.start();
} else {
clipRef.updateAndGet(clip -> {
if (clip == null) {
clip = openClip();
}
if (clip != null) {
clip.loop(count);
}
return clip;
});
}
}
/**
* Stop playing a loop.
*/
public void stop() {
if (streaming) {
streamingStop = true;
} else {
clipRef.updateAndGet(clip -> {
if (clip != null) {
clip.stop();
}
return clip;
});
}
}
private boolean needStreaming() throws URISyntaxException, IOException {
if (url != null) {
if ("file".equals(this.url.getProtocol())) {
return (new File(this.url.toURI()).length() > LARGE_SIZE);
} else {
return this.url.openConnection().getContentLengthLong() > LARGE_SIZE;
}
}
return false;
}
/**
* Play a sound from a buffer
*
* @param wavData data to play
*/
public static void playSoundBuffer(byte[] wavData) {
// get characteristics from buffer
float sampleRate = 11200.0f;
int sampleSizeInBits = 8;
int channels = 1;
boolean signed = (sampleSizeInBits > 8);
boolean bigEndian = true;
AudioFormat format = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
SourceDataLine line;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format); // format is an AudioFormat object
if (!AudioSystem.isLineSupported(info)) {
// Handle the error.
log.warn("line not supported: {}", info);
return;
}
// Obtain and open the line.
try {
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format);
} catch (LineUnavailableException ex) {
// Handle the error.
log.error("error opening line", ex);
return;
}
line.start();
// write(byte[] b, int off, int len)
line.write(wavData, 0, wavData.length);
}
public static class WavBuffer {
public WavBuffer(byte[] content) {
buffer = Arrays.copyOf(content, content.length);
// find fmt chunk and set offset
int index = 12; // skip RIFF header
while (index < buffer.length) {
// new chunk
if (buffer[index] == 0x66
&& buffer[index + 1] == 0x6D
&& buffer[index + 2] == 0x74
&& buffer[index + 3] == 0x20) {
// found it
fmtOffset = index;
return;
} else {
// skip
index = index + 8
+ buffer[index + 4]
+ buffer[index + 5] * 256
+ buffer[index + 6] * 256 * 256
+ buffer[index + 7] * 256 * 256 * 256;
log.debug("index now {}", index);
}
}
log.error("Didn't find fmt chunk");
}
// we maintain this, but don't use it for anything yet
@SuppressFBWarnings(value = "URF_UNREAD_FIELD")
int fmtOffset;
byte[] buffer;
float getSampleRate() {
return 11200.0f;
}
int getSampleSizeInBits() {
return 8;
}
int getChannels() {
return 1;
}
boolean getBigEndian() {
return false;
}
boolean getSigned() {
return (getSampleSizeInBits() > 8);
}
}
public class StreamingSound implements Runnable {
private final URL url;
private AudioInputStream stream = null;
private AudioFormat format = null;
private SourceDataLine line = null;
private jmri.Sensor streamingSensor = null;
private final int count;
/**
* A runnable to stream in sound and play it This method does not read
* in an entire large sound file at one time, but instead reads in
* smaller chunks as needed.
*
* @param url the URL containing audio media
*/
public StreamingSound(URL url) {
this(url, 1);
}
/**
* A runnable to stream in sound and play it This method does not read
* in an entire large sound file at one time, but instead reads in
* smaller chunks as needed.
*
* @param url the URL containing audio media
* @param count the number of times to loop
*/
public StreamingSound(URL url, int count) {
this.url = url;
this.count = count;
}
/** {@inheritDoc} */
@Override
public void run() {
// Note: some of the following is based on code from
// "Killer Game Programming in Java" by A. Davidson.
// Set up the audio input stream from the sound file
try {
// link an audio stream to the sampled sound's file
stream = AudioSystem.getAudioInputStream(url);
format = stream.getFormat();
log.debug("Audio format: {}", format);
// convert ULAW/ALAW formats to PCM format
if ((format.getEncoding() == AudioFormat.Encoding.ULAW)
|| (format.getEncoding() == AudioFormat.Encoding.ALAW)) {
AudioFormat newFormat
= new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
format.getSampleRate(),
format.getSampleSizeInBits() * 2,
format.getChannels(),
format.getFrameSize() * 2,
format.getFrameRate(), true); // big endian
// update stream and format details
stream = AudioSystem.getAudioInputStream(newFormat, stream);
log.info("Converted Audio format: {}", newFormat);
format = newFormat;
log.debug("new converted Audio format: {}", format);
}
} catch (UnsupportedAudioFileException e) {
log.error("AudioFileException {}", e.getMessage());
return;
} catch (IOException e) {
log.error("IOException {}", e.getMessage());
return;
}
streamingStop = false;
if (streamingSensor == null) {
streamingSensor = jmri.InstanceManager.sensorManagerInstance().provideSensor("ISSOUNDSTREAMING");
}
setSensor(jmri.Sensor.ACTIVE);
if (!streamingStop) {
// set up the SourceDataLine going to the JVM's mixer
try {
// gather information for line creation
DataLine.Info info
= new DataLine.Info(SourceDataLine.class, format);
if (!AudioSystem.isLineSupported(info)) {
log.error("Audio play() does not support: {}", format);
return;
}
// get a line of the required format
line = (SourceDataLine) AudioSystem.getLine(info);
line.open(format);
} catch (Exception e) {
log.error("Exception while creating Audio out {}", e.getMessage());
return;
}
}
if (streamingStop) {
line.close();
setSensor(jmri.Sensor.INACTIVE);
return;
}
// Read the sound file in chunks of bytes into buffer, and
// pass them on through the SourceDataLine
int numRead;
byte[] buffer = new byte[line.getBufferSize()];
log.debug("streaming sound buffer size = {}", line.getBufferSize());
line.start();
// read and play chunks of the audio
try {
if (stream.markSupported()) stream.mark(Integer.MAX_VALUE);
int i=0;
while (!streamingStop && ((i++ < count) || (count == Clip.LOOP_CONTINUOUSLY))) {
int offset;
while ((numRead = stream.read(buffer, 0, buffer.length)) >= 0) {
offset = 0;
while (offset < numRead) {
offset += line.write(buffer, offset, numRead - offset);
}
}
if (stream.markSupported()) {
stream.reset();
} else {
stream.close();
try {
stream = AudioSystem.getAudioInputStream(url);
} catch (UnsupportedAudioFileException e) {
log.error("AudioFileException {}", e.getMessage());
closeLine();
return;
} catch (IOException e) {
log.error("IOException {}", e.getMessage());
closeLine();
return;
}
}
}
} catch (IOException e) {
log.error("IOException while reading sound file {}", e.getMessage());
}
closeLine();
}
private void closeLine() {
// wait until all data is played, then close the line
line.drain();
line.stop();
line.close();
setSensor(jmri.Sensor.INACTIVE);
}
private void setSensor(int mode) {
if (streamingSensor != null) {
try {
streamingSensor.setState(mode);
} catch (jmri.JmriException ex) {
log.error("Exception while setting ISSOUNDSTREAMING sensor {} to {}", streamingSensor.getDisplayName(), mode);
}
}
}
}
private final static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Sound.class);
}
|
import React, { useContext, useEffect, useState } from "react";
import {
Form,
FormControl,
Button,
Container,
Row,
Col,
Alert,
} from "react-bootstrap";
import btnStyles from "../../styles/Button.module.css";
import styles from "../../styles/TaskCreateForm.module.css";
import { useNavigate, useParams } from "react-router-dom";
import axios from "axios";
import { CurrentUserContext } from "../../contexts/CurrentUserContext";
import { axiosReq } from "../../api/axiosDefaults";
import { parse, format } from "date-fns";
function TaskCreateForm() {
// Retrieve current user data from CurrentUserContext
const currentUser = useContext(CurrentUserContext);
// Define JSX element to display current username
const userTest = <>{currentUser?.username}</>;
// Define state variable 'taskData' using useState hook, initialized with empty task data
const [taskData, setTaskData] = useState({
task_name: "",
priority: "low",
due_date: "",
notes: "",
task_collection: "",
});
// Destructure properties from 'taskData' state
const { task_name, priority, due_date, notes, task_collection } = taskData;
// Define state variable 'collections' to store task collections, initialized with empty array
const [collections, setCollections] = useState({ results: [] });
// Define state variable 'errors' to handle form validation errors
const [errors, setErrors] = useState({});
// Hook to navigate between routes
const navigate = useNavigate();
// Retrieve 'id' parameter from URL
const { id } = useParams();
useEffect(() => {
// Function to fetch task collections from API
const fetchCollections = async () => {
try {
const response = await axios.get("/task_collections/");
setCollections(response.data);
} catch (error) {}
};
const handleMount = async () => {
try {
// Fetch task data from API
const { data } = await axiosReq.get(`/tasks/${id}`);
const {
task_name,
priority,
due_date,
is_done,
notes,
task_collection,
} = data;
// Parse the original date string and format it to "yyyy-MM-dd"
const parsedDate = parse(due_date, "dd MMM yyyy", new Date());
const formattedDueDate = format(parsedDate, "yyyy-MM-dd");
setTaskData({
task_name,
priority,
due_date: formattedDueDate,
is_done,
notes,
task_collection,
});
} catch (error) {
}
};
fetchCollections();
handleMount();
}, [id]);
const handleChange = (event) => {
setTaskData({
...taskData,
[event.target.name]: event.target.value,
});
};
// Function to navigate back to task list page
const handleCancel = () => {
navigate("/");
};
// Function to handle form submission
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
// Append form data to FormData object
formData.append("task_name", task_name);
formData.append("priority", priority);
formData.append("due_date", due_date);
formData.append("notes", notes);
formData.append("task_collection", task_collection);
try {
// Make PUT request to update task data
await axiosReq.put(`/tasks/${id}`, formData);
navigate(`/tasks/${id}`);
} catch (err) {
// Handle errors if request fails
if (err.response?.status !== 401) {
setErrors(err.response?.data);
}
}
};
return (
<Form
onSubmit={handleSubmit}
className={`${styles.TaskForm} p-4 mt-5 w-75 mx-auto`}
>
<Container className="text-center">
<h2>Edit Task</h2>
{/* Display current username if available */}
{currentUser ? userTest : ""}
<Row className="justify-content-center">
<Col>
{/* Form input fields */}
<Form.Group className="mb-3" controlId="taskName">
<Form.Label>Task Name</Form.Label>
<FormControl
className="text-center"
type="text"
placeholder="Enter task name"
name="task_name"
value={task_name}
required
onChange={handleChange}
/>
</Form.Group>
{/* Display validation errors for task name */}
{errors?.task_name?.map((message, idx) => (
<Alert variant="warning" key={idx}>
{message}
</Alert>
))}
{/* Priority dropdown */}
<Form.Group className="mb-3" controlId="taskPriority">
<Form.Label>Priority</Form.Label>
<Form.Control
className="text-center"
as="select"
name="priority"
value={priority || "low"}
required
onChange={handleChange}
>
<option value="low">Low</option>
<option value="medium">Medium</option>
<option value="high">High</option>
</Form.Control>
</Form.Group>
{/* Display validation errors for priority */}
{errors?.priority?.map((message, idx) => (
<Alert variant="warning" key={idx}>
{message}
</Alert>
))}
{/* Due date input field */}
<Form.Group className="mb-3" controlId="taskDueDate">
<Form.Label>Due Date</Form.Label>
<Form.Control
className="text-center"
type="date"
name="due_date"
value={due_date}
required
onChange={handleChange}
/>
</Form.Group>
{/* Display validation errors for due date */}
{errors?.due_date?.map((message, idx) => (
<Alert variant="warning" key={idx}>
{message}
</Alert>
))}
{/* Task collection dropdown */}
<Form.Group className="mb-3" controlId="taskCollection">
<Form.Label>Collection</Form.Label>
<Form.Control
className="text-center"
as="select"
name="task_collection"
value={task_collection}
onChange={handleChange}
>
<option value="" disabled>
{" "}
Select a collection
</option>
{collections.results.length === 0 && (
<option value="" disabled>
No collections available
</option>
)}
{collections.results.map((collection) => (
<option key={collection.id} value={collection.id}>
{collection.title}
</option>
))}
</Form.Control>
</Form.Group>
{/* Display validation errors for task collection */}
{errors?.task_collection?.map((message, idx) => (
<Alert variant="warning" key={idx}>
{message}
</Alert>
))}
{/* Notes input field */}
<Form.Group className="mb-3" controlId="taskNotes">
<Form.Label>Notes</Form.Label>
<Form.Control
className="text-center"
as="textarea"
rows={4}
placeholder="Enter additional notes"
name="notes"
value={notes}
onChange={handleChange}
/>
</Form.Group>
{/* Display validation errors for notes */}
{errors?.notes?.map((message, idx) => (
<Alert variant="warning" key={idx}>
{message}
</Alert>
))}
{/* Cancel button */}
<Button
variant="primary"
className={`me-2 ${btnStyles.CancelButton}`}
onClick={handleCancel}
>
Cancel
</Button>
{/* Save button */}
<Button
variant="primary"
className={`${btnStyles.ConfirmButton}`}
type="submit"
>
Save
</Button>
</Col>
</Row>
</Container>
</Form>
);
}
export default TaskCreateForm;
|
import {
Box,
Flex,
Button,
Checkbox,
Slider,
SliderTrack,
SliderFilledTrack,
SliderThumb,
Text,
} from '@chakra-ui/react';
import React from 'react';
import { useRecoilState, useSetRecoilState } from 'recoil';
import { playSound } from '../../hooks/useSound';
import {
enableSoundState,
finishDialogOpenState,
removeAlertOpenState,
soundVolumeState,
} from '../../modules/store';
const Options: React.FC = () => {
const setFinishDialogOpen = useSetRecoilState(finishDialogOpenState);
const setRemoveAlertOpen = useSetRecoilState(removeAlertOpenState);
const [enableSound, setEnableSound] = useRecoilState(enableSoundState);
const [soundVolume, setSoundVolume] = useRecoilState(soundVolumeState);
return (
<Box position="fixed" right="16px" top="16px">
<Flex justifyContent="right">
<Button marginRight={4} onClick={() => setRemoveAlertOpen(true)}>
抜ける
</Button>
<Button colorScheme="red" onClick={() => setFinishDialogOpen(true)}>
解散
</Button>
</Flex>
<Flex marginTop={4} justifyContent="right">
<Checkbox
isChecked={enableSound}
colorScheme="green"
onChange={(event) => {
setEnableSound(event.target.checked);
localStorage.enableSound = event.target.checked.toString();
}}
>
みんな揃ったら音鳴ってほしい!
</Checkbox>
</Flex>
{enableSound && (
<Flex marginTop={4} justifyContent="right" alignItems="center">
<Text fontSize="16px">音量</Text>
<Box width="160px" marginX={2}>
<Slider
aria-label="slider-ex-1"
defaultValue={soundVolume}
min={0}
max={100}
onChange={(value) => {
setSoundVolume(value);
localStorage.soundVolume = value.toString();
}}
>
<SliderTrack>
<SliderFilledTrack />
</SliderTrack>
<SliderThumb />
</Slider>
</Box>
<Button
colorScheme="blue"
size="sm"
onClick={() => playSound('/sounds/neruneru.mp3', soundVolume)}
>
試聴
</Button>
</Flex>
)}
</Box>
);
};
export { Options };
|
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BpNet Trainer."""
import glob
import logging
import os
import shutil
import keras
import tensorflow as tf
from nvidia_tao_tf1.blocks.trainer import Trainer
import nvidia_tao_tf1.core as tao_core
from nvidia_tao_tf1.core import distribution
from nvidia_tao_tf1.core.utils import mkdir_p, set_random_seed
from nvidia_tao_tf1.cv.common.utilities.serialization_listener import \
EpochModelSerializationListener
from nvidia_tao_tf1.cv.common.utilities.tlt_utils \
import get_latest_checkpoint, get_step_from_ckzip, get_tf_ckpt, load_pretrained_weights
from nvidia_tao_tf1.cv.common.utilities.tlt_utils import get_latest_tlt_model, load_model
from nvidia_tao_tf1.cv.detectnet_v2.tfhooks.task_progress_monitor_hook import (
TaskProgressMonitorHook
)
from nvidia_tao_tf1.cv.detectnet_v2.tfhooks.utils import get_common_training_hooks
logger = logging.getLogger(__name__)
MODEL_EXTENSION = ".hdf5"
class BpNetTrainer(Trainer):
"""BpNet Trainer class for building training graph and graph execution."""
@tao_core.coreobject.save_args
def __init__(self,
checkpoint_dir,
log_every_n_secs=1,
checkpoint_n_epoch=1,
num_epoch=2,
summary_every_n_steps=1,
infrequent_summary_every_n_steps=0,
validation_every_n_epoch=20,
max_ckpt_to_keep=5,
pretrained_weights=None,
load_graph=False,
inference_spec=None,
finetuning_config=None,
use_stagewise_lr_multipliers=False,
evaluator=None,
random_seed=42,
key=None,
final_model_name='bpnet_model',
**kwargs):
"""__init__ method.
Args:
checkpoint_dir (str): path to directory containing checkpoints.
log_every_n_secs (int): log every n secs.
checkpoint_n_epoch (int): how often to save checkpoint.
num_epoch (int): Number of epochs to train for.
summary_every_n_steps (int): summary every n steps.
infrequent_summary_every_n_steps (int): infrequent summary every n steps.
validation_every_n_steps (int): run evaluation every n steps.
max_ckpt_to_keep (int): How many checkpoints to keep.
pretrained_weighted (str): Pretrained weights path.
use_stagewise_lr_multipliers (bool): Option to enable use of
stagewise learning rate multipliers using WeightedMomentumOptimizer.
evaluator (TAOObject): evaluate predictions and save statistics.
random_seed (int): random seed.
"""
super(BpNetTrainer, self).__init__(**kwargs)
assert checkpoint_n_epoch <= num_epoch, "Checkpoint_n_epochs must be \
<= num_epochs"
assert (num_epoch % checkpoint_n_epoch) == 0, "Checkpoint_n_epoch should\
be a divisor of num_epoch"
self._checkpoint_dir = checkpoint_dir
self._pretrained_weights = pretrained_weights
self._load_graph = load_graph
self._log_every_n_secs = log_every_n_secs
self._checkpoint_n_epoch = checkpoint_n_epoch
self._num_epoch = num_epoch
self._infrequent_summary_every_n_steps = infrequent_summary_every_n_steps
self._evaluator = evaluator
self._random_seed = random_seed
self._summary_every_n_steps = summary_every_n_steps
self._max_ckpt_to_keep = max_ckpt_to_keep
self._validation_every_n_epoch = validation_every_n_epoch
self._steps_per_epoch = self._total_loss = self._train_op = None
self.inference_spec = inference_spec
self._finetuning_config = finetuning_config
if self._finetuning_config is None:
self._finetuning_config = {
'is_finetune_exp': False,
'checkpoint_path': None,
}
self.use_stagewise_lr_multipliers = use_stagewise_lr_multipliers
self._key = key
self._generate_output_sequence()
self.final_model_name = final_model_name
# Checks
if self._load_graph:
assert self._pretrained_weights is not None, "Load graph is True,\
please specify pretrained model to use to load the graph."
assert self.inference_spec is not None, "Please specify inference spec\
path in the config file."
@property
def train_op(self):
"""Return train op of Trainer."""
return self._train_op
def _check_if_first_run(self):
files = [
file for file in glob.glob(
self._checkpoint_dir +
'/model.epoch-*')]
return (not bool(len(files)))
def _generate_output_sequence(self):
"""Generates required output sequence."""
stages = self._model._stages
cmaps = [('cmap', i) for i in range(1, stages + 1)]
pafs = [('paf', i) for i in range(1, stages + 1)]
output_seq = []
output_seq.extend(cmaps)
output_seq.extend(pafs)
self.output_seq = output_seq
def update_regularizers(self, keras_model, kernel_regularizer=None,
bias_regularizer=None):
"""Update regularizers for models that are being loaded."""
model_config = keras_model.get_config()
for layer, layer_config in zip(keras_model.layers, model_config['layers']):
# Updating regularizer parameters for conv2d, depthwise_conv2d and dense layers.
if type(layer) in [keras.layers.convolutional.Conv2D,
keras.layers.core.Dense,
keras.layers.DepthwiseConv2D]:
if hasattr(layer, 'kernel_regularizer'):
layer_config['config']['kernel_regularizer'] = kernel_regularizer
if hasattr(layer, 'bias_regularizer'):
layer_config['config']['bias_regularizer'] = bias_regularizer
prev_model = keras_model
keras_model = keras.models.Model.from_config(model_config)
keras_model.set_weights(prev_model.get_weights())
return keras_model
def _build_distributed(self):
"""Build the training and validation graph, with Horovod Distributer enabled."""
# Use Horovod distributor for multi-gpu training.
self._ngpus = distribution.get_distributor().size()
# Set random seed for distributed training.
seed = distribution.get_distributor().distributed_seed(self._random_seed)
set_random_seed(seed)
# Must set the correct learning phase, `1` is training mode.
keras.backend.set_learning_phase(1)
with tf.name_scope("DataLoader"):
# Prepare data for training and validation.
data = self._dataloader()
# Total training samples and steps per epoch.
self._samples_per_epoch = self._dataloader.num_samples
self._steps_per_epoch = \
self._samples_per_epoch // (self._dataloader.batch_size * self._ngpus)
self._last_step = self._num_epoch * self._steps_per_epoch
with tf.name_scope("Model"):
if self._load_graph:
logger.info(("Loading pretrained model graph as is from {}...").format(
self._pretrained_weights))
# Load the model
loaded_model = load_model(self._pretrained_weights, self._key)
logger.warning("Ignoring regularization factors for pruning exp..!")
# WAR is to define an input layer explicitly with data.images as
# tensor. This resolves the input type/shape mismatch error.
# But this creates a submodel within the model. And currently,
# there are two input layers.
# TODO: See if the layers can be expanded or better solution.
input_layer = keras.layers.Input(
tensor=data.images,
shape=(None, None, 3),
name='input_1')
# TODO: Enable once tested.
# loaded_model = self.update_regularizers(
# loaded_model, self._model._kernel_regularizer, self._model._bias_regularizer
# )
loaded_model = self.update_regularizers(loaded_model)
predictions = loaded_model(input_layer)
self._model._keras_model = keras.models.Model(
inputs=input_layer, outputs=predictions)
else:
logger.info("Building model graph from model defintion ...")
predictions = self._model(inputs=data.images)
# Print out model summary.
# print_model_summary(self._model._keras_model) # Disable for TLT
if self._check_if_first_run(
) and not self._finetuning_config["is_finetune_exp"]:
logger.info("First run ...")
# Initialize model with pre-trained weights
if self._pretrained_weights is not None and not self._load_graph:
logger.info(
("Intializing model with pre-trained weights {}...").format(
self._pretrained_weights))
load_pretrained_weights(
self._model._keras_model,
self._pretrained_weights,
key=self._key,
logger=None)
elif self._finetuning_config["is_finetune_exp"]:
logger.info(
("Finetuning started -> Loading from {} checkpoint...").format(
self._finetuning_config["checkpoint_path"]))
# NOTE: The last step here might be different because of the difference in
# dataset sizes - steps_per_epoch might be small for a smaller
# dataset
current_step = get_step_from_ckzip(self._finetuning_config["checkpoint_path"])
if "epoch" in self._finetuning_config["checkpoint_path"]:
current_step *= self._steps_per_epoch
self._last_step = current_step + (
self._num_epoch - self._finetuning_config["ckpt_epoch_num"]
) * self._steps_per_epoch
logger.info("Updated last_step: {}".format(self._last_step))
else:
logger.info(
"Not first run and not finetuning experiment -> \
Loading from latest checkpoint...")
if self.use_stagewise_lr_multipliers:
lr_mult = self._model.get_lr_multipiers()
else:
lr_mult = {}
with tf.name_scope("Loss"):
label_slice_indices = self._dataloader.pose_config.label_slice_indices
self._losses = self._loss(data.labels,
predictions,
data.masks,
self.output_seq,
label_slice_indices)
self._model_loss = self._model.regularization_losses()
self._total_loss = tf.reduce_sum(
self._losses) / self._dataloader.batch_size + self._model_loss
tf.summary.scalar(name='total_loss', tensor=self._total_loss)
with tf.name_scope("Optimizer"):
# Update decay steps
_learning_rate_scheduler_type = type(self._optimizer._learning_rate_schedule).__name__
if 'SoftstartAnnealingLearningRateSchedule' in _learning_rate_scheduler_type:
self._optimizer._learning_rate_schedule.last_step = self._last_step
elif 'BpNetExponentialDecayLRSchedule' in _learning_rate_scheduler_type:
self._optimizer._learning_rate_schedule.update_decay_steps(
self._steps_per_epoch)
self._optimizer.build()
self._optimizer.set_grad_weights_dict(lr_mult)
self._train_op = self._optimizer.minimize(
loss=self._total_loss,
global_step=tf.compat.v1.train.get_global_step())[0]
def build(self):
"""Build the training and validation graph."""
self._build_distributed()
def train(self):
"""Run training."""
is_master = distribution.get_distributor().is_master()
if not is_master:
checkpoint_dir = None
checkpoint_path = None
else:
checkpoint_dir = self._checkpoint_dir
checkpoint_path = self._finetuning_config["checkpoint_path"]
mkdir_p(checkpoint_dir)
# TODO: tensorboard visualization of sample outputs at each stage
# TODO: CSV Logger like in Keras for epoch wise loss summary
# TODO: Add more log_tensors: stagewise_loss etc.
log_tensors = {
'step': tf.compat.v1.train.get_global_step(),
'loss': self._total_loss,
'epoch': tf.compat.v1.train.get_global_step() / self._steps_per_epoch}
serialization_listener = EpochModelSerializationListener(
checkpoint_dir=checkpoint_dir,
model=self._model,
key=self._key,
steps_per_epoch=self._steps_per_epoch,
max_to_keep=None
)
listeners = [serialization_listener]
common_hooks = get_common_training_hooks(
log_tensors=log_tensors,
log_every_n_secs=self._log_every_n_secs,
checkpoint_n_steps=self._checkpoint_n_epoch *
self._steps_per_epoch,
model=None,
last_step=self._last_step,
checkpoint_dir=checkpoint_dir,
scaffold=self.scaffold,
steps_per_epoch=self._steps_per_epoch,
summary_every_n_steps=self._summary_every_n_steps,
infrequent_summary_every_n_steps=0,
listeners=listeners,
key=self._key,
)
# Add hook to stop training if the loss becomes nan
self._hooks = self._hooks + [tf.train.NanTensorHook(
self._total_loss, fail_on_nan_loss=True
)]
if is_master:
self._hooks.append(TaskProgressMonitorHook(log_tensors,
checkpoint_dir,
self._num_epoch,
self._steps_per_epoch))
hooks = common_hooks + self._hooks
# If specific checkpoint path provided, then pick up the params from that
# Otherwise, use the latest checkpoint from the checkpoint dir
if self._finetuning_config["is_finetune_exp"]:
latest_step = get_step_from_ckzip(checkpoint_path)
if "epoch" in checkpoint_path:
latest_step *= self._steps_per_epoch
checkpoint_filename = get_tf_ckpt(checkpoint_path, self._key, latest_step)
else:
checkpoint_filename = get_latest_checkpoint(checkpoint_dir, self._key)
self.run_training_loop(
train_op=self._train_op,
hooks=hooks,
checkpoint_filename_with_path=checkpoint_filename
)
# Once training is completed, copy the lastest model to weights directory
if is_master:
latest_tlt_model_path = get_latest_tlt_model(checkpoint_dir, extension=MODEL_EXTENSION)
if latest_tlt_model_path and os.path.exists(latest_tlt_model_path):
final_model_path = os.path.join(checkpoint_dir, self.final_model_name + MODEL_EXTENSION)
logger.info("Saving the final step model to {}".format(final_model_path))
shutil.copyfile(latest_tlt_model_path, final_model_path)
|
<?php
namespace App\Http\Controllers;
use App\Models\PaymentRequest;
use App\Models\User;
use App\Traits\Processor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Validator;
class PaystackController extends Controller
{
use Processor;
private PaymentRequest $payment;
private $user;
public function __construct(PaymentRequest $payment, User $user)
{
$config = $this->payment_config('paystack', 'payment_config');
$values = false;
if (!is_null($config) && $config->mode == 'live') {
$values = json_decode($config->live_values);
} elseif (!is_null($config) && $config->mode == 'test') {
$values = json_decode($config->test_values);
}
if ($values) {
$config = array(
'publicKey' => env('PAYSTACK_PUBLIC_KEY', $values->public_key),
'secretKey' => env('PAYSTACK_SECRET_KEY', $values->secret_key),
'paymentUrl' => env('PAYSTACK_PAYMENT_URL', 'https://api.paystack.co'),
'merchantEmail' => env('MERCHANT_EMAIL', $values->merchant_email),
);
Config::set('paystack', $config);
}
$this->payment = $payment;
$this->user = $user;
}
public function index(Request $request)
{
$validator = Validator::make($request->all(), [
'payment_id' => 'required|uuid'
]);
if ($validator->fails()) {
return response()->json($this->response_formatter(GATEWAYS_DEFAULT_400, null, $this->error_processor($validator)), 400);
}
$data = $this->payment::where(['id' => $request['payment_id']])->where(['is_paid' => 0])->first();
if (!isset($data)) {
return response()->json($this->response_formatter(GATEWAYS_DEFAULT_204), 200);
}
$payer = json_decode($data['payer_information']);
$reference = \Unicodeveloper\Paystack\Facades\Paystack::genTranxRef();
return view('payment-gateway.paystack', compact('data', 'payer', 'reference'));
}
public function redirectToGateway(Request $request)
{
return Paystack::getAuthorizationUrl()->redirectNow();
}
public function handleGatewayCallback(Request $request)
{
$paymentDetails = Paystack::getPaymentData();
if ($paymentDetails['status'] == true) {
$this->payment::where(['attribute_id' => $paymentDetails['data']['orderID']])->update([
'payment_method' => 'paystack',
'is_paid' => 1,
'transaction_id' => $request['trxref'],
]);
$data = $this->payment::where(['attribute_id' => $paymentDetails['data']['orderID']])->first();
if (isset($data) && function_exists($data->success_hook)) {
call_user_func($data->success_hook, $data);
}
return $this->payment_response($data, 'success');
}
$payment_data = $this->payment::where(['attribute_id' => $paymentDetails['data']['orderID']])->first();
if (isset($payment_data) && function_exists($payment_data->failure_hook)) {
call_user_func($payment_data->failure_hook, $payment_data);
}
return $this->payment_response($payment_data, 'fail');
}
}
|
from django.db import models
from store.models import *
from orders.models import *
from django.contrib.auth.models import User
from django.utils import timezone
# Модель для хранения данных о продажах
class SalesStatistics(models.Model):
product = models.OneToOneField(Product, on_delete=models.CASCADE, verbose_name="Товар")
total_sales = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="Сумма продаж")
total_quantity = models.PositiveIntegerField(default=0, verbose_name="Количество единиц")
share_of_total = models.DecimalField(max_digits=5, decimal_places=2, default=0, verbose_name="Доля продаж %")
class Meta:
verbose_name = 'Статистика продаж'
verbose_name_plural = 'Статистика продаж'
def __str__(self):
return f"Статистика продаж для {self.product.name}"
|
"use strict";
/**
* Copyright 2015 CANAL+ Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
Object.defineProperty(exports, "__esModule", { value: true });
var compat_1 = require("../../compat");
var eme_1 = require("../../compat/eme");
var config_1 = require("../../config");
var errors_1 = require("../../errors");
var log_1 = require("../../log");
var array_includes_1 = require("../../utils/array_includes");
var flat_map_1 = require("../../utils/flat_map");
var is_null_or_undefined_1 = require("../../utils/is_null_or_undefined");
var media_keys_infos_store_1 = require("./utils/media_keys_infos_store");
/**
* @param {Array.<Object>} keySystems
* @param {MediaKeySystemAccess} currentKeySystemAccess
* @param {Object} currentKeySystemOptions
* @returns {null|Object}
*/
function checkCachedMediaKeySystemAccess(keySystems, currentKeySystemAccess, currentKeySystemOptions) {
var mksConfiguration = currentKeySystemAccess.getConfiguration();
if ((0, compat_1.shouldRenewMediaKeySystemAccess)() || mksConfiguration == null) {
return null;
}
var firstCompatibleOption = keySystems.filter(function (ks) {
// TODO Do it with MediaKeySystemAccess.prototype.keySystem instead
if (ks.type !== currentKeySystemOptions.type) {
return false;
}
if ((!(0, is_null_or_undefined_1.default)(ks.persistentLicenseConfig) ||
ks.persistentState === "required") &&
mksConfiguration.persistentState !== "required") {
return false;
}
if (ks.distinctiveIdentifier === "required" &&
mksConfiguration.distinctiveIdentifier !== "required") {
return false;
}
return true;
})[0];
if (firstCompatibleOption != null) {
return { keySystemOptions: firstCompatibleOption,
keySystemAccess: currentKeySystemAccess };
}
return null;
}
/**
* Find key system canonical name from key system type.
* @param {string} ksType - Obtained via inversion
* @returns {string|undefined} - Either the canonical name, or undefined.
*/
function findKeySystemCanonicalName(ksType) {
var e_1, _a;
var EME_KEY_SYSTEMS = config_1.default.getCurrent().EME_KEY_SYSTEMS;
try {
for (var _b = __values(Object.keys(EME_KEY_SYSTEMS)), _c = _b.next(); !_c.done; _c = _b.next()) {
var ksName = _c.value;
if ((0, array_includes_1.default)(EME_KEY_SYSTEMS[ksName], ksType)) {
return ksName;
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return undefined;
}
/**
* Build configuration for the requestMediaKeySystemAccess EME API, based
* on the current keySystem object.
* @param {Object} keySystemTypeInfo
* @returns {Array.<Object>} - Configuration to give to the
* requestMediaKeySystemAccess API.
*/
function buildKeySystemConfigurations(keySystemTypeInfo) {
var keyName = keySystemTypeInfo.keyName, keyType = keySystemTypeInfo.keyType, keySystem = keySystemTypeInfo.keySystemOptions;
var sessionTypes = ["temporary"];
var persistentState = "optional";
var distinctiveIdentifier = "optional";
if (!(0, is_null_or_undefined_1.default)(keySystem.persistentLicenseConfig)) {
persistentState = "required";
sessionTypes.push("persistent-license");
}
if (!(0, is_null_or_undefined_1.default)(keySystem.persistentState)) {
persistentState = keySystem.persistentState;
}
if (!(0, is_null_or_undefined_1.default)(keySystem.distinctiveIdentifier)) {
distinctiveIdentifier = keySystem.distinctiveIdentifier;
}
var _a = config_1.default.getCurrent(), EME_DEFAULT_AUDIO_CODECS = _a.EME_DEFAULT_AUDIO_CODECS, EME_DEFAULT_VIDEO_CODECS = _a.EME_DEFAULT_VIDEO_CODECS, EME_DEFAULT_WIDEVINE_ROBUSTNESSES = _a.EME_DEFAULT_WIDEVINE_ROBUSTNESSES, EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES = _a.EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES;
// From the W3 EME spec, we have to provide videoCapabilities and
// audioCapabilities.
// These capabilities must specify a codec (even though you can use a
// completely different codec afterward).
// It is also strongly recommended to specify the required security
// robustness. As we do not want to forbide any security level, we specify
// every existing security level from highest to lowest so that the best
// security level is selected.
// More details here:
// https://storage.googleapis.com/wvdocs/Chrome_EME_Changes_and_Best_Practices.pdf
// https://www.w3.org/TR/encrypted-media/#get-supported-configuration-and-consent
var audioCapabilities;
var videoCapabilities;
var audioCapabilitiesConfig = keySystem.audioCapabilitiesConfig, videoCapabilitiesConfig = keySystem.videoCapabilitiesConfig;
if ((audioCapabilitiesConfig === null || audioCapabilitiesConfig === void 0 ? void 0 : audioCapabilitiesConfig.type) === "full") {
audioCapabilities = audioCapabilitiesConfig.value;
}
else {
var audioRobustnesses = void 0;
if ((audioCapabilitiesConfig === null || audioCapabilitiesConfig === void 0 ? void 0 : audioCapabilitiesConfig.type) === "robustness") {
audioRobustnesses = audioCapabilitiesConfig.value;
}
else if (keyName === "widevine") {
audioRobustnesses = EME_DEFAULT_WIDEVINE_ROBUSTNESSES;
}
else if (keyType === "com.microsoft.playready.recommendation") {
audioRobustnesses = EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES;
}
else {
audioRobustnesses = [];
}
if (audioRobustnesses.length === 0) {
audioRobustnesses.push(undefined);
}
var audioCodecs_1 = (audioCapabilitiesConfig === null || audioCapabilitiesConfig === void 0 ? void 0 : audioCapabilitiesConfig.type) === "contentType" ?
audioCapabilitiesConfig.value :
EME_DEFAULT_AUDIO_CODECS;
audioCapabilities = (0, flat_map_1.default)(audioRobustnesses, function (robustness) {
return audioCodecs_1.map(function (contentType) {
return robustness !== undefined ? { contentType: contentType, robustness: robustness } :
{ contentType: contentType };
});
});
}
if ((videoCapabilitiesConfig === null || videoCapabilitiesConfig === void 0 ? void 0 : videoCapabilitiesConfig.type) === "full") {
videoCapabilities = videoCapabilitiesConfig.value;
}
else {
var videoRobustnesses = void 0;
if ((videoCapabilitiesConfig === null || videoCapabilitiesConfig === void 0 ? void 0 : videoCapabilitiesConfig.type) === "robustness") {
videoRobustnesses = videoCapabilitiesConfig.value;
}
else if (keyName === "widevine") {
videoRobustnesses = EME_DEFAULT_WIDEVINE_ROBUSTNESSES;
}
else if (keyType === "com.microsoft.playready.recommendation") {
videoRobustnesses = EME_DEFAULT_PLAYREADY_RECOMMENDATION_ROBUSTNESSES;
}
else {
videoRobustnesses = [];
}
if (videoRobustnesses.length === 0) {
videoRobustnesses.push(undefined);
}
var videoCodecs_1 = (videoCapabilitiesConfig === null || videoCapabilitiesConfig === void 0 ? void 0 : videoCapabilitiesConfig.type) === "contentType" ?
videoCapabilitiesConfig.value :
EME_DEFAULT_VIDEO_CODECS;
videoCapabilities = (0, flat_map_1.default)(videoRobustnesses, function (robustness) {
return videoCodecs_1.map(function (contentType) {
return robustness !== undefined ? { contentType: contentType, robustness: robustness } :
{ contentType: contentType };
});
});
}
var wantedMediaKeySystemConfiguration = {
initDataTypes: ["cenc"],
videoCapabilities: videoCapabilities,
audioCapabilities: audioCapabilities,
distinctiveIdentifier: distinctiveIdentifier,
persistentState: persistentState,
sessionTypes: sessionTypes,
};
return [
wantedMediaKeySystemConfiguration,
// Some legacy implementations have issues with `audioCapabilities` and
// `videoCapabilities`, so we're including a supplementary
// `MediaKeySystemConfiguration` without those properties.
__assign(__assign({}, wantedMediaKeySystemConfiguration), { audioCapabilities: undefined, videoCapabilities: undefined }),
];
}
/**
* Try to find a compatible key system from the keySystems array given.
*
* This function will request a MediaKeySystemAccess based on the various
* keySystems provided.
*
* This Promise might either:
* - resolves the MediaKeySystemAccess and the keySystems as an object, when
* found.
* - reject if no compatible key system has been found.
*
* @param {HTMLMediaElement} mediaElement
* @param {Array.<Object>} keySystemsConfigs - The keySystems you want to test.
* @param {Object} cancelSignal
* @returns {Promise.<Object>}
*/
function getMediaKeySystemAccess(mediaElement, keySystemsConfigs, cancelSignal) {
log_1.default.info("DRM: Searching for compatible MediaKeySystemAccess");
var currentState = media_keys_infos_store_1.default.getState(mediaElement);
if (currentState !== null) {
if (eme_1.default.implementation === currentState.emeImplementation.implementation) {
// Fast way to find a compatible keySystem if the currently loaded
// one as exactly the same compatibility options.
var cachedKeySystemAccess = checkCachedMediaKeySystemAccess(keySystemsConfigs, currentState.mediaKeySystemAccess, currentState.keySystemOptions);
if (cachedKeySystemAccess !== null) {
log_1.default.info("DRM: Found cached compatible keySystem");
return Promise.resolve({
type: "reuse-media-key-system-access",
value: { mediaKeySystemAccess: cachedKeySystemAccess.keySystemAccess,
options: cachedKeySystemAccess.keySystemOptions },
});
}
}
}
/**
* Array of set keySystems for this content.
* Each item of this array is an object containing the following keys:
* - keyName {string}: keySystem canonical name (e.g. "widevine")
* - keyType {string}: keySystem type (e.g. "com.widevine.alpha")
* - keySystem {Object}: the original keySystem object
* @type {Array.<Object>}
*/
var keySystemsType = keySystemsConfigs.reduce(function (arr, keySystemOptions) {
var EME_KEY_SYSTEMS = config_1.default.getCurrent().EME_KEY_SYSTEMS;
var managedRDNs = EME_KEY_SYSTEMS[keySystemOptions.type];
var ksType;
if (managedRDNs != null) {
ksType = managedRDNs.map(function (keyType) {
var keyName = keySystemOptions.type;
return { keyName: keyName, keyType: keyType, keySystemOptions: keySystemOptions };
});
}
else {
var keyName = findKeySystemCanonicalName(keySystemOptions.type);
var keyType = keySystemOptions.type;
ksType = [{ keyName: keyName, keyType: keyType, keySystemOptions: keySystemOptions }];
}
return arr.concat(ksType);
}, []);
return recursivelyTestKeySystems(0);
/**
* Test all key system configuration stored in `keySystemsType` one by one
* recursively.
* Returns a Promise which will emit the MediaKeySystemAccess if one was
* found compatible with one of the configurations or just reject if none
* were found to be compatible.
* @param {Number} index - The index in `keySystemsType` to start from.
* Should be set to `0` when calling directly.
* @returns {Promise.<Object>}
*/
function recursivelyTestKeySystems(index) {
return __awaiter(this, void 0, void 0, function () {
var chosenType, keyType, keySystemOptions, keySystemConfigurations, keySystemAccess, _1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// if we iterated over the whole keySystemsType Array, quit on error
if (index >= keySystemsType.length) {
throw new errors_1.EncryptedMediaError("INCOMPATIBLE_KEYSYSTEMS", "No key system compatible with your wanted " +
"configuration has been found in the current " +
"browser.");
}
if (eme_1.default.requestMediaKeySystemAccess == null) {
throw new Error("requestMediaKeySystemAccess is not implemented in your browser.");
}
chosenType = keySystemsType[index];
keyType = chosenType.keyType, keySystemOptions = chosenType.keySystemOptions;
keySystemConfigurations = buildKeySystemConfigurations(chosenType);
log_1.default.debug("DRM: Request keysystem access ".concat(keyType, ",") +
"".concat(index + 1, " of ").concat(keySystemsType.length));
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, eme_1.default.requestMediaKeySystemAccess(keyType, keySystemConfigurations)];
case 2:
keySystemAccess = _a.sent();
log_1.default.info("DRM: Found compatible keysystem", keyType, index + 1);
return [2 /*return*/, { type: "create-media-key-system-access",
value: { options: keySystemOptions,
mediaKeySystemAccess: keySystemAccess } }];
case 3:
_1 = _a.sent();
log_1.default.debug("DRM: Rejected access to keysystem", keyType, index + 1);
if (cancelSignal.cancellationError !== null) {
throw cancelSignal.cancellationError;
}
return [2 /*return*/, recursivelyTestKeySystems(index + 1)];
case 4: return [2 /*return*/];
}
});
});
}
}
exports.default = getMediaKeySystemAccess;
|
package it.unina.cinemates.viewmodels.user.movielist.common;
import android.os.Bundle;
import android.util.Log;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import androidx.navigation.NavController;
import java.util.ArrayList;
import java.util.List;
import it.unina.cinemates.R;
import it.unina.cinemates.models.Notification;
import it.unina.cinemates.retrofit.PaginatedResponse;
import it.unina.cinemates.retrofit.backend.BackendRetrofitService;
import it.unina.cinemates.ui.common.utils.SnackbarUtils;
import it.unina.cinemates.views.backend.MovieListBasic;
import it.unina.cinemates.models.Reaction;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ReactionViewModel extends ViewModel {
private List<Reaction> reactions = new ArrayList<>();
private final MutableLiveData<List<Reaction>> movieListReactionsLiveData = new MutableLiveData<>();
public LiveData<List<Reaction>> getMovieListReactionsLiveData() {
return movieListReactionsLiveData;
}
public void setMovieListReactionsLiveData(List<Reaction> reactions) {
this.movieListReactionsLiveData.setValue(reactions);
}
private final MutableLiveData<Integer> movieListTotalReactionsLiveData = new MutableLiveData<>();
public LiveData<Integer> getMovieListTotalReactionsLiveData() {
return movieListTotalReactionsLiveData;
}
public void setMovieListTotalReactionsLiveData(Integer totalReactions) {
this.movieListTotalReactionsLiveData.setValue(totalReactions);
}
public void requestMovieListReactions(Integer movieListId, Integer page) {
BackendRetrofitService.getInstance().getMovieListAPI().getMovieListReactions(movieListId, page).enqueue(
new Callback<PaginatedResponse<List<Reaction>>>() {
@Override
public void onResponse(Call<PaginatedResponse<List<Reaction>>> call, Response<PaginatedResponse<List<Reaction>>> response) {
if (response.isSuccessful()) {
reactions.addAll(response.body().getData());
setMovieListTotalReactionsLiveData(response.body().getTotalRecords());
setMovieListReactionsLiveData(reactions);
} else
setMovieListReactionsLiveData(null);
}
@Override
public void onFailure(Call<PaginatedResponse<List<Reaction>>> call, Throwable t) {
setMovieListReactionsLiveData(null);
}
});
}
public void requestReactionByNotification(Notification notification, NavController navController, FragmentActivity activity){
BackendRetrofitService.getInstance().getReactionApi().getReaction(notification.getContentId()).enqueue(new Callback<Reaction>() {
@Override
public void onResponse(Call<Reaction> call, Response<Reaction> response) {
if(response.body().getReactedListId() == null){
SnackbarUtils.failureSnackbar(activity, activity.getString(R.string.content_removed)).show();
return;
}
BackendRetrofitService.getInstance().getMovieListAPI().getMovieListBasic(response.body().getReactedListId()).enqueue(new Callback<MovieListBasic>() {
@Override
public void onResponse(Call<MovieListBasic> call, Response<MovieListBasic> response) {
Bundle bundle = new Bundle();
bundle.putParcelable("movieList",response.body());
navController.navigate(R.id.navigation_reaction,bundle);
}
@Override
public void onFailure(Call<MovieListBasic> call, Throwable t) {
SnackbarUtils.failureSnackbar(activity, activity.getString(R.string.snackbar_server_unreachable)).show();
}
});
}
@Override
public void onFailure(Call<Reaction> call, Throwable t) {
SnackbarUtils.failureSnackbar(activity, activity.getString(R.string.snackbar_server_unreachable)).show();
}
});
}
public void resetReactions(){
this.reactions.clear();
}
}
|
package com.example.coroutinescodelab
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlin.system.measureTimeMillis
//fun main() {
// val time = measureTimeMillis {
// runBlocking {
// println("Weather forecast")
//// val forecast: Deferred<String> = async {
//// getForecast()
//// }
//// val temperature: Deferred<String> = async {
//// getTemperature()
//// }
// println(getWeatherReport())
// println("Have a good day!")
// }
// }
// println("Execution Time : ${time / 1000.0} seconds")
//}
//
//suspend fun getForecast(): String {
// delay(1000)
// return "Sunny"
//}
//
//suspend fun getTemperature(): String {
// delay(1000)
// return "30\u00b0C"
//}
//
//suspend fun getWeatherReport() = coroutineScope {
// val forecast = async { getForecast() }
// val temperature = async { getTemperature() }
// "${forecast.await()} ${temperature.await()}"
//}
fun main() {
runBlocking {
println("${Thread.currentThread().name} - runBlocking function")
launch {
println("${Thread.currentThread().name} - launch function")
withContext(Dispatchers.Default) {
println("${Thread.currentThread().name} - withContext function")
delay(2000)
println("10 results found.")
}
println("${Thread.currentThread().name} - end of launch function")
}
println("Loading...")
}
}
|
import React from 'react';
import "../node_modules/bootstrap/dist/css/bootstrap.min.css"
import Navbar from "./layout/Navbar";
import Home from "./pages/Home";
import {BrowserRouter as Router, Route, Routes} from "react-router-dom";
import AddUser from "./users/AddUser";
import EditUser from "./users/EditUser";
import ViewUser from "./users/ViewUser";
// TODO removed exact - test
function App() {
return (
<div className="App">
<Router>
<Navbar/>
<Routes>
<Route path="/" element={<Home/>}/>
<Route path="/adduser" element={<AddUser/>}/>
<Route path="/edituser/:id" element={<EditUser/>}/>
<Route path="/viewuser/:id" element={<ViewUser/>}/>
</Routes>
</Router>
</div>
);
}
export default App;
|
import { useState } from 'react'
import Form from 'react-bootstrap/Form'
import Button from 'react-bootstrap/Button'
import Alert from 'react-bootstrap/Alert'
// import { Form, Button } from 'react-bootstrap' <-- questo metodo anche funziona, ma non è ottimale
// questo form creerà una prenotazione in un database sfruttando delle API
// name: string <-- required
// phone: string/number <-- required
// numberOfPeople: string/number <-- required
// dateTime: string <-- required
// smoking: boolean <-- required
// specialRequests <-- NOT required
const initialReservation = {
name: '',
phone: '',
numberOfPeople: 1,
dateTime: '',
smoking: false,
specialRequests: '',
}
const BookingForm = function () {
// creo un sotto-oggetto nello state di BookingForm, che rappresenterà il CONTENUTO del form di prenotazione
// grazie ad una serie di input "controllati", ad ogni pressione di un tasto in un campo noi andremo a modificare
// lo stato del componente in modo da mantenerli sempre "sincronizzati"
// il nostro form sarà SEMPRE consapevole del proprio contenuto!
// alla pressione del tasto submit ci basterà andare a leggere il contenuto dello state, che sarà
// stato automaticamente aggiornato strada facendo
const [reservation, setReservation] = useState(initialReservation)
const handleSubmitThenCatch = (e) => {
e.preventDefault() // fermiamo il comportamento di default del browser
// facciamo la raccolta dati...
// scherzo! l'abbiamo già fatta, è il contenuto del nostro stato!
fetch('https://striveschool-api.herokuapp.com/api/reservation', {
method: 'POST', // uso POST per creare una nuova risorsa
body: JSON.stringify(reservation),
headers: {
'Content-Type': 'application/json',
},
})
.then((res) => {
// finirete qui dentro se la Promise viene risolta!
// la res rappresenta la Response da parte del server
console.log('RES', res)
if (res.ok) {
// la prenotazione è stata salvata correttamente!
window.alert('Prenotazione salvata! Grazie!')
// bello, ma il form è ancora pieno! svuotiamolo:
setReservation(initialReservation)
} else {
// ahia! c'è stato un problema
window.alert('Errore, riprova più tardi!')
throw new Error('Errore nel salvataggio della prenotazione')
// mi auto lancio nel blocco catch
}
})
.catch((err) => {
// finirete qui dentro se la Promise viene rifiutata!
console.log('ERRORE!', err)
})
}
const handleSubmitAsyncAwait = async (e) => {
e.preventDefault() // fermiamo il comportamento di default
// le Promise vanno ATTESE, sia nel caso di Resolved sia nel caso di Rejected
try {
const res = await fetch(
'https://striveschool-api.herokuapp.com/api/reservation',
{
method: 'POST', // uso POST per creare una nuova risorsa
body: JSON.stringify(reservation),
headers: {
'Content-Type': 'application/json',
},
}
)
if (res.ok) {
window.alert('Prenotazione salvata! Grazie!')
// bello, ma il form è ancora pieno! svuotiamolo:
setReservation(initialReservation)
} else {
// ahia! c'è stato un problema
window.alert('Errore, riprova più tardi!')
throw new Error('Errore nel salvataggio della prenotazione')
// mi auto lancio nel blocco catch
}
} catch (err) {
console.log('ERRORE!', err)
}
}
return (
<>
<h2 className="text-center mt-3">Prenota un tavolo ORA!</h2>
<Form onSubmit={handleSubmitAsyncAwait}>
<Form.Group className="mb-3">
<Form.Label>Il tuo nome</Form.Label>
{/* i Form.Control si traducono in HTML in <input /> */}
<Form.Control
type="text"
placeholder="Mario Rossi"
required
onChange={
// qui dentro ci va una funzione che viene eseguita ad ogni cambiamento dell'input
(e) => {
setReservation({
...reservation, // riportando qui dentro TUTTE le proprietà di reservation
name: e.target.value, // il carattere che ho appena scritto
})
}
}
value={reservation.name}
/>
</Form.Group>
{reservation.name === 'Al Bano' && (
<Alert variant="success">FELICITÀ!</Alert>
)}
<Form.Group className="mb-3">
<Form.Label>Numero di telefono</Form.Label>
<Form.Control
type="tel"
placeholder="320xxxxxxx"
required
onChange={(e) => {
setReservation({
...reservation,
phone: e.target.value,
})
}}
value={reservation.phone}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>In quanti siete?</Form.Label>
<Form.Select
aria-label="Default select example"
onChange={(e) => {
setReservation({
...reservation,
numberOfPeople: e.target.value,
})
}}
value={reservation.numberOfPeople}
>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
</Form.Select>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Data / Ora</Form.Label>
<Form.Control
type="datetime-local"
required
onChange={(e) => {
setReservation({
...reservation,
dateTime: e.target.value,
})
}}
value={reservation.dateTime}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Check
type="checkbox"
label="Tavolo fumatori?"
onChange={(e) => {
setReservation({
...reservation,
smoking: e.target.checked,
})
}}
checked={reservation.smoking}
/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Allergie, intolleranze, richieste speciali?</Form.Label>
<Form.Control
as="textarea"
rows={5}
onChange={(e) => {
setReservation({
...reservation,
specialRequests: e.target.value,
})
}}
value={reservation.specialRequests}
/>
</Form.Group>
<Button variant="success" type="submit">
Prenota!
</Button>
</Form>
</>
)
}
export default BookingForm
|
import React, { useContext, useState } from 'react';
import { AuthContext } from '../../contexts/auth';
import { Container, UploadButton, UpLoadText, Avatar,Name,Email,Button,ButtonText,ModalContainer,ButtonBack,Input} from './styles'
import { AntDesign } from '@expo/vector-icons';
import { Modal, Platform } from 'react-native';
import Header from '../../components/Header';
import firebase from '@react-native-firebase/firestore';
import storage from '@react-native-firebase/storage';
import ImagePicker from 'react-native-image-picker'
export default function Profile() {
const { signOut, user, storageUser, setUser} = useContext(AuthContext);
const [url, setUrl] = useState(null);
const [open, setOpen] = useState(null);
const [nome, setNome] = useState(user?.nome)
//update profile
async function updateProfile() {
if(nome === '')
return;
await firebase().collection('users')
.doc(user.uid).update({
nome: nome
})
//find the user post
const postDocs = await firebase().collection('posts')
.where('userId', '==', user.uid).get();
postDocs.forEach(async doc => {
await firebase().collection('posts').doc(doc.id).update({
autor: nome
})
})
let data = {
uid: user.uid,
nome:nome,
email: user.email
};
storageUser(data);
setUser(data);
setOpen(false);
}
const uploadFile = () => {
const options = {
noData: true,
mediaType: 'photo'
};
ImagePicker.launchImageLibrary(options, response => {
console.log(response);
console.log(options);
if(response.didCancel){
console.log('CANCELOU O MODAL.');
}else if(response.error){
console.log('Parece que deu algum erro: ' + response.error);
}else{
uploadFileFirebase(response);
setUrl(response.uri);
}
})
}
// const checkPermissionsAndUpload = async () => {
// const { status } = await PermissionsAndroid.askAsync(PermissionsAndroid.MEDIA_LIBRARY);
// if (status === 'granted') {
// // Permissão concedida, agora você pode chamar o uploadFile
// uploadFile();
// } else {
// // Permissão não concedida
// console.log('Permissão para acessar a galeria foi negada.');
// }
// };
const getFileLocalPath = response => {
const {path, uri} = response;
return Platform.OS === 'android' ? path : uri;
}
const uploadFileFirebase = async response => {
const fileSource = getFileLocalPath(response);
const storageRef = storage().ref('users').child(user?.uid)
return await storageRef.putFile(fileSource);
};
return (
<Container>
<Header />
{
url ?
(
<UploadButton onPress={ uploadFile }>
<UpLoadText>+</UpLoadText>
<Avatar
source={{ uri: url}}
/>
</UploadButton>
):
(
<UploadButton onPress={ uploadFile }>
<UpLoadText>+</UpLoadText>
</UploadButton>
)
}
<Name numberOflines={1}>{ user.nome}</Name>
<Email numberOflines={1}>{ user.email }</Email>
<Button bg="#428cfd" onPress={ () => setOpen(true) }>
<ButtonText color="#FFF">Atualizar perfil</ButtonText>
</Button>
<Button bg="#FFF" onPress={ () => signOut()}>
<ButtonText color="#3b3b3b">Sair</ButtonText>
</Button>
<Modal visible={open} animationType="slide" transparent={true}>
<ModalContainer behavior={ Platform.OS =='android' ? '': 'padding' }>
<ButtonBack onPress={ () => setOpen(false) }>
<AntDesign
name="arrowleft"
size={22}
color="#121212"
/>
<ButtonText color="#121212">Voltar</ButtonText>
</ButtonBack>
<Input
placeholder={user?.nome}
value={nome}
onChangeText={ (text) => setNome(text) }
/>
<Button bg="#428cfd" onPress={ updateProfile }>
<ButtonText color="#f1f1f1">Atualizar</ButtonText>
</Button>
</ModalContainer>
</Modal>
</Container>
);
}
|
<script setup lang="ts">
import { Strategy } from '@/modules/lean/strategy'
import { useSimulationStore } from '@/modules/simulation/simulation-store'
const simulationStore = useSimulationStore()
const strategies: Strategy[] = ['push', 'pull', 'push-dps', 'pull-dps']
</script>
<template>
<div class="simulation-dashboard">
<h3>Dashboard</h3>
<h4>
{{ simulationStore.simulationsDone
}}<span class="sub">/{{ simulationStore.requestedSimulation }}</span>
simulations
</h4>
<table>
<thead>
<tr>
<th>mean values</th>
<th class="numeric">push</th>
<th class="numeric">pull</th>
<th class="numeric">push and DPS</th>
<th class="numeric">pull and DPS</th>
</tr>
</thead>
<tbody>
<tr>
<td>Total days</td>
<td class="numeric" v-for="strategy in strategies" :key="strategy">
{{ simulationStore.meanTotalDays(strategy) }}
</td>
</tr>
<tr>
<td>Lead time</td>
<td class="numeric" v-for="strategy in strategies" :key="strategy">
{{ simulationStore.meanLeadTime(strategy) }}
</td>
</tr>
<tr>
<td>Takt time</td>
<td class="numeric" v-for="strategy in strategies" :key="strategy">
{{ simulationStore.meanTaktTime(strategy) }}
</td>
</tr>
<tr>
<td>Complexity</td>
<td class="numeric" v-for="strategy in strategies" :key="strategy">
{{ simulationStore.meanComplexity(strategy) }}
</td>
</tr>
<tr>
<td>Quality issue</td>
<td class="numeric" v-for="strategy in strategies" :key="strategy">
{{ simulationStore.meanQuality(strategy) }}
</td>
</tr>
<tr>
<td>Team work exp.</td>
<td class="numeric" v-for="strategy in strategies" :key="strategy">
{{ simulationStore.meanTeamWorkExperience(strategy) }}
</td>
</tr>
</tbody>
</table>
</div>
</template>
<style scoped lang="scss">
.simulation-dashboard {
color: var(--primary-color);
width: 100%;
table {
padding: 1rem;
}
}
.numeric {
text-align: right;
}
</style>
|
SYNOPSIS
========
mixed * filter(mixed *arg, string fun, string|object ob, mixed extra...)
mixed * filter(mixed *arg, closure cl, mixed extra... )
mixed * filter(mixed *arg, mapping map, mixed extra... )
string filter(string arg, string fun, string|object ob, mixed extra...)
string filter(string arg, closure cl, mixed extra... )
string filter(string arg, mapping map, mixed extra... )
mapping filter(mapping arg, string func, string|object ob, mixed extra...)
mapping filter(mapping arg, closure cl, mixed extra... )
DESCRIPTION
Call the function `<ob>-><func>()` resp. the closure cl(E) for every
element of the array, or mapping arg(E), and return a result made from
those elements for which the function call returns TRUE. The extra(E)
arguments are passed as additional parameters to the function calls and
must not be references of array of mapping elements (like &(i[1]) ).
If ob(E) is omitted, or neither a string nor an object, it defaults
to `this_object()`.
If arg(E) is an array or struct, the function will be called with each of
the array/struct values as first parameter, followed by the extra(E)
arguments. If the result from the function call is true, the array element
in question is included into the efun result.
If the efun is used with a mapping map(E) instead of a function, every
array element which is key in map(E) is included into the result.
If arg(E) is a mapping, the function will be called with each of the
mapping keys as first, and (if existing) the associated values as second
parameter, followed by the extra(E) arguments. If the result is true, the
mapping element in question is included into the result.
Depending on the width of the mapping arg(E), the function call takes one
of three forms:
widthof(arg) == 0: ob->func(key, 0, extra...)
== 1: ob->func(key, arg[key], extra...)
> 1: ob->func( key
, ({ arg[key,0] ...arg[key,width-1] })
, extra...)
The advantage of this approach is that the two types of multi-dimensional
mappings (mappings with multiple values per key, and mappings of arrays)
can be treated in the same way.
HISTORY
=======
- introduced (3.2.6) -- obsoletes filter_array() for arrays and
filter_indices() with mappings.
- changed (3.3.439) -- adds filtering of strings.
SEE ALSO
========
filter(E), filter_indices(E), map(E), walk_mapping(E), member(E),
m_contains(E)
|
<?php
namespace App\Filament\Pages;
use Filament\Pages\Auth\EditProfile;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Component;
use App\Models\User as Staff;
class MyProfile extends EditProfile
{
protected function getNameFormComponent(): Component
{
return TextInput::make('first_name')
->label('First Name')
->required()
->maxLength(255)
->autofocus();
}
protected function getLastNameFormComponent(): Component
{
return TextInput::make('last_name')
->label('Last Name')
->required()
->maxLength(255);
}
protected function getPhoneNumberFormComponent(): Component
{
return \Ysfkaya\FilamentPhoneInput\Forms\PhoneInput::make('phone_number')
->label('Phone Number')
->unique(Staff::class, 'phone_number', ignoreRecord: true)
->required();
}
protected function getForms(): array
{
return [
'form' => $this->form(
$this->makeForm()
->schema([
$this->getNameFormComponent(),
$this->getLastNameFormComponent(),
$this->getEmailFormComponent(),
$this->getPhoneNumberFormComponent(),
$this->getPasswordFormComponent(),
$this->getPasswordConfirmationFormComponent(),
])
->columns(2)
->operation('edit')
->model($this->getUser())
->statePath('data')
),
];
}
}
|
import {useState, useEffect} from "react";
import {useRates} from './useRates';
import {Block, TBlockProps} from './Block';
function App() {
const [fromCurrency, setFromCurrency] = useState('UAH')
const [toCurrency, setToCurrency] = useState('USD')
const [fromPrice, setFromPrice] = useState(0)
const [toPrice, setToPrice] = useState(0)
const rates = useRates()
const hasRates = Object.keys(rates).length > 0
useEffect(() => {
if(hasRates) {
const result = toPrice * rates[toCurrency] / rates[fromCurrency]
setFromPrice(result)
}
}, [fromCurrency])
useEffect(() => {
if(hasRates) {
const result = fromPrice * rates[fromCurrency] / rates[toCurrency]
setToPrice(result)
}
}, [toCurrency])
const onChangeFromPrice:TBlockProps['onChangePrice'] = (price) => {
const result = price * rates[fromCurrency] / rates[toCurrency]
setFromPrice(price)
setToPrice(result)
}
const onChangeToPrice:TBlockProps['onChangePrice'] = (price) => {
const result = price * rates[toCurrency] / rates[fromCurrency]
setToPrice(price)
setFromPrice(result)
}
return (
<div className="App">
<header className="App-header">
<div>USD: {rates['USD']}</div>
<div>EUR: {rates['EUR']}</div>
</header>
<div className="content">
<Block
price={fromPrice}
currency={fromCurrency}
onChangePrice={onChangeFromPrice}
onChangeCurrency={setFromCurrency}
/>
<Block
price={toPrice}
currency={toCurrency}
onChangePrice={onChangeToPrice}
onChangeCurrency={setToCurrency}
/>
</div>
</div>
);
}
export default App;
|
// ignore: depend_on_referenced_packages
import 'package:flutter/material.dart';
import 'package:yourself_in_time_project/common/widgets/comment.dart';
class TestMe extends StatefulWidget {
@override
_TestMeState createState() => _TestMeState();
}
class _TestMeState extends State<TestMe> {
final formKey = GlobalKey<FormState>();
final TextEditingController commentController = TextEditingController();
List filedata = [
{
'name': 'Osman Ergin',
'pic': 'https://picsum.photos/300/30',
'message': 'Programına bayıldım',
'date': '2021-01-01 12:00:00'
},
{
'name': 'Nedim Keskin',
'pic': 'https://www.adeleyeayodeji.com/img/IMG_20200522_121756_834_2.jpg',
'message': 'Çok cool adamım',
'date': '2021-01-01 12:00:00'
},
{
'name': 'Taner Yoldas',
'pic': 'assets/images/user1.png',
'message': 'Very cool',
'date': '2021-01-01 12:00:00'
},
{
'name': 'Hasan Ekim',
'pic': 'https://picsum.photos/300/30',
'message': 'Bayıldım.Tebrikler',
'date': '2021-01-01 12:00:00'
},
];
Widget commentChild(data) {
return ListView(
children: [
for (var i = 0; i < data.length; i++)
Padding(
padding: const EdgeInsets.fromLTRB(2.0, 8.0, 2.0, 0.0),
child: ListTile(
leading: GestureDetector(
onTap: () async {
// Display the image in large form.
print("Comment Clicked");
},
child: Container(
height: 50.0,
width: 50.0,
decoration: new BoxDecoration(
color: Colors.blue,
borderRadius: new BorderRadius.all(Radius.circular(50))),
child: CircleAvatar(
radius: 50,
backgroundImage: CommentBox.commentImageParser(
imageURLorPath: data[i]['pic'])),
),
),
title: Text(
data[i]['name'],
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: Text(data[i]['message']),
trailing: Text(data[i]['date'], style: TextStyle(fontSize: 10)),
),
)
],
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Comment Page"),
backgroundColor: Colors.pink,
),
body: Container(
child: CommentBox(
userImage: CommentBox.commentImageParser(
imageURLorPath: "assets/images/user1.png"),
child: commentChild(filedata),
labelText: 'Write a comment...',
errorText: 'Comment cannot be blank',
withBorder: false,
sendButtonMethod: () {
if (formKey.currentState!.validate()) {
print(commentController.text);
setState(() {
var value = {
'name': 'New User',
'pic':
'https://lh3.googleusercontent.com/a-/AOh14GjRHcaendrf6gU5fPIVd8GIl1OgblrMMvGUoCBj4g=s400',
'message': commentController.text,
'date': '2021-01-01 12:00:00'
};
filedata.insert(0, value);
});
commentController.clear();
FocusScope.of(context).unfocus();
} else {
print("Not validated");
}
},
formKey: formKey,
commentController: commentController,
backgroundColor: Colors.pink,
textColor: Colors.white,
sendWidget: Icon(Icons.send_sharp, size: 30, color: Colors.white),
),
),
);
}
}
|
<%@ page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%-- Using Struts2 Tags in JSP --%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ taglib prefix="sb" uri="/struts-bootstrap-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Document Upload</title>
<s:head />
<sb:head />
<link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>
<s:include value="/include/navbar.jsp"></s:include>
<div class="container">
<h2 class="page-header">
<s:if test="document.name==null || document.name==''">Upload Document</s:if>
<s:else>Edit Document</s:else>
</h2>
<s:form action="saveDocument" method="post"
enctype="multipart/form-data" theme="bootstrap"
cssClass="form-horizontal">
<s:if test="document.name==null || document.name==''">
<s:file name="doc" label="Document" required="true" />
</s:if>
<s:else>
<s:hidden name="docFileName" value="%{document.name}" />
<s:textfield value="%{document.name}" disabled="true"
label="Document" />
</s:else>
<s:push value="document">
<s:hidden name="id" />
<s:select name="privacyId" label="File Privacy"
list="#{'1':'Public', '2':'Private', '3':'Draft'}" required="true" />
<s:select name="ownerId" list="userList" listKey="id"
listValue="name" headerKey="" headerValue="Select"
label="File Owner" required="true" />
<s:select name="groupId" list="userGroupList" listKey="id"
listValue="name" headerKey="" headerValue="Select"
label="User Group" required="true" />
<s:textarea name="description" label="Description" cols="20"
rows="3" />
<s:submit cssClass="btn btn-lg btn-success pull-right" />
</s:push>
</s:form>
</div>
</body>
</html>
|
#include "main.h"
/**
* _print_rev_recursion - Recursive function that prints a string in reverse
* @s: This is the string to be reversed
* Return: void
*/
void _print_rev_recursion(char *s)
{
if (*s != '\0')
{
_print_rev_recursion(s + 1);
_putchar(*s);
}
}
|
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { ChannelController } from 'src/channel/channel.controller';
import { AllExceptionsFilter } from 'src/common/exception.filter';
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
import { HealthController } from '@/health/health.controller';
import { HealthModule } from '@/health/health.module';
import { TerminusModule } from '@nestjs/terminus';
import { HttpModule } from '@nestjs/axios';
import { LoggerService } from '@/logger/logger.service';
import { LoggerProvider } from '@/logger/logger.provider';
console.log("ETE"+LoggerProvider['useFactory']);
@Module({
imports: [
PrometheusModule.register({
path: '/teams-integrator/mgmt/prometheus',
defaultMetrics: {
enabled: false,
},
}),
HealthModule,
TerminusModule,
HttpModule,
],
providers: [
LoggerProvider,
LoggerService,
{
provide: APP_FILTER,
useClass: AllExceptionsFilter,
},
],
controllers: [ChannelController, HealthController],
})
export class AppModule {}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Add New Comment</title>
</head>
<body>
<h1>Please add your comment</h1>
<div>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Blanditiis,
vel, tempore corporis est quas magnam officia nesciunt molestias a
praesentium consequatur nulla atque repellat iste sunt voluptatum
molestiae asperiores! Culpa provident deleniti hic fugit repudiandae
exercitationem minus magni explicabo. Veniam molestiae possimus eos
expedita temporibus nulla similique nisi iste libero.
</p>
<p>
Assumenda doloremque sint voluptates ex ducimus, quidem reprehenderit
facere ipsum, labore voluptatibus commodi officiis? Velit praesentium
sed aut ipsa voluptatum dicta laboriosam rem officiis nemo? Error
placeat ipsum qui. Iste quas repudiandae sit inventore nobis quam
molestias doloribus nostrum laboriosam, dignissimos exercitationem
quidem maxime fuga dolor eum ut ad facere.
</p>
<p id="comment-container">
Impedit facere aliquam ratione molestias ex, quod corporis excepturi
voluptatibus eaque nulla est provident consequuntur temporibus minus
veniam ducimus sed, porro officiis nobis numquam? Officia similique, rem
aliquam nostrum dolore hic nam repellat eius repellendus fugit sapiente
sit debitis aut voluptas. Sapiente et fugiat possimus quam
exercitationem soluta voluptatibus minima?
</p>
</div>
<div>
<textarea name="" id="new-comment" cols="60" rows="5"></textarea>
<br />
<button id="btn-post">Post</button>
</div>
<script>
// step-1: add event listener to the post button
document
.getElementById("btn-post")
.addEventListener("click", function () {
// step-2: get the comment
const commentBox = document.getElementById("new-comment");
const newComment = commentBox.value;
// step-3: set the comment inside the comment container
// 1. get the comment container
// 2. create a new element
// 3. set the text of the comment as innerText of the p tag
// 4. add the p tag using appendChild()
const commentContainer = document.getElementById("comment-container");
const p = document.createElement("p");
p.innerText = newComment;
commentContainer.appendChild(p);
commentBox.value = "";
// step-4
});
</script>
</body>
</html>
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ANDROID_IPOWERMANAGER_H
#define ANDROID_IPOWERMANAGER_H
#include <utils/Errors.h>
#include <binder/IInterface.h>
#include <hardware/power.h>
namespace android {
// ----------------------------------------------------------------------------
class IPowerManager : public IInterface
{
public:
// These transaction IDs must be kept in sync with the method order from
// IPowerManager.aidl.
enum {
ACQUIRE_WAKE_LOCK = IBinder::FIRST_CALL_TRANSACTION,
ACQUIRE_WAKE_LOCK_UID = IBinder::FIRST_CALL_TRANSACTION + 1,
RELEASE_WAKE_LOCK = IBinder::FIRST_CALL_TRANSACTION + 2,
UPDATE_WAKE_LOCK_UIDS = IBinder::FIRST_CALL_TRANSACTION + 3,
POWER_HINT = IBinder::FIRST_CALL_TRANSACTION + 4,
UPDATE_WAKE_LOCK_SOURCE = IBinder::FIRST_CALL_TRANSACTION + 5,
IS_WAKE_LOCK_LEVEL_SUPPORTED = IBinder::FIRST_CALL_TRANSACTION + 6,
USER_ACTIVITY = IBinder::FIRST_CALL_TRANSACTION + 7,
WAKE_UP = IBinder::FIRST_CALL_TRANSACTION + 8,
GO_TO_SLEEP = IBinder::FIRST_CALL_TRANSACTION + 9,
NAP = IBinder::FIRST_CALL_TRANSACTION + 10,
IS_INTERACTIVE = IBinder::FIRST_CALL_TRANSACTION + 11,
IS_POWER_SAVE_MODE = IBinder::FIRST_CALL_TRANSACTION + 12,
GET_POWER_SAVE_STATE = IBinder::FIRST_CALL_TRANSACTION + 13,
SET_POWER_SAVE_MODE = IBinder::FIRST_CALL_TRANSACTION + 14,
REBOOT = IBinder::FIRST_CALL_TRANSACTION + 17,
REBOOT_SAFE_MODE = IBinder::FIRST_CALL_TRANSACTION + 18,
SHUTDOWN = IBinder::FIRST_CALL_TRANSACTION + 19,
CRASH = IBinder::FIRST_CALL_TRANSACTION + 20,
};
DECLARE_META_INTERFACE(PowerManager)
// The parcels created by these methods must be kept in sync with the
// corresponding methods from IPowerManager.aidl.
// FIXME remove the bool isOneWay parameters as they are not oneway in the .aidl
virtual status_t acquireWakeLock(int flags, const sp<IBinder>& lock, const String16& tag,
const String16& packageName, bool isOneWay = false) = 0;
virtual status_t acquireWakeLockWithUid(int flags, const sp<IBinder>& lock, const String16& tag,
const String16& packageName, int uid, bool isOneWay = false) = 0;
virtual status_t releaseWakeLock(const sp<IBinder>& lock, int flags, bool isOneWay = false) = 0;
virtual status_t updateWakeLockUids(const sp<IBinder>& lock, int len, const int *uids,
bool isOneWay = false) = 0;
virtual status_t powerHint(int hintId, int data) = 0;
virtual status_t goToSleep(int64_t event_time_ms, int reason, int flags) = 0;
virtual status_t reboot(bool confirm, const String16& reason, bool wait) = 0;
virtual status_t shutdown(bool confirm, const String16& reason, bool wait) = 0;
virtual status_t crash(const String16& message) = 0;
};
// ----------------------------------------------------------------------------
}; // namespace android
#endif // ANDROID_IPOWERMANAGER_H
|
# DESTEIN: Navigating Detoxification of Language Models via Universal Steering Pairs and Head-wise Activation Fusion
This repository contains code for the paper "DESTEIN: Navigating Detoxification of Language Models via Universal Steering Pairs and Head-wise Activation Fusion".
# Setup
Please use the command below to setup the environment needed.
```
conda create -n destein python=3.10
conda activate destein
pip install -r requirements.txt
```
# Data
To maintain the timeliness of the results, we used the [Perspective API](https://github.com/conversationai/perspectiveapi/tree/master/1-get-started) to rescore the toxicity of [Realtoxicityprompts](https://allenai.org/data/real-toxicity-prompts). Simultaneously, we sampled toxic (>=0.5) and non-toxic (<0.5) data as the test set, which are located in the ```./data/RealToxicityPrompts``` folder.
The folder ```./data/act``` contains pre-calculated steering vectors and probe detection results. If you want to replicate the results in the paper, you can apply them directly.
# Detoxification
To generate continuations with DESTEIN and score them for toxicity using the PerspectiveAPI toxicity scorer, run the following command.
```
API_RATE=50
OUTPUT_DIR=generations/results/gpt2-large/test
export CUDA_VISIBLE_DEVICES="4"
python -m run_toxicity_experiment \
--dataset-file data/RealToxicityPrompts/100/test.jsonl \
--model-type gpt2-act \
--model "/nfs-data/user30/model/gpt2-large" \
--tokenizer "/nfs-data/user30/model/gpt2-large" \
--perspective-rate-limit $API_RATE \
--p 0.9 \
--count 20 \
--alpha 0.45 \
--batch-size 25 \
--n 25\
--seed 42 \
$OUTPUT_DIR
```
In general, model_type is one of the base models(gpt2, llama2) and our methods(gpt2-act, llama2-act, opt-act, mpt-act). Different methods have different additional parameters to specify. For details, please refer to our paper.
This script will create three files in OUTPUT_DIR: generations.jsonl with all of the generated continuations, perspective.jsonl with all the scores from Perspective API, and prompted_gens_[model_type].jsonl, which collates the previous two files.
# Evaluation
To evaluate generated output for fluency and diversity, run the following command. The "generations_file" should have the format prompted_gens_[model_type].jsonl.
```
python -m eval.evaluate_generations \
--generations_file $1
```
# Citation
```
@misc{li2024destein,
title={DESTEIN: Navigating Detoxification of Language Models via Universal Steering Pairs and Head-wise Activation Fusion},
author={Yu Li and Zhihua Wei and Han Jiang and Chuanyang Gong},
year={2024},
eprint={2404.10464},
archivePrefix={arXiv},
primaryClass={cs.CL}
}
```
|
import plus from '../../../utils/svg/plus.svg';
import circle from '../../../utils/svg/circle.svg';
import React, { useState } from 'react';
import Styles from './AddStep.module.scss';
import { selectedTodo } from '../../../atoms/selectedTodoAtom';
import { useRecoilValue } from 'recoil';
import axios from '../../../axios';
import { todoBody } from '../../../utils/types';
import { useSetTaskFromTaskDetails } from '../../../utils/customHooks/useUpdateTaskFromTaskDetails';
import { useSetNotification } from '../../../utils/customHooks/useAddNotification';
import { timeMessageObjCreate } from '../../../utils/helperFunction/timeoutMessage';
function AddTodo() {
const [textFocus, setTextFocus] = useState(false);
const [inputText, setInputText] = useState('');
const todo = useRecoilValue(selectedTodo);
const updateTaskFromDetails = useSetTaskFromTaskDetails();
const { addNotification } = useSetNotification();
function inputFocusHandler() {
setTextFocus(true);
}
function inputBlurHandler() {
setTextFocus(false);
}
function inputChangeHandler(e: React.ChangeEvent<HTMLInputElement>) {
setInputText(e.target.value);
}
function enterHandler(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === 'Enter') {
addTodoHandler();
}
}
async function addTodoHandler() {
try {
if (window.navigator.onLine) {
const res = await axios.post<todoBody>(
'/api/step/new',
{
todoId: todo?.id,
stepTitle: inputText.trim(),
},
timeMessageObjCreate('Unable to add step todo'),
);
if (res.status === 200 && todo) {
updateTaskFromDetails(todo, res.data, 'todoBody');
setInputText('');
}
} else {
throw new Error('No internet connection');
}
} catch (e) {
addNotification(e.message, 'Network Error');
}
}
return (
<div
className={
textFocus
? [Styles.container, Styles.containerFocused].join(' ')
: Styles.container
}
>
<div className={Styles.plusContainer}>
<img
src={textFocus ? circle : plus}
alt='add svg'
className={Styles.plus}
/>
</div>
<input
type='text'
placeholder={'Add Step'}
className={Styles.input}
onFocus={inputFocusHandler}
onBlur={inputBlurHandler}
value={inputText}
onChange={inputChangeHandler}
onKeyPress={enterHandler}
/>
{inputText.length > 0 ? (
<div className={Styles.addButton} onClick={addTodoHandler}>
Add
</div>
) : null}
</div>
);
}
export default AddTodo;
|
CREATE OR REPLACE PROCEDURE criar_pedido(
idCliente IN NUMBER,
idProduto IN NUMBER,
quantidade IN NUMBER,
data_pedido IN DATE
)
IS
qtd_estoque NUMBER;
preco_produto NUMBER;
BEGIN
-- Verifica se o produto está em estoque na quantidade desejada
SELECT quantidade_estoque, preco
INTO qtd_estoque, preco_produto
FROM produtos
WHERE id = idProduto;
IF qtd_estoque >= quantidade THEN
-- Cria um novo registro na tabela Pedidos com os detalhes do pedido:
INSERT INTO pedidos (id, id_cliente, id_produto, data_pedido, quantidade, status_pedido, valor_total)
VALUES (seq_id_pedido.nextval, idCliente, idProduto, data_pedido, quantidade, 'Em Processamento', (quantidade*preco_produto));
-- Atualiza o estoque do produto:
UPDATE produtos
SET quantidade_estoque = qtd_estoque - quantidade
WHERE id = idProduto;
DBMS_OUTPUT.PUT_LINE('Pedido criado com sucesso!');
COMMIT;
ELSE
DBMS_OUTPUT.PUT_LINE('Produto fora de estoque.');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Produto não existe');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Erro: ' || SQLCODE || ' - ' || SQLERRM);
END;
|
# Indexing documents for the Chat App
This guide provides more details for using the `prepdocs` script to index documents for the Chat App.
- [Overview of the manual indexing process](#overview-of-the-manual-indexing-process)
- [Chunking](#chunking)
- [Indexing additional documents](#indexing-additional-documents)
- [Removing documents](#removing-documents)
- [Overview of Integrated Vectorization](#overview-of-integrated-vectorization)
- [Indexing of additional documents](#indexing-of-additional-documents)
- [Removal of documents](#removal-of-documents)
- [Scheduled indexing](#scheduled-indexing)
## Overview of the manual indexing process
The `scripts/prepdocs.py` script is responsible for both uploading and indexing documents. The typical usage is to call it using `scripts/prepdocs.sh` (Mac/Linux) or `scripts/prepdocs.ps1` (Windows), as these scripts will set up a Python virtual environment and pass in the required parameters based on the current `azd` environment. Whenever `azd up` or `azd provision` is run, the script is called automatically.

The script uses the following steps to index documents:
1. If it doesn't yet exist, create a new index in Azure AI Search.
2. Upload the PDFs to Azure Blob Storage.
3. Split the PDFs into chunks of text.
4. Upload the chunks to Azure AI Search. If using vectors (the default), also compute the embeddings and upload those alongside the text.
### Chunking
We're often asked why we need to break up the PDFs into chunks when Azure AI Search supports searching large documents.
Chunking allows us to limit the amount of information we send to OpenAI due to token limits. By breaking up the content, it allows us to easily find potential chunks of text that we can inject into OpenAI. The method of chunking we use leverages a sliding window of text such that sentences that end one chunk will start the next. This allows us to reduce the chance of losing the context of the text.
If needed, you can modify the chunking algorithm in `scripts/prepdocslib/textsplitter.py`.
### Indexing additional documents
To upload more PDFs, put them in the data/ folder and run `./scripts/prepdocs.sh` or `./scripts/prepdocs.ps1`.
A [recent change](https://github.com/Azure-Samples/azure-search-openai-demo/pull/835) added checks to see what's been uploaded before. The prepdocs script now writes an .md5 file with an MD5 hash of each file that gets uploaded. Whenever the prepdocs script is re-run, that hash is checked against the current hash and the file is skipped if it hasn't changed.
### Removing documents
You may want to remove documents from the index. For example, if you're using the sample data, you may want to remove the documents that are already in the index before adding your own.
To remove all documents, use the `--removeall` flag. Open either `scripts/prepdocs.sh` or `scripts/prepdocs.ps1` and add `--removeall` to the command at the bottom of the file. Then run the script as usual.
You can also remove individual documents by using the `--remove` flag. Open either `scripts/prepdocs.sh` or `scripts/prepdocs.ps1`, add `--remove` to the command at the bottom of the file, and replace `/data/*` with `/data/YOUR-DOCUMENT-FILENAME-GOES-HERE.pdf`. Then run the script as usual.
## Overview of Integrated Vectorization
Azure AI search recently introduced an [integrated vectorization feature in preview mode](https://techcommunity.microsoft.com/t5/ai-azure-ai-services-blog/announcing-the-public-preview-of-integrated-vectorization-in/ba-p/3960809#:~:text=Integrated%20vectorization%20is%20a%20new%20feature%20of%20Azure,pull-indexers%2C%20and%20vectorization%20of%20text%20queries%20through%20vectorizers). This feature is a cloud-based approach to data ingestion, which takes care of document format cracking, data extraction, chunking, vectorization, and indexing, all with Azure technologies.
See [this notebook](https://github.com/Azure/azure-search-vector-samples/blob/main/demo-python/code/azure-search-integrated-vectorization-sample.ipynb) to understand the process of setting up integrated vectorization.
We have integrated that code into our `prepdocs` script, so you can use it without needing to understand the details.
This feature cannot be used on existing index. You need to create a new index or drop and recreate an existing index.
In the newly created index schema, a new field 'parent_id' is added. This is used internally by the indexer to manage life cycle of chunks.
This feature is not supported in the free SKU for Azure AI Search.
### Indexing of additional documents
To add additional documents to the index, first upload them to your data source (Blob storage, by default).
Then navigate to the Azure portal, find the index, and run it.
The Azure AI Search indexer will identify the new documents and ingest them into the index.
### Removal of documents
To remove documents from the index, remove them from your data source (Blob storage, by default).
Then navigate to the Azure portal, find the index, and run it.
The Azure AI Search indexer will take care of removing those documents from the index.
### Scheduled indexing
If you would like the indexer to run automatically, you can set it up to [run on a schedule](https://learn.microsoft.com/azure/search/search-howto-schedule-indexers).
|
package serialize
import (
"github.com/aquasecurity/trivy-db/pkg/types"
)
type StringSlice []string
type AnalysisResult struct {
// TODO: support other fields as well
// OS *types.OS
// Repository *types.Repository
// PackageInfos []types.PackageInfo
// Applications []types.Application
// Secrets []types.Secret
// SystemInstalledFiles []string // A list of files installed by OS package manager
// Currently it supports custom resources only
CustomResources []CustomResource
}
type CustomResource struct {
Type string
FilePath string
Data any
}
type PostScanAction string
type PostScanSpec struct {
// What action the module will do in post scanning.
// value: INSERT, UPDATE and DELETE
Action PostScanAction
// IDs represent which vulnerability and misconfiguration ID will be updated or deleted in post scanning.
// When the action is UPDATE, the matched result will be passed to the module.
IDs []string
}
type Results []Result
// Result re-defines the Result struct from 'pkg/types/' so TinyGo can compile the code.
// See https://github.com/aquasecurity/trivy/issues/6654 for more details.
type Result struct {
Target string `json:"Target"`
Class string `json:"Class,omitempty"`
Type string `json:"Type,omitempty"`
Vulnerabilities []DetectedVulnerability `json:"Vulnerabilities,omitempty"`
CustomResources []CustomResource `json:"CustomResources,omitempty"`
}
type DetectedVulnerability struct {
VulnerabilityID string `json:",omitempty"`
VendorIDs []string `json:",omitempty"`
PkgID string `json:",omitempty"`
PkgName string `json:",omitempty"`
PkgPath string `json:",omitempty"`
InstalledVersion string `json:",omitempty"`
FixedVersion string `json:",omitempty"`
Status types.Status `json:",omitempty"`
Layer Layer `json:",omitempty"`
SeveritySource types.SourceID `json:",omitempty"`
PrimaryURL string `json:",omitempty"`
// DataSource holds where the advisory comes from
DataSource *types.DataSource `json:",omitempty"`
// Custom is for extensibility and not supposed to be used in OSS
Custom any `json:",omitempty"`
// Embed vulnerability details
types.Vulnerability
}
type DetectedMisconfiguration struct {
Type string `json:",omitempty"`
ID string `json:",omitempty"`
AVDID string `json:",omitempty"`
Title string `json:",omitempty"`
Description string `json:",omitempty"`
Message string `json:",omitempty"`
Namespace string `json:",omitempty"`
Query string `json:",omitempty"`
Resolution string `json:",omitempty"`
Severity string `json:",omitempty"`
PrimaryURL string `json:",omitempty"`
References []string `json:",omitempty"`
Status string `json:",omitempty"`
Layer Layer `json:",omitempty"`
CauseMetadata CauseMetadata `json:",omitempty"`
// For debugging
Traces []string `json:",omitempty"`
}
type CauseMetadata struct {
Resource string `json:",omitempty"`
Provider string `json:",omitempty"`
Service string `json:",omitempty"`
StartLine int `json:",omitempty"`
EndLine int `json:",omitempty"`
Code Code `json:",omitempty"`
Occurrences []Occurrence `json:",omitempty"`
}
type Occurrence struct {
Resource string `json:",omitempty"`
Filename string `json:",omitempty"`
Location Location
}
type Location struct {
StartLine int `json:",omitempty"`
EndLine int `json:",omitempty"`
}
type Code struct {
Lines []Line
}
type Line struct {
Number int `json:"Number"`
Content string `json:"Content"`
IsCause bool `json:"IsCause"`
Annotation string `json:"Annotation"`
Truncated bool `json:"Truncated"`
Highlighted string `json:"Highlighted,omitempty"`
FirstCause bool `json:"FirstCause"`
LastCause bool `json:"LastCause"`
}
type Layer struct {
Digest string `json:",omitempty"`
DiffID string `json:",omitempty"`
CreatedBy string `json:",omitempty"`
}
|
import { CommonPlatformFeeSchema } from "../../schema";
import { DetectableFeature } from "../interfaces/DetectableFeature";
import { TransactionResult } from "../types";
import { ContractWrapper } from "./contract-wrapper";
import type { IPlatformFee } from "@thirdweb-dev/contracts-js";
import { z } from "zod";
/**
* Handle platform fees and recipients
* @remarks Configure platform fees for a contract, which can be applied on certain paid transactions
* @example
* ```javascript
* const contract = await sdk.getContract("{{contract_address}}");
* const feeInfo = await contract.platformFee.get();
* await contract.platformFee.set({
* platform_fee_basis_points: 100, // 1% fee
* platform_fee_recipient: "0x..." // the fee recipient
* })
* ```
* @public
*/
export declare class ContractPlatformFee<TContract extends IPlatformFee> implements DetectableFeature {
featureName: "PlatformFee";
private contractWrapper;
constructor(contractWrapper: ContractWrapper<TContract>);
/**
* Get the platform fee recipient and basis points
* * @example
* ```javascript
* const feeInfo = await contract.platformFee.get();
* ```
* @twfeature PlatformFee
*/
get(): Promise<{
platform_fee_basis_points: number;
platform_fee_recipient: string;
}>;
/**
* Set the platform fee recipient and basis points
* @param platformFeeInfo - the platform fee information
* ```javascript
* await contract.platformFee.set({
* platform_fee_basis_points: 100, // 1% fee
* platform_fee_recipient: "0x..." // the fee recipient
* })
* ```
* @twfeature PlatformFee
*/
set(platformFeeInfo: z.input<typeof CommonPlatformFeeSchema>): Promise<TransactionResult>;
}
//# sourceMappingURL=contract-platform-fee.d.ts.map
|
package graph;// Multi Source shortest path algorithm
// we wil store the graph in 2d array/adj matrix instead of adj list
// we will be building a cost matrix , where cost to reach self is 0
//Negative cycle: If the cost of reaching
import java.util.Arrays;
//matrix[i][j] =min(matrix[i][j], matrix[i ][k]+matrix[k][j]), where i = source node,
// j = destination node and k = the node via which we are reaching from i to j.
// first loop = pick k
// 2 nested loop to pick i and j so we can check matrix[i][j] = min(matrix[i][j], matrix[i ][k]+matrix[k][j])
public class FloydWarshal {
public static void main(String[] args) {
int V = 4;
int[][] matrix = new int[V][V];
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
matrix[i][j] = -1;
}
}
matrix[0][1] = 2;
matrix[1][0] = 1;
matrix[1][2] = 3;
matrix[3][0] = 3;
matrix[3][1] = 5;
matrix[3][2] = 4;
FloydWarshal obj = new FloydWarshal();
obj.shortest_distance(matrix);
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
private void shortest_distance(int[][] matrix) {
int n = matrix.length;
//matrix initialization
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(matrix[i][j] == -1){
matrix[i][j] = (int)(1e9);
}
if(i==j)
matrix[i][j] = 0; // for diagonals
}
}
System.out.println(Arrays.deepToString(matrix));
//main logic
for(int k=0;k<n;k++){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
matrix[i][j] = Math.min(matrix[i][j], matrix[i][k]+matrix[k][j]);
}
}
}
// if any max value replace to -1
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == (int)(1e9))
matrix[i][j] = -1;
}
}
}
}
// time = v^3 (for 3 nested loop)
//space = adj matrix store in 2d array = v^2
|
package http
import (
"bytes"
"github.com/ilhame90/gymshark-task/internal/config"
"github.com/ilhame90/gymshark-task/internal/domain/mocks"
"github.com/ilhame90/gymshark-task/internal/models"
"net/http"
"net/http/httptest"
"testing"
"github.com/golang/mock/gomock"
"github.com/labstack/echo/v4"
"github.com/stretchr/testify/require"
)
func TestPostOrders(t *testing.T) {
testCases := []struct {
name string
body []byte
buildStubs func(usecase *mocks.MockUsecase)
checkResponse func(recorder *httptest.ResponseRecorder)
}{
{
name: "OK",
body: []byte(`{"ordered_items": 1}`),
buildStubs: func(uc *mocks.MockUsecase) {
uc.EXPECT().NumberOfPacks(gomock.Any(), gomock.Eq(1)).Times(1).Return([]models.Pack{{Name: 250, Quantity: 1}})
},
checkResponse: func(recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusOK, recorder.Code)
//requireBodyMatchAccount(t, recorder.Body, respAccount)
},
},
{
name: "Invalid order",
body: []byte(`"ordered_items":-1`),
buildStubs: func(uc *mocks.MockUsecase) {
uc.EXPECT().NumberOfPacks(gomock.Any(), gomock.Any()).Times(0)
},
checkResponse: func(recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusBadRequest, recorder.Code)
},
},
}
for i := range testCases {
tc := testCases[i]
t.Run(tc.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
uc := mocks.NewMockUsecase(ctrl)
tc.buildStubs(uc)
rec := httptest.NewRecorder()
e := echo.New()
grp := e.Group("/v1")
cfg := &config.Config{}
handler := NewOrdersHandler(cfg, uc)
RegisterHandlers(grp, handler)
req := httptest.NewRequest(http.MethodPost, "/v1/orders", bytes.NewReader(tc.body))
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
e.ServeHTTP(rec, req)
tc.checkResponse(rec)
})
}
}
// func requireBodyMatchAccount(t *testing.T, body *bytes.Buffer, account Account) {
// data, err := ioutil.ReadAll(body)
// require.NoError(t, err)
// var gotAccount Account
// err = json.Unmarshal(data, &gotAccount)
// require.NoError(t, err)
// require.Equal(t, account.Id, gotAccount.Id)
// require.Equal(t, account.Currency, gotAccount.Currency)
// require.Equal(t, account.Balance, gotAccount.Balance)
// }
// func requireBodyMatchBalance(t *testing.T, body *bytes.Buffer, balance BalanceResponse) {
// data, err := ioutil.ReadAll(body)
// require.NoError(t, err)
// var gotBalance BalanceResponse
// err = json.Unmarshal(data, &gotBalance)
// require.NoError(t, err)
// require.Equal(t, balance, gotBalance)
// }
|
const express = require('express')
const router = express.Router()
/* NYHEDS MODELLEN */
const Detsker = require('../models/detsker.model')
/* const formData = require('express-form-data')
router.use(formData.parse()) */
/* MULTER */
const multer = require('multer')
const upload = multer({
storage: multer.diskStorage({
destination: function (request, response, cb) {
cb(null, 'public/images/detsker')
},
filename: function (request, file, cb) {
cb(null, file.originalname)
}
})
})
/* GET /*ALL */
/* router.get('/', async (request, response) => {
try {
return response.status(200).json({
ok: "Det sker endpoint"
})
} catch (error) {
return response.status(400).json({
error: `GET: -> ${error.message}`
})
}
}) */
router.get('/', async (request, response) => {
try {
let allDetsker = await Detsker.find();
return response.status(200).json({
ok: "Det sker endpoint",
detskere: allDetsker
});
} catch (error) {
return response.status(400).json({
error: `GET: -> ${error.message}`
});
}
});
/* GET - SELECTED */
router.get('/:id', async (request, response) => {
let detsker = await Detsker.findById(request.params.id)
return response.status(200).json({
images: detsker
})
})
/* POST */
router.post('/', upload.single("image"), async (request, response) => {
console.log('-> POST REQUEST')
try {
let detsker = new Detsker(request.body)
detsker.image = request.file ? request.file.filename : null
await detsker.save()
return response.status(201).json({
message: "SUCCESS: -> Nyt DB element blev oprettet",
created: detsker
})
} catch (error) {
return response.status(400).json({
message: `-> Der skete en fejl i oprettelsen ${error.message}`
})
}
})
/* PUT */
router.put('/:id', upload.single("image"), async (request, response) => {
try {
if (request.file) {
request.body.image = request.file.filename
}
let detsker = await Detsker.findByIdAndUpdate({
_id: request.params.id
},
request.body,
{
new: true
})
if (detsker == null) {
return response.status(404).json({
message: `-> ${request.params.id}`,
updated: null
})
}
return response.status(201).json({
message: "Content blev rettet",
updated: detsker
})
} catch (error) {
return response.status(400).json({
message: `-> ${error.message}`
})
}
})
/* DELETE */
router.delete('/:id', async (request, response) => {
try {
let detsker = await Detsker.findByIdAndDelete(request.params.id)
if (detsker == null) {
return response.status(404).json({
deleted: null,
message: "-> Dette event fandes ikke og kunne ikke blive slettet"
})
}
return res.status(200).json({
deleted: detsker,
message: `-> ${request.body} blev slettet`
})
} catch (error) {
return response.status(400).json({
deleted: null,
message: `-> ${error.message}`
})
}
})
module.exports = router
|
import React from 'react'
import { useParams } from 'react-router-dom'
import '../styles/pages/fichelogement.css'
import Logements from '../data/fiches_logement.json'
import LogementSlideShow from '../components/logementSlideShow'
import LogementHeader from '../components/logementHeader'
import LogementDescription from '../components/logementDescription'
import Erreur from './erreur'
function Fichelogement() {
// Retrieve the id of the current Apartment
const idLogement = useParams("id").id
// include in a table "currentApartment" only apartment with the id retrieved above
const currentApartment = Logements.filter(item => item.id === idLogement);
// if no apartment in the table "currentApartment", call component "Erreur"
if (currentApartment.length === 0) {
return (
<Erreur />
)
}
return (
// call the 3 components to build the "fichelogement"
<div className="ficheLogement">
<LogementSlideShow pictures={currentApartment[0].pictures} numberPhotos={currentApartment[0].pictures.length} />
<LogementHeader currentApartment={currentApartment[0]} />
<LogementDescription currentApartment={currentApartment[0]} />
</div>
)
}
export default Fichelogement
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Form Input Types & Attributes</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Form Input Types & Attributes</h1>
<h2>Input Types</h2>
<form autocomplete="on">
<label for="text-input">Text (Single Line):</label>
<input
type="text"
id="text-input"
name="text-input"
placeholder="Enter some text"
maxlength="20"
/>
<label for="email-input">Email:</label>
<input
type="email"
id="email-input"
name="email-input"
placeholder="abc@gmail.com"
required
pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
title="Please enter a valid email address"
/>
<label for="password-input">Password:</label>
<input
type="password"
id="password-input"
name="password-input"
minlength="8"
/>
<label for="number-input">Number:</label>
<input
type="number"
id="number-input"
name="number-input"
min="1"
max="100"
step="1"
/>
<label for="tel-input">Phone Number:</label>
<input
type="tel"
id="tel-input"
name="tel-input"
placeholder="0712345678"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
/>
<label for="url-input">URL:</label>
<input
type="url"
id="url-input"
name="url-input"
placehoder="https://www.example.com"
/>
<label for="date-input">Date:</label>
<input type="date" id="date-input" name="date-input" />
<label for="time-input">Time:</label>
<input type="time" id="time-input" name="time-input" />
<label for="datetime-local">Date & Time:</label>
<input type="datetime-local" id="datetime-local" name="datetime-local" />
<label for="search-input">Search:</label>
<input
type="search"
id="search-input"
name="search-input"
placeholder="Search for something"
/>
<label for="file-input">File Upload:</label>
<input type="file" id="file-input" name="file-input" accept="image/*" />
<label for="color-input">Color Picker:</label>
<input type="color" id="color-input" name="color-input" value="#ff0000" />
<label for="checkbox">Checkbox (Multiple Choices allowed):</label>
<div class="multiple-inputs">
<input
type="checkbox"
id="checkbox1"
name="checkbox[]"
value="option1"
/>
Option 1
<input
type="checkbox"
id="checkbox2"
name="checkbox[]"
value="option2"
/>
Option 2
<input
type="checkbox"
id="checkbox3"
name="checkbox[]"
value="option3"
/>
Option 3
</div>
<label for="radio1">Radio Button (Only one selection allowed):</label>
<div class="multiple-inputs">
<input type="radio" id="radio1" name="radio" value="option1" /> Option 1
<input type="radio" id="radio2" name="radio" value="option2" /> Option 2
</div>
<label for="textarea">Text Area (Multi-Line Text): </label>
<textarea
id="textarea"
name="textarea"
rows="4"
cols="50"
placeholder="Enter some text"
></textarea>
</form>
</body>
</html>
|
import UIKit
class RegistrationViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
public weak var onEmployeeDataDelegate: (any EmployeeDataSource)?
var employee: Employee!
var vehicle: Vehicle!
var typeContract: TypeContract!
var typeEmployee: TypeEmployee!
var typeVehicle: TypeVehicle!
var fullName: String!
var birthYear: Int!
var monthlySalary: Double!
var occupationRate: Int!
var numbersOfExtra: Int = 0
var employeeId: Int = 0
var vehicleModel: String = ""
var vehicleCategory: String = ""
var hasSideCar: Bool = false
var selectedEmployeeType: String?
let employeeType: [String] = ["Choose Type", "Manager", "Programmer", "Tester"]
var vehicleColor: UIColor!
@IBOutlet weak var employeeTypePicker: UIPickerView!
@IBOutlet weak var employeeTypeTextFiled: UITextField!
@IBOutlet weak var employeeTypeLabel: UILabel!
@IBOutlet weak var employeeIdTextField: UITextField!
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastnameTextField: UITextField!
@IBOutlet weak var birthYearTextField: UITextField!
@IBOutlet weak var monthlySalaryTextField: UITextField!
@IBOutlet weak var occupationRateTextField: UITextField!
@IBOutlet weak var sideCardOption: UISegmentedControl!
@IBOutlet weak var plateNumberTextField: UITextField!
@IBOutlet weak var carTypeTextField: UITextField!
@IBOutlet weak var vehicleModelTextField: UITextField!
@IBOutlet weak var carSideLabel: UILabel!
@IBOutlet weak var typeVehicleOption: UISegmentedControl!
@IBAction func typeVehicleOption(_ sender: UISegmentedControl) {
let position = sender.selectedSegmentIndex
switch position {
case 0:
typeVehicle = .CAR
carTypeTextField.isHidden = false
sideCardOption.isHidden = true
carSideLabel.text = "Car Type"
case 1:
typeVehicle = .MOTORCYCLE
carTypeTextField.isHidden = true
sideCardOption.isHidden = false
carSideLabel.text = "Side Car"
default:
typeVehicle = .CAR
carTypeTextField.isHidden = false
sideCardOption.isHidden = true
carSideLabel.text = "Car Type"
}
}
@IBAction func sideCardSelection(_ sender: UISegmentedControl) {
let optionSelected = sender.selectedSegmentIndex
switch optionSelected {
case 0:
hasSideCar = true
case 1:
hasSideCar = false
default:
hasSideCar = false
}
}
override func viewDidLoad() {
employeeTypePicker.dataSource = self
employeeTypePicker.delegate = self
employeeTypeLabel.text = ""
employeeTypeLabel.isHidden = true
employeeTypeTextFiled.isHidden = true
typeVehicleOption.selectedSegmentIndex = 0
carTypeTextField.isHidden = false
sideCardOption.isHidden = true
typeVehicle = .CAR
}
func createPickerView() {
let pickerView = UIPickerView()
pickerView.delegate = self
}
@IBAction func chooseColorButton(_ sender: UIButton) {
let colorChooserPicker = UIColorPickerViewController()
colorChooserPicker.delegate = self
self.present(colorChooserPicker, animated: true, completion: {
self.vehicleColor = colorChooserPicker.selectedColor
print(self.vehicleColor!)
})
}
@IBAction func registerButton(_ sender: UIButton) {
employeeId = Int(employeeIdTextField.text ?? "") ?? 0
fullName = "\(firstNameTextField.text ?? "") \(lastnameTextField.text ?? "")"
birthYear = Int(birthYearTextField.text ?? "") ?? 0
monthlySalary = Double(monthlySalaryTextField.text ?? "") ?? 0.0
occupationRate = Int(occupationRateTextField.text ?? "") ?? 0
vehicleModel = vehicleModelTextField.text ?? ""
vehicleCategory = carTypeTextField.text ?? ""
numbersOfExtra = Int(employeeTypeTextFiled.text ?? "") ?? 0
guard typeEmployee != nil, typeVehicle != nil, fullName != "",
birthYear != 0, monthlySalary != 0, occupationRate != 0, numbersOfExtra != 0,
vehicleModel != "", vehicleColor != nil
else {
validateEmptyField()
return
}
registerVehicle(typeVehicle: typeVehicle)
registerEmployee(typeEmployee: typeEmployee)
onEmployeeDataDelegate?.onEmployeeDataDelegate(employee: employee)
self.dismiss(animated: true)
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return employeeType.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
selectedEmployeeType = employeeType[row]
employeeOptionSelected()
if selectedEmployeeType == "Manager" {
typeEmployee = .MANAGER
} else if selectedEmployeeType == "Programmer" {
typeEmployee = .PROGRAMMER
} else if selectedEmployeeType == "Tester" {
typeEmployee = .TESTER
} else {
print("Invalid Option")
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return employeeType[row]
}
}
|
@extends('Landing.nav')
@section('content')
{{-- <div class="bg-image-vertical h-100" style="background-color: #EFD3E4;
background-image: url(https://mdbootstrap.com/img/Photos/new-templates/search-box/img1.jpg);
"> --}}
<div class="mask mt-5 align-items-center ">
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-lg-10">
<div class="card" style="border-radius: 1rem;">
<div class="card-body" style=" background-image: linear-gradient(to right ,
#1c0e55,#303446);">
<h1 class="mb-5 text-center create">New Post</h1>
{{--
@if($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>
{{$error}}
</li>
@endforeach
</ul>
</div>
@endif --}}
<form action="{{route('posts.store')}}" method="POST" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="col-12 col-md-6 mb-4">
<div class="form-outline">
<input type="text" value="{{old('title')}}" id="form6Example1" name="title" class="form-control" />
<label class="form-label create" for="form6Example1" >Title</label>
@error("title")
<div class="text-danger ">
{{$message}}
</div>
@enderror
</div>
</div>
<div class="col-12 col-md-6 mb-4">
<div class="form-outline">
<input type="text" id="form6Example2" value="{{old('desc')}}" name="desc" class="form-control" />
<label class="form-label create" for="form6Example2">Description</label>
@error("desc")
<div class="text-danger ">
{{$message}}
</div>
@enderror
</div>
</div>
</div>
<div class="row">
<div class="col-12 col-md-6 mb-4">
<div class="form-outline">
<input type="file" id="form6Example12" value="{{old('img')}}" name="img" class="form-control" />
<label class="form-label create" for="form6Example12" >Image</label>
@error("img")
<div class="text-danger ">
{{$message}}
</div>
@enderror
</div>
</div>
<div class="col-12 col-md-6 mb-4">
<div class="form-outline">
<input type="number" value="{{old('version')}}" id="form6Example112"name="version" class="form-control" />
<label class="form-label create" for="form6Example112">Version</label>
@error("version")
<div class="text-danger ">
{{$message}}
</div>
@enderror
</div>
</div>
</div>
<div class="form-outline mb-4">
<select class="form-select" name="cat_id" id="select">
<option selected>Select Category</option>
@foreach($cats as $cat)
<option value={{$cat->id}}>{{$cat->name}}</option>
@endforeach
</select>
<label class="form-label create" for="select">Category</label>
</div>
<div class="form-outline mb-4">
<textarea class="form-control" value="{{old('content')}}" name="content" id="form6Example7" rows="4"></textarea>
<label class="form-label create" for="form6Example7">Content</label>
@error("content")
<div class="text-danger ">
{{$message}}
</div>
@enderror
</div>
<button type="submit" name="btn" class="btn btn-rounded create" style="color:white; background-color: rgb(153, 120, 151)">Add Post</button>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
@endsection
</body>
</html>
|
import { Delaunay } from "d3-delaunay";
import { useMemo } from "react";
const padding = { top: 0, left: 1.5 * 16, right: 1.5 * 16, bottom: 1.5 * 16 };
const cellGap = 22;
export type Point = {
x: number;
y: number;
};
export type PointWithPath = Point & {
path: string;
};
type UseVoronoiModelProps<T> = {
width: number;
height: number;
data: T[];
};
export const useVoronoiModel = <T extends Point = Point>({
width,
height,
data,
}: UseVoronoiModelProps<T>) => {
const delaunay = useMemo(() => {
return Delaunay.from(
data,
(d) => d.x,
(d) => d.y
);
}, [data]);
const voronoi = useMemo(() => {
const bounds: [number, number, number, number] = [
Number(padding.left) - cellGap / 2,
Number(padding.top) - cellGap / 2,
width - cellGap / 2,
height - cellGap / 2,
];
return delaunay.voronoi(bounds);
}, [delaunay, height, width]);
const enrichedData: (T & PointWithPath)[] = useMemo(
() =>
data.map((d, idx) => ({
...d,
path: voronoi.renderCell(idx),
})),
[data, voronoi]
);
return { delaunay, voronoi, enrichedData };
};
|
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class CustomerFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'company_id' => $this->faker->numberBetween(1, 8),
'name' => $this->faker->firstNameMale(10),
'surname' => $this->faker->lastName(10),
'telephone' => $this->faker->randomNumber(5),
'remarks' => $this->faker->text(10)
];
}
}
|
# Copyright 2023 The kauldron Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""XManager utils."""
from __future__ import annotations
from collections.abc import Iterator
import contextlib
import dataclasses
import functools
import importlib
import json
import typing
from etils import epath
from etils import epy
from kauldron import konfig
from unittest import mock as _mock ; xmanager_api = _mock.Mock()
if typing.TYPE_CHECKING:
from kauldron.train import config_lib # pylint: disable=g-bad-import-order
@functools.cache
def _client() -> xmanager_api.XManagerApi:
return xmanager_api.XManagerApi(xm_deployment_env='alphabet')
@dataclasses.dataclass(frozen=True)
class Experiment:
"""XManager experiment wrapper.
Usage:
```python
xp = kd.xm.Experiment.from_xid(1234)
with xp.adhoc(): # Import from xid
import kauldron as kd
config = kd.konfig.resolve(xp.config)
xp.root_dir.rmtree()
```
"""
exp: xmanager_api.Experiment
_: dataclasses.KW_ONLY
wid: int
@classmethod
def from_xid(cls, xid: int, wid: int) -> Experiment:
"""Factory from an xid.
Args:
xid: Experiment id
wid: Work unit id
Returns:
The experiment object
"""
return cls(_client().get_experiment(xid), wid=wid)
@contextlib.contextmanager
def adhoc(self) -> Iterator[None]:
"""Adhoc imports from the experiment snapshot."""
# TODO(epot): `kd.xm` is already in kauldron. Should support reloading
# kauldron but not reload `XManager`
from etils import ecolab # pylint: disable=g-import-not-at-top # pytype: disable=import-error
with ecolab.adhoc(
f'xid/{self.exp.id}',
reload='kauldron',
restrict_reload=False,
invalidate=False,
):
yield
@functools.cached_property
def artifacts(self) -> dict[str, str]:
"""Mapping artifact name -> value."""
return {a.description: a.artifact for a in self.exp.get_artifacts()}
@functools.cached_property
def root_dir(self) -> epath.Path:
"""Root directory of the artifact."""
path = self.artifacts['Workdir']
return epath.Path(path)
@functools.cached_property
def config(self) -> konfig.ConfigDictLike[config_lib.Trainer]:
"""Unresolved `ConfigDict`."""
# Use a constant rather than hardcoding `config.json`
config_path = self.root_dir / str(self.wid) / 'config.json'
config = json.loads(config_path.read_text())
return _json_to_config(config) # Wrap the dict to ConfigDict # pytype: disable=bad-return-type
@functools.cached_property
def trainer(self) -> config_lib.Trainer:
"""Resolved `ConfigDict`."""
return konfig.resolve(self.config)
def _json_to_config(json_value):
"""Wraps a `dict` to a `ConfigDict` and convert list to tuple."""
match json_value:
case dict():
values = {k: _json_to_config(v) for k, v in json_value.items()}
if qualname := values.get('__qualname__'):
try:
importlib.import_module(qualname.split(':', 1)[0])
except ImportError as e:
epy.reraise(
e,
suffix=(
'\nOn Colab, you might need to access the config from a adhoc'
' import context.'
),
)
return konfig.ConfigDict(values)
case list():
return tuple(_json_to_config(v) for v in json_value)
case _:
return json_value
|
<?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <sebastian@phpunit.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Runner\Filter;
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\TestSuite;
/**
* @small
*/
final class NameFilterIteratorTest extends TestCase
{
public function testCaseSensitiveMatch(): void
{
$this->assertTrue($this->createFilter('BankAccountTest')->accept());
}
public function testCaseInsensitiveMatch(): void
{
$this->assertTrue($this->createFilter('bankaccounttest')->accept());
}
private function createFilter(string $filter): NameFilterIterator
{
$suite = new TestSuite;
$suite->addTest(new \BankAccountTest('testBalanceIsInitiallyZero'));
$iterator = new NameFilterIterator($suite->getIterator(), $filter);
$iterator->rewind();
return $iterator;
}
}
|
import { NgModule, inject } from '@angular/core';
import { ActivatedRouteSnapshot, RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { DettaglioComponent } from './dettaglio/dettaglio.component';
import { MeteoService } from './_services/meteo.service';
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{
path: 'home/dettaglio/:tipo/:lat/:lon',
component: DettaglioComponent,
resolve: {
AlbaETramontoDettaglio: (route: ActivatedRouteSnapshot) => {
return inject(MeteoService).getSearchAlbaETramonto(
route.paramMap.get('lat')!,
route.paramMap.get('lon')!
);
},
DatiMeteoDettaglio: (route: ActivatedRouteSnapshot) => {
return inject(MeteoService).getSearchDatiMeteo(
route.paramMap.get('lat')!,
route.paramMap.get('lon')!,
route.paramMap.get('tipo')!
);
},
City: (route: ActivatedRouteSnapshot) => {
return inject(MeteoService).getSearchByCity(
route.paramMap.get('lat')!,
route.paramMap.get('lon')!
);
},
},
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
|
package com.uleam.appparahelados.ui.registro
import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.*
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.uleam.appparahelados.R
import com.uleam.appparahelados.ui.AppViewModelProvider
import com.uleam.appparahelados.ui.navigation.NavigationController
import com.uleam.appparahelados.ui.theme.md_theme_light_onSecondary
import com.uleam.appparahelados.ui.theme.md_theme_light_onSurfaceVariant
import com.uleam.appparahelados.ui.theme.md_theme_light_secondary
object RegistroDistinationScreen : NavigationController {
override val route = "registro"
override val titleRes = R.string.registros_title
}
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RegistroScreen(
navigateToLogin: () -> Unit,
viewModel: RegisterViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
var nombre by remember { mutableStateOf("") }
var correo by remember { mutableStateOf("") }
var direccion by remember { mutableStateOf("") }
var pass by remember { mutableStateOf("") }
var telefono by remember { mutableStateOf("") }
var passwordVisibility by remember { mutableStateOf(false) }
val alertDialogVisibleState = remember { mutableStateOf(false) }
val showErrorDialog = remember { mutableStateOf(false) }
val errorMessage = remember { mutableStateOf("") }
Scaffold {
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 16.dp)
) {
item {
Encabezado { navigateToLogin() }
Spacer(modifier = Modifier.height(16.dp))
val textFieldModifier = Modifier
.fillMaxWidth()
.clip(RoundedCornerShape(16.dp))
.padding(vertical = 4.dp, horizontal = 16.dp)
val buttonModifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp, horizontal = 16.dp)
OutlinedTextField(
value = nombre,
onValueChange = { nombre = it },
label = { Text(text = "Nombre") },
modifier = textFieldModifier,
colors = TextFieldDefaults.outlinedTextFieldColors(focusedBorderColor = md_theme_light_onSurfaceVariant),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Next),
singleLine = true
)
OutlinedTextField(
value = correo,
onValueChange = { correo = it },
label = { Text(text = "Correo electrónico") },
modifier = textFieldModifier,
colors = TextFieldDefaults.outlinedTextFieldColors(focusedBorderColor = md_theme_light_onSurfaceVariant),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email, imeAction = ImeAction.Next),
singleLine = true
)
OutlinedTextField(
value = direccion,
onValueChange = { direccion = it },
label = { Text(text = "Dirección") },
modifier = textFieldModifier,
colors = TextFieldDefaults.outlinedTextFieldColors(focusedBorderColor = md_theme_light_onSurfaceVariant),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.Next),
singleLine = true
)
OutlinedTextField(
value = telefono,
onValueChange = { telefono = it },
label = { Text(text = "Teléfono") },
modifier = textFieldModifier,
colors = TextFieldDefaults.outlinedTextFieldColors(focusedBorderColor = md_theme_light_onSurfaceVariant),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone, imeAction = ImeAction.Next),
singleLine = true
)
OutlinedTextField(
value = pass,
onValueChange = { pass = it },
label = { Text(text = "Contraseña") },
modifier = textFieldModifier,
visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
val image = if (passwordVisibility)
painterResource(id = R.drawable.visibility)
else painterResource(id = R.drawable.visible)
IconButton(onClick = {
passwordVisibility = !passwordVisibility
}) {
Icon(painter = image, contentDescription = if (passwordVisibility) "Ocultar contraseña" else "Mostrar contraseña")
}
},
colors = TextFieldDefaults.outlinedTextFieldColors(focusedBorderColor = md_theme_light_onSurfaceVariant),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text, imeAction = ImeAction.None),
singleLine = true,
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
val error = validarCamposRegistro(nombre, correo, direccion, pass, telefono)
if (error != null) {
errorMessage.value = error
showErrorDialog.value = true
} else {
viewModel.onSubmitButtonClick(nombre, correo, pass, telefono, direccion)
alertDialogVisibleState.value = true
}
},
modifier = buttonModifier,
colors = ButtonDefaults.buttonColors(
containerColor = Color.Red,
contentColor = md_theme_light_onSecondary
)
) {
Text(text = "Registrarse")
}
if (alertDialogVisibleState.value) {
RegistroExitosoDialog {
alertDialogVisibleState.value = false
navigateToLogin()
}
}
if (showErrorDialog.value) {
AlertDialog(
onDismissRequest = { showErrorDialog.value = false },
title = { Text("Error") },
text = { Text(errorMessage.value) },
confirmButton = {
Button(
onClick = { showErrorDialog.value = false },
colors = ButtonDefaults.buttonColors(
containerColor = md_theme_light_secondary,
contentColor = md_theme_light_onSecondary
)
) {
Text("OK")
}
}
)
}
}
}
}
}
@Composable
fun RegistroExitosoDialog(onClose: () -> Unit) {
AlertDialog(
onDismissRequest = onClose,
title = { Text("¡Registro exitoso!") },
text = { Text("¡Tu registro se ha completado exitosamente! ¿Deseas iniciar sesión ahora?") },
confirmButton = {
Button(
onClick = onClose,
colors = ButtonDefaults.buttonColors(
containerColor = md_theme_light_secondary,
contentColor = md_theme_light_onSecondary
)
) {
Text("OK")
}
}
)
}
fun validarCamposRegistro(
nombre: String,
correo: String,
direccion: String,
pass: String,
telefono: String
): String? {
return when {
nombre.isEmpty() -> "El nombre es obligatorio."
correo.isEmpty() -> "El correo electrónico es obligatorio."
direccion.isEmpty() -> "La dirección es obligatoria."
pass.isEmpty() -> "La contraseña es obligatoria."
telefono.isEmpty() -> "El teléfono es obligatorio."
pass.length < 6 -> "La contraseña debe tener al menos 6 caracteres."
else -> null
}
}
@Composable
fun Encabezado(onBackPressed: () -> Unit) {
Surface(
color = Color.Red,
modifier = Modifier
.fillMaxWidth()
.padding(top = 32.dp)
.height(200.dp)
.padding(horizontal = 4.dp, vertical = 8.dp),
shape = RoundedCornerShape(16.dp)
) {
Column(
modifier = Modifier.fillMaxSize()
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
IconButton(
onClick = onBackPressed,
modifier = Modifier.size(40.dp)
) {
Icon(
imageVector = Icons.Default.ArrowBack,
contentDescription = "Botón de regresar",
tint = Color.White
)
}
}
Spacer(modifier = Modifier.height(8.dp))
Text(
text = "CREA TU CUENTA",
color = Color.White,
fontSize = 50.sp,
fontWeight = FontWeight.Bold,
lineHeight = 48.sp,
modifier = Modifier.padding(start = 16.dp)
)
}
}
}
|
import {
WebSocketGateway,
WebSocketServer,
MessageBody,
} from '@nestjs/websockets'
import { Logger, UseGuards } from '@nestjs/common'
import { SubscribeMessage } from '@nestjs/websockets/decorators'
import { AuthGuard } from '@nestjs/passport'
import { Socket } from 'socket.io'
import { E_Chat, I_ChatMessage, I_ChatUser } from 'models/sockets/chat'
import { PrismaService } from 'modules/prisma/prisma.service'
import { ChatService } from './chat.service'
@WebSocketGateway(8000, { cors: '*' })
export class ChatGateway {
constructor(private chat: ChatService, private prisma: PrismaService) {}
@WebSocketServer()
server
private logger: Logger = new Logger('LobbyChatGateway')
users: I_ChatUser[] = []
async afterInit() {
this.logger.log('Init LobbyChatGateway')
}
handleConnection(client: Socket) {
this.logger.log(`Client connected LobbyGateway: ${client.id}`)
}
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`)
}
@SubscribeMessage('test')
handleMessage(@MessageBody() message: string): void {
this.server.emit('message', message)
}
@SubscribeMessage(E_Chat.requestChatMessages)
getAllMessages(client: Socket) {
const messages = this.chat.getAllMessages()
const payload: { messages: I_ChatMessage[] } = {
messages,
}
client.emit(E_Chat.getChatMessages, payload)
}
@SubscribeMessage(E_Chat.sendChatMessage)
async sendChatMessage(client: Socket, data: { text: string }) {
const usersDB = await this.prisma.user.findMany()
console.log(usersDB)
this.users = usersDB.map(
(user): I_ChatUser => ({
id: user.id,
email: user.email,
socketId: client.id,
}),
)
const user = this.users.find((user) => user.socketId === client.id)
const message = this.chat.createMessage(user, data.text)
const messageLobbyPayload: { message: I_ChatMessage } = {
message,
}
this.server.emit(E_Chat.getChatMessage, messageLobbyPayload)
}
}
|
package openapi
import (
"encoding/json"
"fmt"
"github.com/blinkops/blink-http/consts"
ops "github.com/blinkops/blink-http/openapi/operations"
"github.com/blinkops/blink-sdk/plugin"
"github.com/blinkops/blink-sdk/plugin/connections"
"github.com/getkin/kin-openapi/openapi3"
"strings"
"unicode"
)
type NamedActionsGroup struct {
Name string `yaml:"name"`
Connections map[string]connections.Connection `yaml:"connection_types"`
IconUri string `yaml:"icon_uri"`
IsConnectionOptional bool `yaml:"is_connection_optional"`
Actions []NamedAction `yaml:"actions"`
}
type NamedAction struct {
Name string `yaml:"name"`
DisplayName string `yaml:"display_name"`
Description string `yaml:"description"`
Enabled bool `yaml:"enabled"`
Parameters map[string]plugin.ActionParameter `yaml:"parameters"`
ActionToRun string `yaml:"action_to_run"`
ActionToRunParamValues map[string]string `yaml:"action_to_run_param_values"`
IsConnectionOptional string `yaml:"is_connection_optional"`
}
func (o ParsedOpenApi) getNamedActionsGroup() NamedActionsGroup {
var namedActions []NamedAction
for _, action := range o.actions {
maskedAction := o.mask.GetAction(action.Name)
if len(o.mask.Actions) > 0 && maskedAction == nil {
continue
}
name := action.Name
if maskedAction != nil {
name = maskedAction.Alias
}
opDefinition := o.operations[action.Name]
namedActions = append(namedActions, NamedAction{
Name: name,
DisplayName: getDisplayName(action.Name),
Description: action.Description,
Enabled: true,
Parameters: o.getActionParams(action),
ActionToRun: o.getActionToRun(opDefinition),
ActionToRunParamValues: o.getActionParamValues(action, opDefinition),
})
}
for _, namedAction := range o.mask.NamedActions {
namedActions = append(namedActions, namedAction)
}
group := NamedActionsGroup{
Name: o.mask.Name,
Connections: o.mask.Connections,
IconUri: o.mask.IconUri,
IsConnectionOptional: o.mask.IsConnectionOptional,
Actions: namedActions,
}
return group
}
func (o ParsedOpenApi) getActionToRun(opDefinition *ops.OperationDefinition) string {
return fmt.Sprintf("http.%s", strings.ToLower(opDefinition.Method))
}
func (o ParsedOpenApi) getActionParams(action plugin.Action) map[string]plugin.ActionParameter {
params := map[string]plugin.ActionParameter{}
for paramName, param := range action.Parameters {
if maskedAct, ok := o.mask.Actions[action.Name]; ok {
if maskedParam, ok := maskedAct.Parameters[paramName]; ok {
param.DisplayName = maskedParam.Alias
if maskedParam.Index != 0 {
param.Index = maskedParam.Index
}
}
} else {
param.DisplayName = getDisplayName(paramName)
}
params[paramName] = param
}
return params
}
func (o ParsedOpenApi) getActionParamValues(action plugin.Action, opDefinition *ops.OperationDefinition) map[string]string {
paramValues := map[string]string{}
paramValues["url"] = o.getActionUrlTemplate(opDefinition)
body := getBodyTemplate(action, opDefinition.GetDefaultBody())
if body != "" {
paramValues["body"] = body
}
contentType := opDefinition.GetDefaultBodyType()
if contentType != "" {
paramValues["contentType"] = contentType
}
return paramValues
}
func (o ParsedOpenApi) getActionUrlTemplate(op *ops.OperationDefinition) string {
host := fmt.Sprintf("'%s'", o.requestUrl)
if o.mask.RequestUrl != "" {
connTemplate := fmt.Sprintf("connection.%s.%s", o.mask.RequestUrl, consts.RequestUrlKey)
host = fmt.Sprintf("(exists(%s) ? %s : '%s'),", connTemplate, connTemplate, o.requestUrl)
}
path := fmt.Sprintf("'%s'", op.Path)
for _, param := range op.PathParams {
old := fmt.Sprintf("%s%s%s", consts.ParamPrefix, param.ParamName, consts.ParamSuffix)
expr := fmt.Sprintf("' + params.%s + '", param.ParamName)
path = strings.ReplaceAll(path, old, expr)
}
path = strings.TrimSuffix(path, " + ''")
query := ""
for index, queryParam := range op.QueryParams {
if index == 0 {
query += fmt.Sprintf("'?%s=' + params.%s", queryParam.ParamName, queryParam.ParamName)
} else {
query += fmt.Sprintf(" + '&%s=' + params.%s", queryParam.ParamName, queryParam.ParamName)
}
}
if query != "" {
query = fmt.Sprintf("{{%s}}", query)
}
url := fmt.Sprintf("{{%s + %s}}%s", host, path, query)
return url
}
func getBodyTemplate(action plugin.Action, body *ops.RequestBodyDefinition) string {
if body == nil {
return ""
}
requestBody := map[string]interface{}{}
for paramName := range action.Parameters {
mapKeys := strings.Split(paramName, consts.BodyParamDelimiter)
buildRequestBody(mapKeys, body.Schema.OApiSchema, paramName, requestBody)
}
marshaledBody, err := json.Marshal(requestBody)
if err != nil {
return ""
}
return string(marshaledBody)
}
func getDisplayName(name string) string {
name = strings.ReplaceAll(name, "_", " ")
name = strings.ReplaceAll(name, ".", " ")
name = strings.ReplaceAll(name, "[]", "")
for i := 1; i < len(name); i++ {
if unicode.IsLower(rune(name[i-1])) && unicode.IsUpper(rune(name[i])) && (i+1 < len(name) || !unicode.IsUpper(rune(name[i+1]))) {
name = name[:i] + " " + name[i:]
}
}
upperCaseWords := []string{"url", "id", "ids", "ip", "ssl"}
words := strings.Split(name, " ")
for i, word := range words {
if contains(upperCaseWords, word) {
words[i] = strings.ToUpper(word)
}
}
name = strings.Join(words, " ")
name = strings.ReplaceAll(name, "IDS", "IDs")
return strings.Join(strings.Fields(strings.Title(name)), " ")
}
func contains(list []string, word string) bool {
for _, item := range list {
if item == word {
return true
}
}
return false
}
// Build nested json request body from "." delimited parameters
func buildRequestBody(mapKeys []string, propertySchema *openapi3.Schema, paramName string, requestBody map[string]interface{}) {
key := mapKeys[0]
// Keep recursion going until leaf node is found
if len(mapKeys) == 1 && propertySchema != nil {
subPropertySchema := ops.GetPropertyByName(key, propertySchema)
if subPropertySchema != nil {
requestBody[mapKeys[len(mapKeys)-1]] = castBodyParamType(paramName, subPropertySchema.Type)
}
} else {
if _, ok := requestBody[key]; !ok {
requestBody[key] = map[string]interface{}{}
}
subPropertySchema := ops.GetPropertyByName(key, propertySchema)
buildRequestBody(mapKeys[1:], subPropertySchema, paramName, requestBody[key].(map[string]interface{}))
}
}
// Cast proper parameter types when building json request body
func castBodyParamType(paramValue string, paramType string) interface{} {
switch paramType {
case consts.TypeString:
return fmt.Sprintf("{{params.%s}}", paramValue)
case consts.TypeInteger, consts.TypeNumber:
return fmt.Sprintf("{{int(params.%s)}}", paramValue)
case consts.TypeBoolean:
return fmt.Sprintf("{{bool(params.%s)}}", paramValue)
case consts.TypeArray:
return []interface{}{fmt.Sprintf("{{arr(params.%s)}}", paramValue)}
case consts.TypeObject:
return fmt.Sprintf("{{obj(params.%s)}}", paramValue)
default:
return fmt.Sprintf("{{obj(params.%s)}}", paramValue)
}
}
|
import {
WaterDrop,
Task as MuiTask,
Note as MuiNote,
ArrowBack,
} from "@mui/icons-material";
import {
Typography,
Tabs,
Tab,
Box,
IconButton,
Skeleton,
} from "@mui/material";
import { useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import NotesTab from "./Tabs/NotesTab";
import TasksTab from "./Tabs/TasksTab";
import OverviewTab from "./Tabs/OverviewTab";
import { useQuery } from "react-query";
import { fetchPlant } from "../../../api";
const PlantDetailPage = () => {
const navigate = useNavigate();
const location = useLocation();
const [tab, setTab] = useState(0);
const plantId = location.state.id;
const {
data: plant,
isLoading,
} = useQuery({
queryKey: [`plant${plantId}`],
queryFn: () => fetchPlant(plantId),
});
const handleChange = (e, newValue) => {
setTab(newValue);
};
return (
<div className="plant-detail-container">
<Typography variant="h5">
<IconButton
sx={{ marginLeft: "-20px", marginRight: "5px" }}
onClick={() => navigate("/plants")}
>
<ArrowBack />
</IconButton>
{isLoading ? (
<Skeleton sx={{ width: 300, display: "inline-block" }} />
) : (
plant.name
)}
</Typography>
{isLoading ? (
<Skeleton
variant="rectangular"
sx={{ maxHeight: 700, minHeight: 400, borderRadius: "20px" }}
/>
) : (
<img
alt="plant"
src={plant.img_url}
style={{
objectFit: "contain",
backgroundColor: "rgba(0, 0, 0, 0.11)",
borderRadius: "20px",
}}
></img>
)}
<Box sx={{ width: "100%", margin: "auto" }}>
<Tabs
value={tab}
onChange={handleChange}
aria-label="icon label tabs example"
>
<Tab sx={{ flex: "1 1 0" }} icon={<WaterDrop />} label="Overview" />
<Tab sx={{ flex: "1 1 0" }} icon={<MuiNote />} label="Notes" />
<Tab sx={{ flex: "1 1 0" }} icon={<MuiTask />} label="Tasks" />
</Tabs>
</Box>
{isLoading && <Skeleton variant="rectangular" sx={{ height: 500 }} />}
{tab === 0 && !isLoading && <OverviewTab plant={plant} />}
{tab === 1 && !isLoading && <NotesTab plant={plant.id} />}
{tab === 2 && !isLoading && <TasksTab plant={plant.id} />}
</div>
);
};
export default PlantDetailPage;
|
// Copyright 2021 Goldman Sachs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.finos.legend.authentication.vault;
import org.eclipse.collections.api.map.MutableMap;
import org.eclipse.collections.impl.factory.Maps;
import org.finos.legend.engine.protocol.pure.v1.model.packageableElement.authentication.vault.CredentialVaultSecret;
public class CredentialVaultProvider
{
private MutableMap<Class<? extends CredentialVaultSecret>, CredentialVault> vaults = Maps.mutable.empty();
public CredentialVaultProvider()
{
}
public void register(CredentialVault credentialVault)
{
this.vaults.put(credentialVault.getSecretType(), credentialVault);
}
public CredentialVault getVault(CredentialVaultSecret credentialVaultSecret) throws Exception
{
Class<? extends CredentialVaultSecret> secretClass = credentialVaultSecret.getClass();
if (!this.vaults.containsKey(secretClass))
{
throw new RuntimeException(String.format("CredentialVault for secret of type '%s' has not been registered in the system", secretClass));
}
return this.vaults.get(secretClass);
}
public static Builder builder()
{
return new Builder();
}
public static class Builder
{
private CredentialVaultProvider credentialVaultProvider = new CredentialVaultProvider();
private PlatformCredentialVaultProvider platformCredentialVaultProvider;
public Builder with(PlatformCredentialVaultProvider platformCredentialVaultProvider)
{
this.platformCredentialVaultProvider = platformCredentialVaultProvider;
this.platformCredentialVaultProvider.getVaults().forEach(vault -> credentialVaultProvider.register(vault));
return this;
}
public Builder with(CredentialVault credentialVault)
{
credentialVaultProvider.register(credentialVault);
return this;
}
public CredentialVaultProvider build()
{
return credentialVaultProvider;
}
}
}
|
// Require the Express Module
var express = require('express');
// Create an Express App
var app = express();
// Require body-parser (to receive post data from clients)
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
// Integrate body-parser with our App
app.use(bodyParser.urlencoded({ extended: true }));
// Require path
var path = require('path');
// Setting our Static Folder Directory
app.use(express.static(path.join(__dirname, './static')));
// Setting our Views Folder Directory
app.set('views', path.join(__dirname, './views'));
// Setting our View Engine set to EJS
app.set('view engine', 'ejs');
// Routes
// Root Request
mongoose.connect('mongodb://localhost/quotesdb');
mongoose.Promise = global.Promise;
var allQuotes;
var UserSchema = new mongoose.Schema({
name: {type: String},
msg: {type: String}
}, {timestamps: true})
mongoose.model('Quotes', UserSchema); // We are setting this Schema in our Models as 'User'
var Quote = mongoose.model('Quotes') // We are retrieving this Schema from our Models, named 'User'
app.get('/', function(req, res) {
// This is where we will retrieve the users from the database and include them in the view page we will be rendering.
res.render('form');
})
//
app.get('/quotes', function(req, res) {
// This is where we will retrieve the users from the database and include them in the view page we will be rendering.
allQuotes = "";
Quote.find({}, function(err,quotes) {
for(q in quotes) {
allQuotes += quotes[q].name + " said" + quotes[q].msg;
}
console.log(" Here are the quoets" + allQuotes);
res.render('quotes',{allQuotes:allQuotes});
})
})
app.post('/quotes', function(req, res) {
console.log("POST DATA", req.body);
// create a new User with the name and age corresponding to those from req.body
console.log("your quotes", req.body);
var q = new Quote({name: req.body.name, msg: req.body.msg});
// Try to save that new user to the database (this is the method that actually inserts into the db) and run a callback function with an error (if any) from the operation.
q.save(function(err) {
// if there is an error console.log that something went wrong!
if(err) {
console.log('something went wrong');
} else { // else console.log that we did well and then redirect to the root route
console.log('successfully added a quote from a user!');
res.redirect('/quotes');
}
})
})
// Setting our Server to Listen on Port: 8000
app.listen(8000, function() {
console.log("listening on port 8000");
})
|
<!DOCTYPE html>
<html lang="pt" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="UTF-8">
<title>Cadastrar-se</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<link rel="stylesheet" href="../css/cadastro.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;1,100;1,200;1,300;1,400;1,500;1,600&display=swap" rel="stylesheet">
</head>
<body>
<!--Menu principal da página-->
<nav class="navbar navbar-expand-lg navback">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" aria-current="page" href="/ifmeetings"><i class="bi bi-house-door"></i> Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Sobre nós</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Cursos</a>
</li>
<li class="nav-item">
<a class="nav-link">Equipe</a>
</li>
<li class="nav-item">
<a class="nav-link btn1" href="/usuarios/login" style="padding: 7px 27px 7px 27px; margin-right: 15px;">Entrar</a>
</li>
<li class="nav-item">
<a class="nav-link btn2" href="/ifmeetings" style="padding: 7px 27px 7px 27px; margin: 0;"><i class="bi bi-arrow-return-left"></i> Sair</a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Exibindo mensagem positiva se o cadastro for realizado com sucesso-->
<div th:if="${msgSucesso} != null" class="alert alert-info" role="alert">
<p th:text="${msgSucesso}" class="text-center" style="padding: 0; margin: 0; font-weight: 500;"></p>
</div>
<!--Container do Formulário de Cadastro de Usuários-->
<div class="form">
<div class="form-area">
<img src="../imagens/logo.png" style="width: 200px; margin-top: 30px; margin-left: 40%;">
<form class="row g-3" th:action="@{/usuarios/salvar}" th:object="${usuario}" method="post">
<div class="col-md-12">
<h5 style="color: #185B61"><i class="bi bi-caret-right-fill"></i> Cadastro de Usuários</h5>
</div>
<div class="col-md-4">
<input type="hidden" th:field="${usuario.id}" />
<label for="inputNome" class="form-label">Nome completo: </label>
<input type="text" class="form-control" th:errorclass="is-invalid" id="inputNome" th:field="${usuario.nome}">
<div class="invalid-feedback" th:errors="${usuario.nome}"></div>
</div>
<div class="col-md-4">
<label for="inputEmail" class="form-label">Email:</label>
<input type="email" class="form-control" th:errorclass="is-invalid" id="inputEmail" th:field="${usuario.email}">
<div class="invalid-feedback" th:errors="${usuario.email}"></div>
</div>
<div class="col-md-4">
<label for="inputSenha" class="form-label">Senha:</label>
<input type="password" class="form-control" th:errorclass="is-invalid" id="inputSenha" th:field="${usuario.senha}">
<div class="invalid-feedback" th:errors="${usuario.senha}"></div>
</div>
<div class="col-4">
<label for="inputNumero" class="form-label">Telefone:</label>
<input type="text" class="form-control" th:errorclass="is-invalid" id="inputNumero" placeholder="(xx) xxxxx-xxxx" th:field="${usuario.fone}">
<div class="invalid-feedback" th:errors="${usuario.fone}"></div>
</div>
<div class="col-4">
<label for="inputCpf" class="form-label">CPF:</label>
<input type="text" class="form-control" th:errorclass="is-invalid" id="inputCpf" placeholder="xxx.xxx.xxx-xx" th:field="${usuario.cpf}">
<div class="invalid-feedback" th:errors="${usuario.cpf}"></div>
</div>
<div class="col-md-4">
<label for="inputPublico" class="form-label">Perfil:</label>
<select id="inputPublico" class="form-select" th:field="${usuario.perfil}">
<option value="">Selecione...</option>
<option value="Aluno do IFRN">Aluno do IFRN</option>
<option value="Servidor do IFRN">Servidor do IFRN</option>
<option value="Público Externo">Público Externo</option>
</select>
</div>
<div class="col-md-3">
<label for="inputCidade" class="form-label">Cidade:</label>
<input type="text" class="form-control" th:errorclass="is-invalid" id="inputCidade" th:field="${usuario.cidade}">
<div class="invalid-feedback" th:errors="${usuario.cidade}"></div>
</div>
<div class="col-md-3">
<label for="inputEstado" class="form-label">Estado:</label>
<select id="inputEstado" class="form-select" th:field="${usuario.estado}">
<option value="">Selecione...</option>
<option th:each="e : ${estado}" th:text="${e}" th:value="${e}"></option>
</select>
</div>
<div class="col-md-3">
<label for="inputIdade" class="form-label">Faixa Étaria:</label>
<select id="inputIdade" class="form-select" th:field="${usuario.idade}">
<option value="">Selecione...</option>
<option value="Menor que 16 anos">Menor que 16 anos</option>
<option value="Entre 16 a 25 anos">Entre 16 a 25 anos</option>
<option value="Entre 25 a 40 anos">Entre 25 a 40 anos</option>
<option value="Entre 40 a 60 anos">Entre 40 a 60 anos</option>
<option value="Mais de 60 anos">Mais de 60 anos</option>
</select>
</div>
<div class="col-md-3">
<label for="inputEscolaridade" class="form-label">Cursando:</label>
<select id="inputEscolaridade" class="form-select" th:field="${usuario.escolaridade}">
<option value="">Selecione...</option>
<option value="Ensino Fundamental">Ensino Fundamental</option>
<option value="Ensino Médio">Ensino Médio</option>
<option value="Graduação">Graduação</option>
<option value="Pós-graduação">Pós-graduação</option>
<option value="Mestrado">Mestrado</option>
<option value="Doutorado">Doutorado</option>
<option value="Pós-doutorado">Pós-doutorado</option>
</select>
</div>
<div class="col-md-12">
<label for="inputFoto" class="form-label">Escolha uma foto de perfil:</label>
<input type="file" id="inputFoto" class="form-control" th:field="${usuario.foto}">
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck">
<label class="form-check-label" for="gridCheck">
Ciente de que meus dados serão utilizados apenas para fins acadêmicos da Instituição.
</label>
</div>
</div>
<div class="col-12">
<input type="submit" class="btn btn-info" th:value="${usuario.id} == 0 ? Cadastrar : Editar">
<button type="reset" class="btn" style="background-color: orange;"> Limpar </button><br><br>
<a href="/ifmeetings" style="color: #185B61; text-decoration: none; font-weight: 600;"><i class="bi bi-arrow-left-circle" style="font-size: 18px;"></i> Voltar</a>
</div>
</form>
</div>
</div>
<!--Parte Final do Site-->
<footer>
<div class="container-footer">
<div class="row-footer">
<div class="column-footer">
<ul>
<h4>IF Meetings 2022</h4>
<li style="font-weight: 300;">O IF Meetings é um projeto de Extensão do Instituto Federal de Educação, Ciência e Tecnologia do Rio Grande do Norte - campus João Câmara, do qual oferta aulas de inglês online e gratuitas com professores da instituição para toda
a comunidade.
</li>
</ul>
</div>
<div class="column-footer">
<ul>
<h4>Cursos</h4>
<li><a href="">Iniciante</a></li>
<li><a href="">Elementar</a></li>
<li><a href="">Conversação</a></li>
<li><a href="">Como se inscrever</a></li>
</ul>
</div>
<div class="column-footer">
<ul>
<h4>Links Úteis</h4>
<li><a href="">Portal IFRN</a></li>
<li><a href="">Sobre nós</a></li>
<li><a href="">Dicas</a></li>
<li><a href="">Equipe</a></li>
<li><a href="">Cadastrar-se</a></li>
</ul>
</div>
<div class="column-footer">
<h4>Novidades</h4>
<div class="form1">
<form action="">
<input type="email" placeholder="Digite o seu e-mail">
<button>Enviar</button>
</form>
</div>
<div class="social-media">
<a href="#"><i class="bi bi-facebook"></i></a>
<a href="#"><i class="bi bi-instagram"></i></a>
<a href="#"><i class="bi bi-youtube"></i></a>
<a href="#"><i class="bi bi-whatsapp"></i></a>
<a href="#"><i class="bi bi-telegram"></i></a>
</div>
</div>
</div>
</div>
</footer>
</body>
</html>
|
#install.packages("arsenal")
library(readxl)
library(data.table)
library(lubridate)
library(tidyverse)
library(survival)
library(AdhereR)
library(ggpubr)
library(parallel)
library(arsenal)
memory.limit(size=1000000000)
### STEP1: FIND OPIOID PRODUCT ID
# Lookup lists
lookup_drug_class = data.table(read_excel("\\\\rfawin.partners.org\\mgh-itafisma\\IQVIA\\lookup_lists.xlsx", sheet = "opioids_pain"))
# Filter down to opioid prescription only from the lookup lists
list_opioid_mkted_prod_name = lookup_drug_class$MKTED_PROD_NM
# Product
d_product = fread("\\\\rfawin.partners.org\\mgh-itafisma\\IQVIA\\Product.gz")
# Get the product IDs from the product data where the MKTED_PROD_NM matches
opioid_productID_NM = d_product[MKTED_PROD_NM %in% list_opioid_mkted_prod_name,c("PRODUCT_ID", "MKTED_PROD_NM","USC_CD", "USC_DESC", "STRNT_DESC")]
list_opioid_PRODUCT_ID = opioid_productID_NM$PRODUCT_ID
# 6197 unique product_id
### STEP2: FILTER RX DATA WITH PRODUCT ID
# Selectively read in Rx data
filenum_rx = c(seq(2014,2021,1))
datanames_rx = paste("FACT_RX_", filenum_rx, sep='')
for(i in 1:length(datanames_rx))
{
assign (
datanames_rx[i],
fread(file = paste("\\\\rfawin.partners.org\\mgh-itafisma\\IQVIA\\Rx_data\\", datanames_rx[i], sep=""),
select = c("SVC_DT", "PATIENT_ID","PRODUCT_ID","DAYS_SUPPLY_CNT","DSPNSD_QTY"), quote="")
[PRODUCT_ID %in% list_opioid_PRODUCT_ID]
)
}
FACT_RX = rbind (FACT_RX_2014, FACT_RX_2015, FACT_RX_2016, FACT_RX_2017,
FACT_RX_2018, FACT_RX_2019, FACT_RX_2020, FACT_RX_2021)
RX_product = merge(FACT_RX,opioid_productID_NM, by="PRODUCT_ID",all.x=TRUE )
table(RX_product$USC_DESC)
fwrite(RX_product, "C:\\Users\\hd820\\OneDrive - Mass General Brigham\\Data Repository\\IQVIA analysis\\[P2] Upstream model\\MME calculation\\Data\\RX_product_opioids_2014_2021.csv")
# 351,517,666 LRx
### STEP3: MERGE RX, PRODUCT, PATIENT, MME data, and SAMPLE RESTRICTIONS
df_opioids = fread("C:\\Users\\hd820\\OneDrive - Mass General Brigham\\Data Repository\\IQVIA analysis\\[P2] Upstream model\\MME calculation\\Data\\RX_product_opioids_2014_2021.csv")
# 351,517,666 LRx
list_patient = unique(df_opioids$PATIENT_ID)
# 48,311,539 unique patients
# Product info
df_product = fread("\\\\rfawin.partners.org\\mgh-itafisma\\IQVIA\\Product.gz", select=c("PRODUCT_ID", "NDC_CD", "DOSAGE_FORM_NM"))
df_prescription_product = merge(df_opioids,df_product, by="PRODUCT_ID", all.x=TRUE)
# Patient info
df_patient = fread("\\\\rfawin.partners.org\\mgh-itafisma\\IQVIA\\Patient.gz")[PATIENT_ID %in% list_patient]
df_rx_patient = merge(df_prescription_product,df_patient,by="PATIENT_ID", all.x=TRUE)
# 351,517,666 records
# fwrite(df_rx_patient, "C:\\Users\\hd820\\OneDrive - Mass General Brigham\\Data Repository\\IQVIA analysis\\[P2] Upstream model\\MME calculation\\Data\\df_rx_patient.csv")
# 351,517,666 LRx
# ls()
# rm("df_opioids" , "df_patient", "df_prescription_product", "df_product", "list_patient")
# Sample restriction 1: Keep opioid flag 1
df_rx_patient_1 = df_rx_patient[OPIOID_FLAG==1,]
# 351,403,952 records
# Sample restriction 2: Remove injectables and crude/bulk
df_rx_patient_2 = df_rx_patient_1[!(USC_DESC %in% c("MORPHINE/OPIUM, INJECTABLE","SYNTH NARCOTIC, INJECTABLE","CRUDE/BULK MEDICINAL")),]
# 351,049,715 records
# Sample restriction 3: Based on USC codes
table(df_rx_patient_2$USC_DESC)
table(df_rx_patient_2$USC_CD)
# 2214 2222 2232 9150 34210 34220 34240 34290 34380
# 70861942 24641337 241770343 11621631 1454 1658033 13450 481522 3
rm("df_rx_patient" , "df_rx_patient_1")
df_rx_patient_3 = df_rx_patient_2[USC_CD %in% c(2214,2222,2232),]
# 337,273,622 obs
# fwrite(df_rx_patient_3, "C:\\Users\\hd820\\OneDrive - Mass General Brigham\\Data Repository\\IQVIA analysis\\[P2] Upstream model\\MME calculation\\Data\\df_rx_patient_3.csv")
# Check NDC code;No missing value
check = df_rx_patient_3[,c("PATIENT_ID","NDC_CD")]
sum(is.na(check))
# ls()
# rm("df_rx_patient" , "df_rx_patient_1", "df_rx_patient_2", "check")
### STEP4: READ IN MME CONVERSION FILE
convert = fread("C:\\Users\\hd820\\OneDrive - Mass General Brigham\\Data Repository\\IQVIA analysis\\[P2] Upstream model\\MME calculation\\Data\\MME conversion table.csv")
# Merge the Rx file with the converstion table
df_rx_mme = merge(df_rx_patient_3, convert, by.x = "NDC_CD", by.y = "NDC_Numeric", all.x=TRUE)
# 337,273,622 obs
# Remove extra variables after some checking
df_rx_mme2 = df_rx_mme[,-c("MOUD_FLAG","NALOXONE_FLAG","OPIOID_FLAG",
"NDC","PRODNME","GENNME","Master_Form","Class","Drug","LongShortActing","DEAClassCode")]
# The records could not be linked
missconvert = df_rx_mme2[is.na(MME_Conversion_Factor),]
# 1,592,351 (0.47%) records cannot be linked
missprod = missconvert[,c("MKTED_PROD_NM", "STRNT_DESC","Strength_Per_Unit", "UOM", "MME_Conversion_Factor")]
missprod = missprod[!duplicated(missprod)]
# 87 combinations of drug name and strength
# Save the file for manual check and fix
# fwrite(missprod, "C:\\Users\\hd820\\OneDrive - Mass General Brigham\\Data Repository\\IQVIA analysis\\[P2] Upstream model\\MME calculation\\Data\\Missproduct_toFill_2014_2021.csv")
# The records that can be linked
nomissconvert = df_rx_mme2[!is.na(MME_Conversion_Factor),]
# 335,681,271 obs
# Use this as reference for filling up the missing value
nomissprod = nomissconvert[,c("MKTED_PROD_NM", "STRNT_DESC", "Strength_Per_Unit", "UOM", "MME_Conversion_Factor")]
nomissprod = nomissprod[!duplicated(nomissprod)]
# 384 cominations of drug name and strength
# Use the manual fixed data file to fill up the missing value
tofill = fread("C:\\Users\\hd820\\OneDrive - Mass General Brigham\\Data Repository\\IQVIA analysis\\[P2] Upstream model\\MME calculation\\Data\\Missproduct_Conversion_Factor_2014_2021.csv")
missconvert2 = missconvert[,-c("Strength_Per_Unit","UOM","MME_Conversion_Factor")]
missconvert_fill = merge (missconvert2, tofill, by=c("MKTED_PROD_NM","STRNT_DESC"), all.x=TRUE)
# Comine the nomiss one and the filled up missed rows
RX_convert_full = rbind(nomissconvert, missconvert_fill)
setorder(RX_convert_full, PATIENT_ID, SVC_DT)
# 337,273,622 obs, match the initial dataset
# Check the conversion factor
summary(RX_convert_full$MME_Conversion_Factor)
# No missing value
# Save the full dataset
fwrite(RX_convert_full, "C:\\Users\\hd820\\OneDrive - Mass General Brigham\\Data Repository\\IQVIA analysis\\[P2] Upstream model\\MME calculation\\Data\\RX_Patient_MME_2014to2021.csv")
|
import { test, expect } from '@playwright/test';
import { JouerQuizzFixture } from '../../src/app/quizz/jouer-quizz/jouer-quizz.fixture';
import { serverUrl } from '../e2e.config';
test.describe('Jouer Quizz', () => {
test('lancement de la page jouer quizz', async ({ page }) => {
let urlListQuiz = serverUrl+'liste-quizz';
await page.goto(urlListQuiz);
const quizElement = await page.$('.quiz');
if (quizElement) { // Ajoutez cette vérification
await quizElement.click();
// Maintenant, nous sommes sur la page 'accueil-quiz'
await page.waitForSelector('.btnJouer');
const jouerButton = await page.$('.btnJouer');
if (jouerButton) { // Ajoutez cette vérification
await jouerButton.click();
// Maintenant, nous sommes sur la page 'jouer-quizz'
let urlJouer = page.url();
//create all fixtures
const jouerQuizzFixture = new JouerQuizzFixture(page,"fa9112c9-743c-4ba7-ac7f-2f0569b79609");
await expect(page).toHaveURL(urlJouer);
await test.step(`Questions et buble visibles`, async () => {
const questionBubble = await jouerQuizzFixture.getQuestionBubble();
const isVisible = await questionBubble.isVisible();
expect(isVisible).toBeTruthy();
});
await test.step(`Questions text visible and not empty`, async () => {
await page.waitForSelector('#question-animation', { state: 'visible' });
const questionText = await jouerQuizzFixture.getQuestionText();
const isVisible = await questionText.isVisible();
const elementHandle = await questionText.elementHandle();
let innerText = null;
if (elementHandle !== null) {
innerText = await page.evaluate(el => el.textContent, elementHandle);
}
expect(isVisible).toBeTruthy();
expect(innerText).toBeTruthy();
});
await test.step(`Answer buttons are visible`, async () => {
const answerButtons = await jouerQuizzFixture.getAnswerButtons().elementHandles();
for(const button of answerButtons){
expect(await button.isVisible()).toBeTruthy();
}
});
await test.step(`Validate button is visible`, async () => {
const validateButton = await jouerQuizzFixture.getValidateButton();
expect(await validateButton.isVisible()).toBeTruthy();
});
await test.step(`Quiz title should be not empty`, async () => {
const title = await jouerQuizzFixture.getQuizTitle();
expect(title).toBeTruthy();
});
await test.step(`Timer should be visible and not empty`, async () => {
const timer = await jouerQuizzFixture.getTimer();
expect(timer).toBeTruthy();
});
await test.step(`Select an answer and validate`, async () => {
const selectButton = await jouerQuizzFixture.selectAnswerByIndexAndClick(2);
expect(selectButton.nth(1)).toBeVisible();
const validateButton = await jouerQuizzFixture.getValidateButton();
expect(validateButton).toBeVisible();
await validateButton.click();
const nextButton = await jouerQuizzFixture.getNextQuestionButton();
expect(nextButton).toBeVisible();
await nextButton.click();
const selectButton2 = await jouerQuizzFixture.selectAnswerByIndexAndClick(0);
expect(selectButton2.nth(1)).toBeVisible();
await validateButton.click();
await nextButton.click();
const selectButton3 = await jouerQuizzFixture.selectAnswerByIndexAndClick(3);
expect(selectButton3.nth(1)).toBeVisible();
await validateButton.click();
const resultButton = await jouerQuizzFixture.getResultsButton();
expect(resultButton).toBeVisible();
await resultButton.click();
});
} else {
console.log('Le bouton Jouer n\'a pas été trouvé.');
}
} else {
console.log('Aucune carte de quiz n\'a été trouvée.');
}
});
});
//
// await test.step(`Validate button is visible`, async () => {
// const validateButton = await jouerQuizzFixture.getValidateButton();
// expect(await validateButton.isVisible()).toBeTruthy();
// });
// // Scénario de test
// await test.step(`Quiz title should be not empty`, async () => {
// const title = await jouerQuizzFixture.getQuizTitle();
// expect(title).toBeTruthy();
// });
// await test.step(`Timer should be visible and not empty`, async () => {
// const timer = await jouerQuizzFixture.getTimer();
// expect(timer).toBeTruthy();
// });
// await test.step(`Select an answer and validate`, async () => {
// await jouerQuizzFixture.selectAnswerByIndex(0);
// const validateButton = await jouerQuizzFixture.getValidateButton();
// await validateButton.click();
// });
// await test.step(`Next question button should be enabled`, async () => {
// const isDisabled = await jouerQuizzFixture.getNextButtonDisabledStatus();
// expect(isDisabled).toBeFalsy();
// });
// });
|
<script setup lang="ts">
import type { Events } from '../../../functions/types'
interface Props {
type: string
events: Array<Events>
}
const {
type,
events,
} = defineProps<Props>()
const { isCurrentDay, currentMonthYear, previousMonth, nextMonth, goToDay, currentMonthDayYear, datesOfThePastMonth, datesOfTheMonth, datesOfNextMonth, dayName, month, day, year } = useCalendar()
const { getStyle } = useCalendarTime()
const filteredEvents = computed(() => {
const currentEvents = events.filter((event: Events) => {
return event.day === day.value
})
return currentEvents
})
</script>
<template>
<div>
<div class="flex h-full flex-col">
<header class="flex flex-none items-center justify-between border-b border-gray-200 py-4 px-6">
<div>
<h1 class="text-lg font-semibold leading-6 text-gray-900">
<time
:datetime="`${year}-${month + 1}-${day}`"
class="sm:hidden"
>{{ currentMonthDayYear }}</time>
<time
:datetime="`${year}-${month + 1}-${day}`"
class="hidden sm:inline"
>{{ currentMonthDayYear }}</time>
</h1>
<p class="mt-1 text-sm text-gray-500">
{{ dayName }}
</p>
</div>
<CalendarNav :type="type" />
</header>
<div class="isolate flex flex-auto overflow-hidden bg-white">
<div class="flex flex-auto flex-col overflow-auto">
<div class="sticky top-0 z-10 grid flex-none grid-cols-7 bg-white text-xs text-gray-500 shadow ring-1 ring-black ring-opacity-5 md:hidden">
<button
type="button"
class="flex flex-col items-center pt-3 pb-1.5"
>
<span>W</span>
<!-- Default: "text-gray-900", Selected: "bg-gray-900 text-white", Today (Not Selected): "text-indigo-600", Today (Selected): "bg-indigo-600 text-white" -->
<span class="mt-3 flex h-8 w-8 items-center justify-center rounded-full text-base font-semibold text-gray-900">19</span>
</button>
<button
type="button"
class="flex flex-col items-center pt-3 pb-1.5"
>
<span>T</span>
<span class="mt-3 flex h-8 w-8 items-center justify-center rounded-full text-base font-semibold text-indigo-600">20</span>
</button>
<button
type="button"
class="flex flex-col items-center pt-3 pb-1.5"
>
<span>F</span>
<span class="mt-3 flex h-8 w-8 items-center justify-center rounded-full text-base font-semibold text-gray-900">21</span>
</button>
<button
type="button"
class="flex flex-col items-center pt-3 pb-1.5"
>
<span>S</span>
<span class="mt-3 flex h-8 w-8 items-center justify-center rounded-full bg-gray-900 text-base font-semibold text-white">22</span>
</button>
<button
type="button"
class="flex flex-col items-center pt-3 pb-1.5"
>
<span>S</span>
<span class="mt-3 flex h-8 w-8 items-center justify-center rounded-full text-base font-semibold text-gray-900">23</span>
</button>
<button
type="button"
class="flex flex-col items-center pt-3 pb-1.5"
>
<span>M</span>
<span class="mt-3 flex h-8 w-8 items-center justify-center rounded-full text-base font-semibold text-gray-900">24</span>
</button>
<button
type="button"
class="flex flex-col items-center pt-3 pb-1.5"
>
<span>T</span>
<span class="mt-3 flex h-8 w-8 items-center justify-center rounded-full text-base font-semibold text-gray-900">25</span>
</button>
</div>
<div class="flex w-full flex-auto">
<div class="w-14 flex-none bg-white ring-1 ring-gray-100" />
<div class="grid flex-auto grid-cols-1 grid-rows-1">
<!-- Horizontal lines -->
<div
class="col-start-1 col-end-2 row-start-1 grid divide-y divide-gray-100"
style="grid-template-rows: repeat(48, minmax(3.5rem, 1fr))"
>
<div class="row-end-1 h-7" />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
12AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
1AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
2AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
3AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
4AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
5AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
6AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
7AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
8AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
9AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
10AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
11AM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
12PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
1PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
2PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
3PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
4PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
5PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
6PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
7PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
8PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
9PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
10PM
</div>
</div>
<div />
<div>
<div class="-mt-2.5 -ml-14 w-14 pr-2 text-right text-xs leading-5 text-gray-400">
11PM
</div>
</div>
<div />
</div>
<!-- Events -->
<ol
class="col-start-1 col-end-2 row-start-1 grid grid-cols-1"
style="grid-template-rows: 1.75rem repeat(288, minmax(0, 1fr)) auto; padding: 0"
>
<li
v-for="(event, index) in filteredEvents"
:key="index"
class="relative mt-px flex"
:style="getStyle(event)"
>
<a
href="#"
class="group absolute inset-1 flex flex-col overflow-y-auto rounded-lg bg-blue-50 p-2 text-xs leading-5 hover:bg-blue-100"
>
<p class="order-1 font-semibold text-blue-700">{{ event.title }}</p>
<p class="text-blue-500 group-hover:text-blue-700"><time datetime="2022-01-22T06:00">{{ event.time.from }}</time></p>
</a>
</li>
</ol>
</div>
</div>
</div>
<div class="hidden w-1/2 max-w-md flex-none border-l border-gray-100 py-10 px-8 md:block">
<div class="flex items-center text-center text-gray-900">
<button
type="button"
class="-m-1.5 flex flex-none items-center justify-center p-1.5 text-gray-400 hover:text-gray-500"
@click="previousMonth"
>
<span class="sr-only">Previous month</span>
<!-- Heroicon name: mini/chevron-left -->
<svg
class="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M12.79 5.23a.75.75 0 01-.02 1.06L8.832 10l3.938 3.71a.75.75 0 11-1.04 1.08l-4.5-4.25a.75.75 0 010-1.08l4.5-4.25a.75.75 0 011.06.02z"
clip-rule="evenodd"
/>
</svg>
</button>
<div class="flex-auto font-semibold">
{{ currentMonthYear }}
</div>
<button
type="button"
class="-m-1.5 flex flex-none items-center justify-center p-1.5 text-gray-400 hover:text-gray-500"
@click="nextMonth"
>
<span class="sr-only">Next month</span>
<!-- Heroicon name: mini/chevron-right -->
<svg
class="h-5 w-5"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path
fill-rule="evenodd"
d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z"
clip-rule="evenodd"
/>
</svg>
</button>
</div>
<div class="mt-6 grid grid-cols-7 text-center text-xs leading-6 text-gray-500">
<div>S</div>
<div>M</div>
<div>T</div>
<div>W</div>
<div>T</div>
<div>F</div>
<div>S</div>
</div>
<div class="isolate mt-2 grid grid-cols-7 gap-px rounded-lg bg-gray-200 text-sm shadow ring-1 ring-gray-200">
<!--
Always include: "py-1.5 hover:bg-gray-100 focus:z-10"
Is current month, include: "bg-white"
Is not current month, include: "bg-gray-50"
Is selected or is today, include: "font-semibold"
Is selected, include: "text-white"
Is not selected, is not today, and is current month, include: "text-gray-900"
Is not selected, is not today, and is not current month, include: "text-gray-400"
Is today and is not selected, include: "text-indigo-600"
Top left day, include: "rounded-tl-lg"
Top right day, include: "rounded-tr-lg"
Bottom left day, include: "rounded-bl-lg"
Bottom right day, include: "rounded-br-lg"
-->
<button
v-for="pastDate in datesOfThePastMonth"
:key="pastDate"
type="button"
class="bg-gray-50 py-1.5 text-gray-400 hover:bg-gray-100 focus:z-10"
@click="goToDay(pastDate, (month + 1) - 1)"
>
<!--
Always include: "mx-auto flex h-7 w-7 items-center justify-center rounded-full"
Is selected and is today, include: "bg-indigo-600"
Is selected and is not today, include: "bg-gray-900"
-->
<time
:datetime="`${year}-${month + 1}-${pastDate}`"
class="mx-auto flex h-7 w-7 items-center justify-center rounded-full"
>{{ pastDate }}</time>
</button>
<button
v-for="date in datesOfTheMonth"
:key="date"
type="button"
class="bg-white py-1.5 text-gray-900 hover:bg-gray-100 focus:z-10"
@click="goToDay(date, month + 1)"
>
<time
:datetime="`${year}-${month + 1}-${date}`"
class="mx-auto flex h-7 w-7 items-center justify-center rounded-full"
:class="{ ' bg-gray-900 font-semibold text-white': isCurrentDay(`${month + 1}-${date}-${year}`) }"
>{{ date }}</time>
</button>
<button
v-for="nextDate in datesOfNextMonth"
:key="nextDate"
type="button"
class="bg-gray-50 py-1.5 text-gray-400 hover:bg-gray-100 focus:z-10"
@click="goToDay(nextDate, (month + 1) + 1)"
>
<time
:datetime="`${year}-${month + 1}-${nextDate}`"
class="mx-auto flex h-7 w-7 items-center justify-center rounded-full"
>{{ nextDate }}</time>
</button>
</div>
</div>
</div>
</div>
</div>
</template>
|
# RedisLiteServer
## Introduction
RedisLiteServer is a lightweight C# implementation inspired by the challenge presented in "Write your own Redis Server" by John Crickett, available at [codingchallenges.fyi](https://codingchallenges.fyi/challenges/challenge-redis). This project aims to provide a simplified Redis-like server with fundamental functionalities.
It provides a simple key-value store with support for various commands such as SET, GET, EXISTS, DEL, INCR, DECR, LPUSH, RPUSH, SAVE, and LOAD.
This project is intended to serve as a learning resource for understanding the fundamentals of building a basic Redis server and is not suitable for production use.
## Project Components
### 1. RedisServer
The `RedisServer` class is the core component responsible for handling client connections, processing commands, and managing the key-value store. It uses TCP for communication and allows clients to interact with the server using a simplified Redis-like protocol.
### 2. KeyValueStore
The `KeyValueStore` class represents the in-memory key-value store used by the Redis server. It supports basic operations such as SET, GET, EXISTS, DEL, INCR, DECR, LPUSH, and RPUSH. Additionally, it handles key expiration based on specified options.
### 3. Serializer
The `Serializer` namespace contains classes for serializing and deserializing data. The `RespSerializer` class handles the Redis Serialization Protocol (RESP) format, and the `GeneralSerializer` class extends it to provide additional functionality for serializing and deserializing various data types.
## How to Install and Connect
To use the RedisLiteServer solution:
1. Clone the repository: `git clone https://github.com/YamanNasser/RedisLiteServer.git`
2. Open the solution in Visual Studio or your preferred C# development environment.
3. Build the solution.
To connect to the RedisLiteServer:
1. Start the RedisLiteServer by running the application.
2. Connect to the server using a Redis client library or a Redis CLI.
3. By default, the server listens on `127.0.0.1` and port `6379`.
Example using Redis CLI:
```redis-cli -h 127.0.0.1 -p 6379```
## Demo
Here are examples demonstrating the usage of various commands:
### SET and GET
```
# Set a key
SET myKey "Hello, RedisLiteServer!"
# Get the value for the key
GET myKey
```
### INCR and DECR
```
# Set an integer value
SET counter 10
# Increment the counter
INCR counter
# Decrement the counter
DECR counter
```
### LPUSH and RPUSH
```
# Left push (prepend) items to a list
LPUSH myList "item1" "item2" "item3"
# Right push (append) items to a list
RPUSH myList "item4" "item5"
```
### EXISTS and DEL
```
# Check if a key exists
EXISTS myKey
# Delete a key
DEL myKey
```
### SAVE and LOAD
```
# Save the current database state to a file
SAVE
# Load the database state from a file
LOAD
```
# Contributing
Feel free to explore additional Redis commands and experiment with the provided commands to understand the RedisLiteServer functionalities.
# Connect with me on LinkedIn
<a href="https://www.linkedin.com/in/yamannasser/">Yaman Nasser</a> Software Engineer
# Support
Has this Project helped you learn something New? or Helped you at work? Do Consider Supporting. Here are a few ways by which you can support.
1. Leave a star! ⭐
2. Recommend this awesome project to your colleagues.
|
using CandidateJourney.Domain;
namespace CandidateJourney.API.GraphQLTypes
{
[GraphQLName("AudienceCategory")]
public class AudienceCategoryType : EnumType<AudienceCategory>
{
protected override void Configure(IEnumTypeDescriptor<AudienceCategory> descriptor)
{
descriptor.BindValuesExplicitly();
descriptor.Description("Defines the target audience category for an event.");
descriptor.Value(AudienceCategory.Student)
.Name("STUDENT")
.Description("The event is targeted towards students.");
descriptor.Value(AudienceCategory.All)
.Name("ALL")
.Description("The event is open to all audiences.");
}
}
}
|
import type { PublicKey } from '@solana/web3.js';
import { toBidReceiptAccount } from '../accounts';
import { AuctionHouse, Bid, toLazyBid } from '../models';
import {
Operation,
OperationHandler,
OperationScope,
useOperation,
} from '@/types';
import type { Metaplex } from '@/Metaplex';
// -----------------
// Operation
// -----------------
const Key = 'FindBidByReceiptOperation' as const;
/**
* Finds a Bid by its receipt address.
*
* ```ts
* const nft = await metaplex
* .auctionHouse()
* .findBidByReceipt({ receiptAddress, auctionHouse };
* ```
*
* @group Operations
* @category Constructors
*/
export const findBidByReceiptOperation =
useOperation<FindBidByReceiptOperation>(Key);
/**
* @group Operations
* @category Types
*/
export type FindBidByReceiptOperation = Operation<
typeof Key,
FindBidByReceiptInput,
Bid
>;
/**
* @group Operations
* @category Inputs
*/
export type FindBidByReceiptInput = {
/**
* The address of the bid receipt account.
* This is the account that stores information about this bid.
* The Bid model is built on top of this account.
*/
receiptAddress: PublicKey;
/** A model of the Auction House related to this bid. */
auctionHouse: AuctionHouse;
/**
* Whether or not we should fetch the JSON Metadata for the NFT or SFT.
*
* @defaultValue `true`
*/
loadJsonMetadata?: boolean;
};
/**
* @group Operations
* @category Handlers
*/
export const findBidByReceiptOperationHandler: OperationHandler<FindBidByReceiptOperation> =
{
handle: async (
operation: FindBidByReceiptOperation,
metaplex: Metaplex,
scope: OperationScope
) => {
const { receiptAddress, auctionHouse } = operation.input;
const account = toBidReceiptAccount(
await metaplex.rpc().getAccount(receiptAddress, scope.commitment)
);
scope.throwIfCanceled();
const lazyBid = toLazyBid(account, auctionHouse);
return metaplex
.auctionHouse()
.loadBid({ lazyBid, ...operation.input }, scope);
},
};
|
import logging
import boto3
from botocore.exceptions import ClientError
from django.conf import settings
logger = logging.getLogger(settings.LOGGER_NAME)
class DynamoDBClient:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(DynamoDBClient, cls).__new__(cls)
cls._instance = boto3.client("dynamodb")
return cls._instance
class DynamoDBResource:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super(DynamoDBResource, cls).__new__(cls)
cls._instance = boto3.resource("dynamodb")
return cls._instance
class BaseTable:
_table = None
_table_name: str = None
@classmethod
def _init_table(cls):
table_name = (
cls._table_name
if (not settings.TESTING)
else f"{cls._table_name}_testing"
)
if not cls._table or cls._table.name != table_name:
resource = DynamoDBResource()
cls._table = resource.Table(table_name)
@classmethod
def create_table(cls: "BaseTable") -> None:
if not hasattr(cls, "id"):
cls.id = "id"
if not cls._table_name:
raise NotImplementedError("`_table_name` must be defined in subclass")
if not cls._table_name.startswith(settings.PROJECT_KEY):
raise ValueError(f"`_table_name` must start with `{settings.PROJECT_KEY}_`")
client = DynamoDBClient()
table_name = (
cls._table_name if (not settings.TESTING) else f"{cls._table_name}_testing"
)
try:
client.create_table(
TableName=table_name,
AttributeDefinitions=[{"AttributeName": cls.id, "AttributeType": "N"}],
KeySchema=[{"AttributeName": cls.id, "KeyType": "HASH"}],
ProvisionedThroughput={
"ReadCapacityUnits": settings.DDB_TABLE_READ_CAPACITY_UNITS,
"WriteCapacityUnits": settings.DDB_TABLE_WRITE_CAPACITY_UNITS,
},
)
client.get_waiter("table_exists").wait(
TableName=table_name,
WaiterConfig={"Delay": 5, "MaxAttempts": 10},
)
except ClientError as exc:
if exc.response["Error"]["Code"] != "ResourceInUseException":
logger.exception("Error creating table", exc_info=exc)
raise exc
@classmethod
def delete_table(cls):
if not settings.TESTING:
raise NotImplementedError("This method is only for testing")
if not cls._table_name:
raise NotImplementedError("`_table_name` must be defined in subclass")
if not cls._table_name.startswith(settings.PROJECT_KEY):
raise ValueError(f"`_table_name` must start with `{settings.PROJECT_KEY}_`")
client = DynamoDBClient()
table_name = f"{cls._table_name}_testing"
try:
client.delete_table(TableName=table_name)
client.get_waiter("table_not_exists").wait(
TableName=table_name, WaiterConfig={"Delay": 5, "MaxAttempts": 10}
)
except ClientError as exc:
if exc.response["Error"]["Code"] != "ResourceNotFoundException":
logger.exception("Error deleting table", exc_info=exc)
raise exc
|
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:number_trivia/features/number_trivia/data/models/number_trivia_model.dart';
import 'package:number_trivia/features/number_trivia/domain/entities/number_trivia.dart';
import '../../../../fixtures/fixture_reader.dart';
void main() {
final tNumberTriviaModel = NumberTriviaModel(number: 1, text: 'Test Text');
test(
'should be a subclass os NumberTrivia entity',
() async {
expect(tNumberTriviaModel, isA<NumberTrivia>());
},
);
group('fromJson', () {
test('should return a valid model when the JSON number is a integer', () {
//arrange
final Map<String, dynamic> jsonMap = json.decode(fixture('trivia.json'));
//act
final result = NumberTriviaModel.fromJson(jsonMap);
//assert
expect(result, equals(tNumberTriviaModel));
});
test(
'should return a valid model when the JSON number is regarded as a double',
() {
//arrange
final Map<String, dynamic> jsonMap =
json.decode(fixture('trivia_double.json'));
//act
final result = NumberTriviaModel.fromJson(jsonMap);
//assert
expect(result, equals(tNumberTriviaModel));
});
});
group('toJson', () {
test(
'should return a JSON map containing the proper data',
() {
//act
final result = tNumberTriviaModel.toJson();
//assert
final expectedMap = {'text': 'Test Text', 'number': 1};
expect(result, expectedMap);
},
);
});
}
|
package Class13;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class PreparedStatementAPI {
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String dbURL = "jdbc:mysql://localhost:3306/hplus?user=root&password=Reena@54321";
conn = DriverManager.getConnection(dbURL);
if (conn != null) {
System.out.println("Connection establised using connection");
}
String query = "update emp_tab set name = ? where empno = ?";
ps = conn.prepareStatement(query);
ps.setString(1, "KING2");
ps.setInt(2, 7001);
int rows = ps.executeUpdate();
if (rows != 0)
System.out.println("Update Completed Successfully");
else
System.out.println("Update could not work");
String selectQuery = "SELECT * from emp_tab WHERE empno = ?";
ps = conn.prepareStatement(selectQuery);
ps.setInt(1,7001);
rs = ps.executeQuery();
while (rs.next())
System.out.println(
rs.getInt(1) + "\t" + rs.getString(2) + "\t" + rs.getString(3) + "\t" + rs.getString(4));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package main
import (
"fmt"
"log"
"encoding/json"
"math/rand"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type Movie struct {
ID string `json:"id"`
Isbn string `json:"isbn"`
Title string `json:"title"`
Director *Director `json:"director"`
}
type Director struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
}
var movies []Movie
func getMovies(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(movies)
}
func getMovie(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for _, item := range movies {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
}
func createMovie(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var movie Movie
_ = json.NewDecoder(r.Body).Decode(&movie)
params := mux.Vars(r)
if (params["id"] == "") {
movie.ID = strconv.Itoa(rand.Intn(1000000000))
} else {
movie.ID = params["id"]
}
movies = append(movies, movie)
json.NewEncoder(w).Encode(movie)
}
func updateMovie(w http.ResponseWriter, r *http.Request) {
deleteMovie(w, r)
createMovie(w, r)
}
func deleteMovie(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for index, item := range movies {
if item.ID == params["id"] {
movies = append(movies[:index], movies[index + 1:]...)
break
}
}
json.NewEncoder(w).Encode(movies)
}
func main() {
router := mux.NewRouter()
router.HandleFunc("/movies", getMovies).Methods("GET")
router.HandleFunc("/movies/{id}", getMovie).Methods("GET")
router.HandleFunc("/movies", createMovie).Methods("POST")
router.HandleFunc("/movies/{id}", updateMovie).Methods("PUT")
router.HandleFunc("/movies/{id}", deleteMovie).Methods("DELETE")
fmt.Println("Starting server at port 3000")
log.Fatal(http.ListenAndServe(":3000", router))
}
|
#include <stdio.h> /*printf*/
#include <assert.h> /*assert*/
#include <stdlib.h> /*malloc*/
typedef struct node {
int data;
struct node *next;
} node;
void add(node *head, int x){
/*pre: head points to the first, empty element. The last element's next is NULL
post: a new node containing x is added to the end of the list*/
assert(head!=NULL);
node *p = head;
while (p->next!=NULL) {
p = p->next;
} /*p points to the last element*/
node *element = (node*) malloc(sizeof(node));
element->next = NULL;
element->data = x;
p->next = element;
}
int size(node *l)
{
// Excercise 3 b )
node *p = l;
int size = 0;
while (p->next != NULL)
{
size++;
p = p->next;
}
return size;
}
void printout(node *l)
{
/* pre : head points to the first , empty element . The last element ’s next is NULL
post : the values of the list are printed out */
node *p = l->next;
while (p != NULL)
{
printf(" %d , ", p->data);
p = p->next; /* Iterate to the next node */
}
printf("\n");
}
int largest(node *l)
{
/* pre : head points to the first, empty element. The last element’s next is NULL.
size (l > 0)
post : returns the largest value of the list */
assert(l->next != NULL);
node *p = l->next;
int largest = p->data;
while (p->next != NULL)
{
p = p->next;
if (p->data > largest)
{
largest = p->data;
}
}
return largest;
}
|
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
using System;
using System.Linq;
using System.Threading.Tasks;
using Amazon.Rekognition;
using Amazon.Rekognition.Model;
using AWS.Lambda.Powertools.Logging;
using AWS.Lambda.Powertools.Parameters;
using AWS.Lambda.Powertools.Parameters.SecretsManager;
using AWS.Lambda.Powertools.Parameters.SimpleSystemsManagement;
using AWS.Lambda.Powertools.Parameters.Transform;
namespace PowertoolsWorkshop.Module2.Services;
public interface IImageDetectionService
{
Task<bool> HasPersonLabel(string fileId, string userId, string objectKey);
Task ReportImageIssue(string fileId, string userId);
}
public class ImageDetectionService : IImageDetectionService
{
private static string _filesBucketName;
private static string _apiUrlParameterName;
private static string _apiKeySecretName;
private static IAmazonRekognition _rekognitionClient;
private static IApiService _apiService;
private static ISsmProvider _ssmProvider;
private static ISecretsProvider _secretsProvider;
public ImageDetectionService()
{
_filesBucketName = Environment.GetEnvironmentVariable("BUCKET_NAME_FILES");
_apiUrlParameterName = Environment.GetEnvironmentVariable("API_URL_PARAMETER_NAME");
_apiKeySecretName = Environment.GetEnvironmentVariable("API_KEY_SECRET_NAME");
_apiService = new ApiService();
_rekognitionClient = new AmazonRekognitionClient();
_ssmProvider = ParametersManager.SsmProvider;
_secretsProvider = ParametersManager.SecretsProvider;
}
public async Task<bool> HasPersonLabel(string fileId, string userId, string objectKey)
{
Logger.LogInformation($"Get labels for File Id: {fileId}");
var response = await _rekognitionClient.DetectLabelsAsync(new DetectLabelsRequest
{
Image = new Image
{
S3Object = new S3Object
{
Bucket = _filesBucketName,
Name = objectKey
},
}
}).ConfigureAwait(false);
if (response?.Labels is null || !response.Labels.Any())
{
Logger.LogWarning("No labels found in image");
return false;
}
if (!response.Labels.Any(l =>
string.Equals(l.Name, "Person", StringComparison.InvariantCultureIgnoreCase) &&
l.Confidence > 75))
{
Logger.LogWarning("No person found in image");
return false;
}
Logger.LogInformation("Person found in image");
return true;
}
public async Task ReportImageIssue(string fileId, string userId)
{
var apiUrlParameter = await _ssmProvider
.WithTransformation(Transformation.Json)
.GetAsync<ApiUrlParameter>(_apiUrlParameterName)
.ConfigureAwait(false);
var apiKey = await _secretsProvider
.GetAsync(_apiKeySecretName)
.ConfigureAwait(false);
if (string.IsNullOrWhiteSpace(apiUrlParameter?.Url) || string.IsNullOrWhiteSpace(apiKey))
throw new Exception($"Missing apiUrl or apiKey. apiUrl: ${apiUrlParameter?.Url}, apiKey: ${apiKey}");
Logger.LogInformation("Sending report to the API");
await _apiService.PostAsJsonAsync(apiUrlParameter.Url, apiKey, new { fileId, userId }).ConfigureAwait(false);
Logger.LogInformation("Report sent to the API");
}
}
|
/**
* Tungsten Scale-Out Stack
* Copyright (C) 2009 Continuent Inc.
* Contact: tungsten@continuent.org
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*
* Initial developer(s): Gilles Rayrat.
* Contributor(s): ______________________.
*/
package com.continuent.tungsten.common.cluster.resource.notification;
import com.continuent.tungsten.common.config.TungstenProperties;
/**
* Provides utilities for resource status specific properties, specialized in
* data source representation
*
* @author <a href="mailto:gilles.rayrat@continuent.com">Gilles Rayrat</a>
* @version 1.0
*/
public class HostStatus extends ResourceStatus
{
public static final String PROPERTY_KEY_CLUSTER = "dataServiceName";
public static final String PROPERTY_KEY_HOST = "host";
public static final String PROPERTY_KEY_UPTIME = "uptime";
public static final String PROPERTY_LOAD_AVG_1 = "loadAverage1";
public static final String PROPERTY_LOAD_AVG_5 = "loadAverage5";
public static final String PROPERTY_LOAD_AVG_15 = "loadAverage5";
public static final String PROPERTY_KEY_CPUCOUNT = "cpuCount";
private int cpuCount = 1;
private double loadAverage1 = 0.0;
private double loadAverage5 = 0.0;
private double loadAverage15 = 0.0;
private String uptime = null;
private String host = null;
private String service = null;
public HostStatus(String type, String name, String state,
String clusterName, String host, String uptime, int cpuCount,
double loadAverage1, double loadAverage5, double loadAverage15)
{
super(type, name, state, null);
TungstenProperties hostProperties = new TungstenProperties();
hostProperties.setString(PROPERTY_KEY_CLUSTER, clusterName);
hostProperties.setString(PROPERTY_KEY_HOST, host);
hostProperties.setString(PROPERTY_KEY_UPTIME, uptime);
hostProperties.setInt(PROPERTY_KEY_CPUCOUNT, cpuCount);
hostProperties.setDouble(PROPERTY_LOAD_AVG_1, loadAverage1);
hostProperties.setDouble(PROPERTY_LOAD_AVG_5, loadAverage5);
hostProperties.setDouble(PROPERTY_LOAD_AVG_15, loadAverage5);
}
public int getCpuCount()
{
return cpuCount;
}
public String getUptime()
{
return uptime;
}
public String getHost()
{
return host;
}
public String getService()
{
return service;
}
public double getLoadAverage1()
{
return loadAverage1;
}
public double getLoadAverage5()
{
return loadAverage5;
}
public double getLoadAverage15()
{
return loadAverage15;
}
}
|
from datetime import datetime
from uuid import uuid4
class Refund:
def __init__(self, reason, value, user_id, booking_id):
self.reason = reason
self.value = value
self.user_id = user_id
self.booking_id = booking_id
@classmethod
def from_dict(cls, refund_dict):
return cls(
refund_dict['reason'],
refund_dict['value'],
refund_dict['user_id'],
refund_dict['booking_id']
)
def to_dict(self):
return {
"reason": self.reason,
"value": self.value,
"user_id": self.user_id,
"booking_id": self.booking_id
}
class RefundManager:
def __init__(self, mongo_client, db_name, collection_name):
self.db = mongo_client[db_name]
self.collection = self.db[collection_name]
def get_refunds(self):
refunds_data = self.collection.find()
refunds = [Refund.from_dict(r) for r in refunds_data]
return refunds
def get_refund_by_id(self, _id):
try:
refund_data = self.collection.find_one({"_id": _id})
return Refund.from_dict(refund_data) if refund_data else None
except ValueError:
return None
def write_refund(self, refund):
refund_dict = refund.to_dict()
result = self.collection.insert_one(refund_dict)
return result.inserted_id
def update_refund(self, _id, updated_refund):
updated_data = updated_refund.to_dict()
result = self.collection.update_one({"_id": _id}, {"$set": updated_data})
return result.modified_count
def delete_refund(self, _id):
result = self.collection.delete_one({"_id": _id})
return result.deleted_count
|
import Foundation
import ArgumentParser
import SourceCrawlerKit
@main
struct SourceCrawlerCommand: ParsableCommand {
@Option(name: .shortAndLong, help: "The root path to start the file traversal.")
var rootPath: String?
@Option(name: .customShort("t"), help: "Comma-separated list of file extensions to include in the analysis.")
var fileExtensions: String?
@Option(name: [.customShort("o"), .long], help: "Output file path for the JSON results.")
var outputPath: String?
@Option(name: [.customShort("e"), .long], help: "Comma-separated list of paths to exclude. eg. **/Tests/*.swift")
var excludedPaths: String?
@Flag(name: .customShort("c"), help: "Exclude file contents in output")
var excludeContents: Bool = false
@Flag(name: .customShort("f"), help: "Include function body in output")
var includeBody: Bool = false
mutating func run() throws {
let rootDirectory = rootPath ?? FileManager.default.currentDirectoryPath
let defaultOutputName = URL(fileURLWithPath: rootDirectory).lastPathComponent
let extensions = (fileExtensions ?? "swift,txt,md").components(separatedBy: ",")
let exclusions = excludedPaths?.components(separatedBy: ",") ?? []
let crawler = SwiftSourceCrawler(rootPath: rootDirectory, acceptedExtensions: extensions, excludedPaths: exclusions, includeContents: !excludeContents, includeBody: includeBody)
let results = try crawler.crawlSource()
let encoder = JSONEncoder()
encoder.outputFormatting = [.sortedKeys]
if let jsonData = try? encoder.encode(results) {
let outputURL = URL(fileURLWithPath: outputPath ?? "\(defaultOutputName).json")
try jsonData.write(to: outputURL)
print("Analysis results saved to \(outputURL)")
} else {
print("Failed to serialize results to JSON")
}
}
}
|
import React, { useContext, useState } from "react";
import { UserContext } from "../UserContext";
import axios from "axios";
export const Stream = () => {
const { username: name, streamKey } = useContext(UserContext);
const [title, setTitle] = useState("");
const [selectedFile, setSelectedFile] = useState(null);
function saveTitle(e) {
try {
e.preventDefault();
const formData = new FormData();
formData.append("streamKey", streamKey);
formData.append("image", selectedFile);
formData.append("title", title);
const response = axios.post("/streamInfo", formData);
if (response.status === 200) alert("Stream Info and thumbnail Saved");
} catch (error) {
alert(" some error occured please upload again");
}
}
return (
<div>
<div className="bg-gray-100 h-screen flex flex-col p-6">
<h1 className="text-3xl font-semibold mb-4">
Live Streaming Instructions
</h1>
<p className="text-lg text-gray-700 mb-4 font-bold">
To start streaming live, follow these steps:
</p>
<ol className=" text-gray-800 font-mono text-2xl">
<li className="mb-2">
<span className=" font-bold">Step 1</span>: Give Title and Thumbnail
of your stream
<form
className=" mt-4"
onSubmit={(e) => {
saveTitle(e);
}}
>
<div class="mb-4">
<input
type="text"
id="title"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
placeholder="Your Title Here"
value={title}
onChange={(e) => {
setTitle(e.target.value);
}}
required
></input>
</div>
<div class="mb-4">
<input
type="file"
id="image"
class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
placeholder="Your Title Here"
onChange={(e) => {
setSelectedFile(e.target.files[0]);
}}
required
></input>
</div>
<button
type="submit"
class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
>
Save
</button>
</form>
</li>
<li className="mb-2">
<span className=" font-bold">Step 2</span>: open any Broadcasting
software.
</li>
<li className="mb-2">
<span className=" font-bold">Step 3</span>: Open setting of it and
specify RTMP URL{" "}
<span className=" text-gray-600z text-xl font-bold">
rtmp://127.0.0.1:1935/live
</span>
.
</li>
<li className="mb-2">
<span className=" font-bold">Step 4</span>: Set stream key to{" "}
<span className=" text-gray-600 font-bold text-xl">
{streamKey}
</span>
.
</li>
<li className="mb-2">
<span className=" font-bold">Step 5</span>: Go live and engage with
your audience.
</li>
</ol>
</div>
</div>
);
};
|
package storage
import (
"database/sql"
"fmt"
"os"
"strconv"
_ "github.com/lib/pq"
t "github.com/mrkhay/gobank/type"
"golang.org/x/crypto/bcrypt"
)
type Storage interface {
CreateAccount(*t.Account) error
DeleteAccount(int) error
UpdateAccount(*t.Account) error
GetAccounts() ([]*t.Account, error)
AccountQuerey
Transaction
}
type AccountQuerey interface {
GetAccountByID(int) (*t.Account, error)
GetAccountByNumber(int) (*int, error)
GetAccountByPasswordAndEmail(req *t.LoginRequest) (*t.Account, error)
CheckIfEmailExists(email string) (bool, error)
}
type Transaction interface {
TranscationTest() (bool, error)
Transfer(req *t.TransferRequest) (*t.Transcation, error)
TopUpAccount(req *t.TopUpRequest) error
GetUserTransactions(acc_num int) ([]*t.Transcation, error)
GetTransactions() ([]*t.Transcation, error)
}
type PostgresStorage struct {
db *sql.DB
}
func NewPostgresStorage() (*PostgresStorage, error) {
connStr := os.Getenv("POSTGRES_URI")
db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}
if err := db.Ping(); err != nil {
return nil, err
}
return &PostgresStorage{
db: db,
}, nil
}
func (s *PostgresStorage) Init() error {
return s.CreateAccountTable()
}
func (s *PostgresStorage) CreateAccountTable() error {
querey := `CREATE TABLE IF NOT EXISTS accounts (
id serial,
first_name varchar(50),
last_name varchar(50),
acc_number serial unique,
balance money,
email varchar(50) ,
password varchar(200),
created_at timestamp
)`
_, err := s.db.Exec(querey)
if err != nil {
return err
}
querey = `CREATE TABLE IF NOT EXISTS transactions (
transaction_id uuid primary key,
sen_acc serial references accounts(acc_number),
rec_acc serial references accounts(acc_number),
amount money,
description varchar(80),
status varchar(20),
date timestamp
)`
_, err = s.db.Exec(querey)
if err != nil {
return err
}
querey = `CREATE OR REPLACE VIEW transacationview AS
SELECT t.transaction_id, t.amount, t.description,t.status,t.date,s.acc_number AS sender_acc,
s.first_name AS sender_fn,s.last_name AS sender_ln, s.balance AS sender_balance,s.email AS
sender_email,r.acc_number AS receiver_acc, r.first_name AS receiver_fn,r.last_name AS receiver_ln,
r.balance AS receiver_balance,r.email AS receiver_email FROM transactions t JOIN accounts s ON t.sen_acc=s.acc_number
JOIN accounts r ON t.rec_acc=r.acc_number`
_, err = s.db.Exec(querey)
return err
}
func (s *PostgresStorage) GetAccountByPasswordAndEmail(req *t.LoginRequest) (*t.Account, error) {
rows, err := s.db.Query("select * from accounts where email = $1", req.Email)
if err != nil {
return nil, err
}
for rows.Next() {
acc, err := scanIntoAccount(rows)
if err != nil {
return nil, err
}
// validating password
if err := bcrypt.CompareHashAndPassword([]byte(acc.EncryptedPassword), []byte(req.Pasword)); err != nil {
return nil, fmt.Errorf("invalid password")
} else {
return acc, nil
}
}
return nil, fmt.Errorf("accounts with email [ %s ] not found", req.Email)
}
func (s *PostgresStorage) CreateAccount(acc *t.Account) error {
// begin transaction
tx, err := s.db.Begin()
if err != nil {
return err
}
query :=
`insert into accounts
(first_name, last_name, acc_number, balance, email, password, created_at)
values($1,$2,$3,$4,$5,$6,$7)
RETURNING id`
res, err := tx.Exec(
query,
acc.FirstName,
acc.LastName,
acc.AccountNumber,
acc.Balance,
acc.Email,
acc.EncryptedPassword,
acc.CreatedAt)
if err != nil {
tx.Rollback()
return err
}
i, err := res.RowsAffected()
if err != nil {
return err
}
if i < 1 {
return fmt.Errorf("account not found")
}
err = tx.Commit()
if err != nil {
tx.Rollback()
return err
}
return nil
}
func (s *PostgresStorage) GetAccounts() ([]*t.Account, error) {
rows, err := s.db.Query("select * from accounts")
if err != nil {
return nil, err
}
accounts := []*t.Account{}
for rows.Next() {
account, err := scanIntoAccount(rows)
if err != nil {
return nil, err
}
accounts = append(accounts, account)
}
return accounts, nil
}
func (s *PostgresStorage) GetAccountByNumber(number int) (*int, error) {
rows, err := s.db.Query(`select acc_number from accounts where acc_number = $1`, number)
if err != nil {
return nil, err
}
for rows.Next() {
acc_num := 0
err := rows.Scan(
&acc_num)
if err != nil {
return nil, err
} else {
return &acc_num, nil
}
}
return nil, fmt.Errorf("account with acc_number [ %d ] not found", number)
}
func (s *PostgresStorage) UpdateAccount(*t.Account) error {
return nil
}
func (s *PostgresStorage) DeleteAccount(id int) error {
_, err := s.db.Exec("delete from accounts where id = $1", id)
if err != nil {
return fmt.Errorf("account with id:{ %d } not found", id)
}
return nil
}
func (s *PostgresStorage) GetAccountByID(id int) (*t.Account, error) {
rows, err := s.db.Query("select * from accounts where id = $1", id)
if err != nil {
return nil, err
}
for rows.Next() {
return scanIntoAccount(rows)
}
defer rows.Close()
return nil, fmt.Errorf("account %d not found", id)
}
func (s *PostgresStorage) CheckIfEmailExists(email string) (bool, error) {
rows, err := s.db.Query("select email from accounts where email = $1", email)
if err != nil {
return false, err
}
account := new(t.Account)
for rows.Next() {
err := rows.Scan(
&account.Email,
)
if err != nil {
return false, nil
} else {
return true, nil
}
}
defer rows.Close()
return false, nil
}
// transactions
func (s *PostgresStorage) TranscationTest() (bool, error) {
// begin transaction
tx, err := s.db.Begin()
if err != nil {
return false, err
}
name := "DFGHJK"
// function
res, err := tx.Exec(`delete from accounts where first_name = $1`, name)
if err != nil {
tx.Rollback()
return false, err
}
r, _ := res.RowsAffected()
if r < 1 {
fmt.Println(r)
return false, fmt.Errorf("account not found")
}
// commit the transaction
err = tx.Commit()
if err != nil {
return false, err
}
return true, nil
}
func (s *PostgresStorage) GetTransactiobById(id *string) (*t.Transcation, error) {
rows, err := s.db.Query(`select * from transacationview where transaction_id = $1`, id)
if err != nil {
return nil, err
}
for rows.Next() {
t, err := scanIntoTransaction(rows)
if err != nil {
return nil, err
} else {
return t, nil
}
}
return nil, fmt.Errorf("transaction with id [ %d ] not found", id)
}
func (s *PostgresStorage) Transfer(req *t.TransferRequest) (*t.Transcation, error) {
// begin transaction
tx, err := s.db.Begin()
if err != nil {
fmt.Println("1")
return nil, err
}
amount, err := strconv.ParseFloat(req.Amount, 64)
if err != nil {
fmt.Println("2")
return nil, err
}
// remove from sender account
res, err := tx.Exec(`UPDATE accounts SET balance = balance - $1 WHERE acc_number = $2 AND balance > $1`, amount, req.FromAccount)
if err != nil {
fmt.Println("3")
tx.Rollback()
return nil, err
}
r, err := res.RowsAffected()
if err != nil {
tx.Rollback()
return nil, err
}
if r < 1 {
fmt.Println("4")
tx.Rollback()
return nil, fmt.Errorf("insufficient fund or invalid accound number")
}
// add to receiver account
res, err = tx.Exec(`UPDATE accounts SET balance = $1 + balance WHERE acc_number = $2`, amount, req.ToAccount)
if err != nil {
fmt.Println("6")
tx.Rollback()
return nil, err
}
r, err = res.RowsAffected()
if err != nil {
tx.Rollback()
return nil, err
}
fmt.Println(r)
if r < 1 {
fmt.Println(r)
tx.Rollback()
return nil, fmt.Errorf("something went wrong")
}
transaction, err := t.NewTransaction(&req.FromAccount, &req.ToAccount, req.Amount, "Credit", "Bank Transfer")
if err != nil {
fmt.Println("9")
tx.Rollback()
return nil, err
}
id, err := s.AddTransaction(transaction)
if err != nil {
fmt.Println("10")
tx.Rollback()
return nil, err
}
// commit the transaction
err = tx.Commit()
if err != nil {
fmt.Println("12")
tx.Rollback()
return nil, err
}
t, err := s.GetTransactiobById(id)
if err != nil {
fmt.Println("11")
tx.Rollback()
return nil, err
}
return t, nil
}
func (s *PostgresStorage) AddTransaction(t *t.Transcation) (*string, error) {
query := `
INSERT INTO transactions
(transaction_id,sen_acc,rec_acc,amount,description,status,date)
VALUES($1,$2,$3,$4,$5,$6,$7)
RETURNING transaction_id`
row, err := s.db.Query(
query,
t.Id,
t.Sen_acc.AccountNumber,
t.Rec_acc.AccountNumber,
t.Amount,
t.Description,
t.Status,
t.Date)
if err != nil {
return nil, err
}
var id string
for row.Next() {
err := row.Scan(
&id,
)
if err != nil {
return nil, err
} else {
return &id, nil
}
}
return nil, err
}
func (s *PostgresStorage) TopUpAccount(req *t.TopUpRequest) error {
// begin transaction
tx, err := s.db.Begin()
if err != nil {
return err
}
// function
res, err := tx.Exec(`UPDATE accounts SET balance = balance + $1 WHERE acc_number = $2`, req.Amount, req.Account)
if err != nil {
tx.Rollback()
return fmt.Errorf(tx.Rollback().Error())
}
r, _ := res.RowsAffected()
if r < 1 {
fmt.Println(r)
return fmt.Errorf("account not found")
}
// commit the transaction
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func (s *PostgresStorage) GetUserTransactions(acc_num int) ([]*t.Transcation, error) {
// function
rows, err := s.db.Query(`SELECT * FROM transacationview WHERE sender_acc = $1 OR receiver_acc = $1 `, acc_num)
if err != nil {
return nil, err
}
transactions := []*t.Transcation{}
for rows.Next() {
transcation, err := scanIntoTransaction(rows)
if err != nil {
return nil, err
}
transactions = append(transactions, transcation)
}
return transactions, nil
}
func (s *PostgresStorage) GetTransactions() ([]*t.Transcation, error) {
rows, err := s.db.Query("select * from transacationview")
if err != nil {
return nil, err
}
transactions := []*t.Transcation{}
for rows.Next() {
transcation, err := scanIntoTransaction(rows)
if err != nil {
return nil, err
}
transactions = append(transactions, transcation)
}
return transactions, nil
}
func DropTable(db *sql.DB, n string) error {
if _, err := db.Query(`DROP TABLE $1`, n); err != nil {
return err
}
return nil
}
func scanIntoAccount(rows *sql.Rows) (*t.Account, error) {
account := new(t.Account)
err := rows.Scan(
&account.ID,
&account.FirstName,
&account.LastName,
&account.AccountNumber,
&account.Balance,
&account.Email,
&account.EncryptedPassword,
&account.CreatedAt,
)
return account, err
}
func scanIntoTransaction(rows *sql.Rows) (*t.Transcation, error) {
s := new(t.Account)
r := new(t.Account)
tran := new(t.Transcation)
// s.Balance = sb
// r.Balance = rb
err := rows.Scan(
&tran.Id,
&tran.Amount,
&tran.Description,
&tran.Status,
&tran.Date,
&s.AccountNumber,
&s.FirstName,
&s.LastName,
&s.Balance,
&s.Email,
&r.AccountNumber,
&r.FirstName,
&r.LastName,
&r.Balance,
&r.Email,
)
if err != nil {
return nil, err
}
if err != nil {
return nil, err
}
tran.Sen_acc = *s
tran.Rec_acc = *r
return tran, err
}
|
C#######################################################################
C
C One- and two-dimensional adaptive Gaussian integration routines.
C
C **********************************************************************
SUBROUTINE GADAP(A0,B0,F,EPS,SUM)
IMPLICIT NONE
C
C PURPOSE - INTEGRATE A FUNCTION F(X)
C METHOD - ADAPTIVE GAUSSIAN
C USAGE - CALL GADAP(A0,B0,F,EPS,SUM)
C PARAMETERS A0 - LOWER LIMIT (INPUT,REAL)
C B0 - UPPER LIMIT (INPUT,REAL)
C F - FUNCTION F(X) TO BE INTEGRATED. MUST BE
C SUPPLIED BY THE USER. (INPUT,REAL FUNCTION)
C EPS - DESIRED RELATIVE ACCURACY. IF SUM IS SMALL EPS
C WILL BE ABSOLUTE ACCURACY INSTEAD. (INPUT,REAL)
C SUM - CALCULATED VALUE FOR THE INTEGRAL (OUTPUT,REAL)
C PRECISION - SINGLE
C REQ'D PROG'S - F
C AUTHOR - T. JOHANSSON, LUND UNIV. COMPUTER CENTER, 1973
C REFERENCE(S) - THE AUSTRALIAN COMPUTER JOURNAL,3 P.126 AUG. -71
C
COMMON/GADAP1/ NUM,IFU
INTEGER NUM,IFU
SAVE /GADAP1/
INTEGER N,I,L
REAL AA,BB,F1F,F2F,F3F
REAL A0,B0,F,EPS,SUM,A,B,F1,F2,F3,S
REAL DSUM,C,RED,W1,U2,SS,SOLD
EXTERNAL F
DIMENSION A(300),B(300),F1(300),F2(300),F3(300),S(300),N(300)
1 FORMAT(16H GADAP:I TOO BIG)
DSUM(F1F,F2F,F3F,AA,BB)=5./18.*(BB-AA)*(F1F+1.6*F2F+F3F)
IF(EPS.LT.1.0E-8) EPS=1.0E-8
RED=1.3
L=1
I=1
SUM=0.
C=SQRT(15.)/5.
A(1)=A0
B(1)=B0
F1(1)=F(0.5*(1+C)*A0+0.5*(1-C)*B0)
F2(1)=F(0.5*(A0+B0))
F3(1)=F(0.5*(1-C)*A0+0.5*(1+C)*B0)
IFU=3
S(1)= DSUM(F1(1),F2(1),F3(1),A0,B0)
100 CONTINUE
L=L+1
N(L)=3
EPS=EPS*RED
A(I+1)=A(I)+C*(B(I)-A(I))
B(I+1)=B(I)
A(I+2)=A(I)+B(I)-A(I+1)
B(I+2)=A(I+1)
A(I+3)=A(I)
B(I+3)=A(I+2)
W1=A(I)+(B(I)-A(I))/5.
U2=2.*W1-(A(I)+A(I+2))/2.
F1(I+1)=F(A(I)+B(I)-W1)
F2(I+1)=F3(I)
F3(I+1)=F(B(I)-A(I+2)+W1)
F1(I+2)=F(U2)
F2(I+2)=F2(I)
F3(I+2)=F(B(I+2)+A(I+2)-U2)
F1(I+3)=F(A(I)+A(I+2)-W1)
F2(I+3)=F1(I)
F3(I+3)=F(W1)
IFU=IFU+6
IF(IFU.GT.5000) GOTO 130
S(I+1)= DSUM(F1(I+1),F2(I+1),F3(I+1),A(I+1),B(I+1))
S(I+2)= DSUM(F1(I+2),F2(I+2),F3(I+2),A(I+2),B(I+2))
S(I+3)= DSUM(F1(I+3),F2(I+3),F3(I+3),A(I+3),B(I+3))
SS=S(I+1)+S(I+2)+S(I+3)
I=I+3
IF(I.GT.300)GOTO 120
SOLD=S(I-3)
IF(ABS(SOLD-SS).GT.EPS*(1.+ABS(SS))/2.) GOTO 100
SUM=SUM+SS
I=I-4
N(L)=0
L=L-1
110 CONTINUE
IF(L.EQ.1) GOTO 130
N(L)=N(L)-1
EPS=EPS/RED
IF(N(L).NE.0) GOTO 100
I=I-1
L=L-1
GOTO 110
120 WRITE(6,1)
130 RETURN
END
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Todolist</title>
</head>
<body>
<form name="todoForm">
<table>
<tbody>
<tr>
<td><label for="todo">Todo :</label></td>
<td><input type="text" name="todo" id="todo" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Add" /></td>
</tr>
</tbody>
</table>
</form>
<h1>Todolist</h1>
<table>
<thead>
<tr>
<td>Filter :</td>
<td><input type="text" name="search" id="search" /></td>
</tr>
</thead>
<tbody id="todolistBody">
<tr>
<td><input type="button" value="Done" /></td>
<td>Todo Description</td>
</tr>
</tbody>
</table>
<script>
const todolist = ["Belajar javascript Dasar", "Belajar Javascript OOP", "Belajar Javascript DOM"];
function clearTodolist() {
const todolistBody = document.getElementById("todolistBody");
console.info(todolistBody.firstChild);
while (todolistBody.firstChild) {
todolistBody.removeChild(todolistBody.firstChild);
}
}
function removeTodolist(index) {
todolist.splice(index, 1);
displayTodolist();
}
function addTodolist(index, todo) {
const tr = document.createElement("tr");
const tdButton = document.createElement("td");
tr.appendChild(tdButton);
const buttonDone = document.createElement("input");
buttonDone.type = "button";
buttonDone.value = "Done";
buttonDone.onclick = () => {
removeTodolist(index);
};
tdButton.appendChild(buttonDone);
const tdTodo = document.createElement("td");
tdTodo.textContent = todo;
tr.appendChild(tdTodo);
const todolistBody = document.getElementById("todolistBody");
todolistBody.appendChild(tr);
}
function displayTodolist() {
clearTodolist();
for (let i = 0; i < todolist.length; i++) {
const todo = todolist[i];
const searchText = document.getElementById("search").value.toLowerCase();
if (todo.toLowerCase().includes(searchText)) {
addTodolist(i, todo);
}
}
}
document.forms["todoForm"].onsubmit = function (event) {
event.preventDefault();
const todo = document.forms["todoForm"]["todo"].value;
todolist.push(todo);
document.forms["todoForm"].reset();
console.info(todolist);
displayTodolist();
};
const search = document.getElementById("search");
search.onkeyup = () => {
displayTodolist();
};
search.onkeydown = () => {
displayTodolist();
};
displayTodolist();
</script>
</body>
</html>
|
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'
import dayjs, { Dayjs } from 'dayjs'
import { type AlertColor } from '@mui/material/Alert'
import Grid from '@mui/material/Grid'
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'
import PlaceIcon from '@mui/icons-material/Place'
import React from 'react'
import CenterLayout from '@layouts/CenterLayout'
import Image from 'next/image'
import flag_1 from '../../public/images/flags/US_flag.png'
import flag_2 from '../../public/images/flags/DE_flag.png'
import flag_3 from '../../public/images/flags/RU_flag.png'
import flag_4 from '../../public/images/flags/UA_flag.png'
import {
Backdrop,
ButtonBase,
CircularProgress,
FormControlLabel,
Radio,
RadioGroup,
} from '@mui/material'
import { MINIMAL_PASSWORD_LENGTH } from '@constants/UserSignup'
import SnackbarContext, { Snack } from 'context/SnackbarContext'
import { MobileDatePicker } from '@mui/x-date-pickers'
import { useRouter } from 'next/router'
import { getSession } from 'next-auth/react'
import SettingData from '@constants/Setting.json'
import { Dialog, DialogTitle, Divider, ListItemButton } from '@mui/material'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import ListItemText from '@mui/material/ListItemText'
import { useAtom } from 'jotai'
import languagejson from "../language.json"
import {language, tempEmailJot} from "../jotai"
import cookies from "browser-cookies";
export interface SimpleDialogProps {
open: boolean
selectedValue: number
onClose: (value: number) => void
}
function SimpleDialog(props: SimpleDialogProps) {
const [lang, setLanguage] = useAtom(language)
const { onClose, selectedValue, open } = props
const { name: title, options } = SettingData[lang][0]
const handleClose = () => {
onClose(selectedValue)
}
const handleListItemClick = (value: number) => {
setLanguage(value);
onClose(value)
}
return (
<Dialog onClose={handleClose} open={open}>
<DialogTitle>{title}</DialogTitle>
<List sx={{ pt: 0 }}>
{options.map((option, i) => (
<ListItem key={option + i} disableGutters>
<ListItemButton onClick={() => handleListItemClick(i)}>
<ListItemText primary={option} />
</ListItemButton>
</ListItem>
))}
</List>
</Dialog>
)
}
async function createUser(userData: object) {
const response = await fetch('/api/auth/signup', {
method: 'POST',
body: JSON.stringify(userData),
headers: {
'Content-Type': 'application/json',
},
})
const data = await response.json()
if (!response.ok) {
return {
status: 'error',
data: data.message || 'Something went wrong!',
}
}
return {
status: 'success',
data: 'New User created!',
}
}
export default function SignUp() {
const [lang, setLanguage] = useAtom(language)
const [tempEmail, setTempEmail] = useAtom(tempEmailJot)
const [open, setOpen] = React.useState(false)
const [selectedValue, setSelectedValue] = React.useState(0)
const [options, setOptions] = React.useState(SettingData[lang][0].options)
const flag = [flag_1, flag_2, flag_3, flag_4]
const { setSnack } = React.useContext(SnackbarContext)
const router = useRouter()
const [isLoading, setLoading] = React.useState(true)
const [errors, setErrors] = React.useState({
error: '',
helperText: '',
})
React.useEffect(() => {
const ip = cookies.get("user-ip") ?? "";
const getCountry = async (ip: any) => {
const response = await fetch(`https://ipapi.co/${ip}/country`)
const countryCode = await response.text()
switch (countryCode) {
case 'RU':
setLanguage(2)
break
case 'DE':
setLanguage(1)
break
case 'UA':
setLanguage(3)
break
default:
setLanguage(0)
}
}
// getCountry(ip)
setLanguage(0)
}, [])
React.useEffect(() => {
getSession().then((session) => {
if (session) {
router.replace('/')
} else {
setLoading(false)
}
})
}, [router])
const handleClickOpen = () => {
setOpen(true)
}
const handleClose = (value: number) => {
setOpen(false)
setSelectedValue(value)
}
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault()
const formData = new FormData(event.currentTarget)
const nickname: string = formData.get('nickname') as string
const email: string = formData.get('email') as string
setTempEmail(email)
const password: string = formData.get('password') as string
const sex: string = formData.get('sex') as string
const language: number = selectedValue as number
const repeatPassword: string = formData.get('repeat-password') as string
// Validation
if (!nickname) {
setErrors({
error: 'nickname',
helperText: 'Empty nickname',
})
return
}
if (!email || !email.includes('@')) {
setErrors({
error: 'email',
helperText: 'Email incorrect',
})
return
}
if (!password || password.length < MINIMAL_PASSWORD_LENGTH) {
setErrors({
error: 'password',
helperText: 'Password incorrect',
})
return
}
if (repeatPassword !== password) {
setErrors({
error: 'repeat-password',
helperText: 'Password mismatch',
})
return
}
setErrors({
error: '',
helperText: '',
})
setLoading(true)
// Await for data for any desirable next steps
const res = await createUser({
email: email.toLowerCase(),
password,
nickname,
birthday,
sex,
lang
})
setLoading(false)
setSnack(
new Snack({
message: res.data,
color: res.status as AlertColor,
open: true,
})
)
if (res.status === 'success') {
router.replace('/signin')
}
}
const [birthday, setBirthday] = React.useState<Dayjs | null>(
dayjs('2014-08-18T21:11:54')
)
const [sex, setSex] = React.useState<String | null>('')
const handleChange = (newValue: Dayjs | null) => {
setBirthday(newValue)
}
const handleChangeSex = (val: string | null) => {
setSex(val)
}
return (
<CenterLayout title={languagejson[lang].SignUp}>
<Box
sx={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}>
<Typography component="h1" variant="h5">
{languagejson[lang].WelcometoReson}
</Typography>
<Box
component="form"
noValidate
onSubmit={handleSubmit}
sx={{
mt: 3,
display: 'flex',
flexDirection: 'column',
}}>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
required
fullWidth
id="nickname"
label={languagejson[lang].Nickname}
name="nickname"
autoComplete="given-name"
helperText={errors.error === 'nickname' && errors.helperText}
error={errors.error === 'nickname'}
/>
</Grid>
<Grid item xs={12}>
<RadioGroup
aria-labelledby="demo-radio-buttons-group-label"
defaultValue="diverse"
name="sex"
id="sex"
value={sex}
onChange = {e => handleChangeSex(e.target.value)}
row={true}
sx={{
display: 'flex',
justifyContent: 'space-between',
}}>
<FormControlLabel
value="male"
control={<Radio />}
label={languagejson[lang].male}
/>
<FormControlLabel
value="female"
control={<Radio />}
label={languagejson[lang].female}
/>
<FormControlLabel
value="diverse"
control={<Radio />}
label={languagejson[lang].diverse}
/>
</RadioGroup>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
id="email"
label={languagejson[lang].EmailAddress}
name="email"
autoComplete="email"
helperText={errors.error === 'email' && errors.helperText}
error={errors.error === 'email'}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
name="password"
label={languagejson[lang].Password}
type="password"
id="password"
autoComplete="new-password"
helperText={errors.error === 'password' && errors.helperText}
error={errors.error === 'password'}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
fullWidth
name="repeat-password"
label={languagejson[lang].repeatPassword}
type="password"
id="repeat-password"
autoComplete="repeat-password"
helperText={
errors.error === 'repeat-password' && errors.helperText
}
error={errors.error === 'repeat-password'}
/>
</Grid>
<Grid item xs={12}>
<LocalizationProvider dateAdapter={AdapterDayjs}>
<MobileDatePicker
label={languagejson[lang].birthDate}
inputFormat="DD/MM/YYYY"
value={birthday}
componentsProps={{
actionBar: {
sx: {
backgroundColor: 'background.paper',
button: {
color: 'text.primary',
'&:hover': { bgcolor: 'primary.light' },
},
},
},
}}
onChange={handleChange}
renderInput={(params) => (
<TextField required fullWidth {...params} />
)}
/>
</LocalizationProvider>
</Grid>
</Grid>
<Button
type="submit"
variant="contained"
sx={{
mt: 3,
mb: 2,
alignSelf: 'center',
}}>
{languagejson[lang].SignUp}
</Button>
<Box
sx={{
mt: 2,
display: 'flex',
justifyContent: 'space-between',
}}>
<ButtonBase
sx={{
p: 2,
display: 'flex',
flexDirection: 'column',
}}>
<PlaceIcon
sx={{
fontSize: 80,
color: (theme)=> theme.palette.mode === 'light'? '#333': theme.palette.text.primary,
}}
/>
<Typography component={'span'}>{languagejson[lang].Position}</Typography>
</ButtonBase>
<ButtonBase
sx={{
p: 2,
display: 'flex',
flexDirection: 'column',
}}
onClick = {handleClickOpen}
>
<Image
src={flag[selectedValue]}
alt="language"
width={80}
height={80}
/>
<Typography component={'span'}>{options[lang]}</Typography>
</ButtonBase>
</Box>
</Box>
</Box>
<Backdrop
sx={{
color: '#fff',
zIndex: (theme) => theme.zIndex.drawer + 1,
}}
open={isLoading}>
<CircularProgress color="inherit" />
</Backdrop>
<SimpleDialog
selectedValue={selectedValue}
open={open}
onClose={handleClose}
/>
</CenterLayout>
)
}
|
import numpy as np
import os
import matplotlib.pyplot as plt
import yaml
ROOT_DIR = os.getcwd()
MAIN_DIR = os.path.join(ROOT_DIR, "standard_map")
DATA_DIR = os.path.join(MAIN_DIR, "data")
CONFIG_DIR = os.path.join(MAIN_DIR, "config")
with open(os.path.join(CONFIG_DIR, "parameters.yaml"), "r") as file:
PARAMETERS = yaml.safe_load(file)
class StandardMap:
"""
A class representing the Standard Map dynamical system.
"""
def __init__(self, init_points: int = None, steps: int = None, K: float = None, sampling: str = None, seed: bool = None):
params = PARAMETERS.get("stdm_parameters")
self.init_points = init_points or params.get("init_points")
self.steps = steps or params.get("steps")
self.K = K or params.get("K")
self.sampling = sampling or params.get("sampling")
self.seed = seed or params.get("seed")
self.theta_values = np.array([])
self.p_values = np.array([])
if self.seed is not None:
np.random.seed(seed=self.seed)
def retrieve_data(self):
return self.theta_values, self.p_values
def generate_data(self):
theta, p = self._get_initial_points()
self.theta_values = np.zeros((self.steps, self.init_points))
self.p_values = np.zeros((self.steps, self.init_points))
for iter in range(self.steps):
theta = (theta + p) % (2 * np.pi)
p = p + self.K * np.sin(theta)
self.theta_values[iter] = theta
self.p_values[iter] = p
def plot_data(self):
plt.figure(figsize=(8, 5))
plt.plot(self.theta_values, self.p_values, "bo", markersize=0.3)
plt.xlabel(r"$\theta$")
plt.ylabel("p")
plt.xlim(-0.1, 2.05 * np.pi)
plt.ylim(-1.5, 1.5)
plt.show()
def _get_initial_points(self):
if self.sampling == "random":
theta_init = np.random.uniform(0, 2 * np.pi, self.init_points)
p_init = np.random.uniform(-1, 1, self.init_points)
elif self.sampling == "linear":
theta_init = np.linspace(0, 2 * np.pi, self.init_points)
p_init = np.linspace(-1, 1, self.init_points)
elif self.sampling == "normal":
mu, sigma = 0, 0.8
theta_init = np.random.normal(mu + np.pi, 2*sigma, self.init_points)
p_init = np.random.normal(mu, sigma, self.init_points)
return theta_init, p_init
if __name__ == "__main__":
map = StandardMap(init_points=100, steps=100, sampling="normal")
map.generate_data()
map.plot_data()
|
//START IMPORTS
import React, { useState } from "react";
import DeleteIcon from "@mui/icons-material/Delete";
import { CircularProgress, IconButton } from "@mui/material";
import EditIcon from "@mui/icons-material/Edit";
import Swal from "sweetalert2";
import { useDeleteProductMutation } from "../../features/product/productApiSlice";
import EditProduct from "./EditProduct";
import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye";
import { Link } from "react-router-dom";
//STOP IMPORTS
const ProductActions = ({ params }) => {
const [deleteProduct, { isLoading: isDelLoading }] =
useDeleteProductMutation();
const [edit, setEdit] = useState(false);
const handleEdit = () => {
setEdit(true);
};
const handleDelete = async () => {
try {
Swal.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
showCancelButton: true,
confirmButtonColor: "#3085d6",
cancelButtonColor: "#d33",
confirmButtonText: "Yes, delete it!",
}).then(async (result) => {
if (result.isConfirmed) {
const response = await deleteProduct({
_id: params.row._id,
}).unwrap();
if (
response?.message === "Product deleted successfully" ||
response?.status === 200
) {
Swal.fire({
icon: "success",
title: `Product deleted successfully`,
showConfirmButton: false,
timer: 2500,
});
}
}
});
} catch (err) {
Swal.fire({
icon: "error",
title: "Deletion Failed",
text: `${err?.data?.message}`,
});
}
};
return (
<>
<IconButton
variant="contained"
color="error"
size="small"
style={{ marginLeft: 16 }}
onClick={handleDelete}
>
{isDelLoading ? <CircularProgress color="primary" /> : <DeleteIcon />}
</IconButton>
<IconButton
variant="contained"
color="primary"
size="small"
style={{ marginLeft: 16 }}
onClick={handleEdit}
>
<EditIcon />
</IconButton>
{edit && (
<EditProduct
edit={edit}
_id={params.row._id}
setEdit={setEdit}
pname={params.row.pname}
amount={params.row.price.amount}
currency={params.row.price.currency}
stock={params.row.stock}
desc={params.row.desc}
warranty={params.row.warranty}
/>
)}
<IconButton component={Link} to={`/products/${params.row._id}`}>
<RemoveRedEyeIcon />
</IconButton>
</>
);
};
export default ProductActions;
|
"""
Loading and saving of the .semgrepconfig.yml file.
"""
import re
from pathlib import Path
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
import ruamel.yaml
from attr import asdict
from attr import define
from attr import field
import semgrep.semgrep_interfaces.semgrep_output_v1 as out
from semgrep.git import get_git_root_path
from semgrep.verbose_logging import getLogger
logger = getLogger(__name__)
CONFIG_FILE_PATTERN = re.compile(r"^\.semgrepconfig(\.yml|\.yaml)?$")
@define
class ProjectConfig:
"""
Class that handles loading and validating semgrepconfig files.
Example:
version: v1
tags:
- tag1
- tag2
"""
FILE_VERSION = "v1"
version: str = field(default=FILE_VERSION)
tags: Optional[List[str]] = field(default=None)
@tags.validator
def check_tags(self, _attribute: Any, value: Optional[List[str]]) -> None:
if value is None:
return
if not isinstance(value, list):
raise ValueError("tags must be a list of strings")
for val in value:
if not isinstance(val, str):
raise ValueError("tags must be a list of strings")
@staticmethod
def is_project_config_file(file_path: Path) -> bool:
return CONFIG_FILE_PATTERN.search(file_path.name) is not None
@classmethod
def _find_all_config_files(cls, src_directory: Path, cwd_path: Path) -> List[Path]:
conf_files = []
# Populate stack of directories to traverse
stack = {cwd_path}
temp_path = src_directory
dir_route = cwd_path.relative_to(src_directory)
for parent in dir_route.parents:
temp_path = temp_path / parent
stack.add(temp_path)
# Traverse stack looking for config files
while stack:
cur_path = stack.pop()
if not cur_path.exists():
continue
conf_files += [
f for f in cur_path.iterdir() if cls.is_project_config_file(f)
]
return conf_files
@classmethod
def load_from_file(cls, file_path: Path) -> "ProjectConfig":
yaml = ruamel.yaml.YAML(typ="safe")
logger.debug(f"Loading semgrepconfig file: {file_path}")
with file_path.open("r") as fp:
config: Dict[str, Any] = yaml.load(fp)
cfg = cls(**config)
return cfg
@classmethod
def load_all(cls) -> "ProjectConfig":
src_directory = get_git_root_path()
cwd_path = Path.cwd()
conf_files = cls._find_all_config_files(src_directory, cwd_path)
# Sort by depth asc so deeper configs take precedence
conf_files.sort(key=lambda x: len(x.parts))
# Merge metadata from all config files
all_metadata: Dict[Any, Any] = {}
for conf_file in conf_files:
project_conf = cls.load_from_file(conf_file)
project_conf_data = asdict(project_conf)
all_metadata = {**all_metadata, **project_conf_data}
return cls(**all_metadata)
def to_CiConfigFromRepo(self) -> out.CiConfigFromRepo:
if self.tags is not None:
tags = [out.Tag(x) for x in self.tags]
else:
tags = None
return out.CiConfigFromRepo(version=out.Version(self.version), tags=tags)
|
import 'package:school/webview.dart';
import 'package:flutter/material.dart';
import 'package:introduction_screen/introduction_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
class IntroScreen extends StatelessWidget {
final introKey = GlobalKey<IntroductionScreenState>();
List<PageViewModel> getPages() {
return [
PageViewModel(
title: "abyssinia school system",
body:
"this is completed school information managment system used to manage every school information like student information managment,teacher information managment,acadamical information managment system,finance information ,liberary information managment and other ",
image: Image.asset("assets/logo.JPG"),
decoration: const PageDecoration(
pageColor: Colors.green,
bodyTextStyle: TextStyle(fontSize: 18.0, color: Colors.white),
),
),
PageViewModel(
title: "what it include",
body: "This school management system is designed for various users, including administrators, students, teachers, parents, finance personnel, and librarians. It encompasses both mobile and computer applications, functioning seamlessly in both online and offline modes. it works by amharic and english,and also it has mobile application for admin student teacher and parents",
image: Image.asset("assets/logo.JPG"),
decoration: const PageDecoration(
pageColor: Colors.green,
bodyTextStyle: TextStyle(fontSize: 18.0, color: Colors.white),
),
),
PageViewModel(
title: "what to do ",
body: "if you want to use this completed features of this system contact 0951050364 or contact us on telegram @abyssiniasoftware1",
image: Image.asset("assets/logo.JPG"),
decoration: const PageDecoration(
pageColor: Colors.green,
bodyTextStyle: TextStyle(fontSize: 18.0, color: Colors.white),
),
),
];
}
@override
Widget build(BuildContext context) {
return IntroductionScreen(
key: introKey,
pages: getPages(),
onDone: () {
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) =>WebviewTwo (url:'https://school.asfagroindustry.com/index.php/login'),
),
);
},
onSkip: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('seen', true);
if(prefs.getBool('seen')==true)
Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => WebviewTwo(url:"https://school.abyssniasoftware.com"),
),
);
else Navigator.pushReplacement(
context,
MaterialPageRoute(
builder: (context) => IntroScreen(),
),
);
},
showSkipButton: true,
skip: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.white,
),
child: const Text(
"እለፍ",
style: TextStyle(
color: Colors.blueAccent,
fontSize: 16,
),
),
),
next: const Icon(Icons.arrow_forward,color: Colors.red,size: 21,),
done: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.green,
),
child: const Text(
"ቀጣይ",
style: TextStyle(
color: Colors.white,
fontSize: 16,
),
),
),
dotsDecorator: const DotsDecorator(
size: Size(10.0, 10.0),
color: Colors.grey,
activeColor: Colors.white,
activeSize: Size(22.0, 10.0),
activeShape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(25.0)),
),
),
);
}
}
|
package top.lijingyuan.mockito.learing.lesson06;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/**
* SpyingTest
*
* @author <a href="kangjinghang@gmail.com">kangjinghang</a>
* @date 2021-06-27
* @since 1.0.0
*/
@RunWith(MockitoJUnitRunner.class)
public class SpyingTest {
@Test
public void testSpy() {
List<String> realList = new ArrayList<>();
// 部分方法的mock,只有设置when的时候才会调用Mock的方法
List<String> list = spy(realList);
list.add("Mockito");
list.add("PowerMock");
assertThat(list.get(0), equalTo("Mockito"));
assertThat(list.get(1), equalTo("PowerMock"));
assertThat(list.isEmpty(), equalTo(false));
when(list.isEmpty()).thenReturn(true);
when(list.size()).thenReturn(0);
assertThat(list.get(0), equalTo("Mockito"));
assertThat(list.get(1), equalTo("PowerMock"));
assertThat(list.isEmpty(), equalTo(true));
assertThat(list.size(), equalTo(0));
}
}
|
#
# @lc app=leetcode id=155 lang=python3
#
# [155] Min Stack
#
# https://leetcode.com/problems/min-stack/description/
#
# algorithms
# Easy (45.79%)
# Likes: 4388
# Dislikes: 409
# Total Accepted: 655K
# Total Submissions: 1.4M
# Testcase Example: '["MinStack","push","push","push","getMin","pop","top","getMin"]\n' +
# '[[],[-2],[0],[-3],[],[],[],[]]'
#
# Design a stack that supports push, pop, top, and retrieving the minimum
# element in constant time.
#
#
# push(x) -- Push element x onto stack.
# pop() -- Removes the element on top of the stack.
# top() -- Get the top element.
# getMin() -- Retrieve the minimum element in the stack.
#
#
#
# Example 1:
#
#
# Input
# ["MinStack","push","push","push","getMin","pop","top","getMin"]
# [[],[-2],[0],[-3],[],[],[],[]]
#
# Output
# [null,null,null,null,-3,null,0,-2]
#
# Explanation
# MinStack minStack = new MinStack();
# minStack.push(-2);
# minStack.push(0);
# minStack.push(-3);
# minStack.getMin(); // return -3
# minStack.pop();
# minStack.top(); // return 0
# minStack.getMin(); // return -2
#
#
#
# Constraints:
#
#
# Methods pop, top and getMin operations will always be called on non-empty
# stacks.
#
#
#
# @lc code=start
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = []
def push(self, num):
self.stack.append(num)
if not self.min_stack or self.min_stack[-1] > num:
self.min_stack.append(num)
def pop(self):
num = self.stack.pop()
if num == self.min_stack[-1]:
self.min_stack.pop()
return num
def top(self):
return self.stack[-1]
def getMin(self):
return self.min_stack[-1]
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
# @lc code=end
|
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Homepage</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&family=Ubuntu+Condensed&display=swap" rel="stylesheet">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@200&display=swap" rel="stylesheet">
<script src="https://kit.fontawesome.com/54aebf4ee4.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="styles/common.css">
<link rel="stylesheet" href="styles/nav.css">
<link rel="stylesheet" href="styles/homepage.css">
</head>
<body>
<div class="navigation-wrapper">
<div class="left-column">
<div class="icon">
<i class="fas fa-phone-volume"></i>
</div>
<div class="contact-hours-wrapper">
<div class="phone">
123 456 7890
</div>
<div class="hours">
1 AM - Midnight
</div>
</div>
</div>
<div class="center-column">
<div class="banner-image">
<img src="Images/Logos/decamp-fantastic-fries-logo-white.png" alt="Logo">
</div>
<div class="links-wrapper">
<div class="nav-link">
<a href="index.html">Home</a>
</div>
<div class="nav-link">
<a href="About.html">About</a>
</div>
<div class="nav-link">
<a href="Menu.html">Menu</a>
</div>
<div class="nav-link">
<a href="Contact.html">Contact</a>
</div>
</div>
</div>
<div class="right-column">
<div class="address-wrapper">
<a href="Contact.html">
123 North 200 South<br>
On that road you know
</a>
</div>
<div class="contact-icon">
<a href="Contact.html">
<i class="fas fa-map-marker-alt"></i>
</a>
</div>
</div>
</div>
<div class="hero-section">
<div class="top-heading">
<h1>Html Styled Fries</h1>
</div>
<div class="bottom-heading">
<h3>Coded Fish</h3>
</div>
</div>
<div class="features-section">
<div class="columns-wrapper">
<div class="column">
<i class="fas fa-truck-monster"></i>
<p>We Deliver!</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
</div>
<div class="columns-wrapper">
<div class="column">
<i class="fas fa-wifi"></i>
<p>You can code here</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
</div>
<div class="columns-wrapper">
<div class="column">
<i class="fas fa-chart-line"></i>
<p>100+ kinds of fish and chips</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
</div>
</div>
</div>
<div>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d4543.0387574058395!2d-111.67509703257781!3d40.05116616545269!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x874da4ce3635181f%3A0xb9c96d4520a17368!2sS%20Salem%20Lake%20Dr%2C%20Salem%2C%20UT%2084653!5e0!3m2!1sen!2sus!4v1655484575932!5m2!1sen!2sus" width="100%" height="450" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
</div>
<div class="footer">
<div class="footer-logo">
<img src="Images/Logos/decamp-fantastic-fries-logo-white.png" alt="Logo">
</div>
<div class="footer-phone-hours">
<span class="phone">
123 456 7890
</span>
<span class="hours">
1 AM - Midnight
</span>
</div>
<div class="links-wrapper">
<div class="nav-link">
<a href="index.html">Home</a>
</div>
<div class="nav-link">
<a href="About.html">About</a>
</div>
<div class="nav-link">
<a href="Menu.html">Menu</a>
</div>
<div class="nav-link">
<a href="Contact.html">Contact</a>
</div>
</div>
<div class="social-media-icon-wrapper">
<a href="https://en.wikipedia.org/wiki/Sukhoi_Su-25" target=_blank>
<i class="fab fa-twitter"></i>
</a>
<a href="https://en.wikipedia.org/wiki/Book" target=_blank>
<i class="fab fa-facebook-f"></i>
</a>
<a href="https://en.wikipedia.org/wiki/Camera" target=-blank>
<i class="fab fa-instagram"></i>
</a>
</div>
<div class="coppyright-wrapper">
© 2022 The Website | All rights reserved
</div>
</div>
</body>
</html>
|
package fr.progilone.pgcn.service.document.conditionreport;
import static fr.progilone.pgcn.exception.message.PgcnErrorCode.DESC_VALUE_PROPERTY_MANDATORY;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import fr.progilone.pgcn.domain.document.conditionreport.DescriptionProperty;
import fr.progilone.pgcn.domain.document.conditionreport.DescriptionValue;
import fr.progilone.pgcn.exception.PgcnValidationException;
import fr.progilone.pgcn.exception.message.PgcnErrorCode;
import fr.progilone.pgcn.repository.document.conditionreport.DescriptionRepository;
import fr.progilone.pgcn.repository.document.conditionreport.DescriptionValueRepository;
import fr.progilone.pgcn.util.TestUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.internal.stubbing.answers.ReturnsArgumentAt;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class DescriptionValueServiceTest {
@Mock
private DescriptionRepository descriptionRepository;
@Mock
private DescriptionValueRepository descriptionValueRepository;
private DescriptionValueService service;
@BeforeEach
public void setUp() {
service = new DescriptionValueService(descriptionRepository, descriptionValueRepository);
}
@Test
public void testFindByProperty() {
final List<DescriptionValue> values = new ArrayList<>();
when(descriptionValueRepository.findByPropertyIdentifier("id")).thenReturn(values);
final List<DescriptionValue> actual = service.findByPropertyIdentifier("id");
assertSame(values, actual);
}
@Test
public void testFindAll() {
final List<DescriptionValue> values = new ArrayList<>();
when(descriptionValueRepository.findAll()).thenReturn(values);
final List<DescriptionValue> actual = service.findAll();
assertSame(values, actual);
}
@Test
public void testDelete() {
final String id = "ID-001";
final DescriptionValue value = new DescriptionValue();
when(descriptionValueRepository.findById(id)).thenReturn(Optional.of(value));
service.delete(id);
verify(descriptionValueRepository).delete(value);
}
@Test
public void testSave() {
when(descriptionValueRepository.save(any(DescriptionValue.class))).then(new ReturnsArgumentAt(0));
// #1
try {
final DescriptionValue value = new DescriptionValue();
service.save(value);
fail("testSave failed");
} catch (final PgcnValidationException e) {
TestUtil.checkPgcnException(e, PgcnErrorCode.DESC_VALUE_LABEL_MANDATORY, DESC_VALUE_PROPERTY_MANDATORY);
}
// #2
try {
final DescriptionValue value = new DescriptionValue();
value.setLabel("Label");
value.setProperty(new DescriptionProperty());
final DescriptionValue actual = service.save(value);
assertSame(value, actual);
} catch (final PgcnValidationException e) {
fail("testSave failed");
}
}
}
|
import { useCodeMirror } from '@uiw/react-codemirror';
import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
import { Transaction, type ChangeSpec } from '@codemirror/state';
import type { ViewUpdate} from '@codemirror/view';
import { useEffect, useRef, useState } from 'react';
import yorkie from 'yorkie-js-sdk';
import type { Client, Document, TextChange } from 'yorkie-js-sdk';
export default function Editor() {
const editor = useRef<HTMLDivElement | null>(null);
const [client, setClient] = useState<Client>();
const [doc, setDoc] = useState<Document<unknown>>();
const [code, setCode] = useState('');
const { setContainer, view } = useCodeMirror({
container: editor.current,
extensions: [markdown({ base: markdownLanguage })],
value: code,
onChange(value: string, viewUpdate: ViewUpdate) {
if (!client || !doc) {
return;
}
for (let tr of viewUpdate.transactions) {
const events = ['select', 'input', 'delete', 'move', 'undo', 'redo'];
if (!(events.map((event) => tr.isUserEvent(event)).some(Boolean))) {
continue;
}
if (tr.annotation(Transaction.remote)) {
continue;
}
tr.changes.iterChanges((fromA, toA, fromB, toB, inserted) => {
doc?.update((root) => {
// @ts-ignore
root.content.edit(fromA, toA, inserted.toJSON().join('\n'));
}, `update content byA ${client?.getID()}`);
});
}
},
});
const changeEventHandler = (changes: Array<TextChange>) => {
const clientId = client?.getID();
const changeSpecs: ChangeSpec[] = changes.filter((change) => change.type === 'content' && change.actor !== clientId).map((change) => ({
from: Math.max(0, change.from),
to: Math.max(0, change.to),
insert: change.content,
}));
console.log('changes', changes)
console.log('changeSpecs', changeSpecs)
view?.dispatch({
changes: changeSpecs,
annotations: [Transaction.remote.of(true)],
});
};
const syncText = (doc: Document<unknown>) => {
if (doc) {
// @ts-ignore
const text = doc.getRoot().content;
setCode(text.toString());
}
};
useEffect(() => {
if (doc && view) {
// @ts-ignore
const text = doc.getRoot().content;
text.onChanges(changeEventHandler);
}
}, [doc, view]);
useEffect(() => {
if (editor.current) {
setContainer(editor.current);
(async () => {
// 01. create client with RPCAddr(envoy) then activate it.
const client = new yorkie.Client('http://localhost:8080');
await client.activate();
console.error('client.id', client.getID());
// 02. create a document then attach it into the client.
const doc = new yorkie.Document('codemirror2');
await client.attach(doc);
doc.update((root) => {
// @ts-ignore
if (!root.content) {
// @ts-ignore
root.content = new yorkie.Text();
}
}, 'create content if not exists');
doc.subscribe((event) => {
if (event.type === 'snapshot') {
syncText(doc);
}
});
await client.sync();
// @ts-ignore
const text = doc.getRoot().content;
text.onChanges(changeEventHandler);
syncText(doc);
setDoc(doc);
setClient(client);
})();
}
}, [])
return <div ref={editor} />;
}
|
<!DOCTYPE html>
<html>
<head>
<title>Personal Portfolio</title>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<!--
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
-->
<style>
:root{
--main-white: #f0f0f0;
--main-red: #eb3144;
--main-blue: #45567d;
--main-gray: #303841;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.welcome-section {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100vh;
background-color: #000;
background-image: linear-gradient(62deg, #3a3d40 0%, #181719 100%)
}
.projects-section {
text-align: center;
padding: 7rem 2rem;
background: var(--main-blue);
}
.projects-section-header {
max-width: 640px;
margin: 0 auto 2rem auto;
font-size: 1.5em;
color: var(--main-white);
border-bottom: 0.2rem solid var(--main-white);
}
.projects-section-header a {
width: 320px;
height: 300px;
}
.projects-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
grid-gap: 4rem;
width: 100%;
max-width: 1280px;
margin: 0 auto;
margin-bottom: 6rem;
}
.project {
background: var(--main-gray);
box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.5);
}
.project-tile {
margin: auto;
}
.project-image {
height: calc(100% - 6.8rem);
width: 100%;
object-fit: cover;
}
img {
display: block;
width: 100%;
}
.project-title {
font-size: 1.2rem;
padding: 2rem 0.5rem;
}
.code {
color: var(--main-gray);
transition-property: color;
transition-duration: 0.3s;
transition-timing-function: ease-out;
transition-delay: 0s;
}
.contact-section {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
width: 100%;
height: 80vh;
padding: 0 2rem 0 2rem;
background: var(--main-gray);
}
.contact-links {
display: flex;
justify-content: center;
width: 100%;
max-width: 980px;
margin-top: 4rem;
flex-wrap: wrap;
}
.contact-section-header h2 {
font-style: italic ;
}
.contact-section-header p {
font-size: 3rem ;
}
.contact-details {
font-size: 1.4rem;
text-shadow: 2px 2px 1px #1f1f1f;
transition: transform 0.3 ease-in-out 0s;
}
.btn {
color: var(--main-white) !important;
display: inline-block;
padding: 1rem 2rem;
border-radius: 2px;
}
body {
font-family: "Poppins", sans-serif;
font-size: 1.2rem;
font-weight: 400;
line-height: 1.4;
color: var(--main-white);
background-color: #fff;
margin: auto;
}
.nav {
display: flex;
justify-content: flex-end;
position: fixed;
top: 0;
left: 0;
width: 100%;
background: var(--main-red);
box-shadow: 0 2px rgba(0, 0, 0, 0.4);
z-index: 10;
}
.nav-list {
display: flex;
margin-right: 2rem;
list-style: none;
}
.nav-list a {
display: block;
font-size: 2.2rem;
padding: 1rem;
}
a {
text-decoration: none;
color: var(--main-white);
}
footer {
font-weight: 300;
display: flex;
justify-content: space-evenly;
padding: 2rem 2rem 2rem 2rem;
background-color: var(--main-gray);
border-top: 4px solid var(--main-red);
}
header {
font-size: 1.8em;
}
.welcome-section p {
font-size: 3rem;
font-weight: 200;
font-style: italic;
color: var(--main-red);
}
h1 {
font-size: 6rem;
}
h2 {
font-size: 3.2rem;
}
h1, h2 {
font-family: 'Raleway', sans-serif;
font-weight: 700;
text-align: center;
}
div {
width: 100%;
margin: 0;
padding: 0;
}
#first-list {
margin-bottom: 15px;
}
.project-name-size {
font-size: 0.8em;
}
@media screen and (max-width: 500px) {
}
</style>
</head>
<body>
<nav id="navbar" class="nav">
<ul class="nav-list" >
<li><a href="#welcome-section">About</a></li>
<li><a href="#projects">Work</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
<section id="welcome-section" class="welcome-section">
<h1>My name is Koami DOLA</h1>
<p>A full stack developer </p>
</section>
<section id="projects" class="projects-section">
<h2 class="projects-section-header"> These are some of my personal projects</h2>
<div id="first-list" class="row">
<div class="col-md-4">
<div class="card project-tile" style="width: 18rem;">
<img src="images/foodpreservationpage.png" width="200" height="200" class="card-img-top" alt="...">
<div class="card-body">
<a href="https://codepen.io/matthiasdola/full/PMpYxE" class="btn btn-primary text-center" target="_blank">
<span class="project-name-size">Food preservation Page</span></a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card project-tile" style="width: 18rem;">
<img src="images/trombones.png" width="200" height="200" class="card-img-top" alt="...">
<div class="card-body">
<a href="https://codepen.io/matthiasdola/full/VoWwMP" class="btn btn-primary text-center" target="_blank">
<span class="project-name-size">Product Presentation Page</span></a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card project-tile" style="width: 18rem;">
<img src="images/surveyform.png" width="200" height="200" class="card-img-top" alt="...">
<div class="card-body">
<a href="https://codepen.io/matthiasdola/full/qemyGm" class="btn btn-primary text-center" target="_blank">
<span class="project-name-size">Survey Form Page</span></a>
</div>
</div>
</div>
</div>
<div class="row ">
<div class="col-md-4">
<div class="card project-tile" style="width: 18rem;">
<img src="images/tecnicalpage.png" width="200" height="200" class="card-img-top" alt="...">
<div class="card-body">
<a href="https://codepen.io/matthiasdola/full/MNodZQ" class="btn btn-primary text-center" target="_blank">
<span class="project-name-size">Technical Documentation Page</span></a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card project-tile" style="width: 18rem;">
<img src="images/portfoliopage.png" width="200" height="200" class="card-img-top" alt="...">
<div class="card-body">
<a href="https://codepen.io/matthiasdola/full/pMrqVz" class="btn btn-primary text-center" target="_blank">
<span class="project-name-size">Personal Portfolio Page</span></a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card project-tile" style="width: 18rem;">
<img src="images/githubrepo.png" width="200" height="200" class="card-img-top" alt="...">
<div class="card-body">
<a href="https://github.com/matthdola" class="btn btn-primary text-center" target="_blank">
<span class="project-name-size">Others Projects</span></a>
</div>
</div>
</div>
</div>
</section>
<section id="contact" class="contact-section">
<div class="contact-section-header">
<h2>Let's work together ....</h2>
<p>How do you take coffee?</p>
</div>
<div class="contact-links">
<a id="profile-link" href="https://github.com/matthdola" target="_blank" class="btn contact-details">
<i class="fa fa-github"></i>
GitHub</a>
<a href="https://twitter.com/matthdola" target="_blank" class="btn contact-details">
<i class="fa fa-twitter"></i>
Twitter</a>
<a href="matthiasdaol@gmail.com" target="_blank" class="btn contact-details">
<i class="fa fa-at"></i>
Send a Mail</a>
<a href="tel:0022891746797" target="_blank" class="btn contact-details">
<i class="fa fa-mobile"></i>
Call me</a>
<a href="https://www.linkedin.com/in/matthias-koami-dola-4229b947/" target="_blank" class="btn contact-details">
<i class="fa fa-linkedin"></i>
Linkedin</a>
</div>
</section>
<footer>
<p></p>
<p>Created By Koami DOLA</p>
</footer>
<script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
</body>
</html>
|
import {
Box,
HStack,
Heading,
Image,
Text,
useDisclosure,
Flex,
Avatar,
SkeletonCircle,
SkeletonText,
} from "@chakra-ui/react";
import styles from "./View.module.css";
import HTMLToReact from "html-to-react";
import React, { useEffect, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useParams } from "react-router";
import { getSingleProduct } from "../../Redux/blogReducer/blogActions";
import DrawerComp from "../../components/Drawer/Drawer";
import {
capitalizeFirstLetter,
getBlogReadTime,
monthMap,
} from "../../utils/blogCard";
import {
getProfileUser,
getUserDetails,
} from "../../Redux/userReducer/userActions";
import {
followUser,
getFollowersFollowing,
unfollowUser,
} from "./../../Redux/followerReducer/followerActions";
import { isFollowing, isLiked } from "../../utils/blogUtils";
import { getToken } from "../../utils/cookies";
import {
FaRegBookmark,
FaRegComment,
FaRegThumbsUp,
FaThumbsUp,
} from "react-icons/fa";
import { getBlogComments } from "../../Redux/commentReducer/commentActions";
import {
getBlogLikes,
likeBlog,
unlikeBlog,
} from "../../Redux/likeReducer/likeActions";
const View = () => {
const [currentProductLoading, setCurrentProductLoading] = useState(false);
const [followerLoading, setFollowerLoading] = useState(null);
const [likeLoading, setLikeLoading] = useState(null);
const { onOpen, isOpen, onClose } = useDisclosure();
const btnRef = useRef();
const { likes } = useSelector((state) => state.likeReducer);
const { blogComments } = useSelector((state) => state.commentReducer);
const { currentProduct } = useSelector((state) => state.blogReducer);
const { profileUser, userDetails, isAuth } = useSelector(
(state) => state.userReducer
);
const { followers, following } = useSelector(
(state) => state.followerReducer
);
const dispatch = useDispatch();
const { id } = useParams();
const htmlToReactParser = new HTMLToReact.Parser();
useEffect(() => {
window.scrollTo(0, 0);
const token = getToken("jwt_token");
if (token) {
dispatch(getUserDetails(token));
}
dispatch(getSingleProduct(id, setCurrentProductLoading));
}, []);
useEffect(() => {
if (currentProduct?._id) {
dispatch(getProfileUser(currentProduct?.author_id));
dispatch(getBlogComments(currentProduct?._id));
dispatch(getBlogLikes(currentProduct?._id));
}
}, [currentProduct]);
useEffect(() => {
if (userDetails) {
dispatch(getFollowersFollowing(userDetails._id));
}
}, [userDetails]);
return currentProductLoading == false ? (
<Box
width={{ base: "100%", md: "90%", lg: "80%", xl: "50%" }}
m="auto"
mt={"2rem"}
>
<Heading ml="3.4rem" mb={"1rem"}>
{currentProduct?.title && capitalizeFirstLetter(currentProduct?.title)}
<Box mt="1rem">
<hr></hr>
</Box>
</Heading>
<Flex alignItems={"center"} gap="1rem" ml="4rem" mt="3.5rem">
<Avatar
src={
profileUser?.image
? profileUser?.image
: "https://www.generationsforpeace.org/wp-content/uploads/2018/03/empty.jpg"
}
/>
<Box>
<Flex gap="1rem">
<Text fontWeight={"medium"}>{profileUser?.name}</Text>
<Text
color="green"
cursor={"pointer"}
onClick={() => {
if (!isAuth) {
alert("login to follow");
return;
}
if (isFollowing(profileUser?._id, following)) {
setFollowerLoading(true);
dispatch(
unfollowUser(
profileUser?._id,
userDetails._id,
setFollowerLoading
)
);
} else {
setFollowerLoading(true);
dispatch(
followUser(
profileUser?._id,
userDetails._id,
setFollowerLoading
)
);
}
}}
>
{isAuth && profileUser?._id && followerLoading ? (
<Image
src="https://i.gifer.com/ZKZg.gif"
width="20px"
height="20px"
/>
) : isFollowing(profileUser?._id, following) ? (
"Following"
) : (
"Follow"
)}
</Text>
</Flex>
<Flex gap="1rem">
<Text>{getBlogReadTime(currentProduct?.text?.length)} read</Text>
<Text>
{" "}
{currentProduct?.dateCreated &&
monthMap[+currentProduct?.dateCreated.substring(5, 7)]}{" "}
{currentProduct?.dateCreated &&
currentProduct?.dateCreated.substring(8, 10)}{" "}
,{" "}
{currentProduct?.dateCreated &&
currentProduct?.dateCreated.substring(0, 4)}
</Text>
</Flex>
</Box>
</Flex>
<Box width="85%" m="auto" mt="1rem">
<hr></hr>
<Flex p="0.5rem 0rem" justifyContent={"space-between"}>
<Flex gap="1rem" alignItems={"center"}>
<HStack spacing={"1"}>
<FaRegComment
className={styles["blog-view-icons"]}
onClick={onOpen}
ref={btnRef}
fontSize={"1.4rem"}
></FaRegComment>
<Text>{blogComments?.length && blogComments?.length}</Text>
</HStack>
<HStack spacing={"1"}>
{!isLiked(userDetails?._id, likes) ? (
<Flex>
<FaRegThumbsUp
className={styles["blog-view-icons"]}
fontSize={"1.4rem"}
onClick={() => {
if (isAuth) {
const token = getToken("jwt_token");
setLikeLoading(true);
dispatch(
likeBlog(currentProduct?._id, token, setLikeLoading)
);
}
}}
/>
<Text>{likes?.length && likes?.length}</Text>
{likeLoading && (
<Image
src="https://i.gifer.com/ZKZg.gif"
width="20px"
height="20px"
/>
)}
</Flex>
) : (
<Flex>
<FaThumbsUp
className={styles["blog-view-icons"]}
fontSize={"1.4rem"}
onClick={() => {
if (isAuth) {
const token = getToken("jwt_token");
setLikeLoading(true);
dispatch(
unlikeBlog(currentProduct?._id, token, setLikeLoading)
);
}
}}
/>
<Text>{likes?.length && likes?.length}</Text>
{likeLoading && (
<Image
src="https://i.gifer.com/ZKZg.gif"
width="20px"
height="20px"
/>
)}
</Flex>
)}
</HStack>
</Flex>
<HStack>
<FaRegBookmark
className={styles["blog-view-icons"]}
fontSize={"1.4rem"}
></FaRegBookmark>
</HStack>
</Flex>
<hr></hr>
</Box>
<Box width="85%" m="auto" mt="1rem">
{htmlToReactParser.parse(currentProduct?.description)}
</Box>
<DrawerComp
blogId={currentProduct?._id}
btnRef={btnRef}
onClose={onClose}
onOpen={onClose}
isOpen={isOpen}
/>
</Box>
) : (
<Box
padding="6"
bg="transparent"
width={{ base: "100%", md: "90%", lg: "80%", xl: "50%" }}
m="auto"
mt="4rem"
>
<SkeletonText
mt="4"
noOfLines={1}
spacing="4"
skeletonHeight="10"
width={"50%"}
/>
<Box display={"flex"} mt="1rem" alignItems={"center"} gap="1rem">
{" "}
<SkeletonCircle size="10" w="45px" h="45px"></SkeletonCircle>
<SkeletonText noOfLines={2} skeletonHeight="2" width={"50%"} />
</Box>
<Flex alignItems={"center"} gap="1rem" mt="1rem">
<SkeletonCircle size="10" w="35px" h="35px"></SkeletonCircle>
<SkeletonCircle size="10" w="35px" h="35px"></SkeletonCircle>
</Flex>
<SkeletonText mt="4" noOfLines={1} spacing="4" skeletonHeight="20" />
<SkeletonText mt="4" noOfLines={4} spacing="4" skeletonHeight="2" />
<SkeletonText mt="4" noOfLines={4} spacing="4" skeletonHeight="2" />
<SkeletonText mt="4" noOfLines={4} spacing="4" skeletonHeight="2" />
<SkeletonText mt="4" noOfLines={4} spacing="4" skeletonHeight="2" />
</Box>
);
};
export default View;
|
package com.epam.ta.test;
import com.epam.ta.model.CloudProduct;
import com.epam.ta.service.CloudProductCreator;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.epam.ta.page.GoogleCloudHomePage;
import com.epam.ta.page.GoogleCloudPricingCalculatorPage;
import static com.epam.ta.test.SearchCloudPricingCalculatorTest.RESULTING_TERM;
import static com.epam.ta.test.SearchCloudPricingCalculatorTest.SEARCH_TERM;
public class GoogleCloudPricingCalculatorTest extends CommonConditions {
private GoogleCloudHomePage homePage;
private GoogleCloudPricingCalculatorPage calculatorPage;
private static final String MANUALLY_GOT_ESTIMATION = "2,126.74 / mo";
@BeforeMethod
public void browserSetup() {
homePage = new GoogleCloudHomePage(driver);
}
@Test(description = "Check Google Cloud Calculator is opened")
public void GCPCalculatorIsOpenFromSearch() {
homePage.openPage();
homePage.enterSearchTerm(SEARCH_TERM);
String targetLink = homePage.findTargetingLinkInSearchResults(RESULTING_TERM);
calculatorPage = homePage.navigateWithTargetingLinkFromSearchResults(targetLink);
Assert.assertTrue(calculatorPage.isPageOpened(), "Google Cloud Calculator is failed to open");
}
@Test(description = "Check estimation price is calculated correctly", dependsOnMethods = "GCPCalculatorIsOpenFromSearch")
public void GCPCalculatorPriceEstimatingTest() throws InterruptedException {
calculatorPage.closeCookiesAlert();
CloudProduct testProduct = CloudProductCreator.withAllDataFromProperty();
calculatorPage.activateProductType(testProduct.getComputeEngine());
calculatorPage.enterNumberOfInstances(testProduct.getNumberOfInstances());
calculatorPage.enterOperatingSystems(testProduct.getOperatingSystem());
calculatorPage.enterProvisioningModel(testProduct.getProvisioningModel());
calculatorPage.enterSeries(testProduct.getSeries());
calculatorPage.enterMachineType(testProduct.getMachineType());
calculatorPage.checkAddGPUsCheckbox();
calculatorPage.enterGpuType(testProduct.getGpuType());
calculatorPage.enterGpuNumber(testProduct.getNumberOfGPU());
calculatorPage.enterLocalSSD(testProduct.getLocalSSD());
calculatorPage.enterDataCenterLocation(testProduct.getDataCenterLocation());
calculatorPage.enterCommittedUsage(testProduct.getCommittedUsage());
calculatorPage.clickAddToEstimateButton();
calculatorPage.highlightResultingContent();
Assert.assertEquals(calculatorPage.getEstimationResult(), MANUALLY_GOT_ESTIMATION,
"Estimations got manually and automatically are different!");
}
}
|
package com.example.demo.controller;
import com.example.demo.entity.Category;
import com.example.demo.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class CategoryController {
@Autowired
private CategoryService categoryService;
@GetMapping("/categories")
public ResponseEntity<?> getAllCategories(){
List<Category> categoryList=categoryService.getAllCategories();
if(categoryList !=null){
return ResponseEntity.status(HttpStatus.FOUND).body(categoryList);
}else{
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No Categories ");
}
}
@GetMapping("/categories/{id}")
public ResponseEntity<?> findCategoryById(@PathVariable Long id){
Category category= categoryService.findCategoryById(id);
if(category !=null){
return ResponseEntity.status(HttpStatus.FOUND).body(category);
}else{
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No Category Found For The Corresponding ID");
}
}
@PostMapping("/categories")
public ResponseEntity<?> createCategory(@RequestBody Category category){
try{
return ResponseEntity.status(HttpStatus.CREATED).body(categoryService.createCategory(category));
}catch (Exception e){
return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
}
}
@PutMapping("/categories/{id}/update")
public ResponseEntity<?> updateCategory(@PathVariable Long id,@RequestBody Category category){
try{
return ResponseEntity.status(HttpStatus.OK).body(categoryService.updateCategory(id,category));
}catch (Exception e){
return ResponseEntity.status(HttpStatus.NOT_MODIFIED).body(e.getMessage());
}
}
}
|
import React, { Component } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
import { Link } from "react-router-dom";
export class Edit extends Component {
state = {
aptDate: "",
doctor: "",
patient: "",
type: "",
status: "",
createdBy: ""
};
componentDidMount() {
axios
.get(
"http://localhost:3001/api/appointments/" + this.props.match.params.id
)
.then(response => {
console.log(response.data);
this.setState({
aptDate: response.data.aptDate.substring(0, 10),
doctor: response.data.doctor.userName,
patient: response.data.patient.userName,
type: response.data.type,
status: response.data.status,
createdBy: response.data.createdBy.userName
});
});
}
onChangeInput = event => {
this.setState({ [event.target.name]: event.target.value });
};
onSubmit = event => {
event.preventDefault();
const obj = {
aptDate: this.state.aptDate,
doctor: this.state.doctor,
patient: this.state.patient,
type: this.state.type,
status: this.state.status,
createdBy: this.state.createdBy
};
axios
.put(
"http://localhost:3001/api/appointments/" + this.props.match.params.id,
obj
)
.then(res => {
console.log(res.data);
window.alert("Successfully Updated");
})
.catch(err => console.log(err));
//this.props.history.push("/nurse/appointments");
};
render() {
return (
<div style={{ marginTop: 10 }}>
<h3 align="center">Edit Appointment</h3>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label>Appointment Date: </label>
<input
type="text"
className="form-control"
placeholder="yyyy-mm-dd"
name="aptDate"
value={this.state.aptDate}
onChange={this.onChangeInput}
/>
</div>
<div className="form-group">
<label>Doctor: </label>
<input
type="text"
className="form-control"
name="doctor"
value={this.state.doctor}
onChange={this.onChangeInput}
/>
</div>
<div className="form-group">
<label>Patient: </label>
<input
type="text"
className="form-control"
name="patient"
value={this.state.patient}
onChange={this.onChangeInput}
/>
</div>
<div className="form-group">
<label>Type: </label>
<input
type="text"
className="form-control"
name="type"
value={this.state.type}
onChange={this.onChangeInput}
/>
</div>
<div className="form-group">
<label>Status: </label>
<input
type="text"
className="form-control"
name="status"
value={this.state.status}
onChange={this.onChangeInput}
/>
</div>
<div className="form-group">
<label>Created By: </label>
<input
type="text"
className="form-control"
name="createdBy"
value={this.state.createdBy}
onChange={this.onChangeInput}
/>
</div>
<div className="form-group">
<input
type="submit"
value="Update Appointment"
className="btn btn-primary"
/>
</div>
<Link to={"/nurse/appointments"}>
{" "}
<div className="form-group">
<input
type="submit"
value="Back to List"
className="btn btn-primary"
/>
</div>
</Link>
</form>
</div>
);
}
}
export default Edit;
|
---
title: "Source Code"
output:
html_document:
toc: TRUE
toc_float: TRUE
---
$$\\[.05in]$$
This section of the website provides the source code for both the homepage and tables page of this project. Comments for chunks of code are provided to give context and give purpose to the code.
$$\\[.1in]$$
### [Source Code for Both]{.ul}
```{r both, fig.show='hide', warnings = FALSE, eval = FALSE}
# Load Libraries and Sources
library(tidyverse)
library(plotly)
library(cowplot)
library(RCurl)
library(scales)
source("datawrangle.R")
## Load and Alter Data
download1 <- getURL("https://data.lacity.org/api/views/rpp7-mevy/rows.csv?accessType=DOWNLOAD")
vaxCA <- read.csv(text = download1)
covidCA <- read.csv(url("https://data.chhs.ca.gov/dataset/f333528b-4d38-4814-bebb-12db1f10f535/resource/046cdd2b-31e5-4d34-9ed3-b48cdbc4be7a/download/covid19cases_test.csv"))
covidCA <-
covidCA %>%
mutate(county = area) # Make variable names the same between the two datasets
vaxCA <-
vaxCA %>%
mutate(date = as.Date(vaxCA$date, "%m/%d/%Y")) # Make data variable same format
mergedCA <- merge(vaxCA, covidCA,
by = c("date","county"),
all.x = TRUE)
mergedCA <-
mergedCA %>%
filter(date >= as.Date("2020-12-15")) %>% # Start date of vaccines
filter(date <= as.Date("2021-10-31")) %>% # End date for consistency
group_by(date, county) %>%
summarise(across(c(total_doses,cumulative_total_doses,
pfizer_doses,cumulative_pfizer_doses,
moderna_doses,cumulative_moderna_doses,
jj_doses,cumulative_jj_doses,
partially_vaccinated,
total_partially_vaccinated,fully_vaccinated,
cumulative_fully_vaccinated,at_least_one_dose,
cumulative_at_least_one_dose,population,
cases,cumulative_cases,deaths,
cumulative_deaths,total_tests,
cumulative_total_tests,positive_tests,
cumulative_positive_tests), mean, .groups = date))
mergedCA <-
mergedCA %>%
mutate(dose_standard = (cumulative_total_doses/population),
pfizer_perc = ((cumulative_pfizer_doses/cumulative_total_doses)*100),
moderna_perc = ((cumulative_moderna_doses/cumulative_total_doses)*100),
jj_perc = ((cumulative_jj_doses/cumulative_total_doses)*100),
perc_vaccinated = (cumulative_fully_vaccinated/population)*100,
perc_partial = (cumulative_at_least_one_dose/population)*100)
# Region categories for each county below
superior <- c("Butte", "Colusa", "Del Norte", "Glenn", "Humboldt", "Lake", "Lassen", "Mendocino", "Modoc", "Nevada", "Plumas", "Shasta", "Sierra", "Siskiyou", "Tehama", "Trinity")
central <- c("Alpine", "Amador", "Calaveras", "El Dorado", "Fresno", "Inyo", "Kings", "Madera", "Mariposa", "Merced", "Mono", "Placer", "Sacramento", "San Joaquin", "Stanislaus", "Sutter", "Yuba", "Tulare", "Tuolumne", "Yolo")
bay <- c("Alameda", "Contra Costa", "Marin", "Monterey", "Napa", "San Benito", "San Francisco", "San Mateo", "Santa Clara", "Santa Cruz", "Solano", "Sonoma")
southern <- c("Imperial", "Kern", "Orange", "Riverside", "San Bernardino", "San Diego", "San Luis Obispo", "Santa Barbara", "Ventura", "Los Angeles")
mergedCA <- # Sort counties into their categories
mergedCA %>%
mutate(region = case_when(county %in% superior ~ "Superior California",
county %in% central ~ "Central California",
county %in% bay ~ "Bay Area",
county %in% southern ~ "Southern California"))
mergedCA3 <-
mergedCA %>%
group_by(region,date) %>%
summarise(county = county,
region = region,
ave_moderna = ave(moderna_perc),
ave_pfizer = ave(pfizer_perc),
ave_jj = ave(jj_perc),
moderna_perc = moderna_perc,
pfizer_perc = pfizer_perc,
jj_perc = jj_perc,
moderna_doses = moderna_doses,
pfizer_doses = pfizer_doses,
jj_doses = jj_doses)
mergedCA3[is.na(mergedCA3)] = 0 # Some math is zero divided by zero; replace the errors
dataAge <- datawrangle("Age Group") # Call on function to get data frame for age
dataRace <- datawrangle("Race/Ethnicity") # Call on function to get data frame for race
dataRace[6,3] <- 100.00 # Some data made some values above 100%; manual fix
```
### [Homepage Source Code]{.ul}
```{r homepage, fig.show='hide', warnings = FALSE, eval = FALSE}
# Figure 1
fig1 <-
mergedCA %>%
ggplot() +
geom_line(aes(x = date,
y = cumulative_fully_vaccinated/population*100,
color = county)) +
labs(title = "Percent Fully Vaccinated Since Roll-out by Region", x = "Date",
y = "", color = "County") +
facet_wrap(~region)
ggplotly(fig1) %>%
layout(yaxis = list(title = ""), # below code fixes axis label and title overlap
margin = list(l = 100),
annotations = c(list(text = "Percent Fully Vaccinated (%)",
x = -0.10,
xref = "paper",
y = 0.5,
showarrow = F,
textangle = -90)))
# Figure 2
fig2 <-
mergedCA %>%
ggplot(aes(group = region)) +
geom_line(mapping = aes(x = date, y = total_doses, color = "Doses Administered")) +
geom_line(mapping = aes(x = date, y = cases, color = "Case Count")) +
geom_line(mapping = aes(x = date, y = deaths, color = "Death Count")) +
labs(title = "Doses, Cases, and Deaths by Region", x = "Date", y = "") +
scale_colour_manual(values = c("Doses Administered"="#C78888",
"Case Count"="#88C7C2",
"Death Count"="#E7D366")) +
facet_wrap(~region, scales = "free_y", shrink = TRUE) +
scale_y_continuous(labels = comma) +
theme(legend.title = element_blank(), plot.title.position = "middle")
ggplotly(fig2, tooltip = c("x", "y")) %>%
layout(yaxis = list(title = ""),
margin = list(l = 100),
annotations = c(list(text = "Count",
x = -0.15,
xref = "paper",
y = 0.5,
showarrow = F,
textangle = -90)))
# Figure 3
fig3 <-
mergedCA3 %>%
ggplot(aes(group = region)) +
geom_line(aes(x = date, y = ave_moderna, color = "Moderna")) +
geom_line(aes(x = date, y = ave_pfizer, color = "Pfizer")) +
geom_line(aes(x = date, y = ave_jj, color = "J&J")) +
scale_colour_manual(values = c("Moderna"="#C78888",
"Pfizer"="#88C7C2",
"J&J"="#E7D366")) +
labs(title = "Vaccination Efforts by Company",
x = "Date", y = "", color = "Company") +
theme(legend.title = element_blank(),
axis.title.y = element_text(hjust = -1.5)) +
facet_wrap(~region)
ggplotly(fig3, tooltip = c("x", "y")) %>%
layout(yaxis = list(title = ""),
margin = list(l = 100),
annotations = c(list(
text = "Percent of Total Doses Administered (%)",
x = -0.2,
xref = "paper",
y = 0.5,
showarrow = F,
textangle = -90)))
# Figure 4
fig4palette <- c("#8AA399","#7D84B2","#FD96A9","#FFC857") # custom palette
fig4 <-
dataAge %>%
ggplot(mapping = aes(x = demographic_value, y = region_fully_vax,
fill = demographic_value)) +
geom_bar(stat = "identity") +
labs(x = "Age Group", y = "",
title = "Vaccination Efforts by Age Group",
fill = "Age Group") +
scale_fill_manual(values = fig4palette) +
facet_wrap(~region)
ggplotly(fig4, tooltip = c("x", "y")) %>%
layout(yaxis = list(title = ""),
margin = list(l = 100),
annotations = c(list(
text = "Percent Fully Vaccinated (%)",
x = -0.1,
xref = "paper",
y = 0.5,
showarrow = F,
textangle = -90)))
# Figure 5
fig5palette <- c("#C78888", "#88C7C2", "#E7D366", "#8AA399",
"#7D84B2", "#FD96A9", "#FAA04C")
fig5 <-
dataRace %>%
ggplot(mapping = aes(x = demographic_value, y = region_fully_vax,
fill = demographic_value)) +
geom_bar(stat="identity") +
labs(x = "Race/Ethnicity", y = "",
title = "Vaccination Efforts by Age",
fill = "Race/Ethnicity") +
scale_fill_manual(values = fig5palette) +
theme(axis.text.x = element_blank()) +
facet_wrap(~region)
ggplotly(fig5, tooltip = c("x", "y")) %>%
layout(yaxis = list(title = ""),
margin = list(l = 100),
annotations = c(list(
text = "Percent Fully Vaccinated (%)",
x = -0.2,
xref = "paper",
y = 0.5,
showarrow = F,
textangle = -90)))
```
### [Tables Source Code]{.ul}
```{r tablespage, fig.show='hide', warnings = FALSE, eval = FALSE}
# Table 1
mergedCA %>%
filter(date == "2021-10-31") %>% # ensure desired date is displayed
group_by(region) %>%
summarise(Fully_min = min(cumulative_fully_vaccinated/population)*100,
Fully_mean = mean(cumulative_fully_vaccinated/population)*100,
Fully_max = max(cumulative_fully_vaccinated/population)*100,
Fully_sd = sd(cumulative_fully_vaccinated/population)*100) %>%
knitr::kable(col.names = c("Region", # make table presentable with kable()
"Min %",
"Mean %",
"Max %",
"SD %"), digits = 2, "pipe", align = "c")
# Table 2
mergedCA %>%
group_by(region) %>%
summarise(Cases_min = min(cases),
Cases_mean = mean(cases),
Cases_max = max(cases),
Cases_sd = sd(cases),
Deaths_min = min(deaths),
Deaths_mean = mean(deaths),
Deaths_max = max(deaths),
Deaths_sd = sd(deaths),
Doses_min = min(total_doses),
Doses_mean = mean(total_doses),
Doses_max = max(total_doses),
Doses_sd = sd(total_doses)) %>%
knitr::kable(col.names = c("Region",
"Min Cases",
"Mean Cases",
"Max Cases",
"SD Cases",
"Min Deaths",
"Mean Deaths",
"Max Deaths",
"SD Deaths",
"Min Doses",
"Mean Doses",
"Max Doses",
"SD Doses"), digits = 2, "pipe", align = "c")
# Table 3
mergedCA3 %>%
group_by(region) %>%
summarise(JJ_min = min(jj_doses),
JJ_mean= mean(jj_doses),
JJ_max = max(jj_doses),
JJ_sd = sd(jj_doses),
JJ_cum = sum(jj_doses),
Mod_min = min(moderna_doses),
Mod_mean= mean(moderna_doses),
Mod_max = max(moderna_doses),
Mod_sd = sd(moderna_doses),
Mod_cum = sum(moderna_doses),
Pfi_min = min(pfizer_doses),
Pfi_mean= mean(pfizer_doses),
Pfi_max = max(pfizer_doses),
Pfi_sd = sd(pfizer_doses),
Pfi_cum = sum(pfizer_doses)) %>%
knitr::kable(col.names = c("Region",
"Min J&J",
"Mean J&J",
"Max J&J",
"SD J&J",
"Cum. J&J",
"Min Mod.",
"Mean Mod.",
"Max Mod.",
"SD Mod.",
"Cum. Mod.",
"Min Pfi.",
"Mean Pfi.",
"Max Pfi.",
"SD Pfi.",
"Cum. Pfi."), digits = 2, "pipe", align = "c")
# Table 4
dataAge2 <- datawrangle2("Age Group")
dataAge2 %>%
group_by(region, demographic_value) %>%
summarise(Perc_min = min(perc_fully_vax),
Perc_mean= mean(perc_fully_vax),
Perc_max = max(perc_fully_vax),
Perc_sd = sd(perc_fully_vax)) %>%
knitr::kable(col.names = c("Region",
"Demographic",
"Min %",
"Mean %",
"Max %",
"SD %"), digits = 2, "pipe", align = "cccccc")
# Table 5
dataRace2 <- datawrangle2("Race/Ethnicity")
dataRace2 %>%
filter(perc_fully_vax < 100) %>%
group_by(region, demographic_value) %>%
summarise(Perc_min = min(perc_fully_vax),
Perc_mean= mean(perc_fully_vax),
Perc_max = max(perc_fully_vax),
Perc_sd = sd(perc_fully_vax)) %>%
knitr::kable(col.names = c("Region",
"Demographic",
"Min %",
"Mean %",
"Max %",
"SD %"), digits = 2, "pipe", align = "cccccc")
```
|
#!/usr/bin/env python
# External imports
import json
from pathlib import Path
from typing import List, Dict
from xml.dom.minidom import Document
import pandas as pd
from ruamel.yaml import CommentedMap, CommentedSeq
from urllib.parse import urlparse
# Wrapica imports
from wrapica.utils.globals import NEXTFLOW_PROCESS_LABEL_RE_OBJ, NEXTFLOW_TASK_POD_MAPPING
def convert_base_config_to_icav2_base_config(base_config_path: Path):
"""
Given a base config file, overwrite it to an ICA base config file
By performing the following operations
withLabel:process_single {
cpus = { ... }
memory = { ... }
time = { ... }
}
Converted to
withLabel:process_single {
cpus = { ... }
memory = { ... }
time = { ... }
pod = [ annotation: 'scheduler.illumina.com/presetSize' , value: 'standard-small' ]
}
With the following label mapping
process_single -> standard-small
process_low -> standard-medium
process_high -> standard-xlarge
process_high_memory -> himem-large
:param base_config_path:
:return:
"""
with open(base_config_path, 'r') as base_config_file:
base_config = base_config_file.readlines()
new_base_config = []
process_label = None
for line in base_config:
if NEXTFLOW_PROCESS_LABEL_RE_OBJ.match(line.strip()) is not None:
process_label = NEXTFLOW_PROCESS_LABEL_RE_OBJ.match(line.strip()).group(1)
if process_label is not None and line.strip() == '}' and process_label in NEXTFLOW_TASK_POD_MAPPING.keys():
new_base_config.extend([
f' // Added by Wrapica to allow usability icav2\n',
f' pod = [ annotation: \'scheduler.illumina.com/presetSize\' , value: \'{NEXTFLOW_TASK_POD_MAPPING[process_label]}\' ]\n',
line
])
process_label = None
else:
new_base_config.append(line)
# This configuration should also set the base params and docker params
new_base_config.extend(
"""
// Added by Wrapica to allow usability icav2
params {
outdir = 'out'
publish_dir_mode = 'copy'
igenomes_ignore = false
enable_conda = false
email_on_fail = null
email = null
ica_smoke_test = false
}
// Edited by Wrapica to allow usability icav2
docker {
enabled = true
}
"""
)
with open(base_config_path, 'w') as new_base_config_file:
new_base_config_file.writelines(new_base_config)
def write_params_xml_from_nextflow_schema_json(
nextflow_schema_json_path: Path,
params_xml_path: Path,
pipeline_name: str,
pipeline_version: str
):
"""
Get the params xml from the nextflow json input file (not the assets/schema_input.json file)
:param nextflow_schema_json_path:
:return:
"""
# Initialise the xml doc
doc = Document()
# Create root element
pipeline = doc.createElement('pd:pipeline')
pipeline.setAttribute('xmlns:pd', 'xsd://www.illumina.com/ica/cp/pipelinedefinition')
pipeline.setAttribute('code', pipeline_name)
pipeline.setAttribute('version', pipeline_version)
doc.appendChild(pipeline)
# Create dataInputs element
data_inputs_element = doc.createElement('pd:dataInputs')
pipeline.appendChild(data_inputs_element)
# Create the steps elements
steps = doc.createElement('pd:steps')
pipeline.appendChild(steps)
# Load nextflow_schema_json_path as a dict
with open(nextflow_schema_json_path, 'r') as nextflow_schema_json_file:
nextflow_schema_json = json.load(nextflow_schema_json_file)
# Get the input output options from the nextflow schema json
# And filter out the generic options
all_options = dict(
filter(
# We don't want the generic options though
lambda kv: kv[0] not in ["generic_options", "institutional_config_options"],
nextflow_schema_json.get("definitions").items()
)
)
# Get the params from the input output options
for option_category_name, option_category_schema_definition in all_options.items():
property_definitions = option_category_schema_definition.get("properties", {})
required_property_names = option_category_schema_definition.get("required", [])
# Create step element
category_step = doc.createElement('pd:step')
steps.appendChild(category_step)
category_step.setAttribute('execution', 'MANDATORY')
category_step.setAttribute('code', option_category_name)
# Add label and description
category_label_element = doc.createElement('pd:label')
category_label_element.appendChild(doc.createTextNode(option_category_name))
category_step.appendChild(category_label_element)
category_description_element = doc.createElement('pd:description')
if not option_category_schema_definition.get("description", "") == "":
category_description_element.appendChild(doc.createTextNode(option_category_schema_definition.get("description", "")))
else:
category_description_element.appendChild(doc.createTextNode(option_category_name))
category_step.appendChild(category_description_element)
# Create the tool element
tool_element = doc.createElement('pd:tool')
tool_element.setAttribute('code', option_category_name)
category_step.appendChild(tool_element)
for property_name, property_schema_dict in property_definitions.items():
if property_name == "email":
# We don't want to send an email at the end of the pipeline
continue
if property_name == "outdir":
# We hardcode this to 'out', so we don't make it available in the params xml
continue
if property_name in ["config_profile_name", "config_profile_description"]:
# Don't need these
continue
# Data type
if "type" not in property_schema_dict.keys():
continue
if (
property_schema_dict["type"] == "string" and
(
# Format hint
(
property_schema_dict.get("format", None) is not None
and (
property_schema_dict.get("format") == "file-path" or
property_schema_dict.get("format") == "directory-path"
)
) or
(
property_schema_dict.get("mimetype", None) is not None
and (
property_schema_dict.get("mimetype") == "text/csv" or
property_schema_dict.get("mimetype") == "text/tsv"
)
)
)
):
# We have a file object that needs to be added
# Property schema looks like this:
# {
# "type": "string",
# "format": "file-path",
# "exists": true,
# "schema": "assets/schema_input.json",
# "mimetype": "text/csv",
# "pattern": "^\\S+\\.tsv$",
# "description": "Path to comma-separated file containing information about the samples in the experiment.",
# "help_text": "You will need to create a design file with information about the samples in your experiment before running the pipeline. Use this parameter to specify its location. It has to be a comma-separated file with 3 columns, and a header row. See [usage docs](https://nf-co.re/airrflow/usage#samplesheet-input).",
# "fa_icon": "fas fa-file-csv"
# }
data_input_element = doc.createElement('pd:dataInput')
data_inputs_element.appendChild(data_input_element)
data_input_element.setAttribute('code', property_name)
data_input_element.setAttribute('format', (
"UNKNOWN" if not property_schema_dict.get("mimetype")
else property_schema_dict.get("mimetype").split("/")[-1].upper()
))
data_input_element.setAttribute('type', (
"FILE"
if property_schema_dict.get("mimetype") is not None
or property_schema_dict.get("format") == "file-path"
else "DIRECTORY"
))
data_input_element.setAttribute('required', (
"true"
if property_name in required_property_names
else "false"
))
# We don't allow multi-values just yet
data_input_element.setAttribute('multiValue', "false")
label_element = doc.createElement('pd:label')
label_element.appendChild(doc.createTextNode(property_name))
data_input_element.appendChild(label_element)
description_element = doc.createElement('pd:description')
description_element.appendChild(doc.createTextNode(property_schema_dict.get("description", "")))
data_input_element.appendChild(description_element)
# Parameter type
else:
parameter_element = doc.createElement('pd:parameter')
tool_element.appendChild(parameter_element)
parameter_element.setAttribute('code', property_name)
parameter_element.setAttribute('minValues', (
"1"
if property_name in required_property_names
else "0"
))
# We don't allow multi-values just yet
parameter_element.setAttribute('maxValues', "1")
# Always USER, would love to get some documentation on this one day
parameter_element.setAttribute('classification', "USER")
# Set label and description as childs
label_element = doc.createElement('pd:label')
label_element.appendChild(doc.createTextNode(property_name))
parameter_element.appendChild(label_element)
description_element = doc.createElement('pd:description')
description_element.appendChild(doc.createTextNode(property_schema_dict.get("description", "")))
parameter_element.appendChild(description_element)
# Add type
if (
property_schema_dict["type"] == "string" and
property_schema_dict.get("enum", None) is not None
):
options_type = doc.createElement("pd:optionsType")
parameter_element.appendChild(options_type)
for option in property_schema_dict.get("enum"):
option_type = doc.createElement("pd:option")
option_type.appendChild(doc.createTextNode(str(option)))
options_type.appendChild(option_type)
elif (
property_schema_dict["type"] == "string"
):
string_type = doc.createElement("pd:stringType")
parameter_element.appendChild(string_type)
elif (
property_schema_dict["type"] == "boolean"
):
boolean_type = doc.createElement("pd:booleanType")
parameter_element.appendChild(boolean_type)
elif (
property_schema_dict["type"] == "integer"
):
integer_type = doc.createElement("pd:integerType")
parameter_element.appendChild(integer_type)
elif (
property_schema_dict["type"] == "number"
):
float_type = doc.createElement("pd:floatType")
parameter_element.appendChild(float_type)
# Add default
if "default" in property_schema_dict.keys():
default_element = doc.createElement("pd:value")
default_element.appendChild(doc.createTextNode(str(property_schema_dict.get("default"))))
parameter_element.appendChild(default_element)
# Put it all together
with open(params_xml_path, 'w') as params_xml_file_h:
params_xml_file_h.write(doc.toprettyxml(indent=" ", encoding="UTF-8", standalone=True).decode())
#params_xml_file_h.write("\n")
def generate_samplesheet_file_from_input_dict(samplesheet_dict: List[Dict], schema_input_path: Path,
samplesheet_path: Path):
"""
Generate the samplesheet csv from the samplesheet dict
:param samplesheet_dict:
:return:
"""
from ..project_data import convert_icav2_uri_to_project_data_obj, create_download_url
# Collect the samplesheet list as a dataframe
samplesheet_df = pd.DataFrame(samplesheet_dict)
# Write the samplesheet to a csv
# But note that any icav2 file path should first be presigned before being written to the samplesheet
with open(schema_input_path, 'r') as schema_input_path_h:
schema_input_dict = json.load(schema_input_path_h)
# Get schema input properties
required_columns = schema_input_dict.get("items", {}).get("required", [])
# Check all required columns are present in samplesheet_df columns
for required_column in required_columns:
if required_column not in samplesheet_df.columns:
raise ValueError(f"Required column {required_column} not found in samplesheet")
# Collect all ICAv2 URIs, presign them and write them back to the samplesheet
icav2_uris_to_presign = []
for index, row in samplesheet_df.iterrows():
for column in samplesheet_df.columns:
if row[column].startswith("icav2://"):
if ';' in row[column]:
# We have multiple URIs
icav2_uris_to_presign.extend(row[column].split(';'))
else:
# Presign the URI
icav2_uris_to_presign.append(row[column])
# Presign the URIs
icav2_uris_to_presign = list(set(icav2_uris_to_presign))
# Generate project data objects for each URI
icav2_uris_to_project_data_obj_map = dict(
map(
lambda icav2_uri: (icav2_uri, convert_icav2_uri_to_project_data_obj(icav2_uri)),
icav2_uris_to_presign
)
)
# Specify the presigned url to download
icav2_uris_to_presigned_url = dict(
map(
lambda icav2_uri_kv: (icav2_uri_kv[0], create_download_url(icav2_uri_kv[1].project_id, icav2_uri_kv[1].data.id)),
icav2_uris_to_project_data_obj_map.items()
)
)
# Replace the icav2 URIs with the presigned URLs
for index, row in samplesheet_df.iterrows():
for column in samplesheet_df.columns:
if row[column].startswith("icav2://"):
if ";" in row[column]:
# We have multiple URIs
samplesheet_df.at[index, column] = ";".join(
map(
lambda uri: icav2_uris_to_presigned_url[uri],
row[column].split(';')
)
)
else:
samplesheet_df.at[index, column] = icav2_uris_to_presigned_url[row[column]]
# Write the samplesheet to csv
samplesheet_df.to_csv(samplesheet_path, index=False)
def generate_samplesheet_yaml_template_from_schema_input(
schema_input_path: Path
) -> CommentedSeq:
"""
Pull in the samplesheet schema input and generate a samplesheet template
:param schema_input_path:
:return:
"""
# Load the schema input
with open(schema_input_path, 'r') as schema_input_file:
schema_input = json.load(schema_input_file)
# Get the required columns
required_columns = schema_input.get("items", {}).get("required", [])
all_properties = schema_input.get("items", {}).get("properties", {})
# Generate the samplesheet yaml
samplesheet_yaml = CommentedSeq()
init_record = CommentedMap()
for property_name, property_object in all_properties.items():
init_record[property_name] = ""
if property_name in required_columns:
init_record.yaml_add_eol_comment(
key=property_name,
comment="Required",
)
else:
init_record.yaml_add_eol_comment(
key=property_name,
comment="Optional",
)
# Append the one record as an example to the samplesheet yaml
samplesheet_yaml.append(init_record)
return samplesheet_yaml
def generate_input_yaml_from_schema_json(
nextflow_schema_json_path: Path
) -> CommentedMap:
# Load nextflow_schema_json_path as a dict
with open(nextflow_schema_json_path, 'r') as nextflow_schema_json_file:
nextflow_schema_json = json.load(nextflow_schema_json_file)
# Get the input output options from the nextflow schema json
# And filter out the generic options
all_options = dict(
filter(
# We don't want the generic options though
lambda kv: kv[0] not in ["generic_options", "institutional_config_options"],
nextflow_schema_json.get("definitions").items()
)
)
input_yaml = CommentedMap()
for option_category_name, option_category_schema_definition in all_options.items():
property_definitions = option_category_schema_definition.get("properties", {})
required_property_names = option_category_schema_definition.get("required", [])
first_property_in_category = True
for property_name, property_schema_dict in property_definitions.items():
# Don't add in generic options
if property_name == "email":
# We don't want to send an email at the end of the pipeline
continue
if property_name == "outdir":
# We hardcode this to 'out', so we don't make it available in the params xml
continue
if property_name in ["config_profile_name", "config_profile_description"]:
# Don't need these
continue
# Make sure that this is a proper schema definition
if "type" not in property_schema_dict.keys():
continue
# Check if property is required
required_string = "Required " if property_name in required_property_names else "Optional "
input_yaml[property_name] = f""
# File type
if (
property_schema_dict["type"] == "string" and
property_schema_dict.get("format", None) is not None and
property_schema_dict.get("format") == "file-path"
):
# We have a file object that needs to be added
# Property schema looks like this:
# {
# "type": "string",
# "format": "file-path",
# "exists": true,
# "schema": "assets/schema_input.json",
# "mimetype": "text/csv",
# "pattern": "^\\S+\\.tsv$",
# "description": "Path to comma-separated file containing information about the samples in the experiment.",
# "help_text": "You will need to create a design file with information about the samples in your experiment before running the pipeline. Use this parameter to specify its location. It has to be a comma-separated file with 3 columns, and a header row. See [usage docs](https://nf-co.re/airrflow/usage#samplesheet-input).",
# "fa_icon": "fas fa-file-csv"
# }
if property_schema_dict.get("mimetype", None) is not None:
input_yaml.yaml_add_eol_comment(
key=property_name,
comment=f"icav2//project-id/path/to/file.{property_schema_dict['mimetype'].split('/')[-1]}"
)
else:
input_yaml.yaml_add_eol_comment(
key=property_name,
comment=f": icav2//project-id/path/to/file"
)
# Directory type
elif (
property_schema_dict["type"] == "string" and
property_schema_dict.get("format", None) is not None and
property_schema_dict.get("format") == "directory-path"
):
input_yaml[property_name] = f""
input_yaml.yaml_add_eol_comment(
key=property_name,
comment=f"icav2//project-id/path/to/directory"
)
# Enum Type
elif (
property_schema_dict["type"] == "string" and
property_schema_dict.get("enum", None) is not None
):
input_yaml.yaml_add_eol_comment(
key=property_name,
comment=f"One of {' | '.join(map(str, property_schema_dict['enum']))}"
)
# Boolean Type
elif (
property_schema_dict["type"] == "boolean"
):
input_yaml.yaml_add_eol_comment(
key=property_name,
comment="True | False"
)
# Integer Type
elif (
property_schema_dict["type"] == "integer"
):
input_yaml.yaml_add_eol_comment(
key=property_name,
comment="Integer"
)
# Number Type
elif (
property_schema_dict["type"] == "number"
):
input_yaml.yaml_add_eol_comment(
key=property_name,
comment="Number / Float"
)
# Add a comment if this is the fist of the property definitions for this category
if first_property_in_category:
# Add comment header
input_yaml.yaml_set_comment_before_after_key(
key=property_name,
before=(
"\n" +
option_category_schema_definition.get("description", "") + "\n" +
required_string + property_schema_dict.get("description", "") + (
f"\nDefault: {property_schema_dict.get('default', '')}"
if property_schema_dict.get('default', '') != '' else ""
)
),
indent=4
)
first_property_in_category = False
else:
input_yaml.yaml_set_comment_before_after_key(
key=property_name,
before=required_string + property_schema_dict.get("description", "") + (
(
f"\nDefault: {property_schema_dict.get('default', '')}"
if property_schema_dict.get('default', '') != '' else ""
)
),
indent=4
)
return input_yaml
def download_nextflow_schema_file_from_pipeline_id(
pipeline_id: str,
schema_json_path: Path
):
"""
Download the nextflow schema file from the pipeline id
:param pipeline_id:
:param schema_json_path:
:return:
"""
from ..pipelines import (
download_pipeline_file, list_pipeline_files
)
schema_json_pipeline_file_id = next(
filter(
lambda pipeline_file_iter: pipeline_file_iter.get("name") == "nextflow_schema.json",
list_pipeline_files(pipeline_id)
)
)
download_pipeline_file(
pipeline_id=pipeline_id,
file_id=schema_json_pipeline_file_id.get("id"),
file_path=schema_json_path
)
def download_nextflow_schema_input_json_from_pipeline_id(
pipeline_id: str,
schema_input_json_path: Path
):
"""
Download the nextflow schema file from the pipeline id
:param pipeline_id:
:param schema_input_json_path:
:return:
"""
from ..pipelines import (
download_pipeline_file, list_pipeline_files
)
schema_json_pipeline_file_id = next(
filter(
lambda pipeline_file_iter: pipeline_file_iter.get("name") == "assets/schema_input.json",
list_pipeline_files(pipeline_id)
)
)
download_pipeline_file(
pipeline_id=pipeline_id,
file_id=schema_json_pipeline_file_id.get("id"),
file_path=schema_input_json_path
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.