text
stringlengths
184
4.48M
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Load data data = pd.read_csv('300_dataset.csv') data['Wretwd_sign'] = data['Wretwd'].apply(lambda x: 1 if x > 0 else -1) data['Date'] = pd.to_datetime(data['Date']) # Ensure date format is correct data['Week_Year'] = data['Date'].dt.strftime('%Y-%U') # Define bad market weeks (90%, 80%, and 70% of stocks have negative returns) def bad_market_weeks(percentage): negative_return_percent = data.groupby('Week_Year')['Wretwd_sign'].apply(lambda x: (x == -1).mean()) return negative_return_percent[negative_return_percent > percentage].index bad_weeks_90 = bad_market_weeks(0.9) bad_weeks_80 = bad_market_weeks(0.8) bad_weeks_70 = bad_market_weeks(0.7) # Filter data for bad market weeks bad_market_data_90 = data[data['Week_Year'].isin(bad_weeks_90)] bad_market_data_80 = data[data['Week_Year'].isin(bad_weeks_80)] bad_market_data_70 = data[data['Week_Year'].isin(bad_weeks_70)] # Calculate correlations correlations_90 = bad_market_data_90[['Wretwd_sign', 'SVI_All']].corr() correlations_80 = bad_market_data_80[['Wretwd_sign', 'SVI_All']].corr() correlations_70 = bad_market_data_70[['Wretwd_sign', 'SVI_All']].corr() # Print correlations print("Correlations when 90% of stocks have negative returns:\n", correlations_90) print("Correlations when 80% of stocks have negative returns:\n", correlations_80) print("Correlations when 70% of stocks have negative returns:\n", correlations_70) # Plot and save correlation matrices def plot_and_save_corr_matrix(corr_matrix, title, filename): plt.figure(figsize=(8, 6)) sns.heatmap(corr_matrix, annot=True, cmap='coolwarm', vmin=-1, vmax=1) plt.title(title) plt.savefig(filename) plt.close() plot_and_save_corr_matrix(correlations_90, 'Correlation Matrix (90% Negative Returns)', 'correlations_90.png') plot_and_save_corr_matrix(correlations_80, 'Correlation Matrix (80% Negative Returns)', 'correlations_80.png') plot_and_save_corr_matrix(correlations_70, 'Correlation Matrix (70% Negative Returns)', 'correlations_70.png')
@extends('layouts.default') @section('content') <div class="main-content"> <section class="section"> <div class="section-header"> <h1>@lang('app.data_collections')</h1> <div class="section-header-breadcrumb"> <div class="breadcrumb-item active"><a href="#">Assets</a></div> <div class="breadcrumb-item"><a href="#">@lang('app.data_collections')</a></div> </div> </div> <div class="section-body"> <div class="row mt-4"> <div class="col-12"> <div class="card"> <div class="card-header"> <h4>@lang('app.list_of') @lang('app.data_collection')</h4> </div> <div class="card-body"> <div class="float-left d-flex"> <a href="{{ route('asset.data-collections.create') }}" class="btn btn-primary">Add Data Collection</a> </div> <div class="float-right"> <form action="" method="GET"> <div class="input-group"> <input type="text" class="form-control" name="search" placeholder="@lang('app.search')" value="{{ request()->search }}"> <div class="input-group-append"> <button class="btn btn-primary"><i class="fas fa-search"></i></button> </div> </div> </form> </div> <div class="clearfix mb-3"></div> <div class="table-responsive"> <table class="table table-striped"> <tr> <th>No</th> <th>@lang('app.name')</th> <th>@lang('app.source')</th> <th>@lang('app.price_per_data')</th> <th>@lang('app.total_data')</th> <th>@lang('app.value')</th> <th>#</th> </tr> @forelse ($dataCollections as $item) <tr> <td>{{ (($dataCollections->currentPage()-1) * $dataCollections->perPage()) + $loop->iteration }}</td> <td>{{ $item->name }}</td> <td>{{ $item->source }}</td> <td>{{ $item->price_per_data_label }}</td> <td>{{ $item->total_data_label }}</td> <td>{{ $item->value_label }}</td> <td> <a href="{{ route('asset.data-collections.show', $item) }}" class="btn btn-sm btn-info" data-toggle="tooltip" data-placement="top" title="Lihat Data Collection"> <span class="fa fa-eye"></span></a> <a href="{{ route('asset.data-collections.edit', $item) }}" class="btn btn-sm btn-warning" data-toggle="tooltip" data-placement="top" title="Edit Data Collection"> <span class="fa fa-edit"></span></a> <span data-title="{{ $item->name }}" href="{{ route('asset.data-collections.destroy', $item) }}" class="btn btn-sm btn-danger btn-delete" data-toggle="tooltip" data-placement="top" title="Delete Data Collection"> <span class="fa fa-trash"></span></span> </td> </tr> @empty <tr> <td colspan="7" align="center"> @include('components.not-found-data') </td> </tr> @endforelse </table> </div> <div class="float-right"> {{ $dataCollections->links() }} </div> </div> </div> </div> </div> </div> </section> </div> <form action="" method="POST" id="deleteForm"> @csrf @method('DELETE') <input type="submit" style="display: none;"> </form> @endsection @section('js') <script type="text/javascript"> $('.btn-delete').on('click', function(){ var href = $(this).attr('href'); var title = $(this).data('title'); swal({ title: "Are you sure will delete "+ title +" ?", text: "Once deleted the data cannot be restored !", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { $('#deleteForm').attr('action', href); $('#deleteForm').submit(); } }); }); </script> @endsection
### ----------------------------- STEP I -------------------------------------------- ##----------------------- Data Input and Preprocessing ------------------------------ setwd("C:/Users/thula/OneDrive/Documents/Thulani/University/Winter_semester/Research/Co-expression_network") library(WGCNA) options(stringsAsFactors = FALSE) #Reading data exp = read.csv('Bni.csv',header = T,row.names = 1) #Preprocessing data = t(exp) data = as.data.frame(data) rm(exp) #QC - checking for missing values gsg = goodSamplesGenes(data, verbose = 2); gsg$allOK if (!gsg$allOK) { if (sum(!gsg$goodGenes)>0) printFlush(paste("Removing genes:", paste(names(data)[!gsg$goodGenes], collapse = ", "))) if (sum(!gsg$goodSamples)>0) printFlush(paste("Removing samples:", paste(rownames(data)[!gsg$goodSamples], collapse = ", "))) data = data[gsg$goodSamples, gsg$goodGenes] } #Cluster samples sampleTree = hclust(dist(data), method = "average") # Plot the sample tree as a dendrogram library(grDevices) pdf(file = "Plots/1-sampleClustering.pdf", width = 12, height = 9) par(cex = 0.6) par(mar = c(0,4,2,0)) plot(sampleTree, main = "Sample clustering to detect outliers", sub="", xlab="", cex.lab = 1.5, cex.axis = 1.5, cex.main = 2) dev.off() #No outliers, therefore no need of removing samples #saving tree library(ape) nj_tree = nj(dist(data)) write.tree(nj_tree,"Samples-tree.nwk") #plotClusterTreeSamples(data) #Plot the samples as a heatmap label = c("Bni Pol Sub1-a", "Bni Pol Sub1-b","Bni Pol Sub1-c","Bni Pol Sub2-a", "Bni Pol Sub2-b","Bni Pol Sub2-c", "Bni Pol Sub3-a","Bni Pol Sub3-b","Bni Pol Sub3-c","Bni Stig Sub1-a", "Bni Stig Sub1-b","Bni Stig Sub1-c","Bni Stig Sub2-a", "Bni Stig Sub2-b","Bni Stig Sub2-c", "Bni Stig Sub3-a","Bni Stig Sub3-b","Bni Stig Sub3-c") main = c("Bni Pol Sub1", "Bni Pol Sub1", "Bni Pol Sub1", "Bni Pol Sub2", "Bni Pol Sub2", "Bni Pol Sub2","Bni Pol Sub3", "Bni Pol Sub3","Bni Pol Sub3","Bni Stig Sub1", "Bni Stig Sub1", "Bni Stig Sub1", "Bni Stig Sub2", "Bni Stig Sub2", "Bni Stig Sub2","Bni Stig Sub3", "Bni Stig Sub3","Bni Stig Sub3") dt = as.matrix(dist(data, method = 'euclidean')) row.names(dt) = label colnames(dt) = label library(RColorBrewer) pdf(file = "Plots/1-sampleClustering_heatmap.pdf", width = 20, height = 15) par(cex = 1.6) par(mar=c(1,4,4,1)) coul <- colorRampPalette(brewer.pal(8, "PiYG"))(25) my_group <- as.numeric(factor(main)) colSide <- brewer.pal(4, "Pastel1")[my_group] colMain <- colorRampPalette(brewer.pal(8, "BrBG"))(30) heatmap(dt, col = colMain, RowSideColors=colSide, margins = c(8,2),cexRow = 1.7, cexCol = 1.7) legend(x = "topleft", legend=c("Minimum", "Average", "Maximum"), fill=colorRampPalette(brewer.pal(8, "BrBG"))(3)) dev.off() collectGarbage() #saving data save(data, file = "dataInput.RData") ### --------------------------------- STEP II --------------------------------------- ##-------------------- Network Construction & Module Detection ----------------------- #rm(list = ls(all.names = TRUE)) setwd("C:/Users/thula/OneDrive/Documents/Thulani/University/Winter_semester/Research/Co-expression_network") library(WGCNA) options(stringsAsFactors = FALSE) enableWGCNAThreads() library(grDevices) # Load the data saved in the first part load(file = "dataInput.RData") # Choose a set of soft-thresholding powers powers = c(c(1:10), seq(from = 12, to=30, by=3)) # Call the network topology analysis function sft = pickSoftThreshold(data, powerVector = powers, verbose = 5) # Plot the results: pdf(file = "Plots/2-thresholding.pdf", width = 12, height = 9) par(mfrow = c(1,2)) cex1 = 0.9 # Scale-free topology fit index as a function of the soft-thresholding power plot(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2], xlab="Soft Threshold (power)",ylab="Scale Free Topology Model Fit,signed R^2", type="n", main = paste("Scale independence")) text(sft$fitIndices[,1], -sign(sft$fitIndices[,3])*sft$fitIndices[,2], labels=powers,cex=cex1,col="red") # this line corresponds to using an R^2 cut-off of h abline(h=0.80,col="red") # Mean connectivity as a function of the soft-thresholding power plot(sft$fitIndices[,1], sft$fitIndices[,5], xlab="Soft Threshold (power)",ylab="Mean Connectivity", type="n", main = paste("Mean connectivity")) text(sft$fitIndices[,1], sft$fitIndices[,5], labels=powers, cex=cex1,col="red") dev.off() ##We choose the power 15, which is the lowest power for which the scale-free topology #fit index curve flattens out upon reaching a high value (in this case, roughly 0.90) #convert data to numeric data[] <- lapply(data, as.numeric) ## One-step network construction and module detection net = blockwiseModules(data, power = 15, corType = "pearson", networkType = "signed", TOMType = "signed", minModuleSize = 30, reassignThreshold = 0, mergeCutHeight = 0.25, numericLabels = TRUE, pamRespectsDendro = FALSE, saveTOMs = TRUE, saveTOMFileBase = "TOM", verbose = 3) #SIGNED NETWORK is selected as it is more accurate. #https://peterlangfelder.com/2018/11/25/signed-or-unsigned-which-network-type-is-preferable/ #number of modules and module sizes table(net$colors) #plotting modules # Convert labels to colors for plotting mergedColors = labels2colors(net$colors) write.table(table(mergedColors), 'Modules.txt', quote = F, col.names = F) # Plot the dendrogram and the module colors underneath pdf(file = "Plots/3-Modules.pdf", width = 12, height = 9) plotDendroAndColors(net$dendrograms[[1]], mergedColors[net$blockGenes[[1]]], "Module colors", dendroLabels = FALSE, hang = 0.03, addGuide = TRUE, guideHang = 0.05) dev.off() #saving the environment moduleLabels = net$colors moduleColors = labels2colors(net$colors) MEs0 = moduleEigengenes(data, moduleColors)$eigengenes MEs = removeGreyME(MEs0, greyMEName = paste(moduleColor.getMEprefix(), "grey", sep="")) geneTree = net$dendrograms[[1]] save(MEs, moduleLabels, moduleColors, geneTree, file = "networkConstruction.RData") ### --------------------------------- STEP III --------------------------------------- ##----------------------- Network visualization ------------------------------------- #rm(list = ls(all.names = TRUE)) setwd("C:/Users/thula/OneDrive/Documents/Thulani/University/Winter_semester/Research/Co-expression_network") library(WGCNA) options(stringsAsFactors = FALSE) enableWGCNAThreads() library(grDevices) #load data load(file = "dataInput.RData") # Load network data saved in the second part. load(file = "networkConstruction.RData") #Number of genes and samples nGenes = ncol(data) nSamples = nrow(data) #Visualization using Heatmaps # Calculate topological overlap data[] <- lapply(data, as.numeric) TOM = TOMsimilarityFromExpr(data, power = 15) save(TOM,file = 'TOM_signed.RData') load('TOM_signed.RData') dissTOM = 1-TOM # For reproducibility, we set the random seed set.seed(10) nSize = 1000 select = sample(nGenes, size = nSize) selectTOM = dissTOM[select, select] selectTree = hclust(as.dist(selectTOM), method = "average") selectColors = moduleColors[select] plotDiss = selectTOM^7 #makes the plot more informative diag(plotDiss) = NA #improves the clarity of the plot pdf(file = "Plots/4-Heatmap.pdf", width = 12, height = 9) TOMplot(plotDiss, selectTree, selectColors, main = "Network heatmap plot, selected genes") dev.off() ### ------------------------------- STEP V ------------------------------------------- ##------------------------ Exporting the Network ------------------------------------- #rm(list = ls(all.names = TRUE)) setwd("C:/Users/thula/OneDrive/Documents/Thulani/University/Winter_semester/Research/Co-expression_network") library(WGCNA) options(stringsAsFactors = FALSE) enableWGCNAThreads() #load data load(file = "dataInput.RData") load(file = "networkConstruction.RData") load('TOM_signed.RData') #Hub genes hub = chooseTopHubInEachModule(data, moduleColors, omitColors = "grey", power = 15, type = "signed") write.table(hub,'Hub genes.txt',quote = F, col.names = F, row.names = F) #EXPORTING TO CYTOSCAPE setwd("C:/Users/thula/OneDrive/Documents/Thulani/University/Winter_semester/Research/Co-expression_network") clr = unique(moduleColors) clr = sort(clr) clr = clr[clr != "grey"] probes = names(data) # Select modules for (modules in clr) { # Select module probes inModule = is.finite(match(moduleColors, modules)); modProbes = probes[inModule]; # Select the corresponding Topological Overlap modTOM = TOM[inModule, inModule] dimnames(modTOM) = list(modProbes, modProbes) modTOM = as.table(modTOM) write.csv(modTOM,file = paste("TOM",modules,".csv")) # Export the network into edge and node list files that Cytoscape can read cyt = exportNetworkToCytoscape(modTOM, edgeFile = paste("CytoscapeInput-edges-", paste(modules, collapse="-"), ".txt", sep=""), weighted = TRUE, threshold = 0.01, nodeNames = modProbes, nodeAttr = moduleColors[inModule]); } #genes in the network after thresholding count = numeric() mod = character() for (i in 1: length(clr)) { modules = clr[i] path = paste("CytoscapeInput-edges-",modules,'.txt',sep = "") x = read.delim(path) dt = unique(c(as.character(x$fromNode,x$toNode))) count[i] = length(dt) mod[i] = modules } summary = cbind(mod,count) write.table(summary,file = 'Gene count.txt',row.names = F,quote = F) head(summary) ### ------------------------------- STEP VI ------------------------------------------ ##-------------------------- Validating the Network ---------------------------------- #rm(list = ls(all.names = TRUE)) setwd("C:/Users/thula/OneDrive/Documents/Thulani/University/Winter_semester/Research/Co-expression_network") library(WGCNA) options(stringsAsFactors = FALSE) enableWGCNAThreads() #load data load(file = "dataInput.RData") load(file = "networkConstruction.RData") softPower = 15 adjacency = adjacency(data, power = softPower) setLabels = c("Network", "Test") multiExpr = list(Network = list(data = adjacency), Test = list(data = data)) multiColor = list(Network = moduleColors, Test = moduleColors); nSets = 2 system.time( { mp = modulePreservation(multiExpr, multiColor, referenceNetworks = c(1:2), nPermutations = 200, randomSeed = 1, verbose = 3) } ); # Save the results save(mp, file = "ModulePreservation.RData") ref = 1 test = 2 statsObs = cbind(mp$quality$observed[[ref]][[test]][, -1], mp$preservation$observed[[ref]][[test]][, -1]) statsZ = cbind(mp$quality$Z[[ref]][[test]][, -1], mp$preservation$Z[[ref]][[test]][, -1]); print( cbind(statsObs[, c("medianRank.pres", "medianRank.qual")], signif(statsZ[, c("Zsummary.pres", "Zsummary.qual")], 2)) ) mp_sum = cbind(statsObs[, c("medianRank.pres", "medianRank.qual")], signif(statsZ[, c("Zsummary.pres", "Zsummary.qual")], 2)) write.csv(mp_sum,'Module Preservation.csv',quote = F) # Module labels and module sizes are also contained in the results modColors = rownames(mp$preservation$observed[[ref]][[test]]) moduleSizes = mp$preservation$Z[[ref]][[test]][, 1]; # leave grey and gold modules out plotMods = !(modColors %in% c("grey", "gold")); # Text labels for points text = modColors[plotMods]; # Auxiliary convenience variable plotData = cbind(mp$preservation$observed[[ref]][[test]][, 2], mp$preservation$Z[[ref]][[test]][, 2]) # Main titles for the plot mains = c("Preservation Median rank", "Preservation Zsummary"); # Start the plot sizeGrWindow(10, 5); library(grDevices) pdf(file = "Plots/7-modulePreservation.pdf", width = 12, height = 9) par(mfrow = c(1,2)) par(mar = c(4.5,4.5,2.5,1)) for (p in 1:2) { min = min(plotData[, p], na.rm = TRUE); max = max(plotData[, p], na.rm = TRUE); # Adjust ploting ranges appropriately if (p==2) { if (min > -max/10) min = -max/10 ylim = c(min - 0.1 * (max-min), max + 0.1 * (max-min)) } else ylim = c(max + 0.1 * (max-min), min - 0.1 * (max-min)) plot(moduleSizes[plotMods], plotData[plotMods, p], col = 1, bg = modColors[plotMods], pch = 21, main = mains[p], cex = 2.4, ylab = mains[p], xlab = "Module size", log = "x", ylim = ylim, xlim = c(10, 2000), cex.lab = 1.2, cex.axis = 1.2, cex.main =1.4) labelPoints(moduleSizes[plotMods], plotData[plotMods, p], text, cex = 1, offs = 0.08); # For Zsummary, add threshold lines if (p==2) { abline(h=0) abline(h=2, col = "blue", lty = 2) abline(h=10, col = "darkgreen", lty = 2) } } dev.off()
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>TP2 - Selectores CSS</title> <style> /* Estilos CSS aquí */ body { background-color: #222; color: #ee6; } h1 { text-align: center; text-transform: uppercase; /* Bonus Track */ cursor: pointer; /* Bonus Track */ } p { font-family: sans-serif; } h1, h2, h3 { color: #eee; } strong { border-bottom: 1px solid white; } .the-force { background-color: #444; font-weight: bold; } .light-side { color: #66f; } .dark-side { color: #f33; } #og-trilogy li { list-style-type: circle; } .movies-list:nth-child(2) { padding-left: 20px; } .movies-list:last-child { margin-top: 20px; } /* Bonus Track */ p:first-of-type { color: #efe; } a:visited { color: gray; /* Bonus Track */ } a[href=""] { font-style: italic; /* Bonus Track */ } .movies-list:nth-child(even) { background-color: #111; /* Bonus Track */ } .movies-list:nth-child(odd) { background-color: #333; /* Bonus Track */ } </style> </head> <body> <h1>Star Wars</h1> <p><strong>Star Wars</strong>, conocida también en español como <strong>La guerra de las galaxias</strong>, es una franquicia compuesta primordialmente de una serie de películas concebidas por el cineasta estadounidense George Lucas en la década de 1970, y producidas y distribuidas por <a>The Walt Disney Company</a> a partir de 2012.</p> <p>Su trama describe las vivencias de un grupo de personajes que habitan en una galaxia ficticia e interactúan con elementos como <span class="the-force">«la Fuerza»</span>, un campo de energía metafísico y omnipresente que posee un <span class="the-force light-side">«lado luminoso»</span> impulsado por la sabiduría, la nobleza y la justicia y utilizado por los Jedi, y un <span class="the-force dark-side">«lado oscuro»</span> usado por los Sith y provocado por la ira, el miedo y el odio.</p> <h2>Películas</h2> <h3>Trilogía Original</h3> <ul id="og-trilogy" class="movies-list"> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episodio_IV_-_Una_nueva_esperanza">Star Wars: Episodio IV - Una nueva esperanza</a></li> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episodio_V_-_El_Imperio_contraataca">Star Wars: Episodio V - El Imperio contraataca</a></li> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episode_VI_-_Return_of_the_Jedi">Star Wars: Episode VI - El retorno del Jedi</a></li> </ul> <h3>Trilogía de precuelas</h3> <ul class="movies-list"> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episodio_I_-_La_amenaza_fantasma">Star Wars: Episodio I - La amenaza fantasma</a></li> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episodio_II_-_El_ataque_de_los_clones">Star Wars: Episodio II - El ataque de los clones</a></li> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episodio_III_-_La_venganza_de_los_Sith">Star Wars: Episodio III - La venganza de los Sith</a></li> </ul> <h3>Trilogía de secuelas</h3> <ul class="movies-list"> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episodio_VII_-_El_despertar_de_la_Fuerza">Star Wars: Episodio VII - El despertar de la Fuerza</a></li> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episodio_VIII_-_Los_últimos_Jedi">Star Wars: Episodio VIII - Los últimos Jedi</a></li> <li><a href="https://es.wikipedia.org/wiki/Star_Wars:_Episodio_IX_-_El_ascenso_de_Skywalker">Star Wars: Episodio IX - El ascenso de Skywalker</a></li> </ul> <p>Fuente: <a href="https://es.wikipedia.org/wiki/Star_Wars">Wikipedia</a></p> </body> </html>
import { Button, Container, FormControl, FormLabel, Heading, Input, Stack } from "@chakra-ui/react"; import { getAuth, signInWithEmailAndPassword } from "firebase/auth"; import { VFC } from "react"; import { AppLink } from "../components/shared/AppLink"; import { TextInput, useTextInput } from "../hooks/useTextInput"; import { routes } from "../routes"; import { OnSubmit } from "../types"; const useLoginPage = () => { const [emailInput] = useTextInput(); const [passwordInput] = useTextInput(); const onSubmit: OnSubmit = async (e) => { e.preventDefault(); try { await signInWithEmailAndPassword(getAuth(), emailInput.value, passwordInput.value); } catch (e) { console.error(e); } }; return { emailInput, passwordInput, onSubmit }; }; type LoginFormProps = { emailInput: TextInput; passwordInput: TextInput; onSubmit: OnSubmit; }; const LoginForm: VFC<LoginFormProps> = ({ emailInput, passwordInput, onSubmit }) => { return ( <form onSubmit={onSubmit}> <Stack> <FormControl> <FormLabel>Email</FormLabel> <Input type="email" {...emailInput} /> </FormControl> <FormControl> <FormLabel>Password</FormLabel> <Input type="password" {...passwordInput} /> </FormControl> <Button type="submit">Login</Button> </Stack> </form> ); }; export const Login: VFC = () => { const { emailInput, passwordInput, onSubmit } = useLoginPage(); return ( <Container py="4"> <Stack> <Heading textAlign="center">Login</Heading> <LoginForm {...{ emailInput, passwordInput, onSubmit }} /> <AppLink to={routes["/signup"].path()}>to Signup</AppLink> </Stack> </Container> ); };
# This mini-project is based on the K-Means exercise from 'R in Action' # Go here for the original blog post and solutions # http://www.r-bloggers.com/k-means-clustering-from-r-in-action/ # Exercise 0: Install these packages if you don't have them already # install.packages(c("cluster", "rattle.data","NbClust")) # Now load the data and look at the first few rows data(wine, package="rattle.data") head(wine) # Exercise 1: Remove the first column from the data and scale # it using the scale() function wine_df <- scale(wine[-1]) # Now we'd like to cluster the data using K-Means. # How do we decide how many clusters to use if you don't know that already? # We'll try two methods. # Method 1: A plot of the total within-groups sums of squares against the # number of clusters in a K-means solution can be helpful. A bend in the # graph can suggest the appropriate number of clusters. wssplot <- function(data, nc=15, seed=1234){ wss <- (nrow(data)-1)*sum(apply(data,2,var)) for (i in 2:nc){ set.seed(seed) wss[i] <- sum(kmeans(data, centers=i)$withinss)} plot(1:nc, wss, type="b", xlab="Number of Clusters", ylab="Within groups sum of squares") } wssplot(wine_df) # Exercise 2: # * How many clusters does this method suggest? # This method would suggest 3 clusters due to the bend/sharp decrease from clusters 1 to 3. # * Why does this method work? What's the intuition behind it? # After 3 clusters, the decrease drops off suggesting a 3 cluster solution. The lesser # decrease after cluster 3 implies adding more clusters may not be useful even if WSS is # slightly lower. The method works because it shows how adding more clusters reduces the SS within each cluster. # * Look at the code for wssplot() and figure out how it works # The code plots a function that specifies the max number of clusters and sets a seed for # reproducing the plot. Next, the formula for calculating within-group SS for each number of clusters is defined. # Finally, thethe actual k-means method of assigning clusters is coded followed by the graph and formatting of the graph. # Method 2: Use the NbClust library, which runs many experiments # and gives a distribution of potential number of clusters. library(NbClust) set.seed(1234) nc <- NbClust(wine_df, min.nc=2, max.nc=15, method="kmeans") barplot(table(nc$Best.n[1,]), xlab="Numer of Clusters", ylab="Number of Criteria", main="Number of Clusters Chosen by 26 Criteria") # Exercise 3: How many clusters does this method suggest? 3 clusters # Exercise 4: Once you've picked the number of clusters, run k-means # using this number of clusters. Output the result of calling kmeans() # into a variable fit.km set.seed(1234) fit.km <- kmeans(wine_df, centers = 3, nstart = 25) # Now we want to evaluate how well this clustering does. # Exercise 5: using the table() function, show how the clusters in fit.km$clusters # compares to the actual wine types in wine$Type. Would you consider this a good # clustering? table(fit.km$cluster) table(wine$Type) # while there is more variation in wine type, I would say it is a pretty good fit # Exercise 6: # * Visualize these clusters using function clusplot() from the cluster library # * Would you consider this a good clustering? library("cluster") clusplot(wine_df, fit.km$cluster, main = "clusplot") # yes. The data appears to fall within the 3 clusters with very little overlap or escape.
//go:build (driver_kvs_gocache && (driver_kvs_gocache_bigcache || bigcache)) || drivers_kvs || drivers || all // Copyright (c) 2023 The Go-Enjin 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. package gocache import ( "context" "fmt" "sync" "github.com/allegro/bigcache/v3" gocache "github.com/eko/gocache/lib/v4/cache" store_go_cache "github.com/eko/gocache/store/bigcache/v4" "github.com/go-enjin/be/pkg/gob" "github.com/go-enjin/be/pkg/kvs" "github.com/go-enjin/be/pkg/log" ) type BigCacheSupport interface { AddBigCache(name string, buckets ...string) MakeFeature } func (f *CFeature) AddBigCache(name string, buckets ...string) MakeFeature { f.Lock() defer f.Unlock() f.caches[name] = newBigCache() for _, bucket := range buckets { if _, err := f.caches[name].AddBucket(bucket); err != nil { log.FatalDF(1, "error adding bucket to cache: %v - %v", name, bucket) } } return f } var _ kvs.KeyValueCache = (*cBigCache)(nil) type cBigCache struct { buckets map[string]*cBigCacheStore sync.RWMutex } func newBigCache() (cache *cBigCache) { cache = &cBigCache{ buckets: make(map[string]*cBigCacheStore), } return } func (c *cBigCache) MustBucket(name string) (kvs kvs.KeyValueStore) { if v, err := c.Bucket(name); err != nil { log.FatalDF(1, "error getting required bucket \"%v\": - %v", name, err) } else { kvs = v } return } func (c *cBigCache) Bucket(name string) (kvs kvs.KeyValueStore, err error) { if v, e := c.GetBucket(name); e == nil { kvs = v return } kvs, err = c.AddBucket(name) return } func (c *cBigCache) AddBucket(name string) (kvs kvs.KeyValueStore, err error) { c.Lock() defer c.Unlock() if v, exists := c.buckets[name]; exists { kvs = v //err = BucketExists return } dcfg := bigcache.DefaultConfig(-1) cfg := bigcache.Config{ Shards: dcfg.Shards, LifeWindow: -1, CleanWindow: -1, MaxEntriesInWindow: dcfg.MaxEntriesInWindow, MaxEntrySize: dcfg.MaxEntrySize, StatsEnabled: dcfg.StatsEnabled, Verbose: dcfg.Verbose, Hasher: dcfg.Hasher, HardMaxCacheSize: dcfg.HardMaxCacheSize, Logger: log.PrefixedLogger("bigcache"), } gocacheClient, _ := bigcache.New(context.Background(), cfg) gocacheStore := store_go_cache.NewBigcache(gocacheClient) cacheManager := gocache.New[interface{}](gocacheStore) c.buckets[name] = &cBigCacheStore{ cache: cacheManager, } kvs = c.buckets[name] return } func (c *cBigCache) GetBucket(name string) (kvs kvs.KeyValueStore, err error) { c.RLock() defer c.RUnlock() if v, ok := c.buckets[name]; ok { kvs = v } else { err = BucketNotFound } return } func (c *cBigCache) GetBucketSource(name string) (src interface{}) { c.RLock() defer c.RUnlock() if v, ok := c.buckets[name]; ok { src = v.cache } return } var _ kvs.KeyValueStore = (*cBigCacheStore)(nil) type cBigCacheStore struct { cache *gocache.Cache[interface{}] sync.RWMutex } func (f *cBigCacheStore) Get(key interface{}) (value interface{}, err error) { //f.RLock() //defer f.RUnlock() var ok bool var v interface{} var data []byte if v, err = f.cache.Get(context.Background(), key); err != nil { return } else if data, ok = v.([]byte); !ok { err = fmt.Errorf("value is not []byte: %#+v", v) return } value, err = gob.Decode(data) return } func (f *cBigCacheStore) Set(key interface{}, value interface{}) (err error) { //f.Lock() //defer f.Unlock() var data []byte if data, err = gob.Encode(value); err != nil { return } err = f.cache.Set(context.Background(), key, data) return }
<!-- This is the second step of the questionnaire. It asks for the user's bank account information. The user is asked to provide their checking account and savings account numbers. --> <template> <div class="form-container"> <h2 class="header">Bankinformasjon</h2> <p>Vi vil trenge bankinformasjonen for dette</p> <div class="account-form"> <label for="checkingAccountInput">Brukskonto:</label> <input id="checkingAccountInput" class="account-input" :value="formattedCheckingAccount" @input=" formattedCheckingAccount = ($event.target as HTMLInputElement).value " placeholder="xxxx xx xxxxx" maxlength="13" minlength="13" required /> <div v-if="formErrors.checkingAccount" class="error"> {{ formErrors.checkingAccount }} </div> <div class="input-gap"></div> <label for="savingsAccountInput">Sparekonto:</label> <input id="savingsAccountInput" class="account-input" :value="formattedSavingsAccount" @input=" formattedSavingsAccount = ($event.target as HTMLInputElement).value " placeholder="xxxx xx xxxxx" maxlength="13" minlength="13" required /> <div v-if="formErrors.savingsAccount" class="error"> {{ formErrors.savingsAccount }} </div> </div> <div class="button-container"> <FormButton type="button" @click="goBack">Back</FormButton> <FormButton type="submit" @click="goToNextStep">Next</FormButton> </div> </div> </template> <script setup lang="ts"> import { ref, defineEmits, onMounted, computed } from "vue"; import { useQuestionnaireStore } from "@/stores/questionnaireStore"; import FormButton from "@/components/forms/FormButton.vue"; const emit = defineEmits(["update-step"]); const store = useQuestionnaireStore(); const checkingAccount = ref(store.stepTwoData.checkingAccount); const savingsAccount = ref(store.stepTwoData.savingsAccount); const formErrors = ref({ checkingAccount: "", savingsAccount: "", }); const formattedCheckingAccount = computed({ get: () => formatAccountNumber(checkingAccount.value), set: (val) => { val = val.replace(/\s/g, "").replace(/\D/g, ""); checkingAccount.value = isNaN(parseInt(val)) ? "" : val; }, }); const formattedSavingsAccount = computed({ get: () => formatAccountNumber(savingsAccount.value), set: (val) => { val = val.replace(/\s/g, "").replace(/\D/g, ""); savingsAccount.value = isNaN(parseInt(val)) ? "" : val; }, }); function formatAccountNumber(number: string) { const digits = number.replace(/\D/g, "").substring(0, 11); return formatAsBankAccount(digits); } function formatAsBankAccount(digits: string) { if (digits.length <= 4) { return digits; } else if (digits.length <= 6) { return `${digits.slice(0, 4)} ${digits.slice(4)}`; } else { return `${digits.slice(0, 4)} ${digits.slice(4, 6)} ${digits.slice(6)}`; } } function isFormValid() { const pureChecking = checkingAccount.value.replace(/\s/g, ""); const pureSavings = savingsAccount.value.replace(/\s/g, ""); formErrors.value.checkingAccount = pureChecking.length === 11 ? "" : "Brukskonto må inneholde nøyaktig 11 sifre."; formErrors.value.savingsAccount = pureSavings.length === 11 ? "" : "Sparekonto må inneholde nøyaktig 11 sifre."; return !formErrors.value.checkingAccount && !formErrors.value.savingsAccount; } function goToNextStep() { if (isFormValid()) { store.updateStepTwoData({ checkingAccount: checkingAccount.value.replace(/\s/g, ""), savingsAccount: savingsAccount.value.replace(/\s/g, ""), }); emit("update-step", 3); } } function goBack() { emit("update-step", 1); } onMounted(() => { checkingAccount.value = store.stepTwoData.checkingAccount; savingsAccount.value = store.stepTwoData.savingsAccount; }); </script> <style scoped> .account-form { display: flex; flex-direction: column; gap: 10px; width: 100%; margin-top: 35px; } .account-input { border: none; border-radius: 5px; padding: 10px; margin: 0; width: 100%; } .form-button { width: 100%; } .button-container { display: flex; justify-content: space-between; width: 100%; margin-top: 50px; } .input-gap { margin-bottom: 15px; } .error { color: #e57373; } </style> @/stores/QuestionnaireStore
import { Route, Routes } from 'react-router-dom' import { AddNewAuthor } from './components/authors/AddNewAuthor' import { AuthorDetail } from './components/authors/AuthorDetail' import { EditAuthor } from './components/authors/EditAuthor' import { AddNewBook } from './components/books/AddNewBook' import { BookDetail } from './components/books/BookDetail' import { EditBook } from './components/books/Editbook' import { Header } from './components/Header' import { Authors } from './pages/Authors' import { Books } from './pages/Books' import { Home } from './pages/Home' function App() { return ( <div className="container"> <Header /> <div className="inner-container"> <Routes> <Route path='/' element={<Home />} /> <Route path='authors' element={<Authors />} /> <Route path='authors/:id' element={<AuthorDetail />} /> <Route path='authors/:id/edit' element={<EditAuthor />} /> <Route path='authors/new' element={<AddNewAuthor />} /> <Route path='books' element={<Books />} /> <Route path='books/:id' element={<BookDetail />} /> <Route path='books/:id/edit' element={<EditBook />} /> <Route path='books/new' element={<AddNewBook />} /> </Routes> </div> </div> ) } export default App
import {Alert, Button, FormLabel, TextField, Typography} from "@mui/material"; import React, {useState} from "react"; import {useNavigate} from "react-router-dom"; const NewUser = () => { const [email, setEmail] = useState('') const [firstName, setFirstName] = useState('') const [lastName, setLastName] = useState('') const [emailError, setEmailError] = useState(false) const [firstNameError, setFirstNameError] = useState(false) const [lastNameError, setLastNameError] = useState(false) const [isPending, setIsPending] = useState(false) const [error, setError] = useState(null) const navigate = useNavigate(); const handleSubmit = (event) => { event.preventDefault() const user = {email, firstName, lastName} setIsPending(true) fetch('http://localhost:8085/api/users/', { method: 'POST', headers: {"Content-Type": "application/json"}, body: JSON.stringify(user) }).then((response) => { setIsPending(false) if (response.status !== 200) { response.json().then(data => { setError(data.error) }) console.error('Error:', response) } else { navigate('/') console.log('new user added') } }) } return ( <div style={{marginTop: "100px"}}> <Typography variant="h4"> New User </Typography> {error && <Alert severity="error" sx={{my: 3}}>{error}</Alert>} <form className="d-flex flex-column" onSubmit={handleSubmit}> <TextField label="Email" onChange={e => setEmail(e.target.value)} required variant="outlined" color="primary" type="email" sx={{mb: 3}} fullWidth value={email} error={emailError} placeholder="mail@example.com" /> <TextField label="Fisrt Name" onChange={e => setFirstName(e.target.value)} required variant="outlined" color="primary" type="text" sx={{mb: 3}} fullWidth value={firstName} error={firstNameError} placeholder="Jonh" /> <TextField label="Last Name" onChange={e => setLastName(e.target.value)} required variant="outlined" color="primary" type="text" sx={{mb: 3}} fullWidth value={lastName} error={lastNameError} placeholder="Doe" /> <div className="d-flex justify-content-center"> <Button variant="contained" color="primary" sx={{mx: 1}} type="submit" disabled={isPending}>Create</Button> <Button variant="outlined" color="primary" sx={{mx: 1}} href="/">Back</Button> </div> </form> </div> ); } export default NewUser;
package pl.agnieszkajankowska.enauczyciel.security; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import pl.agnieszkajankowska.enauczyciel.model.Role; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class MyUserDetails implements UserDetails { private final User user; public MyUserDetails(User user) { this.user = user; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { Role role = user.getRole(); List<SimpleGrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority(role.name())); return authorities; } @Override public String getPassword() { return user.getPassword(); } @Override public String getUsername() { return user.getLogin(); } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
--- keywords: Personal Finance,Home Ownership,Mortgage,Commercial Real Estate,Mortgages,Real Estate Investing title: ブランケット住宅ローン description: 包括的住宅ローンは、複数の不動産のローンを調達するための効率的な方法を提供できる資金調達の一種です。 --- # ブランケット住宅ローン ##包括的住宅ローンとは何ですか? 包括的住宅ローンは、複数の不動産をカバーする単一の住宅ローンであり、資産のグループがローンの担保として機能します。不動産開発業者や大規模な投資家は、一度に複数の不動産を購入することが多いため、包括的住宅ローンにより、1回のローンでこれらの取引を簡素化できます。 包括的住宅ローンはまた、借り手がグループから1つの不動産を売却し、他の不動産を返済することなくローンを保持することを可能にします。 包括的住宅ローンは、集合住宅やアパートの建物を含む、商業取引と住宅取引の両方に適用されます。それらはまた家を買って、ひっくり返す会社または開発者によって使用されます。 包括的住宅ローンは包括的ローンとも呼ばれ、他の住宅ローンと同じように借り換えることができます。 ##誰が包括的住宅ローンを取得する必要がありますか? 包括的住宅ローンは、住宅をまとめて購入する企業、または商業用または住宅用の不動産ポートフォリオを所有する経験豊富な投資家または家主向けに設計されています。 「これは、一夜にして本格的な不動産管理に飛び込もうとしている初心者のママとポップの家主のためではありません」とマクブライドは言います。 また、主たる住居と別荘を持つ借り手も対象としていません。 ##包括的住宅ローンの長所と短所 マクブライド氏によると、すべての住宅ローンには閉鎖費用が伴いますが、不動産ごとに個別のローンを組むのではなく、1つのローンだけを閉鎖するため、包括的住宅ローンでいくらか節約できる可能性があります。これらの節約は、追加の不動産やその他のプロジェクトのキャッシュフローの増加につながります。 包括的住宅ローンはより高い頭金を必要とします、しかし-25パーセントの北から50パーセントまで-それは障害になる可能性があります、とマクブライドは付け加えます。ローンを担保している物件の1つが売却された場合、その物件を担保していたローンの一部を返済する必要があります。単にポケットに入れることはできません。 [バルーン支払いで](/balloon-payment)構成されている可能性があります。これにより、借り手は一定期間低額の支払いを行うことができ、その後、一度に多額の一括払いを行うことができます。ローンは、借り手が最初に利息のみを支払うように構成されている場合があります。このタイプの取り決めは、優れた信用とかなりの富と資産を持つ借り手に提供される傾向があります。 ##包括的住宅ローンの貸し手を見つける方法 包括的住宅ローンを専門とする住宅ローンの貸し手は、他の種類のローンを提供するものほど簡単には利用できません。商業貸し手を調査し、彼らの料金、手数料、頭金の要件に注意することから始めます。 「ブランケット住宅ローンには包括的利用可能性がありません」とマクブライドは言います。 「このタイプのローンで借り手と協力している貸し手と住宅ローンブローカーを見つけるために、いくつかの掘り下げを行う必要があります。多くの場合、多くの商業貸付を行う銀行または貸し手は、製品ラインナップの一部としてこれを持っています。」 ##ハイライト -不動産は担保としてまとめられていますが、個々の不動産は住宅ローン全体を引退することなく売却することができます。 -包括的住宅ローンの主な利点は、借り手がより多くの現金を手元に持つことができることです。たとえば、不動産所有者は、複数の住宅ローンの申し込みと締め切りに関連するコストを節約できます。 -包括的住宅ローンの落とし穴には、従来の住宅ローンよりも高い平均コストが含まれます。 -包括的住宅ローンは、開発者、不動産投資家、および足ひれによって一般的に使用されます。 -包括的住宅ローンは、2つ以上の不動産をカバーする単一の住宅ローンです。
import 'dart:math'; import 'package:flutpuz_hack/platform/serializable.dart'; import 'package:meta/meta.dart'; import 'point.dart'; @immutable class Tile implements Serializable { /// Unique identifier of a tile, starts /// from a zero. final int number; final Point<int> targetPoint; final Point<int> currentPoint; const Tile( this.number, this.targetPoint, this.currentPoint, ); Tile move(Point<int> point) => Tile(number, targetPoint, point); @override void serialize(SerializeOutput output) { output.writeInt(number); output.writeSerializable(PointSerializableWrapper(targetPoint)); output.writeSerializable(PointSerializableWrapper(currentPoint)); } } class TileDeserializableFactory extends DeserializableHelper<Tile> { const TileDeserializableFactory() : super(); @override Tile deserialize(SerializeInput input) { final pd = PointDeserializableFactory(); final number = input.readInt(); final targetPoint = input.readDeserializable(pd); final currentPoint = input.readDeserializable(pd); return Tile(number, targetPoint, currentPoint); } }
import Link from 'next/link'; import React from 'react'; import { classNames } from 'utils/classNames'; import './Text.scss'; type Props<T extends React.ElementType> = React.ComponentProps<T> & { as?: T; bold?: boolean; variant?: 'normal' | 'light' | 'lighter'; size?: number | string; children?: React.ReactNode; className?: string; }; export const Text = <T extends React.ElementType = 'span'>({ bold, variant, size, as, children, className, ...rest }: Props<T>) => { const names = classNames('text', variant, { bold }, className); const Component = as || 'span'; return ( <Component className={names} style={{ fontSize: size }} {...rest}> {children} </Component> ); }; Text.Link = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as={Link} />; }; Text.P = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as="p" />; }; Text.Div = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as="div" />; }; Text.H1 = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as="h1" />; }; Text.H2 = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as="h2" />; }; Text.H3 = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as="h3" />; }; Text.H4 = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as="h4" />; }; Text.H5 = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as="h5" />; }; Text.H6 = <T extends React.ElementType>(props: Props<T>) => { return <Text {...props} as="h6" />; };
use std::io::{ stdin, stdout, Write }; fn read_int (message: &str) -> i32 { let mut number_str = String::new(); print!("{}", message); // Ensure that all intermediately buffered contents reach the standard output. stdout().flush().unwrap(); // Read a line from the standard input. stdin().read_line(&mut number_str).unwrap(); let number: i32 = number_str.trim().parse().expect("Veuillez entrer un nombre entier."); // Return the number. number } fn main() { println!("TP2.Ex2: Compare two integers.\n"); let n1 = read_int("n1 = "); let n2 = read_int("n2 = "); print!("\nResult : "); if n1 > n2 { println!("{} > {}", n1, n2); } else if n1 < n2 { println!("{} < {}", n1, n2); } else { println!("{} = {}", n1, n2); } }
package leetCode.easy; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class E0014_LongestCommonPrefix { // solution 1 public static String longestCommonPrefix1(String[] strs) { int minSize = Arrays.stream(strs).min(new Comparator<String>() { @Override public int compare(String o1, String o2) { if (o1.length() > o2.length()) { return 1; } return -1; } }).orElse("").length(); List<Character> list = new ArrayList<Character>(); for (int i = 0; i < minSize; i++) { char c = strs[0].charAt(i); boolean flag = true; for (int j = 1; j < strs.length; j++) { if (strs[j].charAt(i) != c) { flag = false; break; } } if (flag) { list.add(c); continue; } break; } return list.stream().map(String::valueOf).collect(Collectors.joining()); } // solution 2 (faster) public static String longestCommonPrefix2(String[] strs) { Arrays.sort(strs); // 按字母排序 String s1 = strs[0]; String s2 = strs[strs.length - 1]; int idx = 0; while (idx < s1.length() && idx < s2.length()) { if (s1.charAt(idx) == s2.charAt(idx)) { idx++; } else { break; } } return s1.substring(0, idx); } public static void main(String[] args) { System.out.println(longestCommonPrefix1(new String[] { "flower", "flow", "flight" })); System.out.println(longestCommonPrefix1(new String[] { "dog", "racecar", "car" })); System.out.println(longestCommonPrefix2(new String[] { "flower", "flow", "flight" })); System.out.println(longestCommonPrefix2(new String[] { "dog", "racecar", "car" })); } }
import { Button, Form, Input, InputNumber, Select, Spin, message } from "antd"; import { useEffect, useState } from "react"; import { useNavigate, useParams } from "react-router-dom"; import ReactQuill from "react-quill"; import "react-quill/dist/quill.snow.css"; const UpdateProductPage = () => { const [loading, setLoading] = useState(false); const [categories, setCategories] = useState([]); const navigate = useNavigate() const [form] = Form.useForm(); const apiUrl = import.meta.env.VITE_API_BASE_URL; const params = useParams(); const productId = params.id useEffect(() => { const fetchData = async () => { setLoading(true); try { const [categoriesResponse, singleProductResponse] = await Promise.all([ fetch(`${apiUrl}/api/categories`), fetch(`${apiUrl}/api/products/${productId}`), ]); if(!categoriesResponse.ok || !singleProductResponse.ok){ message.error("Data fetch failed") return; } const [categoriesData, singleProductData] = await Promise.all([ categoriesResponse.json(), singleProductResponse.json(), ]); setCategories(categoriesData) if(singleProductData){ form.setFieldsValue({ name: singleProductData.name, current: singleProductData.price.current, discount: singleProductData.price.discount, description: singleProductData.description, img: singleProductData.img.join("\n"), colors: singleProductData.colors.join("\n"), sizes: singleProductData.sizes.join("\n"), category: singleProductData.category, }); } } catch (error) { console.log("Data Error", error); } finally { setLoading(false); } } fetchData() }, [apiUrl,productId, form]); const onFinish = async (values) => { const imgLinks = values.img .split("\n") .map((link) => link.trim()); const colors = values.colors .split("\n") .map((link) => link.trim()); const sizes = values.sizes .split("\n") .map((link) => link.trim()); setLoading(true); try { const response = await fetch(`${apiUrl}/api/products/${productId}`, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ ...values, price: { current: values.current, discount: values.discount }, colors, sizes, img: imgLinks, }), }); if (response.ok) { message.success("The product has been update successfully"); navigate("/admin/products") } else { message.error("An error occurred while updating the product"); } } catch (error) { console.log("Product update error", error); } finally { setLoading(false); } }; return ( <Spin spinning={loading}> <Form name="basic" layout="vertical" form={form} onFinish={onFinish}> <Form.Item label="Product Name" name="name" rules={[ { required: true, message: "Please input your product name!", }, ]} > <Input /> </Form.Item> <Form.Item label="Product Category" name="category" rules={[ { required: true, message: "Please pick your product category!", }, ]} > <Select> {categories.map((category) => ( <Select.Option value={category._id} key={category._id}> {category.name} </Select.Option> ))} </Select> </Form.Item> <Form.Item label="Price" name="current" rules={[ { required: true, message: "Please input your product price!", }, ]} > <InputNumber /> </Form.Item> <Form.Item label="Discount Rate" name="discount" rules={[ { required: true, message: "Please input your discount rate!", }, ]} > <InputNumber /> </Form.Item> <Form.Item label="Product Description" name="description" rules={[ { required: true, message: "Please input your Product Description!", }, ]} > <ReactQuill theme="snow" style={{ backgroundColor: "white" }} /> </Form.Item> <Form.Item label="Product Img (Links)" name="img" rules={[ { required: true, message: "Please input your four pieces Product Img (Link)!", }, ]} > <Input.TextArea placeholder="Please use a new line for each image link." autoSize={{ minRows: 4 }} /> </Form.Item> <Form.Item label="Product Colors (RGB Codes)" name="colors" rules={[ { required: true, message: "Please input your minimum one pieces Product Colors!", }, ]} > <Input.TextArea placeholder="Please use a new line for each RGB Codes link." autoSize={{ minRows: 4 }} /> </Form.Item> <Form.Item label="Product Size (Links)" name="sizes" rules={[ { required: true, message: "Please input your minimum one pieces Product sizes (Link)!", }, ]} > <Input.TextArea placeholder="Please use a new line for each body size." autoSize={{ minRows: 4 }} /> </Form.Item> <Button type="primary" htmlType="submit"> Update </Button> </Form> </Spin> ); }; export default UpdateProductPage;
// // CellDomainView.swift // FawGen // // Created by Erick Olibo on 26/06/2019. // Copyright © 2019 DEFKUT Creations OU. All rights reserved. // import UIKit /// A UIView representing the domain extension text and availability status /// of a domain, display as a rectangle of 8:5 ratio class CellDomainView: UIView { // MARK: - Properties public enum AvailabilityStatus: String { case normal case available case taken case unknown } public var status: AvailabilityStatus = .normal { didSet { updateAvailabilityUI() } } private(set) var domainExt: DomainExtension = .com private(set) var view: UIView! // MARK: - Outlets @IBOutlet weak var extensionLabel: UILabel! // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) commonInitialization() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInitialization() } /// This method set the basic characteristics during the awake from NIB /// of the Cell Domain View private func commonInitialization() { let view = Bundle.main.loadNibNamed(String(describing: type(of: self)), owner: self, options: nil)?.first as! UIView view.frame = bounds view.autoresizingMask = [ UIView.AutoresizingMask.flexibleWidth, UIView.AutoresizingMask.flexibleHeight] view.addSubview(extensionLabel) view.layer.cornerRadius = 5 self.view = view self.addSubview(view) } /// Special Initialization with the domain extension to add more functions /// to the already initialized Domain View (via init(frame) ) /// - Parameter info: this is the Domain Extension type that will /// be core to this CellDomainView. /// - Parameter status: Set the availability status of this entity. /// - Note: This method has a default Availability status of .normal public func initialize(_ info: DomainExtension, status: AvailabilityStatus = .normal) { let dot = "." extensionLabel.text = (info == .couk) ? ".co.uk" : dot + info.rawValue self.domainExt = info self.status = status } /// Updates the Availability status of the Cell Domain View and updates the UI private func updateAvailabilityUI() { switch status { case .normal: extensionLabel.textColor = .white view.backgroundColor = FawGenColors.secondary.color case .available: extensionLabel.textColor = .white view.backgroundColor = FawGenColors.availableStatus.color case .taken: extensionLabel.textColor = .gray view.backgroundColor = .darkGray case .unknown: extensionLabel.textColor = .white view.backgroundColor = FawGenColors.unknown.color } } }
#include <stdio.h> #include <stdlib.h> #include "matrix.h" #include "matrix_op.h" #include "matrix_init.h" #include "matrix_task.h" int main() { const double eps = 0.0001; size_t n = 3; matrix * test_matrix = matrix_alloc(n, n); matrix * test_matrix2 = matrix_alloc(n, n); matrix * test_exp_matrix = matrix_alloc(n, n); matrix * term_matrix = matrix_alloc(n, 1); // matrix * sols_matrix = matrix_alloc(n, 1); double test_matrix_3_x_3[3][3] = {{3.0, 2.0, -4.0}, {2.0, 3.0, 3.0}, {5.0, -3.0, 1.0}}; double test_exp_matrix_3_x_3[3][3] = {{1.0, 0.0, 0.0}, {0.0, 2.0, 0.0}, {0.0, 0.0, -1.0}}; double test_term_matrix_3_x_1[3] = {3.0, 15.0, 14.0}; for (size_t i = 0; i < n; ++i){ for (size_t j = 0; j < n; ++j){ matrix_set(test_matrix, i, j, test_matrix_3_x_3[i][j]); matrix_set(test_matrix2, i, j, test_matrix_3_x_3[i][j]); matrix_set(test_exp_matrix, i, j, test_exp_matrix_3_x_3[i][j]); } } printf("-------------------\n"); printf("Matrix test \n"); matrix_print(test_matrix); printf("-------------------\n"); printf("-------------------\n"); printf("Matrix norm %lf\n", matrix_op_norm(test_matrix)); printf("-------------------\n"); size_t k = 0; printf("Введите размер квадратной матрицы (Гаусс)\n"); scanf("%zu", &k); matrix * matrix_inp = matrix_alloc(k, k); for (size_t i = 0; i < k; ++i){ for (size_t j = 0; j < k; ++j){ double val; printf("A[%zu][%zu] = ", i, j); scanf("%lf", &val); printf("\n"); matrix_set(matrix_inp, i, j, val); } } printf("Введите матрицу свободных членов \n"); matrix * term_matrix_inp = matrix_alloc(k, 1); matrix * sols_matrix = matrix_alloc(k, 1); for (size_t i = 0; i < k; ++i){ double val; printf("A[%zu][%d] = ", i, 0); scanf("%lf", &val); matrix_set(term_matrix_inp, i, 0, val); matrix_set(sols_matrix, i, 0, 0); } //printf("Term matrix\n"); // matrix_print(term_matrix); // printf("-------------------\n"); // sols_matrix = matrix_task_gauss(test_matrix, term_matrix, sols_matrix, n); sols_matrix = matrix_task_gauss(matrix_inp, term_matrix_inp, sols_matrix, k); printf("-------------------\n"); if (sols_matrix != NULL){ printf("Solution matrix\n"); matrix_print(sols_matrix); } printf("-------------------\n"); printf("Введите размер квадратной матрицы (экспонента) \n"); scanf("%zu", &k); matrix * matrix_exp_inp = matrix_alloc(k, k); for (size_t i = 0; i < k; ++i){ for (size_t j = 0; j < k; ++j){ double val; printf("A[%zu][%zu] = ", i, j); scanf("%lf", &val); printf("\n"); matrix_set(matrix_exp_inp, i, j, val); } } //test_exp_matrix = matrix_task_exponent(test_exp_matrix, eps); matrix * matrix_exp_res = matrix_task_exponent(matrix_exp_inp, eps); printf("-------------------\n"); printf("Exp matrix\n"); //matrix_print(test_exp_matrix); matrix_print(matrix_exp_res); printf("-------------------\n"); //printf("-------------------\n"); // printf("Matrix test exp \n"); // matrix_print(test_exp_matrix); // printf("-------------------\n"); matrix * product = matrix_op_mult_alloc(test_matrix, test_exp_matrix); printf("-------------------\n"); printf("Product matrix (test exp * test) \n"); matrix_print(product); printf("-------------------\n"); for (size_t i = 0; i < n; ++i){ matrix_set(term_matrix, i, 0, test_term_matrix_3_x_1[i]); matrix_set(sols_matrix, i, 0, 0); } printf("-------------------\n"); printf("-------------------\n"); printf("Matrix det\n %lf", matrix_op_det(test_matrix)); printf("-------------------\n"); printf("-------------------\n"); printf("Matrix inv\n"); matrix_print(matrix_op_inverse(test_matrix2)); printf("\n-------------------\n"); matrix_free(test_matrix); matrix_free(test_matrix2); matrix_free(test_exp_matrix); matrix_free(term_matrix); matrix_free(matrix_inp); matrix_free(term_matrix_inp); matrix_free(sols_matrix); matrix_free(matrix_exp_inp); matrix_free(product); matrix_free(matrix_exp_res); return 0; }
import React from 'react'; import Image from 'next/image'; import Link from 'next/link'; import TechLabel from '../components/shared/TechLabel'; function Projects(props) { return ( <div> <h2 className='font-bold text-2xl md:text-3xl tracking-tight mb-6 mt-2 text-title dark:text-gray-200'>Projects</h2> <a href="https://www.matchoffice.com" target="_blank" className='relative flex mb-6 rounded items-start hover:bg-white hover:top-[-4px] transition-all duration-200 hover:ease-out'> <div class="relative group"> <div class="absolute -inset-1 bg-gradient-to-r from-[#a5dff9] to-[#30A9DE] dark:from-[#386276] dark:to-[#103343] rounded blur opacity-25 group-hover:opacity-0 md:group-hover:opacity-100 transition duration-1000 group-hover:duration-200"></div> <div class="relative p-4 bg-white ring-1 ring-gray-900/5 dark:ring-blue rounded leading-none block sm:flex justify-start space-x-0 sm:space-x-6 dark:bg-navigation"> <div className='relative h-20 w-20 block mr-4 shrink-0'> <Image className='rounded-full' src="/images/matchoffice.png" alt='project-matchoffice' layout='fill' objectFit='contain' /> </div> <div> <h4 className='text-lg font-bold tracking-tight text-title dark:text-gray-200'>Matchoffice</h4> <p className='leading-5 text-gray-700 dark:text-gray-300 text-sm mt-2 mb-4 pr-8'> One of the leading players in the commercial property lease market in the world. Independent portal that collects all business centres in one place, making it easier for potential tenants to find their future office spaces for rent. </p> <div className='flex md:flex-row pr-0 sm:pr-48 flex-wrap'> <TechLabel title='Ruby on Rails' /> <TechLabel title='React' /> <TechLabel title='Redux' /> <TechLabel title='Bootstrap' /> <TechLabel title='Webpack' /> </div> </div> </div> </div> </a> {/* <a href="https://www.upwork.com/freelancers/~01872814c9610089a8" target="_blank" className='relative top-0 flex mb-6 rounded p-4 items-start border hover:shadow-projects hover:border hover:border-black hover:bg-white hover:top-[-4px] transition-all duration-200 hover:ease-out bg-gradient-to-l from-white to-sky-50 hover:bg-gradient-to-r'> <div className='relative h-16 w-16 block mr-4 shrink-0'> */} <a href="https://www.upwork.com/freelancers/~01872814c9610089a8" target="_blank" className='relative top-0 flex mb-6 rounded items-start hover:bg-white hover:top-[-4px] transition-all duration-200 hover:ease-out bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-white to-sky-50 hover:bg-gradient-to-l'> <div class="relative group"> <div class="absolute -inset-1 bg-gradient-to-r from-[#a5dff9] to-[#30A9DE] dark:from-[#386276] dark:to-[#103343] rounded blur opacity-25 group-hover:opacity-100 transition duration-1000 group-hover:duration-200"></div> <div class="relative p-4 bg-white ring-1 ring-gray-900/5 dark:ring-blue rounded leading-none block sm:flex justify-start space-x-0 sm:space-x-6 dark:bg-navigation"> <div className='relative h-20 w-20 block mr-4 shrink-0'> <Image className='rounded-full' src="/images/upwork.png" alt='project-irream' layout='fill' objectFit='contain' /> </div> <div> <h4 className='text-lg font-bold tracking-tight text-title dark:text-gray-200'>Freelancer on Upwork</h4> <p className='leading-5 text-gray-700 dark:text-gray-300 text-sm mt-2 mb-4 pr-8'> I have worked with a wide range of clients and projects to deliver high-quality work that exceeds client expectations, committed to creating visually appealing, user-friendly websites that drive results. </p> <div className='flex md:flex-row pr-0 sm:pr-48 flex-wrap'> <TechLabel title='HTML/CSS' /> <TechLabel title='React' /> <TechLabel title='JavaScript' /> <TechLabel title='Api Integration' /> </div> </div> </div> </div> </a> {/* <a href="https://www.english-irream.com/" target="_blank" className='relative top-0 flex mb-6 rounded p-4 items-start border hover:shadow-projects hover:border hover:border-black hover:bg-white hover:top-[-4px] transition-all duration-200 hover:ease-out bg-gradient-to-r from-white to-sky-50 hover:bg-gradient-to-l'> <div className='relative h-16 w-16 block mr-4 shrink-0'> */} <a href="https://www.english-irream.com/" target="_blank" className='relative top-0 flex mb-6 rounded items-start hover:bg-white hover:top-[-4px] transition-all duration-200 hover:ease-out bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-white to-sky-50 hover:bg-gradient-to-l'> <div class="relative group"> <div class="absolute -inset-1 bg-gradient-to-r from-[#bde7fa] to-[#64c1e8] dark:from-[#386276] dark:to-[#103343] rounded blur opacity-25 group-hover:opacity-100 transition duration-1000 group-hover:duration-200 "></div> <div class="relative p-4 bg-white ring-1 ring-gray-900/5 dark:ring-blue rounded leading-none block sm:flex items-top justify-start space-x-0 sm:space-x-6 dark:bg-navigation"> <div className='relative h-20 w-20 block mr-4 shrink-0'> <Image className='rounded-full' src="/images/irream.png" alt='project-irream' layout='fill' objectFit='contain' /> </div> <div> <h4 className='text-lg font-bold tracking-tight text-title dark:text-gray-200'>English Irream School</h4> <p className='leading-5 text-gray-700 dark:text-gray-300 text-sm mt-2 mb-4 pr-8'> landing page for a language school, where you can find the main information, attract potential students, and encourage them to sign up for courses. Read reviews or feedback from previous students. {/* landing page for a language school, where you can read main information ab is a place where you get confidence in speaking a foreign language. Boost your communication skills. IRREAM language school is a place where you get confidence in speaking a foreign language. */} </p> <div className='flex md:flex-row pr-0 sm:pr-48 flex-wrap'> <TechLabel title='React' /> <TechLabel title='AWS Hosting' /> </div> </div> </div> </div> </a> </div> ); } export default Projects;
--- keywords: Business,Marketing Essentials title: 品牌忠诚度 description: 品牌忠诚的客户认为,某个品牌比任何竞争对手都提供更高的质量和更好的服务,而价格并不重要。 --- # 品牌忠诚度 [市场研究](/market-research)指标(品牌忠诚度和客户忠诚度)上得分高的公司不仅[收入增长](/revenue)速度比行业同行快 2.5 倍,而且还提供了两个在 10 年的时间框架内给股东[的回报](/return)[是](/return)五倍。品牌忠诚度——对特定品牌重复购买的长期承诺——不依赖于价格这一事实使得该指标成为利润和盈利能力(即相对于费用的利润)的特别强大的驱动因素。 品牌忠诚度对盈利能力如此重要的主要原因很简单:大多数公司 65% 的收入来自与现有客户的重复业务。不仅忠诚于品牌的现有客户的购买频率比新客户高 90%,而且维持品牌忠诚度的细分市场也远低于吸引新客户的营销成本。 在 2020 年大流行期间销售额暴跌之后,每个行业的企业都比以往任何时候都更加重要的是加大对旨在保留每家公司最宝贵资产的营销计划的投资:他们现有的品牌忠诚客户群。 ## 什么是品牌忠诚度? 与基于金钱(价格和折扣)的客户忠诚度不同,品牌忠诚度基于感知(形象和体验)。品牌忠诚的客户认为,某个品牌比任何竞争对手都代表着更高的质量和更好的服务——而价格并不重要。品牌忠诚客户的总购买量可能会减少,但他们购买的利润率会更大。一旦建立起来,品牌忠诚度就很容易保持——当然,前提是产品质量和服务水平仍然很高。保持品牌忠诚度的成本也低于客户忠诚度,后者需要不断提供低价和定期折扣以保持市场上最优惠的地位。 ## 如何建立品牌忠诚度 大多数成熟的品牌产品在竞争激烈的市场中运营,与新老竞争对手的产品争夺[市场份额](/marketshare),其中许多产品几乎无法区分。为了在这种动态中茁壮成长,营销部门采用各种策略来建立和维持品牌忠诚度,包括监控购买趋势、分析支出数据以及针对现有忠诚和可能成为忠诚的客户群设计广告活动。 以下是创建和维护品牌忠诚度客户群的一些最常被引用的策略,可以将您的业务提升到一个新的水平。 **一流的质量:** 品牌忠诚度的首要条件(基本条件)是质量。无论你的营销预算有多大,有多少名人代言,低质量的产品和服务总是会在社交媒体上被嘲笑。另一方面,始终如一地提供一流质量的公司会将客户转变为品牌忠诚的拥护者,他们传播积极的口碑,从不觉得有必要在其他地方购物。 **客户服务:** 卓越的客户服务是昂贵的——24/7 的聊天代表、社交媒体经理、电话接线员、支持票务人员——但确保客户始终获得一流的服务是一项提高服务水平的投资产生巨大回报的品牌忠诚度。事实上,在拥挤的市场中,让客户感到受到重视的一流服务可能是使品牌与竞争对手区分开来的唯一因素。为了使客户服务最大限度地提高品牌忠诚度,客户必须能够访问用户友好的系统来提交反馈和登记投诉——并且应该培训一个专门的员工团队来及时处理他们的提交。 **品牌大使:** 除了在社交媒体上提供免费口碑广告的品牌忠诚客户外,公司还聘请代言人担任其产品的品牌大使。除了拥有扎实的营销背景和具有跨平台参与网络(通过博客、电子邮件、网络研讨会)建立的在线形象外,成功的品牌大使还应具有真实、专业的形象,对产品和服务的深入了解,以及在建立忠诚的客户关系方面拥有高度发达的专业知识。除此之外,最好的品牌大使还擅长收集关键的客户和竞争对手情报,这些情报可以转化为有利可图的业务改进。 **忠诚度计划:** 建立奖励现有客户业务的计划是建立品牌忠诚度的最直接方式之一。值得重申的是——无论兑换商店积分、折扣和免费产品多么昂贵——投资于现有客户的保留和忠诚度远低于营销新客户的成本。对于高价品牌来说尤其如此,因为忠诚计划会员的独家折扣可能是选择高价品牌而不是更便宜的选择的正确动机。 **在线社区:**随着电子商务的持续加速——美国 2022 年的在线支出预计将达到 1 万亿美元——建立在线社区以提高品牌忠诚度对于各行各业的企业来说至关重要。与静态广告不同,社交媒体有一系列工具可以与客户建立更深入、更个人的联系,从举办问答和与员工的直播到带领客户参观企业的幕后之旅。数字社区不仅可以作为与在网上花费数小时的客户进行互动的便捷接入点,而且作为网站的扩展,社区还可以作为从社交互动到购买转化的桥梁。 ## 品牌忠诚度领导者 以下是两个通过优先考虑质量和客户服务对品牌忠诚度进行高利润投资的公司的例子。这些品牌忠诚度领导者不仅可以为他们的产品收取更高的费用,而且还可以节省营销成本——向现有客户进行社交媒体和电子邮件营销只是吸引新客户成本的一小部分。 **Apple:** 2021 年,Apple 的品牌忠诚度得分高达 92%——这家科技巨头保留的现有客户比例高于任何行业的任何其他公司。 Apple 作为全球最有价值品牌的地位不仅基于革命性的技术和最先进的设计,还基于无与伦比的品牌影响力和一流的客户服务。任何曾经见过一排排顾客围着 Apple 商店等待最新版本的人都明白,品牌影响力对产品的真正价值的影响与市场表现的任何其他驱动因素一样多,甚至更多。随着 Apple 推出包括 Apple TV 和游戏在内的收费服务,该公司可能会增加更多[的钱包(](/share-of-wallet) [SOW](/share-of-wallet) ),即客户在牺牲竞争对手的情况下在一家公司的品牌上花费的美元金额。 **耐克:**耐克成为世界上最有价值的运动品牌的最重要原因之一是行业领先的会员计划,它提供了四个品牌忠诚度驱动因素:1) 排他性(获得独家特权:门票和产品发射); 2) 社区(免费锻炼课程、培训支持);个性化(生日和周年纪念礼物、个性化产品推荐); 4)全渠道体验(店内、现场、移动应用)。 ## 品牌忠诚度和盈利能力统计 几十年来,品牌忠诚度和盈利能力之间的相关性已得到充分证明。以下是一些令人印象深刻的统计数据: **客户留存率:** 2020 年,哈佛商学院报告称——“在一个又一个行业”——将客户留存率提高 5% 会使利润增加至少 25% 到 95%——这一统计数据“引发了急于制定保留策略,其中许多继续支付巨额红利。” **客户生命周期价值 (CLV):** Microsoft 报告了将忠诚度与长期奖励联系起来的最重要统计数据之一:品牌忠诚度提高 7%,每位客户的客户生命周期价值 (CLV) 提高 85% . (CLV 是衡量公司增长的指标,是在关系的整个生命周期内从单个客户那里获得的预期总收入。) **客户服务:** 83% 的客户会因为糟糕的客户服务体验而更换品牌。 **始终如一的质量:** 74% 的消费者表示产品质量是保持品牌忠诚度的主要原因。 [企业社会责任](/corp-social-responsibility)(CSR) 问题上采取强硬立场的品牌花费更多。 ## 品牌忠诚度:客户资本主义与股东至上 有人可能会问——如果盈利能力和品牌忠诚度等客户指标之间的联系如此完善——为什么企业经常忽视他们最有价值的客户?哈佛商业评论 (HBR) 对这个问题提出了一些有趣的答案:财务会计和股东至上。 哈佛商业评论的文章认为,由于财务披露规则和公司会计惯例几乎不需要报告客户价值,因此将季度收益优先于客户关系的短期心态使管理层和股东都忽视了忠诚度在盈利能力中发挥的关键作用。加上财务报告的遗漏,两种截然不同的盈利策略——股东至上与客户资本主义——影响了品牌忠诚度等客户指标如何被列为利润驱动因素。 一方面,在 1950 年代,被福布斯称为“商业咨询之父”、被通用电气董事长[杰克·韦尔奇称为“上世纪最伟大的管理思想家”的彼得·德鲁克](/jack-welch)说:“企业的真正目的是创造并留住客户。”另一方面,在 1970 年代,[米尔顿·弗里德曼 (Milton Friedman](/milton-friedman) ) 说,公司的存在是为了使股东价值最大化——时期——哈佛商业评论称这一论点引入了“股东至上的时代”。 “客户资本主义”方法的当前拥护者认为,将客户——而不是股东——放在首位的公司可以为股东创造更大的价值。例如,在 2019 年,《纽约时报》报道了商业圆桌会议的首席执行官——包括苹果的蒂姆·库克、亚马逊的杰夫·贝佐斯、通用汽车的玛丽·巴拉、Vista Equity Partners 的罗伯特·史密斯和拉里·芬克等权势人物贝莱德——打破了数十年的公司正统观念,发表声明称“公司的目的”不再只是促进股东的利益。取而代之的是,公司现在必须在几个新方面提供价值:直接向客户和间接地通过支持客户在保护环境和与供应商的道德打交道等问题上的价值观。 ## 强调 - 品牌忠诚度——基于对比任何竞争对手更高质量和更好服务的感知重复购买特定品牌——不依赖于价格。 - 品牌忠诚度的首要条件是质量。无论营销支出有多大,质量差都会扼杀品牌忠诚度。 - 品牌忠诚度领导者还可以在 10 年的时间框架内为股东带来两到五倍的回报。 - 品牌忠诚度得分高的公司收入增长速度是行业同行的 2.5 倍。 ## 常问问题 ### 什么是品牌大使? 品牌大使是公司聘请作为其产品代言人的专业营销人员。为了取得成功,品牌大使需要建立在线形象、跨平台参与网络、对产品和服务有深入的了解,以及建立忠诚客户关系方面的高度发达的专业知识。 ### 为什么品牌忠诚度很重要? 品牌忠诚度之所以重要的主要原因是它是盈利能力的主要驱动力:大多数公司 65% 的收入来自与现有客户的重复业务——忠诚于品牌的现有客户的购买频率比新客户高 90%, ### 品牌忠诚度和客户忠诚度有什么区别? 品牌忠诚度基于感知(形象和体验);客户忠诚度是基于金钱的(价格和折扣)。品牌忠诚客户认为,某个品牌比任何竞争对手都代表着更高的质量和更好的服务——价格并不重要。客户忠诚度需要提供低价和定期折扣,以保持市场上最优惠的价格。
import base64 import os import random import time import allure from selenium.webdriver.common.by import By from generator.generator import generated_person, generated_file from locators.elements_page_locators import (TextBoxPageLocators, CheckBoxPageLocators, RadioButtonPageLocators , ButtonsPageLocators, UploadAndDownloadPageLocators) from pages.base_page import BasePage class TextBoxPage(BasePage): locators = TextBoxPageLocators() @allure.step("Fill in all fields") def fill_all_fields(self): person_info = next(generated_person()) full_name = person_info.full_name email = person_info.email current_address = person_info.current_address.replace("\n", " ") permanent_address = person_info.permanent_address.replace("\n", " ") with allure.step("Filling fields"): self.element_is_visible(self.locators.FULL_NAME).send_keys(full_name) self.element_is_visible(self.locators.EMAIL).send_keys(email) self.element_is_visible(self.locators.CURRENT_ADDRESS).send_keys(current_address) self.element_is_visible(self.locators.PERMANENT_ADDRESS).send_keys(permanent_address) with allure.step("Click submit button"): self.element_is_visible(self.locators.SUBMIT).click() return full_name, email, current_address, permanent_address @allure.step("Check form") def check_filled_form(self): full_name = self.element_is_present(self.locators.CREATED_FULL_NAME).text.split(':')[1] email = self.element_is_present(self.locators.CREATED_EMAIL).text.split(':')[1] current_address = self.element_is_present(self.locators.CREATED_CURRENT_ADDRESS).text.split(':')[1] permanent_address = self.element_is_present(self.locators.CREATED_PERMANENT_ADDRESS).text.split(':')[1] return full_name, email, current_address, permanent_address class CheckBoxPage(BasePage): locators = CheckBoxPageLocators() @allure.step("Open full list") def open_full_list(self): self.element_is_visible(self.locators.EXPAND_ALL_BUTTON).click() @allure.step("Click random checkbox") def click_random_checkbox(self): item_list = self.elements_are_visible(self.locators.ITEM_LIST) count = 21 for _ in range(count): # use a for loop to iterate elements item = random.choice(item_list) # use random.choice to select a random element self.go_to_element(item) item.click() @allure.step("Get Checked checkbox") def get_checked_checkboxes(self): checked_list = self.elements_are_present(self.locators.CHECKED_ITEMS) data = [] for box in checked_list: title_item = box.find_element(By.XPATH, self.locators.TITLE_ITEM) data.append(title_item.text) return str(data).replace(' ', '').replace('.doc', '').lower() @allure.step("Get output result") def get_output_result(self): result_list = self.elements_are_present(self.locators.OUTPUT_RESULT) data = [] for item in result_list: data.append(item.text) return str(data).replace(' ', '').lower() class RadioButtonPage(BasePage): locators = RadioButtonPageLocators() @allure.step("Click on button") def click_on_button(self, button): buttons = {'yes': self.locators.YES_RB, 'impressive': self.locators.IMPRESSIVE_RB, 'no': self.locators.NO_RB} if button not in buttons: raise ValueError(f"Invalid button: {button}. Expected one of: {', '.join(buttons.keys())}") button_locator = buttons[button] try: button_element = self.element_is_visible(button_locator) button_element.click() except Exception as e: raise RuntimeError(f"Error clicking on button '{button}': {str(e)}") @allure.step("Get result") def get_output_result(self): return self.element_is_present(self.locators.OUTPUT_RESULT).text class ButtonsPage(BasePage): locators = ButtonsPageLocators() @allure.step("Click on different buttons") def click_on_diff_button(self, type_click): if type_click == "double": self.action_double_click(self.element_is_visible(self.locators.DOUBLE)) return self.check_clicked_on(self.locators.SUCCESS_DOUBLE) if type_click == "right": self.action_right_click(self.element_is_visible(self.locators.RIGHT)) return self.check_clicked_on(self.locators.SUCCESS_RIGHT) if type_click == "click": self.element_is_visible(self.locators.CLICK).click() return self.check_clicked_on(self.locators.SUCCESS_CLICK) @allure.step("Check is clicked on") def check_clicked_on(self, element): return self.element_is_present(element).text class UploadAndDownloadPage(BasePage): locators = UploadAndDownloadPageLocators() @allure.step("Upload file") def upload_file(self): file_name, path = generated_file() self.element_is_present(self.locators.UPLOAD).send_keys(path) os.remove(path) text = self.element_is_present(self.locators.UPLOADED).text return file_name.split('\\')[-1], text.split('\\')[-1] @allure.step("Download file") def download_file(self): current_directory = os.path.dirname(os.path.realpath(__file__)) link = self.element_is_present(self.locators.DOWNLOAD).get_attribute('href') # Decode the base64-encoded link link_bytes = base64.b64decode(link) # Find the start of the JPEG content offset = link_bytes.find(b'\xff\xd8') # Generate a random filename with a unique identifier file_name = f'filetest_{random.randint(0, 9999)}_{random.randint(0, 9999)}.jpg' file_path = os.path.join(current_directory, file_name) # Write the decoded content to the file with open(file_path, 'wb') as f: f.write(link_bytes[offset:]) # Check if the file exists file_exists = os.path.exists(file_path) os.remove(file_path) return file_exists
<?php namespace Versatile\Core\Support; use Countable; use Illuminate\Container\Container; use Illuminate\Support\Str; use Illuminate\Support\Traits\Macroable; use Versatile\Core\Contracts\ModuleInterface; use Versatile\Core\Contracts\ModulesRepositoryInterface; use Versatile\Core\Exceptions\ModuleNotFoundException; abstract class ModuleRepository implements ModulesRepositoryInterface, Countable { use Macroable; /** * Application instance. * * @var \Illuminate\Contracts\Foundation\Application */ protected $app; /** * The module path. * * @var string|null */ protected $path; /** * The scanned paths. * * @var array */ protected $paths = []; /** * @var string */ protected $jsonFile = 'module.json'; /** * @var string */ protected $stubPath; /** * The constructor. * * @param Container $app * @param string|null $path */ public function __construct(Container $app, $path = null) { $this->app = $app; $this->path = $path; } abstract protected function createModule($name); /** * Add other module location. * * @param string $path * * @return $this */ public function addLocation($path) { $this->paths[] = $path; return $this; } /** * Get all additional paths. * * @return array */ public function getPaths() : array { return $this->paths; } /** * Get scanned modules paths. * * @return array */ public function getScanPaths() : array { $paths = $this->paths; $paths[] = $this->getPath(); if ($this->config('scan.enabled')) { $paths = array_merge($paths, $this->config('scan.paths')); } $paths = array_map(function ($path) { return ends_with($path, '/*') ? $path : str_finish($path, '/*'); }, $paths); return $paths; } /** * Get & scan all modules. * * @return Collection * @throws \Exception */ public function scan() : Collection { $paths = $this->getScanPaths(); $modules = []; foreach ($paths as $key => $path) { $manifests = $this->app['files']->glob("{$path}/{$this->jsonFile}"); is_array($manifests) || $manifests = []; foreach ($manifests as $manifest) { $name = Json::make($manifest)->get('folder'); $modules[$name] = $this->createModule($name); } } return new Collection($modules); } /** * Get all modules. * * @return Collection * @throws \Exception */ public function all() : Collection { if (!$this->config('cache.enabled')) { return $this->scan(); } return $this->formatCached($this->getCached()); } /** * Format the cached data as array of modules. * * @param array $cached * @return Collection */ protected function formatCached($cached) : Collection { $modules = []; foreach ($cached as $name => $module) { $path = $module["path"]; $modules[$name] = $this->createModule($this->app, $name, $path); } return new Collection($modules); } /** * Get cached modules. * * @return Collection */ public function getCached() { return $this->app['cache']->remember($this->config('cache.key'), $this->config('cache.lifetime'), function () { return $this->scan(); }); } /** * Get modules by status. * * @param int $status * @return Collection * @throws \Exception */ public function getByStatus($status) : Collection { $modules = []; foreach ($this->all() as $name => $module) { if ($module->isStatus($status)) { $modules[$name] = $module; } } return new Collection($modules); } /** * Determine whether the given module exist. * * @param $name * @return bool * @throws \Exception */ public function has($name) : bool { return array_key_exists($name, $this->all()); } /** * Get list of enabled modules. * * @return Collection * @throws \Exception */ public function allEnabled() : Collection { return $this->getByStatus(1); } /** * Get list of disabled modules. * * @return Collection * @throws \Exception */ public function allDisabled() : Collection { return $this->getByStatus(0); } /** * Get count from all modules. * * @return int * @throws \Exception */ public function count() : int { return count($this->all()); } /** * Get all ordered modules. * * @param string $direction * @return Collection * @throws \Exception */ public function getOrdered($direction = 'asc') : Collection { $modules = $this->allEnabled(); uasort($modules, function (Module $a, Module $b) use ($direction) { if ($a->order == $b->order) { return 0; } if ($direction == 'desc') { return $a->order < $b->order ? 1 : -1; } return $a->order > $b->order ? 1 : -1; }); return $modules; } /** * Get a module path. * * @return string */ public function getPath() : string { return $this->path ?: $this->config('paths.modules', base_path('Modules')); } /** * Find a specific module. * * @param $folder * @return mixed|void * @throws \Exception */ /** * @param $folder * @return ModuleInterface|null * @throws \Exception */ public function find($folder) { foreach ($this->all() as $module) { if ($module->folder === strtolower($folder)) { return $module; } } return null; } /** * Find all modules that are required by a module. If the module cannot be found, throw an exception. * * @param $folder * @return Collection * @throws ModuleNotFoundException */ public function findRequirements($folder) : Collection { $requirements = []; $module = $this->findOrFail($folder); foreach ($module->getRequires() as $folder) { $requirements[] = $this->find($folder); } return new Collection($requirements); } /** * Find a specific module, if there return that, otherwise throw exception. * * @param $folder * @return ModuleInterface * @throws ModuleNotFoundException */ public function findOrFail($folder) { $module = $this->find($folder); if ($module !== null) { return $module; } throw new ModuleNotFoundException("Module [{$folder}] does not exist!"); } /** * Get all modules as laravel collection instance. * * @param $status * @return Collection * @throws \Exception */ public function collections($status = 1) : Collection { return new Collection($this->getByStatus($status)); } /** * Get module path for a specific module. * * @param $module * @return string */ public function getModulePath($module) { try { return $this->findOrFail($module)->getPath() . '/'; } catch (ModuleNotFoundException $e) { return $this->getPath() . '/' . Str::studly($module) . '/'; } } /** * Get a specific config data from a configuration file. * * @param $key * * @param null $default * @return mixed */ public function config($key, $default = null) { return $this->app['config']->get('versatile.modules.' . $key, $default); } /** * Get storage path for module used. * * @return string */ public function getUsedStoragePath() : string { $directory = storage_path('app/modules'); if ($this->app['files']->exists($directory) === false) { $this->app['files']->makeDirectory($directory, 0777, true); } $path = storage_path('app/modules/modules.used'); if (!$this->app['files']->exists($path)) { $this->app['files']->put($path, ''); } return $path; } /** * Set module used for cli session. * * @param $name * @throws ModuleNotFoundException */ public function setUsed($name) { $module = $this->findOrFail($name); $this->app['files']->put($this->getUsedStoragePath(), $module); } /** * Forget the module used for cli session. */ public function forgetUsed() { if ($this->app['files']->exists($this->getUsedStoragePath())) { $this->app['files']->delete($this->getUsedStoragePath()); } } /** * Get module used for cli session. * * @return string * @throws ModuleNotFoundException */ public function getUsedNow() : string { return $this->findOrFail($this->app['files']->get($this->getUsedStoragePath())); } /** * Get laravel filesystem instance. * * @return \Illuminate\Filesystem\Filesystem */ public function getFiles() { return $this->app['files']; } /** * Determine whether the given module is activated. * * @param string $name * @return bool * @throws ModuleNotFoundException */ public function enabled($name) : bool { return $this->findOrFail($name)->enabled(); } /** * Determine whether the given module is not activated. * @param string $name * @return bool * @throws ModuleNotFoundException */ public function disabled($name) : bool { return !$this->enabled($name); } /** * Enabling a specific module. * @param string $name * @return void * @throws ModuleNotFoundException */ public function enable($name) { $this->findOrFail($name)->enable(); } /** * Disabling a specific module. * * @param string $name * @return void * @throws ModuleNotFoundException */ public function disable($name) { $this->findOrFail($name)->disable(); } /** * Delete a specific module. * * @param string $name * @return bool * @throws ModuleNotFoundException */ public function delete($name) : bool { return $this->findOrFail($name)->delete(); } }
package com.example.monefy.Manager.billings; import android.util.Log; import com.example.monefy.basic.functionality.model.billings.Billings; import com.example.monefy.basic.functionality.model.DataLoadListener; import com.example.monefy.basic.functionality.model.billings.TypeBillings; import com.example.monefy.Manager.firebase.FirebaseManager; import com.example.monefy.Manager.billings.OnBillingsCallback; import java.util.ArrayList; import java.util.List; public class BillingsManager { private static BillingsManager billingsManager; public static BillingsManager getBillingsManager(){ if(billingsManager == null){ billingsManager = new BillingsManager(); } return billingsManager; } public BillingsManager() {} private List<Billings> billingsList = new ArrayList<>(); public List<Billings> getBillingsList() { return billingsList; } /** * loadBillings - Здійснює загрузку рахунків. * @return billingsList повертає список рахунків */ public void loadBillings(DataLoadListener dataLoadListener){ FirebaseManager.getBillingsData(new OnBillingsCallback() { @Override public void onBillingsDataReceived(List<Billings> billings) { updateBillings(billings); dataLoadListener.onDataLoaded(); } @Override public void onBillingsDataNotFound() { Log.d("error","Відсутні дані");; } @Override public void onBillingsDataError(Exception e) { Log.e("ERROR", "Помилка при отриманні даних: " + e.getMessage()); } }); } private void updateBillings(List<Billings> billings){ billingsList.clear(); billingsList.addAll(billings); } /** * sortingBillings - сортирує рахунки, повертає список рахунків необхідного типу. * @param billingList - Список рахунків. * @param typeBillings - Список типів рахунки. * @return */ public static List<Billings> sortingBillings(List<Billings> billingList, List<TypeBillings> typeBillings){ List<Billings> billings = new ArrayList<>(); for(Billings bill : billingList){ for(TypeBillings typeBill : typeBillings){ if(bill.getTypeBillings().equals(typeBill.getTitle())){ billings.add(bill); break; } } } return billings; } /** * sortingBillings - сортирує рахунки, повертає список рахунків необхідного типу. * @param billingList - Список рахунків. * @param typeBillings - Тип рахунку. * @return */ public static List<Billings> sortingBillings(List<Billings> billingList, TypeBillings typeBillings){ List<Billings> billings = new ArrayList<>(); for(Billings bill : billingList){ if(bill.getTypeBillings().equals(typeBillings.getTitle())){ billings.add(bill); } } return billings; } }
from logic import * AKnight = Symbol("A is a Knight") AKnave = Symbol("A is a Knave") BKnight = Symbol("B is a Knight") BKnave = Symbol("B is a Knave") CKnight = Symbol("C is a Knight") CKnave = Symbol("C is a Knave") # Puzzle 0 # A says "I am both a knight and a knave." knowledge0 = And( Implication(AKnight,And(AKnave,AKnight)), And(Or(AKnave,AKnight),Not(And(AKnave,AKnight))) ) # Puzzle 1 # A says "We are both knaves." # B says nothing. knowledge1 = And( Implication(AKnight,And(AKnave,BKnave)), Implication(AKnave,Or(And(AKnave,Not(BKnave)),And(BKnave,Not(AKnave)))), And(Or(AKnave,AKnight),Not(And(AKnave,AKnight))), And(Or(BKnave,BKnight),Not(And(BKnave,BKnight))) ) # Puzzle 2 # A says "We are the same kind." # B says "We are of different kinds." knowledge2 = And( Implication(AKnight,Or(And(AKnave,BKnave),And(AKnight,BKnight))), Implication(AKnave,Or(And(AKnight,BKnave),And(AKnave,BKnight))), Implication(BKnight,Or(And(AKnight,BKnave),And(AKnave,BKnight))), Implication(BKnave,Or(And(AKnave,BKnave),And(AKnight,BKnight))), And(Or(AKnave,AKnight),Not(And(AKnave,AKnight))), And(Or(BKnave,BKnight),Not(And(BKnave,BKnight))) ) # Puzzle 3 # A says either "I am a knight." or "I am a knave.", but you don't know which. # B says "A said 'I am a knave'." # B says "C is a knave." # C says "A is a knight." knowledge3 = And( And(Or(AKnave,AKnight),Not(And(AKnave,AKnight))), And(Or(BKnave,BKnight),Not(And(BKnave,BKnight))), And(Or(CKnave,CKnight),Not(And(CKnave,CKnight))), Implication(BKnight,And( Implication(AKnight,AKnave), Implication(AKnave,AKnight))), Implication(BKnave,And( Implication(AKnight,AKnight), Implication(AKnave,AKnave))), Implication(BKnight,CKnave), Implication(BKnave,CKnight), Implication(CKnight,AKnight), Implication(CKnave,AKnave) ) def main(): symbols = [AKnight, AKnave, BKnight, BKnave, CKnight, CKnave] puzzles = [ ("Puzzle 0", knowledge0), ("Puzzle 1", knowledge1), ("Puzzle 2", knowledge2), ("Puzzle 3", knowledge3) ] for puzzle, knowledge in puzzles: print(puzzle) if len(knowledge.conjuncts) == 0: print(" Not yet implemented.") else: for symbol in symbols: if model_check(knowledge, symbol): print(f" {symbol}") if __name__ == "__main__": main()
import React, { useEffect, useState } from 'react' const MainWeatherCard = ({weather}) => { return ( <div className='weatherCard col-12 bg-slate-200 rounded-md'> <div className="row md:h-80"> {/* left part */} <div className="col-sm-12 col-md-6 h-[200px] md:h-full bg-cover bg-center rounded-md" style={{ backgroundImage: 'url("./assets/colombo.jpg")' }} > <h1 className='text-5xl'>{weather.name}</h1> <h1 className='text-3xl'>{weather.sys.country}</h1> <h1 className='text-1xl'>{}</h1> </div> {/* right part */} <div className="col-sm-12 col-md-6 text-3xl h-full"> <div className="row h-[50%]"> <div className="col-6 border-2"> <div className="inner flex flex-col items-center justify-center m-1 bg-slate-300 h-[80%] rounded-md pl-2 shadow-md shadow-slate-400"> <h1 className='text-2xl md:text-3xl'>{weather.weather[0].description}</h1> </div> </div> <div className="col-6 border-2"> <div className="inner flex flex-col items-center justify-center m-1 bg-slate-300 h-[80%] rounded-md shadow-md shadow-slate-400"> <img width={75} height={75} src={`http://openweathermap.org/img/w/${weather.weather[0].icon}.png`} alt="" /> </div> </div> </div> <div className="row h-[50%]"> <div className="col-6 border-2"> <div className="inner flex flex-col items-center justify-center m-1 bg-slate-300 h-[80%] rounded-md shadow-md shadow-slate-400"> <img src="./assets/icons/temp.svg" width={30} alt="" /> <h1 className=''>{weather.main.temp} &#8451;</h1> </div> </div> <div className="col-6 border-2"> <div className="inner flex flex-col items-center justify-center m-1 bg-slate-300 h-[80%] rounded-md shadow-md shadow-slate-400"> <img src="./assets/icons/humidity.svg" width={50} alt="" /> <h1 className=''>{weather.main.humidity} %</h1> </div> </div> </div> </div> </div> </div> ) } export default MainWeatherCard
const sizes = { small: `font-sm px-[0.8rem] py-[0.4rem] uppercase font-semibold text-center`, medium: `font-md px-[1.6rem] py-[1.2rem] font-medium text-center`, large: `font-lg px-[2.4rem] py-[1.2rem] font-medium text-center`, }; const variations = { primary: `text-indigo-50 bg-indigo-600 hover:bg-indigo-700`, secondary: `text-gray-600 bg-gray-0 border-[1px] border-solid border-gray-200 hover:bg-gray-50`, danger: `text-red-100 bg-red-700 hover:bg-red-800`, }; function Button({ size = "medium", variation = "primary", content, onClick }) { return ( <button className={`border-none rounded-sm shadow-sm ${sizes[size]} ${variations[variation]}`} onClick={onClick} > {content} </button> ); } export default Button;
import type { AppProps } from 'next/app' import { ReactElement, useState } from 'react' import { trpc } from '@/utils/trpc' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { httpBatchLink } from '@trpc/client' import superjson from 'superjson' import Head from 'next/head' const getBasePath = (): string => { if (process.env.NEXT_PUBLIC_STAGE === 'development') { return '' } else { return 'https://stock-status-ruddy.vercel.app' } } const MyApp = ({ Component, pageProps }: AppProps): ReactElement | null => { const [queryClient] = useState( () => new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, refetchOnMount: true, refetchOnReconnect: false, keepPreviousData: true, retry: 1, cacheTime: 1000 * 60 * 60 * 24 * 7, }, }, }) ) const [trpcClient] = useState(() => trpc.createClient({ transformer: superjson, links: [ httpBatchLink({ url: `${getBasePath()}/api/trpc`, fetch(url, options) { return fetch(url, { ...options, credentials: 'include', }) }, }), ], }) ) return ( <> <Head> <title>Paint Stock Status</title> </Head> <trpc.Provider client={trpcClient} queryClient={queryClient}> <QueryClientProvider client={queryClient}> <Component {...pageProps} /> </QueryClientProvider> </trpc.Provider> </> ) } export default MyApp
#!/usr/bin/env python # -*- coding: utf-8 -*- # YAFF is yet another force-field code # Copyright (C) 2011 - 2013 Toon Verstraelen <Toon.Verstraelen@UGent.be>, # Louis Vanduyfhuys <Louis.Vanduyfhuys@UGent.be>, Center for Molecular Modeling # (CMM), Ghent University, Ghent, Belgium; all rights reserved unless otherwise # stated. # # This file is part of YAFF. # # YAFF is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 3 # of the License, or (at your option) any later version. # # YAFF is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/> # #-- from __future__ import division import sys import argparse import traceback from fnmatch import fnmatch import pkg_resources import numpy as np import yaff from molmod.units import * from molmod.constants import * #yaff.log.set_level(yaff.log.high) def parse_args(): parser = argparse.ArgumentParser(prog='yaff-opttest', description='Test driver for the geometry/cell optimizer in YAFF.') parser.add_argument('test', default=None, nargs='?', help='Select one test to run. If not given, all tests are executed.') parser.add_argument('-v', '--verbose', default=False, action='store_true', help='Do not suppress the output during the optimization.') parser.add_argument('-x', '--xyz', default=False, action='store_true', help='Write XYZ trajectory files for the optimizations.') return parser.parse_args() class FileFormatError(IOError): pass fields = { 'case': (True, str), 'system': (True, str), 'forcefield': (True, str), 'maxiter': (True, int), 'energy': (True, (lambda s: float(s)*kjmol)), 'dof': (True, {'cartesian': yaff.CartesianDOF, 'strain': yaff.StrainCellDOF}), 'gpos_rms': (False, float), 'neg_hessian_evals': (False, int), } def load_cases(select_title=None): # 1) Load the file yaff.log('Loading test cases') cases_data = {} with pkg_resources.resource_stream(yaff.__name__, 'data/opttest/cases.txt') as f: for line in f: # Read line, skip comments and empty lines line = line[:line.find('#')].strip() if len(line) == 0: continue # Split line into key and data words = line.split() if len(words) != 2: raise FileFormatError('A line should contain exactly two words.') key, data = words # Store line if key not in fields: raise FileFormatError('Uknown key encountered: %s' % key) if key == 'case': current = {} cases_data[data] = current elif current is None: raise FileFormatError('The first line should have a \'case\' key.') current[key] = data # 2) Convert the arguments: for args in cases_data.values(): title = args['case'] for name, (required, fieldtype) in fields.items(): if name not in args: if required: raise FileFormatError('Case \'%s\' does not have a field \'%s\'.' % (title, name)) else: continue if isinstance(fieldtype, type) or callable(fieldtype): try: args[name] = fieldtype(args[name]) except TypeError: raise FileFormatError('The field \'%s\' of case \'%s\' could not be converted to the type %s' % (name, title, type)) elif isinstance(fieldtype, dict): data = args[name] if data not in fieldtype: raise FileFormatError('Could not interpert field \'%s\' of case \'%s\'. Please select one of %s' % (name, title, list(fieldtype.keys()))) args[name] = fieldtype[data] else: raise NotImplementedError if select_title is not None: cases_data = dict((name, args) for name, args in cases_data.items() if fnmatch(name, select_title)) if len(cases_data) == 0: raise ValueError('Could not find test case \'%s\'.' % select_title) # 3) Make Case objects cases = [] for args in cases_data.values(): title = args['case'] yaff.log('Preparing case \'%s\'.' % title) system = yaff.System.from_file(pkg_resources.resource_filename(yaff.__name__, 'data/' + args['system'])) if system.cell.nvec == 0: ff_args = {'rcut': 200.0} else: ff_args = {} ff = yaff.ForceField.generate(system, pkg_resources.resource_filename(yaff.__name__, 'data/' + args['forcefield']), **ff_args) dof_args = dict((key, data) for key, data in args.items() if (key.endswith('_rms') or key.endswith('_max'))) dof = args['dof'](ff, **dof_args) maxiter = args['maxiter'] energy = args['energy'] neg_hessian_evals = args.get('neg_hessian_evals', None) case = Case(title, ff, dof, maxiter, energy, neg_hessian_evals) cases.append(case) return cases class Case(object): def __init__(self, title, ff, dof, maxiter, energy, neg_hessian_evals): self.title = title self.ff = ff self.dof = dof self.maxiter = maxiter self.energy = energy self.neg_hessian_evals = neg_hessian_evals def run(self, verbose, xyz): if not verbose: output = open('/dev/null', 'w') yaff.log.set_file(output) self._optimize(verbose, xyz) if self.neg_hessian_evals is not None: self._check_hessian() if not verbose: yaff.log.set_file(sys.stdout) output.close() self._report() def _optimize(self, verbose, xyz): self.ff.system.pos *= np.random.uniform(0.99, 1.01, self.ff.system.pos.shape) try: hooks = [] if xyz: hooks.append(XYZWriter('trajectory_%s.xyz' % self.title)) opt = yaff.QNOptimizer(self.dof, hooks=hooks) opt.run(self.maxiter) self.niter = opt.counter self.error = False except: traceback.print_exc() self.niter = -1 self.error = True pass self.energy = self.ff.energy self.gpos = self.ff.gpos def _check_hessian(self): if self.ff.system.cell.nvec != 0: # external rotations should be implemented properly for periodic systems. # 1D -> one external rotation, 2D and 3D -> no external rotation raise NotImplementedError('The hessian test is only working for isolated systems') # compute hessian hessian = yaff.estimate_cart_hessian(self.ff) # construct basis of external/internal degrees (rows) x, y, z = self.ff.system.pos.T natom = self.ff.system.natom ext_basis = np.array([ [1.0, 0.0, 0.0]*natom, [0.0, 1.0, 0.0]*natom, [0.0, 0.0, 1.0]*natom, # TODO: this assumes geometry is centered for good conditioning np.ravel(np.array([np.zeros(natom), z, -y]).T), np.ravel(np.array([-z, np.zeros(natom), x]).T), np.ravel(np.array([y, -x, np.zeros(natom)]).T), ]).T u, s, vt = np.linalg.svd(ext_basis, full_matrices=True) rank = (s > s.max()*1e-10).sum() # for linear and int_basis = u[:,rank:] # project hessian int_hessian = np.dot(int_basis.T, np.dot(hessian, int_basis)) evals = np.linalg.eigvalsh(int_hessian) self.num_neg_evals = (evals < 0).sum() # call tamkin as double check import tamkin system = self.ff.system mol = tamkin.Molecule(system.numbers, system.pos, system.masses, self.energy, self.gpos, hessian) nma = tamkin.NMA(mol, tamkin.ConstrainExt()) invcm = lightspeed/centimeter #print nma.freqs/invcm self.num_neg_evals = (nma.freqs < 0).sum() def _report(self): if self.error: self.status = 'ERROR' elif not self.dof.converged: self.status = 'FAILED' elif self.ff.energy > self.energy: self.status = 'HIGH-ENERGY' elif self.neg_hessian_evals is not None and self.num_neg_evals != self.neg_hessian_evals: self.status = 'HESSIAN' else: self.status = 'SUCCESS' yaff.log('%s %11s %5i %10s %3s' % ( self.title.ljust(39), self.status, self.niter, yaff.log.energy(self.energy), ' ' if self.neg_hessian_evals is None else str(self.num_neg_evals), )) def main(): args = parse_args() with yaff.log.section('LOAD'): cases = load_cases(args.test) with yaff.log.section('RUN'): yaff.log('Case Status #iter Energy Neg') yaff.log.hline() niters = [] status_counts = {} success = True for case in cases: case.run(args.verbose, args.xyz) niters.append(case.niter) status_counts[case.status] = status_counts.get(case.status, 0) + 1 success &= case.status == 'SUCCESS' yaff.log.hline() yaff.log('Total number of iterations: %i' % sum(niters)) yaff.log('Maximum number of iterations: %i' % max(niters)) yaff.log('Number of tests: %i' % len(cases)) if success: yaff.log('OK') else: yaff.log('Failure: %s' % ', '.join('%i %s' % (count, status) for status, count in sorted(status_counts.items()))) sys.exit(-1) if __name__ == '__main__': main()
import { useCallback, useMemo, useReducer } from 'react'; import { useDevices } from '../hooks/useDevices'; import { IDevice } from '../shared'; import { createdDevice, deletedDevice, requestDevices, requestDevicesSuccess, updatedDevice } from './actions'; import { reducer } from './reducer'; import { IDispatch, initialState, IState } from './state'; /// I created this store in order to manage the device list on the client side /// adding, editing and deleting only the specific item instead of making a request /// after every action is done. export const useStore = (): [IState, IDispatch] => { const getDevices = useDevices(); const [state, dispatch] = useReducer(reducer, initialState); const onCreatedDevice = useCallback((device: IDevice) => { dispatch(createdDevice(device)); }, []); const onDeletedDevice = useCallback((id: string) => { dispatch(deletedDevice(id)); }, []); const onRequestDevices = useCallback(async () => { dispatch(requestDevices()); try { const devices = await getDevices(); dispatch(requestDevicesSuccess(devices)); } catch (error) { console.log(error); } }, [getDevices]); const onUpdatedDevice = useCallback((device: IDevice) => { dispatch(updatedDevice(device)); }, []); const returnDispatch = useMemo( () => ({ onCreatedDevice, onRequestDevices, onDeletedDevice, onUpdatedDevice, }), [onCreatedDevice, onRequestDevices, onDeletedDevice, onUpdatedDevice], ); return [state, returnDispatch]; };
### 解题思路 - 使用最大堆得到尚未排序的最大元素 - 每次从堆中弹中最大元素 - 在数组中找到当前最大元素的下标,进行局部翻转,将其翻转到第一位。再一次全局翻转,每次有一个元素被置于最终位置 给出一个例子: 给出待排序序列 `[3,2,4,1]`,将其全部入优先队列(大顶堆),从堆顶弹出最大元素**4**,找到其下标,为**2**。那么就从下标**0**开始到**2**进行元素翻转(逆置)。翻转后的结果为[4,2,3,1],此时最大元素被置于首位,再一次全局翻转为[1,3,2,4],则将当前最大元素**4**置于最终位置!对所有待排元素进行上述操作,直到优先队列为空。 ### 代码 ```cpp class Solution { public: vector<int> result; priority_queue<int> pq; // 将元素进行翻转(逆置) void t_sort(vector<int>&A ,int left, int right){ int mid = (left+right) >> 1; int i = 0; while(left+i<=mid){ int temp = A[left+i]; A[left+i] = A[right-i]; A[right-i] = temp; i++; } } vector<int> pancakeSort(vector<int>& A) { for(auto n:A) pq.push(n); int i = A.size()-1; while(!pq.empty()){ int top = pq.top(); pq.pop(); int index = find(A.begin(), A.end(), top) - A.begin(); result.emplace_back(index+1); t_sort(A, 0, index); t_sort(A, 0, i); result.emplace_back(i+1); i --; } return result; } }; ```
import { HttpException, Injectable, NotFoundException } from '@nestjs/common'; import { TaskStatus } from './task-status.enum'; import { CreateTaskDto } from './dto/create-task.dto'; import { GetTasksFilterDto } from './dto/get-tasks-filter.dto'; import { TaskRepository } from './task.repository'; import { InjectRepository } from '@nestjs/typeorm'; import { Task } from './task.entity'; import { DeleteResult } from 'typeorm'; import { User } from '../auth/user.entity'; import { GetUser } from '../auth/get-user-decorator'; @Injectable() export class TasksService { constructor( @InjectRepository(TaskRepository) private tasksRepository: TaskRepository, ) {} getTasks( filterDto: GetTasksFilterDto, @GetUser() user: User, ): Promise<Task[]> { return this.tasksRepository.getTasks(filterDto, user); } async getTaskById(id: string, user: User): Promise<Task> { const found = await this.tasksRepository.findOne({ id, user }); if (!found) { throw new NotFoundException(`Task with id ${id} not found.`); } return found; } createTask(createTaskDto: CreateTaskDto, user: User): Promise<Task> { return this.tasksRepository.createTask(createTaskDto, user); } async deleteTask(id: string, user: User): Promise<void> { const result = await this.tasksRepository.delete({ id, user }); if (result.affected === 0) { throw new NotFoundException(`Task with id ${id} not found.`); } } async updateTaskStatus( id: string, status: TaskStatus, user: User, ): Promise<Task> { const task = await this.getTaskById(id, user); task.status = status; await this.tasksRepository.save(task); return task; } // getTaskById(id: string): Task { // const found = this.tasks.find((task) => task.id === id); // if (!found) { // throw new NotFoundException(`Task with id ${id} not found.`); // } // return found; // } // createTask(createTaskDto: CreateTaskDto): Task { // const { title, description } = createTaskDto; // const task: Task = { // id: uuid(), // title, // description, // status: TaskStatus.OPEN, // }; // this.tasks.push(task); // return task; // } // deleteTask(id: string): void { // const found = this.getTaskById(id); // this.tasks = this.tasks.filter((task) => task.id !== found.id); // } // updateTaskStatus(id: string, status: TaskStatus): Task { // const task = this.getTaskById(id); // task.status = status; // return task; // } }
import React, { useEffect } from "react"; import { RefreshControl, StyleSheet } from "react-native"; import { Icon } from 'react-native-elements'; import colors from '~/theme/color'; import ScrollViewBox from "~/components/ScrollViewBox"; import ConfirmButton from '~/components/Button/ConfirmButton'; import EmptyPending from "./components/EmptyPending"; import Content from "./components/Content"; const PendingScreen = (props) => { const { buy, sell, navigation, handleGetPendingOrder, handleLockPendingOrder, handleStartPendingOrder, handleDeletePendingOrder, } = props; useEffect(() => { handleGetPendingOrder(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const hasBuy = buy.size > 0; const hasSell = sell.size > 0; if (!hasBuy && !hasSell) { return ( <EmptyPending onPress={() => navigation.navigate("Sell-Create-Pending-List")} /> ); } const lockPending = (id, type) => () => { const payload = { id, type }; handleLockPendingOrder(payload); }; const deletePending = (id, type) => () => { const payload = { id, type }; handleDeletePendingOrder(payload); }; const startPending = (id, type) => () => { const payload = { id, type }; handleStartPendingOrder(payload); }; return ( <ScrollViewBox scrollViewProps={{ refreshControl: ( <RefreshControl refreshing={false} onRefresh={handleGetPendingOrder} /> ), }} > {[buy, sell].map((d, index) => ( <Content key={`${index}`} hide={!d.size > 0} data={d} lockPending={lockPending} startPending={startPending} deletePending={deletePending} goToDetail={() => navigation.navigate("Sell-Create-Pending", { orderType: d.get("type"), orderId: d.get("id"), }) } /> ))} <ConfirmButton type="primary" title="新增" icon={<Icon name='add' size={30} color={colors.secondary} />} onPress={() => navigation.navigate("Sell-Create-Pending-List")} containerStyle={styles.buttonStyle} /> </ScrollViewBox> ); }; const styles = StyleSheet.create({ buttonStyle: {paddingLeft: 20, paddingRight: 20}, }); export default PendingScreen;
<!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>Final-Test</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aos@2.3.4/dist/aos.min.css"> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css"> </head> <body> <nav class="navbar navbar-expand-lg navbar-custom" data-bs-theme="dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Anton's</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav me-auto mb-2 mb-lg-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About Us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Our Work </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Web Design</a></li> <li><a class="dropdown-item" href="#">Mobile Apps Design</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">Other</a></li> </ul> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact Us</a> </li> </ul> <form class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> <div id="carouselExampleCaptions" class="carousel slide slider-home"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="2" aria-label="Slide 3"></button> </div> <div class="carousel-inner"> <div class="carousel-item active"> <img src="tim-stief-YFFGkE3y4F8-unsplash-2.jpg" class="d-block w-100" alt="banner-1"> <div class="carousel-caption d-none d-md-block"> <h5>First slide label</h5> <p>Some representative placeholder content for the first slide.</p> </div> </div> <div class="carousel-item"> <img src="neom-SUIMrEKVOXc-unsplash.jpg" class="d-block w-100" alt="banner-2"> <div class="carousel-caption d-none d-md-block"> <h5>Second slide label</h5> <p>Some representative placeholder content for the second slide.</p> </div> </div> <div class="carousel-item"> <img src="tim-stief-YFFGkE3y4F8-unsplash.jpg" class="d-block w-100" alt="banner-3"> <div class="carousel-caption d-none d-md-block"> <h5>Third slide label</h5> <p>Some representative placeholder content for the third slide.</p> </div> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <div class="section-skill"> <div class="container"> <div class="row gx-3 gy-3"> <div class="col-lg-4"> <div class="skill-box"> <i class="bi bi-filetype-html icon-skill"></i> <p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veniam suscipit tenetur autem distinctio eos modi, assumenda hic </p> <button type="button" class="btn btn-warning" >Read More</button> </div> </div> <div class="col-lg-4"> <div class="skill-box"> <i class="bi bi-filetype-css icon-skill"></i> <p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veniam suscipit tenetur autem distinctio eos modi, assumenda hic </p> <button type="button" class="btn btn-warning">Read More</button> </div> </div> <div class="col-lg-4"> <div class="skill-box"> <i class="bi bi-filetype-java icon-skill"></i> <p> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Veniam suscipit tenetur autem distinctio eos modi, assumenda hic </p> <button type="button" class="btn btn-warning">Read More</button> </div> </div> </div> </div> </div> <div class="section-artikel"> <div class="container"> <div class="item-artikel"> <div class="row"> <div class="col-lg-7"> <div class="caption d-flex flex-column justify-content-center"> <h2>First featurette heading. It’ll blow your mind.</h2> <p>Some great placeholder content for the first featurette here. Imagine some exciting prose here.</p> </div> </div> <div class="col-lg-5"> <div class="image-artikel" style="background: url(neom-SUIMrEKVOXc-unsplash.jpg);" data-aos="fade-down"></div> <!-- data-aos="fade-down" somehow gak jalan padahal script sudah ada--> </div> </div> </div> <div class="item-artikel"> <div class="row"> <div class="col-lg-5"> <div class="image-artikel" style="background: url(tim-stief-YFFGkE3y4F8-unsplash-2.jpg);"></div> </div> <div class="col-lg-7"> <div class="caption d-flex flex-column justify-content-center"> <h2>Oh yeah, it’s that good. See for yourself..</h2> <p>Another featurette? Of course. More placeholder content here to give you an idea of how this layout would work with some actual real-world content in place.</p> </div> </div> </div> </div> <div class="item-artikel"> <div class="row"> <div class="col-lg-7"> <div class="caption d-flex flex-column justify-content-center"> <h2>And lastly, this one. Checkmate.</h2> <p>And yes, this is the last block of representative placeholder content. Again, not really intended to be actually read, simply here to give you a better view of what this would look like with some actual content. Your content.</p> </div> </div> <div class="col-lg-5"> <div class="image-artikel" style="background: url(tim-stief-YFFGkE3y4F8-unsplash.jpg);"></div> </div> </div> </div> </div> </div> <div class="container"> <form class="cmxform" id="commentForm" method="get" action=""> <fieldset> <legend>Please provide your contact details:</legend> <p> <label for="cname">Name</label> <input id="cname" class="form-control" name="name"> </p> <p> <label for="cemail">E-Mail</label> <input id="cemail" class="form-control" type="email" name="email"> </p> <p> <label for="curl">URL </label> <input id="curl" class="form-control" type="url" name="url"> </p> <p> <label for="cage">Date of Birth </label> <input id="cage" class="form-control" type="date" name="age"> </p> <p> <input class="submit btn btn-primary" type="submit" value="Submit"> </p> </fieldset> </form> </div> <div class="footer"> <div class="container"> <div class="row"> <div class="col-6"> <p>© 2023 X Company, Inc. · <a href="#">Privacy</a> · <a href="#">Terms</a></p> </div> <div class="col-6"> <div class="d-flex justify-content-end"> <a href="#">Back to top</a> </div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script> <script src="https://unpkg.com/aos@2.3.1/dist/aos.js"></script> <script> $(document).on('ready', function () { AOS.init({ duration: 650, once: false }); }); </script> </body> </html>
<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; use App\Http\Controllers\TaskController; use App\Http\Controllers\MovieController; Route::get('/user', function (Request $request) { return $request->user(); })->middleware('auth:sanctum'); // Tutorial from ChatGPT on fully Laravel guide with Controllers, Seeders, Migration Route::get('/movies', 'MovieController@index'); Route::get('movies/{id}', 'MovieController@show'); Route::get('movies/genre/{genre}', 'MovieController@findByGenre'); // Tutorial from Youtube Route::get('/moviez', function () { return "Hello from API's"; }); // Custom made Route::get('/moviez2', function () { return response()->json([ 'titlez' => 'Hellooo', 'descz' => 'youre sooo kool', 'moviez_code' => 1 ]); }); // Tutorial from ChatGPT on Laravel but important parts only // Route::middleware('auth:sanctum')->group(function () { // Route::get('/tasks', [TaskController::class, 'index']); // Route::post('/tasks', [TaskController::class, 'store']); // Route::get('/tasks/{id}', [TaskController::class, 'show']); // Route::put('/tasks/{id}', [TaskController::class, 'update']); // Route::delete('/tasks/{id}', [TaskController::class, 'destroy']); // }); // custom Route::group([], function () { Route::get('/tasks', [TaskController::class, 'index']); Route::post('/tasks', [TaskController::class, 'store']); Route::get('/tasks/{id}', [TaskController::class, 'show']); Route::put('/tasks/{id}', [TaskController::class, 'update']); Route::delete('/tasks/{id}', [TaskController::class, 'destroy']); });
import React from "react"; import styles from "./styles/leftsidenav.module.scss"; import LogoSVG from "../assets/SVG-Components/LogoSVG"; import ApodSVG from "../assets/SVG-Components/ApodSVG"; import KnowYAPOD from "../assets/SVG-Components/KnowYAPOD"; import CurositySVG from "../assets/SVG-Components/CurositySVG"; import IsroSVG from "../assets/SVG-Components/IsroSVG"; import { NavLink } from "react-router-dom"; const LeftSideNav = () => { return ( <nav className={styles.sideNavContainer}> <NavLink aria-label="Home" name="home" to="/" className={({ isActive }) => isActive ? `${styles.active}` : `${styles.unActive}` } > <LogoSVG /> </NavLink> <NavLink aria-label="APOD" name="apod" to="/apod" className={({ isActive }) => isActive ? `${styles.active}` : `${styles.unActive}` } > <ApodSVG /> </NavLink> <NavLink aria-label="KPOD" name="kpod" to="/k-pod" className={({ isActive }) => isActive ? `${styles.active}` : `${styles.unActive}` } > <KnowYAPOD /> </NavLink> <NavLink aria-label="CUROSITY" name="curosity" to="/curosity" className={({ isActive }) => isActive ? `${styles.active}` : `${styles.unActive}` } > <CurositySVG /> </NavLink> <NavLink aria-label="ISRO" name="isro" to="/ISRO" className={({ isActive }) => isActive ? `${styles.active}` : `${styles.unActive}` } > <IsroSVG /> </NavLink> </nav> ); }; export default LeftSideNav;
import React, { useState } from "react"; import axios from "axios"; const FormRatingAdd = (props) => { const [movie, setMovie] = useState(' '); const [genre, setGenre] = useState(' '); const [rating, setRating] = useState(' '); function handleMovieChange(movieName) { console.log(movieName.target.value); setMovie(movieName.target.value) } function handleGenreChange(evt) { console.log(evt.target.value); setGenre(evt.target.value) } function handleRatingChange(evt) { console.log(evt.target.value); setRating(evt.target.value) } function handleSubmit(evt) { console.log(evt) console.log("You entered" + movie + "in the searchbox") console.log("You entered" + genre + "in the searchbox") evt.preventDefault() evt.preventDefault() const movieData = { movies: movie ? movie : null, personId: props.id, genreid: genre, rating: rating }; axios.post("http://localhost:5106/setrating", movieData).then((response) => { console.log(response.status, response.data); }); } const allGenres = [ { id: 1, name: "Action" }, { id: 2, name: "Drama" }, { id: 3, name: "Animation" }, { id: 4, name: "Horror" }, { id: 5, name: "Adventure" }, { id: 6, name: "Comedy" }, { id: 7, name: "Crime" }, { id: 8, name: "Documentary" }, { id: 9, name: "Family" }, { id: 10, name: "Fantasy" }, { id: 11, name: "History" }, { id: 12, name: "Music" }, { id: 13, name: "Mystery" }, { id: 14, name: "Romance" }, { id: 15, name: "Science Fiction" }, { id: 16, name: "TV Movie" }, { id: 17, name: "Thriller" }, { id: 18, name: "War" }, { id: 19, name: "Western" } ] const ratings = [1, 2, 3, 4, 5]; return ( <> <h1>Add movie</h1> <form onSubmit={handleSubmit}> <input type="text" placeholder="Type in movie" value={movie} onChange={handleMovieChange} /> {/* <label> <select value={rating} onChange={handleRatingChange}></select> </label> */} <label> Genre </label> <select onChange={handleGenreChange}> <option value=""> Select a genre </option> {allGenres.map(genre => (<option value={genre.id}>{genre.name}</option>))} </select> <label> Rating </label> <select onChange={handleRatingChange}> <option value=""> Rate your movie! </option> {ratings.map(option => (<option value={option}>{option}</option>))} </select> <button type="submit">Add</button> </form> </> ) } export default FormRatingAdd;
import { computed, type Ref, unref } from 'vue'; type NumberOrRef = number | Ref<number>; /** * Calculates the wrapped around value within a given range. * * @param {NumberOrRef} value - The value to be wrapped around. * @param {NumberOrRef} min - The minimum value of the range. * @param {NumberOrRef} max - The maximum value of the range. * @returns - The wrapped around value within the range. */ export const useWrapAround = ( value: NumberOrRef, min: NumberOrRef, max: NumberOrRef, ) => { const _value = unref(value); const _min = unref(min); const _max = unref(max); return computed(() => { if (_value >= _max) { return _min; } if (_value < _min) { return _max - 1; } return _value; }); };
import { Component } from '@angular/core'; import { SimpleService } from './Service'; class Item { name: string; date: string; constructor(name: string, date: string) { this.name = name; this.date = date; } } @Component({ selector: 'app-editor', templateUrl: './editor.component.html', styleUrls: ['./app.component.scss'] }) export class EditorComponent { text: string = ""; items: Item[] = [ ]; constructor( private service: SimpleService ) { } ngOnInit() { this.items = this.service.getItems(); } addItem(name: string) { if (name == null || name.trim() == "") return; let item = new Item(name, new Date().toLocaleString()) this.service.addItem(item); } copyItem(item: Item): void { let item_copy = new Item(item.name, new Date().toLocaleString()) this.service.addItem(item_copy); } deleteItem(i: number): void { this.service.deleteItem(i); } SortName(): void { this.service.SortName(); } SortDate(): void { this.service.SortDate(); } }
Ракетодинамика или динамика ракет — наука о движении летательных аппаратов (ЛА), снабжённых реактивными двигателями. Является составной частью механики тел переменной массы, так как во время работы двигателя существенно меняется масса ракеты за счёт активного ускорения. Например, одноступенчатые ракеты теряют до 90 % стартовой массы. История Ракетодинамика была основана в конце XIX — начале XX века трудами К. Э. Циолковского и И. В. Мещерского с написания первоначальной формулы Циолковского и уравнения Мещерского соответственно. Однако, не все считают Циолковского основоположником динамики ракет, так как Мещерский написал своё уравнение на 6 лет раньше, а в докторской диссертации Г. К. Михайлова, защищенной в 1977 году, было показано, что изначально это решение было получено английскими исследователями У. Муром в 1810—1811 годах, а также П. Г. Тэйтом и У. Дж. Стилом в 1856 году. Разделы Существуют три важнейших раздела ракетодинамики: Изучение движения центра тяжести ракет; Изучение движения ракет относительно центра тяжести; Экспериментальная ракетодинамика. Ссылки Ракетодинамика (Физический энциклопедический словарь, 1983)Журнал «Астронавтика и ракетодинамика» ВИНИТИ (недоступная ссылка) Литература Мещерский И. В. «Работы по механике тел переменной массы» М.-Л.: ГИТТЛ, 1949. — 276с. (2-ое изд. 1952.)Космодемьянский А. А., «Механика тел переменной массы (Теория реактивного движения)» Ч. 1. М.: Издательство: ВВИА им. Жуковского, 1947.Карагодин В. М., «Теоретические основы механики тела переменного состава», М.: ГНТИ ОБОРОНГИЗ, 1963. — 179 с.Михайлов Г. К., «К истории динамики систем переменного состава» Известия АН СССР: Механика твердого тела, 1975, № 5, с. 41-51.Гурин А. И. «Основы механики тел переменной массы и ракетодинамике» М.: изд-во МГПИ, 1960. — 222c.Абгарян К. А., Рапопорт И. М. «Динамика ракет», М.: Машиностроение, 1969. — 378c. — 8000 экз.Мандрыка А. П. «Генезис современной ракетодинамики» Л.: Наука, 1971. — 216 с.Москаленко Г. М. «Инженерные методы проектирования в ракетодинамике» М.: Машиностроение, 1974. — 392 c.Абгарян К. А., Калязин Э. Л., Мишин В. П., Рапопорт И. М. «Динамика ракет» 2-е, перераб. и доп. М.: Машиностроение, 1990. — 463 c. 4400 экз. ISBN 5-217-00354-5 См. также Ракета Ракетный двигатель Реактивная тяга Ракетогидродинамика Циркон (гиперзвуковая ракета) Калибр (универсальная ракета) П-800 "Оникс" == Примечания ==
[Now Document Example] Show how the document syntax works. [templates/html_base] description "Basic HTML structure." <html> <head> <title>$page_title</title> </head> <body> % body % BODY % ---- % </body> </html> [templates/htmls] description "Display a list of files in HTML format." extends html_base <div class="files-list"> % body % <h2>Files in $directory</h2> <ul> % file % <li>$file</li> % --- % </ul> % --- % </div> [commands/run] description "Show how templates work." template htmls (page_title = "Directory Listings Example") | as tpl list "/home" "/opt" | foreach directory { obj $tpl : emit "body" list a b c d | foreach file { obj $tpl : emit "file" } } obj $tpl : render | as rendered_template obj $rendered_template : split "\n" : length | as line_count obj $line_count : eq 22 | assert "Rendered template should have 22 lines, not $line_count ." obj $rendered_template : find "<h2>Files in /home</h2>" : neq -1 | assert "There should be a h2 header for /home"
import React, { useEffect, useState } from 'react' import { Helmet } from "react-helmet" import { ToastContainer, toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import "./feedback.css" export default function Feedback() { const [name, setName] = useState("") const [email, setEmail] = useState("") const [message, setMessage] = useState(""); useEffect(() => { const script = document.createElement('script'); script.src = "https://smtpjs.com/v3/smtp.js"; script.async = true; document.body.appendChild(script); return () => { document.body.removeChild(script); } }, []); const changeHandler = (e) => { if (e.target.id == "name") { setName(e.target.value); } else if (e.target.id == "email") { setEmail(e.target.value); } else if (e.target.id == "message") { setMessage(e.target.value); } } const submitHandler = (e) => { window.Email.send({ Host: "smtp.elasticemail.com", Username: "mulla.musaddik77@gmail.com", Password: "3708DFF15892AE0839A72BAB0067BA8EFC06", To: 'nitin3.ak@gmail.com', From: "mulla.musaddik77@gmail.com", Subject: "Feedback from " + name, Body: message+"\n"+"email: "+email }).then( res=>{ console.log(res) if(res == "OK"){ toast.success('Message is Sent! Our team will contact you soon ..', { position: "top-center", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); }else{ toast.error('Message cant be sent..try again later!', { position: "top-center", autoClose: 5000, hideProgressBar: false, closeOnClick: true, pauseOnHover: true, draggable: true, progress: undefined, }); } } ); } return ( <> <div className='navbar2'> <a href='/'><i class="fa-solid fa-arrow-left"></i></a> </div> <div className='feed-box'> <div className='feed-card'> <div className='input-box-feed'> <label htmlFor='name'>Name</label> <input type={"text"} id="name" value={name} onChange={changeHandler} placeholder="Name"/> </div> <div className='input-box-feed'> <label htmlFor='email'>email</label> <input type={"text"} id="email" value={email} onChange={changeHandler} placeholder="email"/> </div> <div className='input-box-feed'> <label htmlFor='message'>message</label> <textarea type={"textarea"} id="message" value={message} onChange={changeHandler} /> </div> <button type="button" onClick={submitHandler}>Send</button> </div> <ToastContainer position="top-center" autoClose={5000} hideProgressBar={false} newestOnTop={false} closeOnClick rtl={false} pauseOnFocusLoss draggable pauseOnHover /> </div> </> ) }
install_github('mattroumaya/doubleheadr') library(tidyverse) library(devtools) library(readxl) library(doubleheadr) demo <- doubleheadr::demo df4k_demo<-read_excel('/Users/ilanvourman/Documents/OnBeing/OnBeing Survey Drafts/SurveyJune16_Missing_to_use_copy.xlsx') df4k_demo%>%clean_headr(rep_val = '...', clean_names = TRUE)%>%colnames() View(df4k_demo) df4k_demo2 <- df4k_demo %>% clean_headr(rep_val = '...') %>% trim_headr(c('please_provide_your_contact_', '_response')) #after column 120 here all email sign ups, have to see if rest of data aligns with full sheet# #save.image("~/OnBeing/OnBeingAnalysis2.RData") save.image("~/OnBeingAnalysis2.RData") savehistory("~/OnBeing/OnBeinghistory2.Rhistory") # uploading Full Responses## # full_demo<-read_excel('/Users/ilanvourman/Documents/OnBeing/OnBeing Survey Drafts/Survey_condensed_use_IV1_formatted.xlsx') full_demo%>%clean_headr(rep_val = '...', clean_names = TRUE)%>%colnames() full_demo2 <- full_demo %>% clean_headr(rep_val = '...') %>% trim_headr(c('please_provide_your_contact_', '_response')) devtools::install_github("mattroumaya/surveymonkey") usethis::edit_r_profile() library(surveymonkey) options(sm_oauth_token = "cOmUpOXfevWx560egh1njqAG36aYQUiG8wE.tB9lPUwPn0A56fJlF0kEPRG6KymF-O4p29apyFKc0zAngtu.sjnkgNw04SqHUcyg4Mwshj5cAc1E2LCMsO54DNDjInDJ") getOption("sm_oauth_token") surveys<- surveymonkey::browse_surveys(10) View(surveys) a_survey_obj <- surveymonkey::fetch_survey_obj(506448196) survey_df <- surveymonkey::parse_survey(a_survey_obj) View(survey_df) collectors <- get_collectors(506448196) rollups<-surveymonkey::fetch_survey_obj survey_df_1 <- surveymonkey::parse_survey(a_survey_obj,oauth_token="cOmUpOXfevWx560egh1njqAG36aYQUiG8wE.tB9lPUwPn0A56fJlF0kEPRG6KymF-O4p29apyFKc0zAngtu.sjnkgNw04SqHUcyg4Mwshj5cAc1E2LCMsO54DNDjInDJ",fix_duplicates = 'drop') str(survey_df_1) View(survey_df_1) #write.csv(survey_df_1,"survey_df1_parsed.csv") survey_df_2 <-strip_html(survey_df_1) write.csv(survey_df_2,"survey_df_2.csv") ## #**Take IDs where prefered way of on being is NA and how long have you been a listener isn't NA to get missing responses**# write.csv(df4k_demo2,'df4k_responses.csv') select_4k <- df4k_demo2%>%select("whats_your_preferred_way_of_listening_to_on_being_select_one_i_attentively_listen_to_the_show_without_distractions" ,"whats_your_preferred_way_of_listening_to_on_being_select_one_i_listen_while_i_aom_doing_other_activities_for_example_making_art_cleaning_commuting_working_out_at_work","whats_your_preferred_way_of_listening_to_on_being_select_one_i_take_notes_while_i_listen_to_the_show","whats_your_preferred_way_of_listening_to_on_being_select_one_i_listen_with_other_people","whats_your_preferred_way_of_listening_to_on_being_select_one_other_please_specify") colnames(select_4k)<-c('attentive','while_doing_other','while_taking_notes','with_other_people','other') select_4k2<-select_4k%>%mutate(attentive=ifelse(attentive!='NA','I attentively listen to the show, without distractions',NA)) select_4k2 <- select_4k2%>%mutate(while_doing_other=ifelse(while_doing_other!='NA',"I listen while I'm doing other activities (for example, making art, cleaning, commuting, working out, at work)",NA)) select_4k2 <- select_4k2 %>% mutate(while_taking_notes=ifelse(while_taking_notes!='NA','I take notes while I listen to the show',NA)) select_4k2 <-select_4k2 %>% mutate(with_other_people=ifelse(with_other_people!='NA','I listen with other people',NA)) select_4k2 <-select_4k2 %>% mutate(other=ifelse(other!='NA',other,NA)) install.packages('naniar') library('naniar') select_4k3 <- select_4k2 %>% replace_with_na_all(condition = ~.x =='NA') write.csv(select_4k3,'select_4k3.csv') df<-select_4k3 #for (i in 2:ncol(df)) #df[,i] = ifelse(is.na(df[,i]), df[,i-1],df[,i])# #df[] <- Reduce(function(x, y) ifelse(is.na(x), x, y), df, accumulate = TRUE)# df2<-data.frame(t(df)) %>% fill(., names(.)) %>% t()# #do not run #df$"What's your preferred way of listening to On Being?" <- ifelse(is.na(df$other), df$with_other_people, df$other) # df$"What's your preferred way of listening to On Being?" <- ifelse(is.na(df$other), df$while_taking_notes, df$other) # df$"What's your preferred way of listening to On Being?" <- ifelse(is.na(df$other), df$while_doing_other, df$other) # df$"What's your preferred way of listening to On Being?" <- ifelse(is.na(df$other), df$"What's your preferred way of listening to On Being?", df$other)# # # # ###now df2$other becomes "What's your preferred way of listening to On Being?"# df2<-as.data.frame(df2) write.csv(df2,'df2.csv') #now take survey df2 and use Full_preferred_way corrected column starting respondant 118062235156# #using preferred fixed csv3 preferred_fixed<-read.csv(file.choose(),stringsAsFactors = FALSE) survey_df_2<-survey_df_2%>%mutate(respondent_id=as.numeric(respondent_id)) survey_df3<-cbind(survey_df_2,preferred_fixed) #getting rid of duplicate respondant ID# survey_df3<-survey_df3%>%select(-140) #columns that contain numbers?# library(dplyr) #numeric.cols<-survey_df3 %>%select(contains('br')) write.csv(survey_df3,'survey_df3.csv') #survey_df3_distinct<-survey_df3%>%distinct(respondent_id) survey_df4<-mutate_if(survey_df3,is.character,as.factor) survey_df4_no_NA<-survey_df4%>%n(survey_d) # survey_df4_sum1 <- survey_df4 %>%group_by(`How old are you?`,`How do you interact or engage with On Being? Select all that apply. - I follow the On Being Project on social media`)%>%filter(!is.na(`How old are you?`),!is.na(`How do you interact or engage with On Being? Select all that apply. - I follow the On Being Project on social media`))%>%summarise(n=n()) survey_df4_sum1 survey_df4_sum1<-as.data.frame(survey_df4_sum1) ggplot(survey_df4_sum1,aes(x=`How old are you?`,color=`How do you interact or engage with On Being? Select all that apply. - I follow the On Being Project on social media`))+geom_histogram(binwith=0.5,stat="count") #used# ggplot(survey_df4_sum1,aes(x=`How old are you?`,n,stat="identity"))+geom_col(aes(fill=`How old are you?`))+ggtitle("I Follow On Being on Social Media")+geom_text(aes(label=n)) survey_df4_sum_age_gender <- survey_df4 %>%group_by(`How old are you?`,`How do you identify?`)%>%filter(!is.na(`How old are you?`),!is.na(`How do you identify?`))%>%summarise(`How do you interact or engage with On Being? Select all that apply. - I follow the On Being Project on social media`=n()) ggplot(survey_df4_sum_age_gender,aes(x=`How old are you?`,`How do you interact or engage with On Being? Select all that apply. - I follow the On Being Project on social media`,stat="identity"))+geom_col(aes(fill=`How do you identify?`))+ggtitle("I Follow On Being on Social Media")+geom_text(aes(label=`How do you interact or engage with On Being? Select all that apply. - I follow the On Being Project on social media`))+facet_wrap(~`How do you identify?`)+scale_y_continuous('Follow on social') colnames(survey_df4[105:110]) survey_df4_sum_age_gender # # ggplot(survey_df4,aes(x=`How old are you?`,color="How much do you agree with the following statements? For each row, rank your reactions from 1 (\"Strongly disagree\") to 5 (\"Strongly agree\"). Please select one answer per row. - I often get deeply lost in my thoughts"))+geom_histogram(binwith=0.5,stat="count")+facet_wrap(~`How do you identify?`) # ˆtaking out extra long names from header survey_df3a<-survey_df3 survey_df3a <- survey_df3 %>% trim_headr(c('.Select.all.that.apply.', 'How.do.you.interact.or.engage.with.On.Being.')) # columns 26 to 35 are all how do you interact or engage with on being, with last column colnames(survey_df3a[26:35]) # survey_df3a_select <- survey_df3a%>%dplyr::select(c(1:3,26:35)) # duplicates<-fullc1%>%janitor::get_dupes() colnames(survey_df3a_select) survey_df3a_select2<-survey_df3a_select%>%trim_headr(' - ') # key_colsM=c() # survey_df3a_select_distinct<-survey_df3a_select%>%distinct(collector_id,respondent_id,.keep_all=TRUE)%>%group_by(respondent_id) # # library(stringr) # survey_df3a_select2a<-make.names(names=names(survey_df3a_select2), unique=TRUE, allow_ = TRUE) # names(survey_df3a_select)<-colnames(survey_df3a_select2a) library(dplyr) cases_rolled <- survey_df3a_select2 %>%group_by(respondent_id) %>%arrange(collector_id, .by_group = TRUE) %>% summarise(across(everything(),~paste0(unique(na.omit(.x)), collapse = "; "))) #renaming columns for how listen/engage to have clearer names# cases_rolled2<-cases_rolled colnames(cases_rolled2)[4:13]<-c('Follow_social',"Listen_on_radio","Listen_to_podcast","Listen_Poetry_Unbound","Tried_wisdom_app","I_read_newsletter","I_visit_website","Attended_events","Have_donated","Don't_interact") str(cases_rolled2) Turning into True False cols_change<-names(cases_rolled2[,c(4:13)]) cases_rolled3<-cases_rolled2%>%mutate(across(all_of(cols_change),~ifelse(nchar(.x)==0,"No","Yes"))) # save.image("~/OnBeingAnalysis3.RData") cases_rolled3<-cases_rolled3%>%mutate_if(is.character,as.factor) str(cases_rolled3) prop.count<-cases_rolled3%>%mutate(across(all_of(cols_change),~ifelse(factor(.x)=="No",0,1))) #used# prop.count2<-prop.count%>%group_by(collector_id)%>%tally()%>%mutate(proportion_per_collector_engaging = n / sum(n),n_total = sum(n)) ggplot(prop.count2,aes(x=collector_id,proportion_per_collector_engaging,stat="identity"))+geom_col(aes(fill=collector_id))+ggtitle("Overall Pre-Disposed Engagement level by Collector")+geom_text(aes(label=n))+ylab("Proportion (%)")+geom_text(aes(label=round(proportion_per_collector_engaging,3),position="dodge",vjust=2.55)) library(dplyr) survey_df3b<-full_join(survey_df3a,prop.count,by=c('respondent_id')) survey_df3b<-full_join(survey_df3a,prop.count,by=c('respondent_id'),keep=FALSE) survey_df3b<-survey_df3b%>%select(-survey_id.x,-collector_id.x)%>%rename(survey_id=survey_id.y) survey_df3b<-survey_df3b %>% rename(collector_id=collector_id.y) now removing prefix for how express values colnames(survey_df3b)[90:102] colnames(survey_df3b)[90:102]<-c('How_express_values-Kindess_hospitality','How_express_values-Grace','How_express_values-Volunteer','How_express_values-community_service','How_express_values-Giving_philanthropy','How_express_values-Community_organizing',"How_express_values-Mediation_social_healing","How_express_values-Mutual_aid","How_express_values-Political_engagement","How_express_values-Evangelism","How_express_values-Social_activism","How_express_values-Environmental_activism","How_express_values-other") colnames_values<-colnames(survey_df3b)[90:102] str(survey_df3b[colnames_values]) View(is.na(survey_df3b)[colnames_values]) #already factors# # save.image("~/OnBeingAnalysis3.RData") survey_df3c<-survey_df3b%>%mutate(across(all_of(colnames_values),~ifelse(is.na(.x),NA,.x))) # Gives 1 and NAs colnames_values2<-colnames(survey_df3c)[90:102] survey_df3c<-survey_df3c%>%mutate_at(vars(colnames_values2),function(x) replace(x,is.na(x),0)) survey_df3c<-survey_df3c%>%rename(Gender=`How do you identify?`) survey_df3c<-survey_df3c%>%rename(Gender_other=`How do you identify? - Prefer to self-describe:`) survey_df3c<-survey_df3c%>%rename(Ethnicity=`How would you describe yourself? `) survey_df3c<-survey_df3c%>%rename(Age=`How old are you?`) # should have Use `all_of(colnames_values2)` instead of `colnames_values2` survey_df3c_values<-survey_df3c%>%group_by(collector_id)%>%tally()%>%mutate(proportion_per_collector_values= n / sum(n),n_total = sum(n)) colnames(collectors) colnames(survey_df3c[1:20]) # Mering collectors with full survey collectors_select<-collectors%>%select(name,id,href,type) survey_df3c_values_collector_sum<-survey_df3c_values%>%group_by(collector_id)%>%tally() #only 12 instead of 21 in collectors table survey_df3d<-survey_df3c%>%mutate(collector_id=as.factor(collector_id)) collectors_select<-collectors_select%>%mutate(id=as.factor(id)) survey_df3c_collectors_merge<-left_join(survey_df3d,collectors_select,by=c("collector_id"="id")) survey_df3c_collectors_merge<-survey_df3c_collectors_merge%>%rename(collector_name=name) survey_df3c_values_collector_sum2<-survey_df3c_collectors_merge%>%group_by(collector_id)%>%tally() sum_values<-survey_df3c_collectors_merge%>%group_by(collector_name)%>%tally()%>%mutate(proportion_per_collector_values= n / sum(n),n_total = sum(n)) library(forcats) sum_values_ordered<-sum_values%>%mutate(as.factor(collector_name)) sum_values_ordered<-sum_values_ordered%>%mutate(collector_name=fct_reorder(collector_name,proportion_per_collector_values,.fun='length')) #below used to reorder before plot# sum_values_ordered<-sum_values_ordered%>%arrange(desc(proportion_per_collector_values)) sum_values_ordered2<-transform(sum_values_ordered,collector_name=reorder(collector_name,order(proportion_per_collector_values,decreasing=TRUE))) ggplot(sum_values_ordered2,aes(x=collector_name,proportion_per_collector_values,stat="identity"))+geom_col(aes(fill=collector_name))+ggtitle("Overall Value summary by Collector")+geom_text(aes(label=n))+ylab("Proportion (%)")+geom_text(aes(label=round(proportion_per_collector_values,3),position="dodge",vjust=2.55)) wrap.it <- function(x, len) { sapply(x, function(y) paste(strwrap(y, len), collapse = "\n"), USE.NAMES = FALSE) } wrap.labels <- function(x, len) { if (is.list(x)) { lapply(x, wrap.it, len) } else { wrap.it(x, len) } } sum_values_ordered2_wrap<-wrap.labels(sum_values_ordered2$collector_name,1) ggplot(sum_values_ordered2_wrap,aes(x=collector_name,proportion_per_collector_values,stat="identity"))+geom_col(aes(fill=collector_name))+ggtitle("Overall Value summary by Collector")+geom_text(aes(label=n))+ylab("Proportion (%)")+geom_text(aes(label=round(proportion_per_collector_values,3),position="dodge",vjust=2.55)) library(stringr) sum_values_ordered2$newcollectorname = str_wrap(sum_values_ordered2$collector_name, width = 15) sum_values_ordered2<-transform(sum_values_ordered2,newcollectorname=reorder(newcollectorname,order(proportion_per_collector_values,decreasing=TRUE))) #used# ggplot(sum_values_ordered2,aes(x=newcollectorname,proportion_per_collector_values,stat="identity"))+geom_col(aes(fill=collector_name))+ggtitle("Overall Value summary by Collector")+xlab("")+geom_text(aes(label=n))+ylab("Proportion (%)")+geom_text(aes(label=round(proportion_per_collector_values,3),position="dodge",vjust=2.55))+theme(axis.text=element_text(size=8),axis.title=element_text(size=14,face="bold"))
import React, { useState, } from 'react'; /* ----------------------------------- MUI ---------------------------------- */ import { TextField, Button, IconButton, Snackbar, Alert, } from "@mui/material"; /* -------------------------------- MUI Icon -------------------------------- */ import { CloseFullscreenOutlined, } from '@mui/icons-material'; /* -------------------------------------------------------------------------- */ /* EmailForgotPassword */ /* -------------------------------------------------------------------------- */ const EmailForgotPassword = () => { /* ----------------------------------- ENV ---------------------------------- */ const serverUrl = process.env.REACT_APP_BASE_URL; /* ---------------------------------- Data ---------------------------------- */ const [email, setEmail] = useState(""); const [emailError, setEmailError] = useState(""); /* -------------------------------------------------------------------------- */ /* inputStyle */ /* -------------------------------------------------------------------------- */ const inputStyle = { width: "100%", color: "#595959", // border: 1, // borderColor: "#CCCCCC", // borderRadius: "0.5rem", // padding: "0.5rem 0.5rem", my: 1 }; /* -------------------------------- SnackBar -------------------------------- */ // * SnackBar const [openSnackbar, setOpenSnackbar] = useState(false); const [errorSnackbar, setErrorSnackbar] = useState(""); const [severity, setSeverity] = useState(""); // * handleClose const handleClose = (event, reason) => { if (reason === 'clickaway') { return; } setOpenSnackbar(false); }; // * action const action = ( <React.Fragment> <Button color="secondary" size="small" onClick={handleClose} > UNDO </Button> <IconButton size="small" aria-label="close" color="inherit" onClick={handleClose} > <CloseFullscreenOutlined fontSize="small" /> </IconButton> </React.Fragment> ); /* ------------------------------ handleSubmit ------------------------------ */ const handleSubmit = async () => { // * Validation if (!email) { // * Set Email setEmailError("Please Enter your Email"); // * Snackbar setOpenSnackbar(true); setSeverity("error"); setErrorSnackbar("Please Enter your Email"); return; } // * Data Structure const send = { "email": email, }; // * Fetch const response = await fetch(`${serverUrl}/auth/forgot-password`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(send), }); // * Return const data = await response.json(); // * Snackbar if(data.error) { setOpenSnackbar(true); setSeverity("error"); setErrorSnackbar(data.error); } else { setOpenSnackbar(true); setSeverity("success"); setErrorSnackbar(data.success); } } /* ---------------------------------- View ---------------------------------- */ return ( <div className={` bg-gray-50 flex items-center justify-center min-w-screen min-h-screen p-5 `} > {/* -------------------------------- SnackBar -------------------------------- */} <Snackbar open={ openSnackbar } autoHideDuration={6000} onClose={ handleClose } message={ errorSnackbar } action={ action } > { severity === "success" ? <Alert onClose={ handleClose } severity="success" sx={{ width: '100%' }} > { errorSnackbar } </Alert> : <Alert onClose={ handleClose } severity="error" sx={{ width: '100%' }} > { errorSnackbar } </Alert> } </Snackbar> {/* ---------------------------------- Main ---------------------------------- */} <div className={` w-full lg:max-w-3xl bg-white text-gray-800 p-8 lg:p-12 shadow-xl rounded-lg `} > <div> <h1 className={` text-2xl text-gray-800 font-bold `} > Forgot Password? </h1> <p className={` mt-1 text-gray-500 font-semibold `} > Please enter your email we will send you a link to reset your password. </p> </div> <div className={`mt-10`}> {/* ---------------------------------- Email --------------------------------- */} <TextField label="Email" placeholder="Email" onChange={(e) => setEmail(e.target.value)} value={ email } sx={inputStyle} /> {/* Error Log */} <div className={emailError ? `mt-1 text-center p-2 bg-red-400 text-white` : `` } > { emailError } </div> <Button fullWidth onClick={ () => handleSubmit() } sx={{ m: "2rem 0", p: "1rem", color: "#ffffff", backgroundColor: "#3b98f5", "&:hover": { backgroundColor: "#027cf5" }, // backgroundColor: palette.primary.main, // color: palette.background.alt, // "&:hover": { color: palette.primary.main }, }} > Send </Button> </div> </div> </div> ) } export default EmailForgotPassword
# Environment Setup - Next.js 14.0.1 npx create-next-app@14.0.1 antonio-trello-clone ``` √ Would you like to use TypeScript? Yes √ Would you like to use ESLint? Yes √ Would you like to use Tailwind CSS? Yes √ Would you like to use `src/` directory? No √ Would you like to use App Router? (recommended) Yes √ Would you like to customize the default import alias (@/\*)? No ``` `cd antonio-trello-clone` `npx shadcn-ui@latest init` ``` √ Would you like to use TypeScript (recommended)? ... yes √ Which style would you like to use? » Default √ Which color would you like to use as base color? » Neutral √ Where is your global CSS file? ... app/globals.css √ Would you like to use CSS variables for colors? ... yes √ Where is your tailwind.config.js located? ... tailwind.config.ts √ Configure the import alias for components: ... @/components √ Configure the import alias for utils: ... @/lib/utils √ Are you using React Server Components? ... yes √ Write configuration to components.json. Proceed? ... yes ``` `npm run dev` # Folders Setup ... # Marketing npx shadcn-ui@latest add button # Authentication Clerk setup: https://clerk.com/ - login - add application ``` application name: antonio-trello turn off email address create application copy API KEYS to .env .gitignore .env npm i @clerk/nextjs ``` .env ``` NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY= CLERK_SECRET_KEY= NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/ NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/ ``` # Organizations Clerk dashboard: https://dashboard.clerk.com/ - Organizations - "Enable" # Sidebar ``` npm i usehooks-ts zustand` npx shadcn-ui@latest add accordion skeleton separator sheet ``` # Settings ... # Server Actions NeonDB: https://neon.tech/ - login - create service ``` npm i -D prisma npx prisma init npx prisma generate npx prisma db push npx prisma studio . npx shadcn-ui@latest add input npm i zod ``` .env ``` DATABASE_URL= ``` .package.json ``` "scripts": { "postinstall": "prisma generate" }, ``` # Use Action (error log) ... # Form Components `npx shadcn-ui@latest add label` # Form Popover ``` npm i sonner npx shadcn-ui@latest add popover tooltip ``` # Create Board Unsplash ``` npm i unsplash-js unsplash.com/developer - register https://unsplash.com/oauth/applications - create application copy Access Key ``` .env ``` NEXT_PUBLIC_UNSPLASH_ACCESS_KEY= ``` ``` npx prisma migrate reset npx prisma db push npx prisma generate ``` # Board List ... # Board Page ``` npm i lodash npm i -D @types/lodash ``` # List Form ``` npx prisma migrate reset npx prisma db push npx prisma generate npx prisma studio - "view list" ``` # List Header ... # List Options ... # Card Form `npx shadcn-ui@latest add textarea` # Drag and Drop ``` npm i @hello-pangea/dnd ``` # Card Modal ``` npx shadcn-ui@latest add dialog npm i @tanstack/react-query ``` # Card Actions ... # Activity ``` npm i date-fns npx shadcn-ui@latest add avatar npx prisma db push npx prisma generate ``` # Stripe ``` npx prisma db push npx prisma generate ``` Stripe API KEY & Webhook ``` npm i stripe stripe.com - login - create store "antonio-trello" click developers tab api keys - copy secret key to .env . webhooks - "test in local environment" download & open stripe cli - visit link - allow access run stripe listen --forward-to localhost:3000/api/webhook copy webhook signing secret to .env . stripe.com - search "billing portal" - customer portal click "activate test link" validate Billing - "Manage Billing" show "Stripe Plan" ``` Stripe Payment ``` Card Information: 4242* Cardholder name: a click "Pay and subscribe" show "200" requests validate OrgSubscription in "npx prisma studio" validate "create new board unlimited" validate can create new board validate Billing - "Manage Billing" show "Stripe Plan" ``` .env ``` NEXT_PUBLIC_APP_URL=http://localhost:3000 STRIPE_API_KEY= STRIPE_WEBHOOK_SECRET= ``` Webhook production ``` stripe.com - login - developers tab - "add endpoint" copy vercel endpoint to stripe "endpoint url" + "api/webhook/ select events - checkout.session.completed & invoice.payment.succeeded click "add events" - "add endpoint" click "reveal signing secret" - copy to vercel env vars copy endpoint url to vercel env var NEXT_PUBLIC_APP_URL + remove "/" at end ``` # Deployment foreach ``` git add . git commit -m "XX: message" git push validate deployment succeed ``` once ``` github.com/new - name "antonio-trello" - create repo use second option - "push an existing repo" . vercel.com/new - import "antonio-trello" - deploy settings - environment variables - add from .env ```
import AsyncStorage from '@react-native-async-storage/async-storage'; import axios from 'axios'; import React, {useEffect, useRef, useState} from 'react'; import { ActivityIndicator, Alert, SafeAreaView, ScrollView, StatusBar, StatusBarStyle, Switch, Text, TouchableOpacity, useColorScheme, View, } from 'react-native'; import RBSheet from 'react-native-raw-bottom-sheet'; import Icon from 'react-native-vector-icons/Ionicons'; import {useDispatch} from 'react-redux'; import {logout, themeToggler} from '../../features/users/usersSlice'; import {useAppSelector} from '../../redux/hooks'; import {headerStyles, lightTheme} from '../../styles'; import HistoryPage from '../ClientsPage/HistoryPage'; import FeedBackPage from '../FeedbackPage/FeedBackPage'; import {ProfileStyles} from './styles'; interface UserData { balance: string; first_name: string; id: number; last_name: string; passengers_count: number; phone_number: string; username: string; } const MenuItems = [ { label: 'История пассажиров', icon: 'people', routeName: 'History', }, { label: 'Обратная связь', icon: 'shield-checkmark', routeName: 'Feedback', }, ]; const ProfilePage = () => { const dispatch = useDispatch(); const handleLogout = async () => { Alert.alert('Выйти из аккаунта', 'Вы точно хотите выйти?', [ { text: 'Отмена', }, { text: 'Выйти из аккаунта', onPress: async () => { await AsyncStorage.removeItem('access'); await AsyncStorage.removeItem('refresh'); dispatch(logout()); }, }, ]); }; const [historyData, setHistoryData] = useState<UserData | null>(null); const refRBSheet: React.MutableRefObject<any> = useRef(); const refRBSheet2: React.MutableRefObject<any> = useRef(); const {profileData} = useAppSelector(select => select.profileData); const [isEnabled, setIsEnabled] = useState(false); const {themeColor} = useAppSelector(select => select.themeColor); const STYLES: StatusBarStyle[] = ['default', 'dark-content', 'light-content']; const [statusBarStyle, setStatusBarStyle] = useState<StatusBarStyle>( STYLES[0], ); const colorScheme = useColorScheme(); const toggleSwitch = () => { if (isEnabled) { dispatch(themeToggler('light')); setStatusBarStyle(STYLES[1]); } else { dispatch(themeToggler('dark')); setStatusBarStyle(STYLES[2]); } setIsEnabled(previousState => !previousState); }; useEffect(() => { async function fetchHistoryData() { const token = await AsyncStorage.getItem('access'); axios .get(`https://1s-taxi.uz/api/v1/orders/history/`, { headers: { Authorization: `Bearer ${token}`, }, }) .then(res => { setHistoryData(res.data); }); } themeColor === 'light' ? setStatusBarStyle(STYLES[1]) : setStatusBarStyle(STYLES[2]); themeColor === 'light' ? setIsEnabled(false) : setIsEnabled(true); fetchHistoryData(); }, []); return ( <SafeAreaView> <StatusBar barStyle={statusBarStyle} /> <ScrollView showsVerticalScrollIndicator={false}> <View style={ProfileStyles.container}> <View style={ProfileStyles.userInfo}> <Icon size={100} color={themeColor === 'dark' ? 'white' : 'black'} name="person-circle" /> <View style={ProfileStyles.userData}> {profileData ? ( <> <Text style={[ headerStyles.title, {marginBottom: 10}, themeColor === 'light' && lightTheme.lightText, ]}> {profileData.first_name} {profileData.last_name} </Text> <Text style={[ ProfileStyles.carNumber, themeColor === 'light' && lightTheme.lightText, ]}> {profileData.phone_number} </Text> <Text style={[ ProfileStyles.carNumber, themeColor === 'light' && lightTheme.lightText, ]}> {profileData.username} · {profileData.car_number} </Text> <Text style={[ ProfileStyles.carNumber, themeColor === 'light' && lightTheme.lightText, ]}> {profileData.car_brand} </Text> </> ) : ( <ActivityIndicator size={20} color="gray" /> )} </View> </View> <View style={ProfileStyles.itemsContainer}> <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }}> {profileData ? ( <> <View style={ProfileStyles.card}> <Text style={[ headerStyles.title, themeColor === 'light' && lightTheme.lightText, ]}> {Number(profileData.balance)} </Text> <Text style={{color: 'gray'}}>Баланс</Text> </View> <View style={ProfileStyles.card}> <Text style={[ headerStyles.title, themeColor === 'light' && lightTheme.lightText, ]}> {profileData.passengers_count} </Text> <Text style={{color: 'gray'}}>Клиентов</Text> </View> </> ) : ( <></> )} </View> <View style={{marginTop: 20}}> <Text style={{ marginLeft: 15, fontSize: 18, fontWeight: '600', color: themeColor === 'light' ? '#141414' : 'white', marginBottom: 15, }}> Действия </Text> {MenuItems.map((touch, index) => ( <TouchableOpacity key={index} onPress={() => { touch.routeName === 'History' ? refRBSheet.current.open() : refRBSheet2.current.open(); }}> <View style={ProfileStyles.item}> <Text style={[ ProfileStyles.itemTxt, themeColor === 'light' && lightTheme.lightText, ]}> {touch.label} </Text> <Icon size={24} name={touch.icon} color={themeColor === 'light' ? '#141414' : 'white'} /> </View> </TouchableOpacity> ))} <View style={ProfileStyles.item}> <Text style={[ ProfileStyles.itemTxt, themeColor === 'light' && lightTheme.lightText, ]}> Тёмный режим </Text> <Switch trackColor={{false: '#767577', true: 'gray'}} thumbColor={isEnabled ? 'white' : '#141414'} ios_backgroundColor="#3e3e3e" onValueChange={toggleSwitch} value={isEnabled} /> </View> <TouchableOpacity onPress={() => handleLogout()}> <View style={ProfileStyles.item}> <Text style={[ ProfileStyles.itemTxt, themeColor === 'light' && lightTheme.lightText, ]}> Выйти </Text> <Icon size={24} name="log-out" color={themeColor === 'light' ? '#141414' : 'white'} /> </View> </TouchableOpacity> </View> </View> <RBSheet ref={refRBSheet} useNativeDriver={false} height={600} closeOnPressBack={true} dragOnContent={false} draggable={true} customStyles={{ wrapper: { backgroundColor: 'transparent', }, draggableIcon: { backgroundColor: themeColor === 'light' ? '#000' : '#fff', }, container: { borderTopLeftRadius: 20, borderTopRightRadius: 20, backgroundColor: themeColor === 'light' ? '#fff' : '#212121', shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, }} customModalProps={{ animationType: 'fade', statusBarTranslucent: true, }} customAvoidingViewProps={{ enabled: false, }}> <HistoryPage historyData={historyData} /> </RBSheet> <RBSheet ref={refRBSheet2} useNativeDriver={false} height={250} closeOnPressBack={true} dragOnContent={false} draggable={true} customStyles={{ wrapper: { backgroundColor: 'transparent', }, draggableIcon: { backgroundColor: themeColor === 'light' ? '#000' : '#fff', }, container: { borderTopLeftRadius: 20, borderTopRightRadius: 20, backgroundColor: themeColor === 'light' ? '#fff' : '#212121', shadowColor: '#000', shadowOffset: { width: 0, height: 2, }, shadowOpacity: 0.25, shadowRadius: 3.84, elevation: 5, }, }} customModalProps={{ animationType: 'fade', statusBarTranslucent: true, }} customAvoidingViewProps={{ enabled: false, }}> <FeedBackPage /> </RBSheet> </View> </ScrollView> </SafeAreaView> ); }; export default ProfilePage;
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> </head> <body> <p th:text="${msg}"></p> <p th:text="#{empty}"></p> <h1>Student list</h1> <a th:href="@{/student/showFormCreate}">Add new student</a> <table class="table table-striped"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Gender</th> <th>Language</th> </tr> </thead> <tbody> <tr th:each="student, loop : ${studentList}"> <td th:text="${loop.count}"></td> <td th:text="${student.name}"></td> <td th:if="${student.gender == true}" th:text="${'Male'}"></td> <td th:if="${student.gender == false}" th:text="${'Female'}"></td> <td> <th:block th:each="lang : ${student.languages}"> <span th:text="${lang}"></span> </th:block> </td> </tr> </tbody> </table> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </body> </html>
import React from "react"; import { Text, TouchableOpacity, StyleSheet } from "react-native"; const RED_COLOR = "rgb(230, 53, 43)"; const RED_COLOR_DISABLED = "rgba(230, 53, 43,0.5)"; const BLUE_COLOR = "rgb(0, 110, 230)"; const BLUE_COLOR_DISABLED = "rgba(0, 110, 230,0.5)"; //InitButtonObjectParse export const initButtonInstance = { isInline: false, onClick:()=>{}, disabled: false, text: 'No Text for this button!', isDanger: true, style:{} } const ButtonField = ({ theme, isInline = initButtonInstance.isInline, onClick = initButtonInstance.onClick, disabled = initButtonInstance.disabled, text = initButtonInstance.text, isDanger = initButtonInstance.isDanger, style = initButtonInstance.style }) => { let colorStyle = null; let backgroundButtonColor = null; let backgroundButtonTextColor = disabled ? "rgba(255,255,255,0.5)" : "white"; if (!theme) { colorStyle = { color: isDanger ? RED_COLOR : BLUE_COLOR, }; backgroundButtonColor = { backgroundColor: isDanger ? disabled ? RED_COLOR_DISABLED : RED_COLOR : disabled ? BLUE_COLOR_DISABLED : BLUE_COLOR, }; } else { colorStyle = isDanger ? { color: theme.buttonDangerColor } : { color: theme.buttonNormalColor }; backgroundButtonColor = { backgroundColor: isDanger ? disabled ? theme.buttonDangerDisabledColor : theme.buttonDangerColor : disabled ? theme.buttonNormalDisabledColor : theme.buttonNormalColor, }; } return isInline ? ( <TouchableOpacity style={{...styles.inlineContainerStyle, ...style}} onPress={onClick || ON_CLICK_EMPTY} disabled={disabled} > <Text style={{ ...styles.textStyle, ...colorStyle }}>{text}</Text> </TouchableOpacity> ) : ( <TouchableOpacity style={{ ...styles.normalContainerStyle, ...backgroundButtonColor,...style }} onPress={onClick || ON_CLICK_EMPTY} disabled={disabled} > <Text style={{ ...styles.textStyle, color: backgroundButtonTextColor }}>{text}</Text> </TouchableOpacity> ); }; //const functions const ON_CLICK_EMPTY = ()=>{console.error('No on click initialized for this button')} const styles = StyleSheet.create({ inlineContainerStyle: { height: 35, marginHorizontal: 5, alignSelf: "center", justifyContent: "center", }, normalContainerStyle: { height: 50, marginHorizontal: 5, backgroundColor: "white", alignSelf: "stretch", justifyContent: "center", marginHorizontal: 15, borderRadius: 5, }, textStyle: { fontSize: 16, textAlign: "center", }, }); export default ButtonField;
package day8 import helpers.Helpers object Day8 { def main(args: Array[String]): Unit = { // val input = Helpers.readFile("day8/test.txt") // val input = Helpers.readFile("day8/test1_1.txt") // val input = Helpers.readFile("day8/test3.txt") val input = Helpers.readFile("day8/day8.txt") val (instructions, nodes) = parse(input) val loopingIndexedInstructions = Helpers.infiniteStream(instructions) val nodeLookup = nodes.map(node => node.id -> node).toMap val part1 = process(loopingIndexedInstructions, nodeLookup) println(s"Part 1 : $part1") val part2 = process2(loopingIndexedInstructions, nodeLookup) println(s"Part 2: $part2") } def process(instructions: LazyList[(Char)], nodeLookup: Map[String, Node]): Long = { val startNode = nodeLookup.getOrElse("AAA", return -1) instructions.foldLeft((nodeLookup("AAA"), 1L))((acc, nextInstruction) => { val previousNode = acc._1 val stepCount = acc._2 val nextNode = nodeLookup(previousNode.next(nextInstruction)) if (nextNode.id.equals("ZZZ")) { return stepCount //indexes start at 0 } (nextNode, stepCount + 1) }) ??? } def process2(instructions: LazyList[(Char)], nodeLookup: Map[String, Node]) = { val startingNodes = nodeLookup .filter(_._1.endsWith("A")) .toSeq .map(_._2) //loop size , first index def _findLoopSize(startNode: Node): (Long, Long) = { //seen nodes: Map[Node.Id -> Index seen at] //when I find a node that I've seen before, I'll know the first index, and then the loop size //I don't want to assume that the starting nodes will hit a Z node in exactly the same loop size // (The start node branch can enter the loop at any point) instructions.foldLeft((startNode, 1L, Map[String, Long](startNode.id -> 0)))((acc, nextInstruction) => { val previousNode = acc._1 val stepCount = acc._2 val seenNodes = acc._3 val nextNode = nodeLookup(previousNode.next(nextInstruction)) val updatedMap: Map[String, Long] = seenNodes.get(nextNode.id) match { case Some(previousIndex) => { if (nextNode.id.endsWith("Z")) { return (stepCount - previousIndex, previousIndex) } seenNodes } case None => { seenNodes + (nextNode.id -> stepCount) } } (nextNode, stepCount + 1, updatedMap) }) ??? } //checked that there are only 1 Z nodes in each loop, and the start and Z always point to the same node val loopSizes = startingNodes.map(startNode => _findLoopSize(startNode)).map(_._1) // loopSizes.foreach(println) Helpers.lcm(loopSizes) } def parse(input: Seq[String]) = { val itr = input.iterator val instructions = itr.next() itr.next() //throw away empty line val instructionRegex = """^(\w{3}) = \((\w{3}), (\w{3})\)$""".r val nodes = itr.map(line => { val instructionRegex(id, left, right) = line Node(id, left, right) }).toSeq (instructions.toCharArray.toSeq, nodes) } case class Node(id: String, left: String, right: String) { def next(instruction: Char): String = { instruction match { case 'L' => left case 'R' => right } } } }
/* * @(#) ParserArrayTest.java * * json-simple Simple JSON Parser and Formatter * Copyright (c) 2021, 2023 Peter Wall * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.pwall.json.parser.test; import java.util.List; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import net.pwall.json.parser.ParseException; import net.pwall.json.parser.ParseOptions; import net.pwall.json.parser.Parser; import static net.pwall.json.parser.Parser.MAX_DEPTH_EXCEEDED; public class ParserArrayTest { @Test public void shouldParseEmptyArray() { Object result = Parser.parse("[]"); assertTrue(result instanceof List); List<?> list = (List<?>)result; assertEquals(0, list.size()); } @Test public void shouldParseArrayOfString() { Object result = Parser.parse("[\"simple\"]"); assertTrue(result instanceof List); List<?> list = (List<?>)result; assertEquals(1, list.size()); assertEquals("simple", list.get(0)); } @Test public void shouldParseArrayOfTwoStrings() { Object result = Parser.parse("[\"Hello\",\"world\"]"); assertTrue(result instanceof List); List<?> list = (List<?>)result; assertEquals(2, list.size()); assertEquals("Hello", list.get(0)); assertEquals("world", list.get(1)); } @Test public void shouldParseArrayOfArray() { Object result = Parser.parse("[[\"Hello\",[\"world\",\"universe\"]]]"); assertTrue(result instanceof List); List<?> list1 = (List<?>)result; assertEquals(1, list1.size()); assertTrue(list1.get(0) instanceof List); List<?> list2 = (List<?>)list1.get(0); assertEquals(2, list2.size()); assertEquals("Hello", list2.get(0)); assertTrue(list2.get(1) instanceof List); List<?> list3 = (List<?>)list2.get(1); assertEquals(2, list3.size()); assertEquals("world", list3.get(0)); assertEquals("universe", list3.get(1)); } @Test public void shouldThrowExceptionOnTrailingComma() { ParseException e = assertThrows(ParseException.class, () -> Parser.parse("[\"simple\",]")); assertEquals("Illegal JSON syntax", e.getText()); assertEquals("/1", e.getPointer()); assertEquals("Illegal JSON syntax at /1", e.getMessage()); } @Test public void shouldAllowTrailingCommaWithOption_arrayTrailingComma() { ParseOptions options = new ParseOptions(ParseOptions.DuplicateKeyOption.ERROR, false, false, true, 1000); Object result = Parser.parse("[\"simple\",]", options); assertTrue(result instanceof List); List<?> list = (List<?>)result; assertEquals(1, list.size()); assertEquals("simple", list.get(0)); } @Test public void shouldThrowExceptionOnMissingClosingBracket() { ParseException e = assertThrows(ParseException.class, () -> Parser.parse("[\"simple\"")); assertEquals("Missing closing bracket in JSON array", e.getText()); assertEquals("", e.getPointer()); assertEquals("Missing closing bracket in JSON array", e.getMessage()); } @Test public void shouldAllowNestingUpToMaximumDepth() { ParseOptions options = new ParseOptions(ParseOptions.DuplicateKeyOption.ERROR, false, false, false, 50); StringBuilder allowed = new StringBuilder(101); for (int i = 50; i > 0; i--) allowed.append('['); allowed.append('1'); for (int i = 50; i > 0; i--) allowed.append(']'); Object result = Parser.parse(allowed.toString(), options); for (int i = 50; i > 0; i--) { assertTrue(result instanceof List<?>); result = ((List<?>)result).get(0); } assertEquals(1, result); } @Test public void shouldThrowExceptionOnNestingDepthExceeded() { ParseOptions options = new ParseOptions(ParseOptions.DuplicateKeyOption.ERROR, false, false, false, 50); StringBuilder excessive = new StringBuilder(51); for (int i = 51; i > 0; i--) excessive.append('['); ParseException pe = assertThrows(ParseException.class, () -> Parser.parse(excessive.toString(), options)); assertEquals(MAX_DEPTH_EXCEEDED, pe.getText()); assertEquals(MAX_DEPTH_EXCEEDED, pe.getMessage()); assertEquals("", pe.getPointer()); } }
public class Video implements Comparable<Video>{ private String title; private double durationInMinutes; private int views; private int likes; private double watchTime; public Video(){ title = "java interfaces"; durationInMinutes = 30; views = 2000; likes = 300; watchTime = 756438.5; } public int getLikes() { return likes; } public void setLikes(int likes) { this.likes = likes; } public Video(String title, double durationInMinutes, int views, int likes, double watchTime) { this.title = title; this.durationInMinutes = durationInMinutes; this.views = views; this.likes = likes; this.watchTime = watchTime; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public double getDurationInMinutes() { return durationInMinutes; } public void setDurationInMinutes(double durationInMinutes) { this.durationInMinutes = durationInMinutes; } public int getViews() { return views; } public void setViews(int views) { this.views = views; } public double getWatchTime() { return watchTime; } public void setWatchTime(double watchTime) { this.watchTime = watchTime; } @Override public String toString() { return "\"Title: " + title + ". Duration: " + durationInMinutes + ". Views: " + views + ". Likes: " + likes + ". WatchTime: " + watchTime + ".\""; } @Override public int compareTo(Video o) { if (this.watchTime < o.watchTime) return -1; if (this.watchTime > o.watchTime) return 1; return 0; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof Video)) return false; return this.watchTime == ((Video) obj).watchTime; } }
60%:用暴力搜索可以将解决60%的数据,如果i和j相连,j和k相连,i和k不相连,那么可以认为i和k可以构成联合最大权值,用一个O(N^3)的循环即可。 100%: 这个题AC的思路很多,可以跑树,用LCA处理两个兄弟之间的关系,也可以跑图,想要,存储一定要用前向星。(不会问度娘)。我能够AC还要感谢@yangs\_s,如果不是他的博客http://blog.csdn.net/yangs\_s/article/details/47359967,这个题我也做不出AC来的,我在这里把他的思路说一下吧。 有两个关键点。 首先输出分为两部分,可以把题目分成两部分来看,对一个点来说,最大的乘积自然就是和它相邻的两个权值最大的节点的权值的乘积, 读入后顺手处理一下就能出来。 第二个关键点就是加法结合律。 没错,加法结合律! 我看到神犇的博客后伏案长叹,这是小学三年级的内容,我就这样还给老师了。 我们假设和o点相邻的点有a,b,c,d,e,f,g七个,假设他们的权值就是a,b,c,d,e,f,g。某二逼青年的计算过程是这样的:sum:=a·b+a·c+a·d…….+a….+e\*g….,但其实我们这样处理,我们先用加法运算法则,发现sum其实就是每个点的权值乘以可以联合(距离为2)的节点的所有权值之和,所以说,我们在读入数据的时候,可以预先处理一下,把每个节点周围相邻节点的权值之和给加起来,就以上述为例,在处理时,把a,b,c….g的权值加起来为s[o]{o点相邻点的权值之和},然后在计算时,就可以用sum:=a·(s[o]-a)+b·(s[o]-b)…..很自然的结果就出来了! 算法的时间复杂度应该是O(kn),k应该是一个很小很小远小于N的常数,应该和LCA的差不多了吧。 ```delphi (const ma=10007; const mx=200000; type ss=record u,v:longint; end; var s:array[1..mx] of int64;//s[i]表示和结点i所有相连的点的权值之和 e:array[1..mx] of ss;//存的是边 w,max1,max2:array[1..mx]of longint; {w[i]表示第i个点的权值 max1[i]表示和i相连得结点中权值最大的结点 max2[i]表示和i相连得结点中权值最小的结点 } n,i,j,ans1,ans2:longint; procedure box; var i,j:longint; begin fillchar(s,sizeof(s),0); fillchar(e,sizeof(e),0); fillchar(w,sizeof(w),0); fillchar(max1,sizeof(max1),0); fillchar(max2,sizeof(max2),0); ans1:=0; ans2:=0; end; //变量初始化 procedure work(x:longint;var a,b:longint); //x的值是不会被改变的,a和b是可以被改变的 begin //首先已经得出值的数组是合法的,再次更改过后也一定是合法的 if x>a then begin b:=a; a:=x; end else if x>b then b:=x; end; //用来比较大小的过程,必须用全局变量 procedure change; var i,u,v:longint; begin for i:=1 to n-1 do begin u:=e[i].u; v:=e[i].v; inc(s[u],w[v]); inc(s[v],w[u]); work(w[v],max1[u],max2[u]); work(w[u],max1[v],max2[v]); //不断更新结点周围的最大值和次大值 end; end; //预处理程序 procedure main1; var i:longint; begin for i:=1 to n do if max1[i]*max2[i]>ans1 then ans1:=max1[i]*max2[i]; end; //处理最大的联合权值 procedure main2; var i,j,u,v:longint; begin for i:=1 to n-1 do begin u:=e[i].u; v:=e[i].v; ans2:=(ans2+((s[u]-w[v])*w[v]) mod ma) mod ma; ans2:=(ans2+((s[v]-w[u])*w[u]) mod ma) mod ma; end; end; //处理权值之和 procedure init; var i,j:longint; begin readln(n); for i:=1 to n-1 do readln(e[i].u,e[i].v); for i:=1 to n do read(w[i]); end; procedure printf; begin writeln(ans1,' ',ans2); end; begin box; init; change; main1; main2; printf; end. ) ```
Lab: Recursion This document defines the in-class exercises (lab) for the "Algortihms" course @ Software University. Part I - Recursion 1.Recursive Array Sum Write a program that finds the sum of all elements in an integer array. Use recursion. Note: In practice recursion should not be used here (instead use an iterative solution), this is just an exercise. Examples Input Output 1 2 3 4 10 -1 0 1 0 Hints Write a recursive method. It will take as arguments the input array and the current index. The method should return the current element + the sum of all next elements (obtained by recursively calling it). The recursion should stop when there are no more elements in the array. 2.Recursive Factorial Write a program that finds the factorial of a given number. Use recursion. Note: In practice recursion should not be used here (instead use an iterative solution), this is just an exercise. Examples Input Output 5 120 10 3628800 Hints Write a recursive method. It will take as arguments an integer number. The method should return the current element * the result of calculating factorial of current element - 1 (obtained by recursively calling it). The recursion should stop when there are no more elements in the array. 3.Recursive Drawing Write a program that draws the figure below depending on n. Use recursion. Examples Input Output 2 ** * # ## 5 ***** **** *** ** * # ## ### #### ##### Hints Set the bottom of the recursion Define pre- and post- recursive behavior 4.Generating 0/1 Vectors Generate all n-bit vectors of zeroes and ones in lexicographic order. Examples Input Output 3 000 001 010 011 100 101 110 111 5 00000 00001 00010 … 11110 11111 Hints The method should receive as parameters the array which will be our vector and a current index Bottom of recursion should be when the index is outside of the vector To generate all combinations, create a for loop with a recursive call 5.Generating Combinations Generate all n choose k combinations. Read the set of elements, then number of elements to choose. Examples Input Output 1 2 3 4 2 1 2 1 3 1 4 2 3 2 4 3 4 1 2 3 4 5 3 1 2 3 1 2 4 1 2 5 … 3 4 5 Hints The method should receive the following parameters Set the bottom of the recursion Loop through all possible picks for a given index of the vector Part II - 8 Queens Puzzle In this lab we will implement a recursive algorithm to solve the "8 Queens" puzzle. Our goal is to write a program to find all possible placements of 8 chess queens on a chessboard, so that no two queens can attack each other (on a row, column or diagonal). Examples Input Output (no input) * - - - - - - - - - - - * - - - - - - - - - - * - - - - - * - - - - * - - - - - - - - - - - * - - * - - - - - - - - - * - - - - * - - - - - - - - - - - - * - - - - - - - - - * - - * - - - - - - - - - - - * - - - - * - - - - - * - - - - - - - - - - * - - - … (90 solutions more) 1.Learn about the "8 Queens" Puzzle Learn about the "8 Queens" puzzle, e.g. from Wikipedia: http://en.wikipedia.org/wiki/Eight_queens_puzzle. 2.Define a Data Structure to Hold the Chessboard First, let’s define a data structure to hold the chessboard. It should consist of 8 x 8 cells, each either occupied by a queen or empty. Let’s also define the size of the chessboard as a constant: 3.Define a Data Structure to Hold the Attacked Positions We need to hold the attacked positions in some data structure. At any moment during the execution of the program, we need to know whether a certain position {row, col} is under attack by a queen or not. There are many ways to store the attacked positions: By keeping all currently placed queens and checking whether the new position conflicts with some of them. By keeping an int[,] matrix of all attacked positions and checking the new position directly in it. This will be complex to maintain because the matrix should change many positions after each queen placement/removal. By keeping sets of all attacked rows, columns and diagonals. Let’s try this idea: The above definitions have the following assumptions: The Rows are 8, numbered from 0 to 7. The Columns are 8, numbered from 0 to 7. The left diagonals are 15, numbered from -7 to 7. We can use the following formula to calculate the left diagonal number by row and column: leftDiag = col - row. The right diagonals are 15, numbered from 0 to 14 by the formula: rightDiag = col + row. Let’s take as an example the following chessboard with 8 queens placed on it at the following positions: {0, 0}; {1, 6}; {2, 4}; {3, 7}; {4, 1}; {5, 3}; {6, 5}; {7, 2} Following the definitions above for our example the queen {4, 1} occupies the row 4, column 1, left diagonal -3 and right diagonal 5. 4.Write the Backtracking Algorithm Now, it is time to write the recursive backtracking algorithm for placing the 8 queens. The algorithm starts from row 0 and tries to place a queen at some column at row 0. On success, it tries to place the next queen at row 1, then the next queen at row 2, etc. until the last row is passed. The code for putting the next queen at a certain row might look like this: Initially, we invoke this method from row 0: 5.Check if a Position is Free Now, let’s write the code to check whether a certain position is free. A position is free when it is not under attack by any other queen. This means that if some of the rows, columns or diagonals is already occupied by another queen, the position is occupied. Otherwise it is free. A sample code might look like this: Recall that col-row is the number of the left diagonal and row+col is the number of the right diagonal. 6.Mark / Unmark Attacked Positions After a queen is placed, we need to mark as occupied all rows, columns and diagonals that it can attack: On removal of a queen, we will need a method to mark as free all rows, columns and diagonals that were attacked by it. Write it yourself: 7.Print Solutions When a solution is found, it should be printed at the console. First, introduce a solutions counter to simplify checking whether the found solutions are correct: Next, pass through all rows and through all columns at each row and print the chessboard cells: 8.Testing the Code The "8 queens" puzzle has 92 distinct solutions. Check whether your code generates and prints all of them correctly. The solutionsFound counter will help you check the number of solutions. Below are the 92 distinct solutions: Submit your code in judge, printing all 92 solutions, separated by a single line. 9.Optimize the Solution Now we can optimize our code: Remove the attackedRows set. It is not needed because all queens are placed consecutively at rows 0…7. Try to use bool[] array for attackedColumns, attackedLeftDiagonals and attackedRightDiagonals instead of sets. Note that arrays are indexed from 0 to their size and cannot hold negative indexes. * Permutation Based Solution Try to implement the more-efficient permutation-based solution of the "8 Queens" puzzle. Look at this code to grasp the idea: http://introcs.cs.princeton.edu/java/23recursion/Queens.java.html. Part III - Find All Paths in a Labyrinth You are given a labyrinth. Your goal is to find all paths from the start (cell 0, 0) to the exit, marked with 'e'. Empty cells are marked with a dash '-'. Walls are marked with a star '*'; On the first line, you will receive the dimensions of the labyrinth. Next you will receive the actual labyrinth. The order of the paths does not matter. Examples Input Output 3 3 --- -*- --e RRDD DDRR 3 5 -**-e ----- ***** DRRRRU DRRRUR Hints Create methods for reading and finding all paths in the labyrinth. Create a static list that will hold every direction (basically the path) Finding all paths should be recursive Implement all helper methods that are present in the code above.
package com.example.contacts.data.remote.network import com.example.contacts.data.remote.model.request.CreateUserRequest import com.example.contacts.data.remote.model.request.LoginRequest import com.example.contacts.data.remote.model.request.RegisterRequest import com.example.contacts.data.remote.model.response.CreateUserResponse import com.example.contacts.data.remote.model.response.ListUserResponse import com.example.contacts.data.remote.model.response.LoginResponse import com.example.contacts.data.remote.model.response.RegisterResponse import retrofit2.Response import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POST import retrofit2.http.Query interface ApiService { @POST("api/register") suspend fun registerUser(@Body registerRequest : RegisterRequest): Response<RegisterResponse> @POST("api/login") suspend fun loginUser(@Body loginRequest : LoginRequest): Response<LoginResponse> @POST("api/users") suspend fun createUser(@Body createUserRequest: CreateUserRequest): Response<CreateUserResponse> @GET("api/users") suspend fun listUser(@Query("page")page:Int) : Response<ListUserResponse> }
<?php namespace App\Http\Controllers; use App\Dto\Connection\StoreDto; use App\Http\Requests\Connection\StoreRequest; use App\Http\Resources\ConnectionRequestResource; use App\Models\ConnectionRequest; use App\Services\ConnectionRequestService; use Illuminate\Http\JsonResponse; use Illuminate\Http\Resources\Json\AnonymousResourceCollection; use Illuminate\Support\Facades\Auth; class RequestController extends Controller { public function __construct( public ConnectionRequestService $connectionRequestService, ) { $this->middleware('auth'); } public function showSent(): AnonymousResourceCollection { $connectionRequests = $this->connectionRequestService->getSentRequestsForUser(Auth::user()); return ConnectionRequestResource::collection( $connectionRequests->paginate(config('pagination.items_per_page')) ); } public function showReceived(): AnonymousResourceCollection { $connectionRequests = $this->connectionRequestService->getReceivedRequestsForUser(Auth::user()); return ConnectionRequestResource::collection( $connectionRequests->paginate(config('pagination.items_per_page')) ); } public function store(StoreRequest $request): JsonResponse { $connectionRequest = $this->connectionRequestService->store(StoreDto::fromRequest($request), Auth::user()); return response()->json([ 'message' => __('Request has been created.'), 'request' => ConnectionRequestResource::make($connectionRequest), ]); } public function destroy(ConnectionRequest $connectionRequest): JsonResponse { $connectionRequest->delete(); return response()->json([ 'message' => __('Request has been removed.'), ]); } public function accept(ConnectionRequest $connectionRequest): JsonResponse { $this->connectionRequestService->accept($connectionRequest, Auth::user()); return response()->json([ 'message' => __('Request has been accepted.'), ]); } }
#include "pch.h" #include "Hello2DMain.h" #include "Common\DirectXHelper.h" using namespace Hello2D; using namespace Windows::Foundation; using namespace Windows::System::Threading; using namespace Concurrency; // Loads and initializes application assets when the application is loaded. Hello2DMain::Hello2DMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) : m_deviceResources(deviceResources), m_pointerLocationX(0.0f) { // Register to be notified if the Device is lost or recreated m_deviceResources->RegisterDeviceNotify(this); // TODO: Replace this with your app's content initialization. m_sceneRenderer = std::unique_ptr<Sample2DSceneRenderer>(new Sample2DSceneRenderer(m_deviceResources)); m_fpsTextRenderer = std::unique_ptr<SampleFpsTextRenderer>(new SampleFpsTextRenderer(m_deviceResources)); // TODO: Change the timer settings if you want something other than the default variable timestep mode. // e.g. for 60 FPS fixed timestep update logic, call: /* m_timer.SetFixedTimeStep(true); m_timer.SetTargetElapsedSeconds(1.0 / 60); */ } Hello2DMain::~Hello2DMain() { // Deregister device notification m_deviceResources->RegisterDeviceNotify(nullptr); } // Updates application state when the window size changes (e.g. device orientation change) void Hello2DMain::CreateWindowSizeDependentResources() { // TODO: Replace this with the size-dependent initialization of your app's content. m_sceneRenderer->CreateWindowSizeDependentResources(); } void Hello2DMain::StartRenderLoop() { // If the animation render loop is already running then do not start another thread. if (m_renderLoopWorker != nullptr && m_renderLoopWorker->Status == AsyncStatus::Started) { return; } // Create a task that will be run on a background thread. auto workItemHandler = ref new WorkItemHandler([this](IAsyncAction ^ action) { // Calculate the updated frame and render once per vertical blanking interval. while (action->Status == AsyncStatus::Started) { critical_section::scoped_lock lock(m_criticalSection); Update(); if (Render()) { m_deviceResources->Present(); } } }); // Run task on a dedicated high priority background thread. m_renderLoopWorker = ThreadPool::RunAsync(workItemHandler, WorkItemPriority::High, WorkItemOptions::TimeSliced); } void Hello2DMain::StopRenderLoop() { m_renderLoopWorker->Cancel(); } void Hello2D::Hello2DMain::Zoom(bool zoomIn) { m_sceneRenderer->Zoom(zoomIn); } void Hello2D::Hello2DMain::ToggleRenderingMode() { m_sceneRenderer->ToggleRenderingMode(); } void Hello2D::Hello2DMain::ToggleFeathering() { m_sceneRenderer->ToggleFeathering(); } // Updates the application state once per frame. void Hello2DMain::Update() { ProcessInput(); // Update scene objects. m_timer.Tick([&]() { // TODO: Replace this with your app's content update functions. m_sceneRenderer->Update(m_timer); m_fpsTextRenderer->Update(m_timer); }); } // Process all input from the user before updating game state void Hello2DMain::ProcessInput() { // TODO: Add per frame input handling here. m_sceneRenderer->TrackingUpdate(m_pointerLocationX); } // Renders the current frame according to the current application state. // Returns true if the frame was rendered and is ready to be displayed. bool Hello2DMain::Render() { // Don't try to render anything before the first Update. if (m_timer.GetFrameCount() == 0) { return false; } // Render the scene objects. // TODO: Replace this with your app's content rendering functions. m_sceneRenderer->Render(); m_fpsTextRenderer->Render(); return true; } // Notifies renderers that device resources need to be released. void Hello2DMain::OnDeviceLost() { m_sceneRenderer->ReleaseDeviceDependentResources(); m_fpsTextRenderer->ReleaseDeviceDependentResources(); } // Notifies renderers that device resources may now be recreated. void Hello2DMain::OnDeviceRestored() { m_sceneRenderer->CreateDeviceDependentResources(); m_fpsTextRenderer->CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); }
package com.example.jobschedulerexample; import android.app.job.JobParameters; import android.app.job.JobService; import android.util.Log; public class ExampleJobService extends JobService { private static final String TAG = "ExampleJobService"; private boolean jobCancelled = false; @Override public boolean onStartJob(JobParameters params) { Log.d(TAG, "Job started"); doInBackground(params); return true; } @Override public boolean onStopJob(JobParameters params) { Log.d(TAG, "Job cancelled before completion"); jobCancelled = true; return true; } private void doInBackground(final JobParameters parameters){ new Thread(new Runnable() { @Override public void run() { for(int i = 0; i<10; i++){ Log.d(TAG, "run: "+i); if(jobCancelled){ return; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Log.d(TAG, "Job finished"); jobFinished(parameters, false); } }).start(); } }
<?php namespace App\Exports; use App\Models\Treatment; use Maatwebsite\Excel\Concerns\FromCollection; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\WithMapping; use Carbon\Carbon; class TreatmentsExport implements FromCollection, WithHeadings, WithMapping { protected $month; public function __construct($month) { $this->month = $month; } public function collection() { $startDate = Carbon::createFromFormat('Y-m', $this->month)->startOfMonth(); $endDate = Carbon::createFromFormat('Y-m', $this->month)->endOfMonth(); return Treatment::with('obats') ->whereBetween('tanggal_pengobatan', [$startDate, $endDate]) ->get(); } public function headings(): array { return [ 'Nama Pasien', 'Usia', 'Alamat', 'No HP', 'Keluhan', 'Jenis Pengobatan', 'Tanggal Pengobatan', 'Harga Perawatan', 'Harga Obat', 'Obat yang Digunakan', ]; } public function map($treatment): array { $obatDetails = $treatment->obats->map(function ($obat) { return $obat->nama . ' (' . $obat->pivot->jumlah_obat . ')'; })->implode(', '); return [ $treatment->nama_pasien, $treatment->usia, $treatment->alamat, $treatment->no_hp, $treatment->keluhan, $treatment->jenis_pengobatan, $treatment->tanggal_pengobatan, $treatment->harga_perawatan, $treatment->harga_obat, $obatDetails, ]; } }
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Links</title> <style> /* SELETORES PERSONALIZADOS # = id . = class : = pseudo-class :: = pseudo-elemento > = clildren */ body { font-family: Arial, Helvetica, sans-serif; } a { color: red; text-decoration: none; font-weight: bold; } a:visited { color: darkred; } a:hover { color: black; text-decoration: underline; } a:active { color: yellow; } .especial { background-color: rgb(230, 108, 108); } .especial::before { content: '✧'; } .especial::after { content: '✧'; } </style> </head> <body> <h1>Personalizando links</h1> <ul> <li><a href="https://gustavoguanabara.github.io"class="especial">Repositório Github...</a></li> <li><a href="https://youtube.com/cursoemvideo/" class="especial">Canal do Youtube...</a></li> <li><a href="https://www.cursoemvideo.com" target="_blan">Site do Curso em Vídeo...</a></li> </ul> </body> </html>
//yi-ting sie //課程練習:class //透過滑鼠的每次點擊,每次產生出五個圓形,並藉由交疊出現的方體,進而浮現出其它的圖形。 //Sheng-Fen Nik Chien (2011), Complexity, 數位學習平台http://moodle.ncku.edu.tw/course/view.php?id=43022 int _num = 5; Circle[] _circleArr = { }; void setup() { size(400, 400); background(255); smooth(); strokeWeight(random(3)); fill(150, 50); drawCircles(); } void draw() { background(255); for (int i=0; i<_circleArr.length; i++) { Circle thisCirc = _circleArr[i]; thisCirc.updateMe(); } } void mouseReleased() { drawCircles(); } void drawCircles() { for (int i=0; i<_num; i++) { Circle thisCirc = new Circle(); thisCirc.drawMe(); _circleArr = (Circle[])append(_circleArr, thisCirc); } } class Circle { float x, y; float radius; color linecol, fillcol; float alph; float xmove, ymove; Circle() { x = random(width); y = random(height); radius = random(100) + 10; linecol = color(random(255), random(255), random(255)); fillcol = color(random(255), random(255), random(255)); alph = random(255);//透明度 xmove = random(10) - 5; ymove = random(10) - 5; } void drawMe() { noStroke(); fill(fillcol, alph); ellipse(x, y, radius*2, radius*2); stroke(linecol, 150); noFill(); ellipse(x, y, 10, 10); } void updateMe() { x += xmove; y += ymove; if (x > (width+radius)) { x=0-radius; } if (x < (0-radius)) { x=width+radius; } if (y > (height+radius)) { y=0-radius; } if (y < (0-radius)) { y=height+radius; } boolean touching = false; for (int i=0; i<_circleArr.length; i++) { Circle otherCirc = _circleArr[i]; if (otherCirc != this) { float dis = dist(x, y, otherCirc.x, otherCirc.y); float overlap = dis - radius - otherCirc.radius; if (overlap < 0) { float midx, midy; midx = (x + otherCirc.x)*2; midy = (y + otherCirc.y)/2; stroke(0, 100); noFill(); overlap *= +1; rect(midx, midy, overlap*10, overlap); } } } //drawMe(); } } void keyPressed() { saveFrame("class003.jpg"); }
from dataclasses import dataclass from enum import Enum, auto from typing import Any, Generator, Optional from string import digits class TokenType(Enum): INT = auto() FLOAT = auto() PLUS = auto() MINUS = auto() EOF = auto() LPAREN = auto() RPAREN = auto() MUL = auto() DIV = auto() MOD = auto() EXP = auto() NEWLINE = auto() def __repr__(self) -> str: return f"{self.__class__.__name__}.{self.name}" CHARS_AS_TOKENS = { "+": TokenType.PLUS, "-": TokenType.MINUS, "*": TokenType.MUL, "/": TokenType.DIV, "%": TokenType.MOD, "(": TokenType.LPAREN, ")": TokenType.RPAREN, "**": TokenType.EXP, "/n": TokenType.EOF, "\n": TokenType.NEWLINE, # Corrected the typo here } @dataclass class Token: type: TokenType value: Any = None class Tokenizer: def __init__(self, code: str)-> None: self.code = code self.ptr: int = 0 self.beginning_of_line = True def peek(self, length: int = 1) -> str: """Returns the substring that will be tokenized next.""" substring = self.code[self.ptr : self.ptr + length] if self.ptr + length <= len(self.code) else "" return substring def next_token(self) -> Token: while self.ptr < len(self.code) and self.code[self.ptr] == " ": self.ptr += 1 if self.ptr == len(self.code): return Token(TokenType.EOF) char = self.code[self.ptr] if char == "\n": self.ptr += 1 if not self.beginning_of_line: self.beginning_of_line = True return Token(TokenType.NEWLINE) else: return self.next_token() self.beginning_of_line = False if self.peek(length=2) == "**": self.ptr += 2 return Token(TokenType.EXP) char = self.code[self.ptr] if char in CHARS_AS_TOKENS: self.ptr += 1 return Token(CHARS_AS_TOKENS[char]) if char in digits or (char == "." and self.peek(2)[1] in digits): integer = self.consume_int() if self.ptr < len(self.code) and self.code[self.ptr] == ".": self.ptr += 1 decimal = self.consume_decimal() if decimal: float_str = f"{integer}.{decimal}" else: float_str = f"{integer}." return Token(TokenType.FLOAT, float(float_str)) return Token(TokenType.INT, int(integer)) raise RuntimeError(f"Can't tokenize {char!r}.") def consume_decimal(self) -> float: """Reads a decimal part that starts with a . and returns it as a float.""" start = self.ptr # Check if there are any digits after the decimal point has_digits = False while self.ptr < len(self.code) and self.code[self.ptr] in digits: has_digits = True self.ptr += 1 # If no digits are found, return 0.0 as the decimal part if not has_digits: return 0.0 decimal = self.code[start:self.ptr] # Handle the case of multiple consecutive dots dot_count = decimal.count(".") if dot_count > 1: raise RuntimeError(f"Invalid float format: {decimal}") # Handle the case where the decimal is at the end of the string if decimal.endswith("."): raise RuntimeError(f"Invalid float format: {decimal}") return float(decimal) def __iter__(self) -> Generator[Token, None, None]: while (token := self.next_token()).type != TokenType.EOF: yield token yield token # Yield thE EOF token too. def consume_int(self) -> str: """Reads an integer from the source code.""" start = self.ptr while self.ptr < len(self.code) and self.code[self.ptr] in digits: self.ptr += 1 return self.code[start:self.ptr] if __name__ == "__main__": code = "1 + .2 + 0.005 + 123.456 - .12 - 73. - 456 - 789" tokenizer = Tokenizer(code) print(code) for tok in tokenizer: print(f"\t{tok.type}, {tok.value}")
package ua.tonkoshkur.weather.session; import jakarta.persistence.EntityManager; import jakarta.persistence.EntityManagerFactory; import jakarta.persistence.Query; import lombok.RequiredArgsConstructor; import ua.tonkoshkur.weather.common.dao.BaseDao; import java.time.LocalDateTime; import java.util.Optional; @RequiredArgsConstructor public class SessionDao extends BaseDao { private final EntityManagerFactory entityManagerFactory; public Optional<Session> findById(String sessionId) { try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { Session session = entityManager.find(Session.class, sessionId); return Optional.ofNullable(session); } } public Session save(Session session) { try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { executeTransactional(entityManager, () -> entityManager.persist(session)); return session; } } public Session update(Session session) { try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { executeTransactional(entityManager, () -> entityManager.merge(session)); return session; } } public void deleteById(String sessionId) { try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { executeTransactional(entityManager, () -> { Session session = entityManager.find(Session.class, sessionId); entityManager.remove(session); }); } } public void deleteByExpiresAtBefore(LocalDateTime dateTime) { String sql = "delete from Session s where expiresAt < :dateTime"; try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { Query query = entityManager.createQuery(sql) .setParameter("dateTime", dateTime); executeTransactional(entityManager, query::executeUpdate); } } public void deleteAll() { String sql = "delete from Session"; try (EntityManager entityManager = entityManagerFactory.createEntityManager()) { Query query = entityManager.createQuery(sql); executeTransactional(entityManager, query::executeUpdate); } } }
<?php namespace App\Http\Livewire\Admin; use App\Models\Category; use Livewire\Component; use illuminate\Support\Str; class AddAdminCategoryComponent extends Component { public $name; public $slug; public function generateslug(){ $this->slug=Str::slug($this->name); } public function updated($fields){ $this->validateOnly($fields,[ 'name'=>'required', 'slug'=>'required|unique:categories' ]); } public function storeCategory() { $this->validate([ 'name'=>'required', 'slug'=>'required|unique:categories' ]); $category=new Category(); $category->name=$this->name; $category->slug=$this->slug; $category->save(); session()->flash('message','Category has been created successfully'); } public function render() { return view('livewire.admin.add-admin-category-component')->layout('layouts.base'); } }
/** * @file document_config.h Declaration of DocumentConfig model node. * * Copyright (c) 2011-2018 Cloudware S.A. All rights reserved. * * This file is part of pg-jsonapi. * * pg-jsonapi is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * pg-jsonapi 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 Affero General Public License * along with pg-jsonapi. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #ifndef CLD_PG_JSONAPI_DOCUMENT_CONFIG_H #define CLD_PG_JSONAPI_DOCUMENT_CONFIG_H #include <stdlib.h> #include <string> #include <map> #include "resource_config.h" namespace pg_jsonapi { /** * @brief Configuration of a JSONAPI document associated to a base URL, * containing general options, resources and their configuration. */ class DocumentConfig { private: typedef std::map<std::string, ResourceConfig> ResourceConfigMap; typedef ResourceConfigMap::iterator ResourceConfigMapIterator; private: // Attributes bool is_valid_; std::string base_url_; std::string query_config_; std::string query_default_config_; bool version_; bool compound_; uint page_size_; uint page_limit_; bool show_links_; bool show_null_; bool restrict_type_; bool restrict_attr_; bool empty_is_null_; std::string default_order_by_; bool use_request_accounting_schema_; bool use_request_sharded_schema_; bool use_request_company_schema_; bool use_request_accounting_prefix_; std::string template_search_path_; std::map<std::string, pg_jsonapi::ResourceConfig> resources_; private: // Methods bool Validate(); ResourceConfig* Resource (const std::string& a_type); public: // Methods DocumentConfig (const std::string a_base_url); virtual ~DocumentConfig (); bool LoadConfigFromDB(bool& o_config_exists); static bool DefaultHasVersion (); static bool DefaultIsCompound (); static uint DefaultPageSize (); static uint DefaultPageLimit (); static uint MaximumPageLimit (); static bool DefaultShowLinks (); static bool DefaultShowNull (); static bool DefaultTypeRestriction(); static bool DefaultAttrRestriction(); static bool DefaultEmptyIsNull(); static bool DefaultRequestAccountingSchema(); static bool DefaultRequestShardedSchema(); static bool DefaultRequestCompanySchema(); static bool DefaultRequestAccountingPrefix(); bool HasVersion () const; bool IsCompound () const; uint PageSize () const; uint PageLimit () const; bool ShowLinks () const; bool ShowNull () const; bool HasTypeRestriction () const; bool HasAttrRestriction () const; bool EmptyIsNull () const; bool UseRequestAccountingSchema () const; bool UseRequestShardedSchema () const; bool UseRequestCompanySchema () const; bool UseRequestAccountingPrefix () const; const std::string& DefaultOrder () const; const std::string& SearchPathTemplate () const; bool ValidateRequest (const std::string& a_type, const std::string& a_related); bool IsIdentifier (const std::string& a_name) const; bool IsValidField (const std::string& a_type, const std::string& a_field) const; const ResourceConfig& GetResource (const std::string& a_type) const; const std::string& ConfigQuery (); }; typedef std::map<std::string, DocumentConfig> DocumentConfigMap; inline bool DocumentConfig::DefaultHasVersion () { return true; } inline bool DocumentConfig::DefaultIsCompound () { return true; } inline uint DocumentConfig::DefaultPageSize () { return 1000; } inline uint DocumentConfig::DefaultPageLimit () { return 20000; } inline uint DocumentConfig::MaximumPageLimit () { return 1048576; // we will not allow to return results above maximum number of lines on excel } inline bool DocumentConfig::DefaultShowLinks () { return true; } inline bool DocumentConfig::DefaultShowNull () { return true; } inline bool DocumentConfig::DefaultTypeRestriction () { return false; } inline bool DocumentConfig::DefaultAttrRestriction () { return false; } inline bool DocumentConfig::DefaultEmptyIsNull () { return false; } inline bool DocumentConfig::DefaultRequestAccountingSchema () { return false; } inline bool DocumentConfig::DefaultRequestShardedSchema () { return false; } inline bool DocumentConfig::DefaultRequestCompanySchema () { return false; } inline bool DocumentConfig::DefaultRequestAccountingPrefix () { return false; } inline bool DocumentConfig::HasVersion () const { return version_; } inline bool DocumentConfig::IsCompound () const { return compound_; } inline uint DocumentConfig::PageSize () const { return page_size_; } inline uint DocumentConfig::PageLimit () const { return page_limit_; } inline bool DocumentConfig::ShowLinks () const { return show_links_; } inline bool DocumentConfig::ShowNull () const { return show_null_; } inline bool DocumentConfig::HasTypeRestriction () const { return restrict_type_; } inline bool DocumentConfig::HasAttrRestriction () const { return restrict_attr_; } inline bool DocumentConfig::EmptyIsNull () const { return empty_is_null_; } inline bool DocumentConfig::UseRequestAccountingSchema () const { return use_request_accounting_schema_; } inline bool DocumentConfig::UseRequestShardedSchema () const { return use_request_sharded_schema_; } inline bool DocumentConfig::UseRequestCompanySchema () const { return use_request_company_schema_; } inline bool DocumentConfig::UseRequestAccountingPrefix () const { return use_request_accounting_prefix_; } inline const std::string& DocumentConfig::DefaultOrder () const { return default_order_by_; } inline const std::string& DocumentConfig::SearchPathTemplate () const { return template_search_path_; } inline bool DocumentConfig::IsIdentifier(const std::string& a_name) const { if ( 0 == strcmp(a_name.c_str(), "id") || 0 == strcmp(a_name.c_str(), "type") ) { return true; } return false; } inline bool DocumentConfig::IsValidField (const std::string& a_type, const std::string& a_field) const { if ( 0 == resources_.count(a_type) ) { return false; } else { return ( resources_.at(a_type).IsField(a_field) || resources_.at(a_type).IsValidAttribute(a_field) ); } } inline const ResourceConfig& DocumentConfig::GetResource (const std::string& a_type) const { return resources_.at(a_type); } inline const std::string& DocumentConfig::ConfigQuery () { if ( 0 == query_config_.size() ) { query_config_ = "SELECT config FROM public.jsonapi_config WHERE prefix = '" + base_url_ + "'"; } return query_config_; } inline pg_jsonapi::ResourceConfig* pg_jsonapi::DocumentConfig::Resource (const std::string& a_type) { std::map<std::string, pg_jsonapi::ResourceConfig>::iterator it = resources_.find(a_type); if ( resources_.end() == it ) { /* if resource does not exist, create it with default values */ resources_.insert( std::pair<std::string,pg_jsonapi::ResourceConfig>(a_type, ResourceConfig(this, a_type)) ); it = resources_.find(a_type); } return &(it->second); } } // namespace pg_jsonapi #endif // CLD_PG_JSONAPI_DOCUMENT_CONFIG_H
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); class ApiFeature { constructor(mongooseQuery, queryString, queryCondition = {}) { this.pageSize = 5; this.page = 1; this.mongooseQuery = mongooseQuery; this.queryString = queryString; this.queryCondition = queryCondition; } //[1]to make pagination paginate() { this.page = (!this.queryString.page || this.queryString.page <= 0) ? this.page : this.queryString.page; this.pageSize = (!this.queryString.pageSize || this.queryString.pageSize <= 0) ? this.pageSize : this.queryString.pageSize; let skip = (this.page - 1) * this.pageSize; this.mongooseQuery.skip(skip).limit(this.pageSize); return this; } //[2] to make filter filter() { let filterObj = Object.assign({}, this.queryString); delete filterObj.page; delete filterObj.sort; delete filterObj.fields; delete filterObj.keyword; let filterObjToStr = JSON.stringify(filterObj); filterObjToStr = filterObjToStr.replace(/\b(gt|gte|lt|lte)\b/g, (match) => `$${match}`); filterObjToStr = JSON.parse(filterObjToStr); this.mongooseQuery.find(filterObj); this.queryCondition = Object.assign(Object.assign({}, this.queryCondition), filterObj); return this; } //[3] to make sort sort() { if (this.queryString.sort) { let sortBy = this.queryString.sort.replace(/,/g, " "); this.mongooseQuery.sort(sortBy); } return this; } //[4] to make search search(conditions) { if (this.queryString.search) { this.mongooseQuery.find(conditions); this.queryCondition = Object.assign(Object.assign({}, this.queryCondition), conditions); } return this; } //[5] to make select fields() { if (this.queryString.fields) { let fields = this.queryString.fields.replace(/,/g, " "); this.mongooseQuery.select(fields); } return this; } //[6] to get the result get() { return __awaiter(this, void 0, void 0, function* () { return yield this.mongooseQuery; }); } //[7] to get the total length getTotal() { return __awaiter(this, void 0, void 0, function* () { return yield this.mongooseQuery.model.countDocuments(this.queryCondition); }); } } exports.default = ApiFeature; // ex to use // const getAllUser = catchError(async (request, response, next) => { // let apiFeature = new ApiFeature(userModel.find(), request.query) // .paginate() // .filter() // .fields() // .search() // .sort(); // //? execute query // let result = await apiFeature.mongooseQuery; // response.status(200).json({ // message: "Done 😃", // result, // }); // });
package com.example.christopher.countries; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; public class CountryAdapter extends RecyclerView.Adapter<MyViewHolder> { private static final String TAG = "CountryAdapter"; private List<Country> countryList; private MainActivity mainAct; public CountryAdapter(List<Country> empList, MainActivity ma) { this.countryList = empList; mainAct = ma; } @NonNull @Override public MyViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) { Log.d(TAG, "onCreateViewHolder: MAKING NEW"); View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.country_entry, parent, false); itemView.setOnClickListener(mainAct); itemView.setOnLongClickListener(mainAct); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull MyViewHolder holder, int position) { Country country = countryList.get(position); holder.country.setText(country.getName()); holder.capital.setText("Capital: " + country.getCapital()); holder.population.setText("Population: " + String.format("%,d", country.getPopulation())); holder.region.setText(country.getRegion()); holder.subRegion.setText(country.getSubRegion()); } @Override public int getItemCount() { return countryList.size(); } }
import { NestFactory } from '@nestjs/core'; import { FastifyAdapter, NestFastifyApplication, } from '@nestjs/platform-fastify'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { AppModule } from './app.module'; import { convertBoolStrToBoolean } from './common/helpers'; import { validationPipe } from './common/pipes'; import { AppConfigService } from './config/app-config.service'; import { FilmStatsModule } from './modules/film-stats'; import { FilmStatsSubscriber } from './systems/service-bus/film-stats.subscriber'; import { INestApplication } from '@nestjs/common'; const configureEdgeService = async (app: INestApplication) => { const filmStatsSubscriber = app .select(FilmStatsModule) .get(FilmStatsSubscriber); await filmStatsSubscriber.subscribe(); }; async function bootstrap() { const app = await NestFactory.create<NestFastifyApplication>( AppModule, new FastifyAdapter(), ); const configService = app.get<AppConfigService>(AppConfigService); const HOST = configService.get<string>('NEST_HOST'); const PORT = configService.get<string>('NEST_PORT'); const GLOBAL_PREFIX = configService.get<string>('GLOBAL_PREFIX'); app.setGlobalPrefix(GLOBAL_PREFIX); const ENABLE_SWAGGER = configService.get<string>('ENABLE_SWAGGER'); if (convertBoolStrToBoolean(ENABLE_SWAGGER)) { const swaggerConfig = new DocumentBuilder() .setTitle(configService.get('npm_package_name')) .setVersion(configService.get('npm_package_version')) .addBearerAuth() .build(); const document = SwaggerModule.createDocument(app, swaggerConfig); const SWAGGER_DOCS_PATH = configService.get<string>('SWAGGER_DOCS_PATH'); SwaggerModule.setup(SWAGGER_DOCS_PATH, app, document); } app.useGlobalPipes(validationPipe).enableCors(); await configureEdgeService(app); await app.listen(PORT, HOST, () => { console.log(`Server listens on http://${HOST}:${PORT}`); }); } bootstrap();
<!DOCTYPE html> <html lang="en"> <head> <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> <link href="https://fonts.googleapis.com/css?family=Share+Tech|Share+Tech+Mono" rel="stylesheet" /> <link href="./css/style.css" rel="stylesheet"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1"> <meta name="robots" content="index, follow, noodp"> <meta name="googlebot" content="index, follow"> <meta name="google" content="notranslate"> <meta name="format-detection" content="telephone=no"> <title>The test site of an institute</title> </head> <body> <!-- Button of the right menu --> <div class="rightmenu" onclick="modal.show('openModal');"> <svg xmlns="http://www.w3.org/2000/svg" class="" height="50px" viewBox="4 0 24 24" width="24px" fill="#fff"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/></svg> </div> <!-- MODAL WINDOW --> <div id="openModal" class="modal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Title and close button of modal --> <div class="modal-header"> <h3 class="modal-title">Add new sections</h3> <a onclick="modal.close('openModal');" title="Close" class="close">x</a> </div> <!-- Content --> <div class="modal-body" style="min-height: 350px;"> <!-- Main menu - list of buttons --> <div class="btnsmodal"> <div id="link_course" class="row smodal" onclick="nav_modal(this.id)">New course</div> <div id="link_newsubject" class="row smodal" onclick="nav_modal(this.id)">New subject</div> <div id="link_teachers" class="row smodal" onclick="nav_modal(this.id)">New teacher</div> <div id="link_students" class="row smodal" onclick="nav_modal(this.id)">New student</div> </div> <!-- forms to add data --> <div id="add_data" class="container collapse"> <!-- arrow to back to main menu and reset forms --> <div class="btn_arrow" onclick="resetmodal()"><div class="arrow left"></div></div> <div id="link_course_newdata" class="newdata collapse"> <!-- New Course --> <form id="form_course" action="" style="margin-top: 20px;"> <fieldset> <legend>Create new Course</legend> <div class="input-group"> <label class="input-group-text" for="selected_facultet" style="font-size: 1rem;">Faculty</label> <select class="form-select" id="selected_faculty" required aria-placeholder="Choose"></select> </div> <div class="input-group"> <input id="inp_course" class="form-control" type="text" minlength="5" maxlength="20" required placeholder="Title course"> <button type="submit">Go</button> </div> </fieldset> </form> </div> <!-- New subject --> <div id="link_newsubject_newdata" class="newdata collapse"> <form id="form_newsubject" action="" style="margin-top: 20px;"> <fieldset> <legend>Create new subject</legend> <div class="input-group"> <label class="input-group-text" for="selected_course" style="font-size: 1rem;">Course</label> <select class="form-select" id="selected_course" required aria-placeholder="Choose"></select> </div> <div class="input-group"> <input id="inp_newsubject" class="form-control" type="text" minlength="5" maxlength="20" required placeholder="Title subject"> <button type="submit">Go</button> </div> </fieldset> </form> </div> <!-- New teacher --> <div id="link_teachers_newdata" class="newdata collapse"> <form id="form_teacher" action="" style="margin-top: 20px;"> <fieldset> <legend>Add new teacher</legend> <div class="input-group"> <label class="input-group-text" for="selected_subject" style="font-size: 1rem;">Subject</label> <select class="form-select" id="selected_subject" required aria-placeholder="Choose"></select> </div> <div class="input-group"> <input id="inp_teacher_name" class="form-control" type="text" minlength="5" maxlength="20" required placeholder="Surname teacher"> </div> <div class="input-group"> <span class="input-group-text">€</span> <input id="inp_teacher_salary" class="form-control" type="number" minlength="1" maxlength="8" required placeholder="Salary"> <input id="inp_teacher_birth" class="form-control" type="date" minlength="5" maxlength="20" required> </div> <button class="btn" type="submit" style="margin-left:80%;">Go</button> </fieldset> </form> </div> <!-- Add student --> <div id="link_students_newdata" class="newdata collapse"> <form id="form_student" action="" style="margin-top: 20px;"> <fieldset> <legend>Add new student</legend> <div class="input-group"> <label class="input-group-text" for="selected_course_student" style="font-size: 1rem;">Course</label> <select class="form-select" id="selected_course_student" required aria-placeholder="Choose"></select> </div> <div class="input-group"> <input id="inp_teacher_name" class="form-control" type="text" minlength="5" maxlength="20" required placeholder="Surname student"> </div> <div class="input-group"> <span class="input-group-text">Reg No</span> <input id="inp_student_regnum" class="form-control" type="number" minlength="5" maxlength="5" required placeholder="12345"> <input id="inp_student_birth" class="form-control" type="date" minlength="5" maxlength="20" required> </div> <button class="btn" type="submit" style="margin-left:80%;">Go</button> </fieldset> </form> </div> </div> </div> </div> </div> </div> <!-- MODAL END --> <!-- navbar --> <nav id="navbar" class="navbar"> <h4 class="logottl">Management System</h4> <!-- Stylize of button of main menu --> <input class="menu-btn" type="checkbox" style="display: none;" id="menu-btn" /> <label class="menu-icon" for="menu-btn"><span class="navicon"></span></label> <ul class="link-group"> <li class="link"><a href="#">Faculties</a></li> <li class="link"><a href="#">Teachers</a></li> <li class="link"><a href="#">Students</a></li> <li class="link"><a href="#" onclick="window.location.reload()">Logout</a></li> </ul> </nav> <!-- Main Part of site --> <!-- Logo and title of the top of site --> <header class="container" style="margin-top:100px; border: 1px #000;"> <div class="row"> <div class="col-sm-5" style="text-align:center;"> <img id="logo" src="./img/logo.png" alt="Test University"> </div> <div id="title" class="col-sm-6" style="margin: auto;text-align: center;">Faculties and courses</div> <div class="col-md-1"></div> </div> </header> <!-- Faculties --> <section id="sec_faculty" class="container active"></section> <!-- Teachers --> <section id="sec_teachers" class="container"> <div class="row"> Teachers </div> </section> <!-- Students --> <section id="sec_students" class="container"> <div class="row"> Students </div> </section> <!-- narrow-button to up on the top of site--> <a id="narrowup" type="button" onclick="slowscroll()"> <svg xmlns="http://www.w3.org/2000/svg" style="right:25px;bottom:25px;z-index:2;position:fixed;" width="20" height="20" fill="#837a7a" class="bi bi-arrow-up" viewBox="0 0 16 16"> <path fill-rule="evenodd" d="M8 15a.5.5 0 0 0 .5-.5V2.707l3.146 3.147a.5.5 0 0 0 .708-.708l-4-4a.5.5 0 0 0-.708 0l-4 4a.5.5 0 1 0 .708.708L7.5 2.707V14.5a.5.5 0 0 0 .5.5z"></path> </svg> </a> <!-- temp.js is a file with template of objects --> <script src="./js/temp.js"></script> <!-- Main JS --> <script src="./js/app.js"></script> </body> </html>
import { Complex, Complex2d, cdiv, cmult } from "../../mathVector/Complex2d" import { BSplineR1toC2 } from "../R1toC2/BSplineR1toC2" export class RationalBSplineR1toC1 { private readonly spline: BSplineR1toC2 /** * Create a B-Spline * @param controlPoints The control points array * @param knots The knot vector */ constructor(controlPoints: Complex2d[] = [new Complex2d({x: 0, y: 0}, {x: 1, y: 0})], knots: number[] = [0, 1]) { this.spline = new BSplineR1toC2(controlPoints, knots) } get knots() : number[] { return this.spline.knots } get degree() : number { return this.spline.degree } get controlPoints(): Complex2d[] { return this.spline.controlPoints } evaluate(u: number) : Complex { const result = this.spline.evaluate(u) const p = cdiv(result.c0, result.c1) return {x: p.x, y: p.y} } controlPoints2D() : Complex[] { let result: Complex[] = [] for (let cp of this.spline.controlPoints) { const p = cdiv(cp.c0, cp.c1) result.push({x: p.x, y: p.y}) } return result } clone(): RationalBSplineR1toC1 { return new RationalBSplineR1toC1(this.spline.controlPoints, this.spline.knots) } insertKnot(u: number, times: number = 1) { let s = this.spline.insertKnot(u, times) return new RationalBSplineR1toC1(s.controlPoints, s.knots) } setControlPointPosition(index: number, value: Complex2d) { const s = this.spline.setControlPointPosition(index, value) return new RationalBSplineR1toC1(s.controlPoints, s.knots) } setControlPointWeight(controlPointIndex: number, w: Complex) { const c0 = this.controlPoints[controlPointIndex].c0 const c1 = this.controlPoints[controlPointIndex].c1 const s = this.setControlPointPosition(controlPointIndex, new Complex2d(cdiv(cmult(c0, w), c1), w)) return new RationalBSplineR1toC1(s.controlPoints, s.knots) } getControlPointWeight(controlPointIndex: number) { return this.controlPoints[controlPointIndex].c1 } distinctKnots() { let result = [this.knots[0]] let temp = result[0] for (let i = 1; i < this.knots.length; i += 1) { if (this.knots[i] !== temp) { result.push(this.knots[i]); temp = this.knots[i]; } } return result; } grevilleAbscissae() { let result = [] for (let i = 0; i < this.spline.controlPoints.length; i += 1) { let sum = 0 for (let j = i + 1; j < i + this.spline.degree + 1; j += 1) { sum += this.spline.knots[j] } result.push(sum / this.spline.degree) } return result } }
using System; using System.Collections.Generic; namespace EightPuzzleProblem { class Program { static void Main(string[] args) { Console.WriteLine("Enter the start state of the puzzle (9 integers, separated by spaces):"); int[,] start = ReadPuzzle(); Console.WriteLine("Start puzzle:"); PrintPuzzle(start); Console.WriteLine("Enter the goal state of the puzzle (9 integers, separated by spaces):"); int[,] goal = ReadPuzzle(); Console.WriteLine("Goal puzzle:"); PrintPuzzle(goal); List<Tuple<int[,], int>> solution = Solve(start, goal); if (solution == null) { Console.WriteLine("No solution found"); return; } Console.WriteLine("Solution:"); foreach (var step in solution) { Console.WriteLine("solution {0}:", step.Item2); PrintPuzzle(step.Item1); Console.WriteLine(); } Console.ReadLine(); } // to covert the number that you give to int and convert 1D to 2D matrix static int[,] ReadPuzzle() { int[,] puzzle = new int[3, 3]; string[] input = Console.ReadLine().Split(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { puzzle[i, j] = int.Parse(input[i * 3 + j]); } } return puzzle; } // to make sure that the program find the goal static bool IsSolved(int[,] puzzle, int[,] goal) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (puzzle[i, j] != goal[i, j]) { return false; } } } return true; } // to find the blank place which is zero static void FindZero(int[,] puzzle, out int row, out int col) { row = col = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (puzzle[i, j] == 0) { row = i; col = j; return; } } } } // this will start to solve the program static List<Tuple<int[,], int>> Solve(int[,] start, int[,] goal) { List<Tuple<int[,], int>> solution = new List<Tuple<int[,], int>>(); Queue<Tuple<int[,], int>> q = new Queue<Tuple<int[,], int>>(); q.Enqueue(Tuple.Create(start, 0)); while (q.Count > 0) { Tuple<int[,], int> state = q.Dequeue(); int[,] puzzle = state.Item1; int step = state.Item2; if (IsSolved(puzzle, goal)) { solution.Add(state); return solution; } int row, col; FindZero(puzzle, out row, out col); if (row > 0) { int[,] newPuzzle = (int[,])puzzle.Clone(); newPuzzle[row, col] = newPuzzle[row - 1, col]; newPuzzle[row - 1, col] = 0; q.Enqueue(Tuple.Create(newPuzzle, step + 1)); solution.Add(Tuple.Create(newPuzzle, step + 1)); } if (row < 2) { int[,] newPuzzle = (int[,])puzzle.Clone(); newPuzzle[row, col] = newPuzzle[row + 1, col]; newPuzzle[row + 1, col] = 0; q.Enqueue(Tuple.Create(newPuzzle, step + 1)); solution.Add(Tuple.Create(newPuzzle, step + 1)); } if (col > 0) { int[,] newPuzzle = (int[,])puzzle.Clone(); newPuzzle[row, col] = newPuzzle[row, col - 1]; newPuzzle[row, col - 1] = 0; q.Enqueue(Tuple.Create(newPuzzle, step + 1)); solution.Add(Tuple.Create(newPuzzle, step + 1)); } if (col < 2) { int[,] newPuzzle = (int[,])puzzle.Clone(); newPuzzle[row, col] = newPuzzle[row, col + 1]; newPuzzle[row, col + 1] = 0; q.Enqueue(Tuple.Create(newPuzzle, step + 1)); solution.Add(Tuple.Create(newPuzzle, step + 1)); } } return null; } // print the input as 3*3 matrix static void PrintPuzzle(int[,] puzzle) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Console.Write("{0} ", puzzle[i, j]); } Console.WriteLine(); } } } }
<?php namespace App\Entity; use App\Repository\DrinkRepository; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; #[ORM\Entity(repositoryClass: DrinkRepository::class)] class Drink { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; #[ORM\Column(length: 255)] #[Assert\Regex('/^[a-zA-ZÀ-ÿ\s\-\0-9]/', message: 'Only letters and numbers.')] #[Assert\Length( min: 10, max: 25, minMessage: 'Name must be at least {{ limit }} characters long', maxMessage: 'Name must be no longer than {{ limit }} characters' )] private ?string $name = null; #[ORM\Column(length: 255)] #[Assert\Regex('/^[a-zA-ZÀ-ÿ\s\0-9_.-]*$/', message: 'Only numbers and letters and spaces.')] #[Assert\Length( min: 20, max: 140, minMessage: 'Description must be at least {{ limit }} characters long', maxMessage: 'Description must be no longer than {{ limit }} characters' )] private ?string $description = null; #[ORM\Column] #[Assert\Positive] #[Assert\Range( min: 5, max: 50, notInRangeMessage: "Price must be between {{ min }} and {{ max }}." )] private ?float $price = null; #[ORM\Column(length: 255)] #[Assert\NotBlank] private ?string $illustration = null; #[ORM\ManyToOne(inversedBy: 'drinks')] #[ORM\JoinColumn(nullable: true)] private ?DrinkCategory $drinkcategory = null; public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): static { $this->name = $name; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): static { $this->description = $description; return $this; } public function getPrice(): ?float { return $this->price; } public function setPrice(float $price): static { $this->price = $price; return $this; } public function getIllustration(): ?string { return $this->illustration; } public function setIllustration(string $illustration): static { $this->illustration = $illustration; return $this; } public function getDrinkcategory(): ?DrinkCategory { return $this->drinkcategory; } public function setDrinkcategory(?DrinkCategory $drinkcategory): static { $this->drinkcategory = $drinkcategory; return $this; } }
--- keywords: Investing,Cryptocurrency,Altcoins title: الأثير (ETH) description: الأثير هو العملة المشفرة لشبكة إيثريوم. تتطلب جميع البرامج المرتبطة بشبكة Ethereum قوة حوسبة ؛ الأثير هو الرمز المميز المستخدم للدفع مقابل هذه القوة. --- # الأثير (ETH) ## ما هو الأثير (ETH)؟ الأثير هو رمز المعاملات الذي يسهل العمليات على شبكة إيثريوم. تتطلب جميع البرامج والخدمات المرتبطة بشبكة Ethereum قوة حوسبة (وهذه القوة الحاسوبية ليست مجانية). الأثير هو شكل من أشكال الدفع للمشاركين في الشبكة لتنفيذ العمليات المطلوبة على الشبكة. بينما يمكن اعتبار الأثير العملة المشفرة لشبكة Ethereum ، بالمعنى المجازي ، فمن الأكثر دقة الإشارة إليه على أنه "وقود" الشبكة. يقوم الأثير بتتبع وتسهيل جميع المعاملات في الشبكة. تختلف هذه العملية بشكل ملحوظ عن طريقة عمل [العملة المشفرة القياسية](/cryptocurrency). ومع ذلك ، فإن الإيثر لديه بعض الخصائص التي تجعله مشابهًا للعملات المشفرة الأخرى ، مثل البيتكوين. ## فهم الأثير (ETH) تستخدم تقنية Ethereum تطوير blockchain لاستبدال تخزين بيانات المستهلك ، بما في ذلك السجلات المالية ، من قبل شركات الإنترنت التابعة لجهات خارجية. blockchain هو نوع فريد من قواعد البيانات ؛ في blockchain ، يتم تخزين البيانات في كتل مرتبطة ببعضها البعض بترتيب زمني. تم استخدام Blockchain في الأصل لتسجيل معاملات البيتكوين. اليوم ، يوفر الأساس لمعظم العملات المشفرة الرئيسية. يهدف نموذج Ethereum إلى خلق موقف تكون فيه البيانات الشخصية للمستهلكين أقل عرضة للقرصنة لأنه لا توجد شركة واحدة تقوم بتخزينها. مثل العملات المشفرة الأخرى ، فإن الأثير هو وسيلة للتبادل. ومع ذلك ، على عكس العملات المشفرة الأخرى ، لا يمكن استخدام الرموز المميزة إلا لغرض واحد محدد: لتسهيل حساب التطبيقات اللامركزية على شبكة Ethereum. يمكن للمستخدمين استبدال العملات المشفرة الأخرى برموز الإيثر ، ولكن لا يمكن استبدال الرموز المميزة للإيثر بعملات مشفرة أخرى لتوفير قوة الحوسبة لمعاملات Ethereum. تدعم شبكة Ethereum إنشاء وتشغيل تطبيقات رقمية لامركزية - تسمى [dapps](/decentralized-applications-dapps) - للاستخدام الشخصي والتجاري. يتم تعقب الموارد الحسابية المطلوبة لتنفيذ هذه العمليات ودفع ثمنها باستخدام الرموز المميزة للإيثر. قد يحتاج المطور الذي ينشئ تطبيقات Ethereum إلى دفع رسوم لاستضافة التطبيقات وتنفيذها على شبكة Ethereum ، وقد يحتاج المستخدم الذي يستخدم هذه التطبيقات إلى الدفع مقابل استخدام التطبيق. تعمل الأثير كوسيط للسماح بمثل هذه المدفوعات. المطور الذي ينشئ تطبيقًا يستخدم الحد الأدنى من موارد الشبكة سيدفع عددًا أقل من رموز الإيثر مقارنةً بالمطور الذي ينشئ تطبيقات عالية الموارد. تمامًا كما يتطلب المحرك غير الفعال مزيدًا من الوقود - ويستهلك المحرك الفعال وقودًا أقل - تتطلب التطبيقات المتعطشة للبيانات مزيدًا من الأثير لمعالجة المعاملات. كلما احتاج التطبيق إلى مزيد من القوة والوقت الحسابيين ، زادت رسوم الأثير التي يتم تحصيلها مقابل إكمال الإجراء. ## كيف يختلف إيثر عن بيتكوين؟ إيثر هي ثاني أكبر عملة افتراضية في العالم من حيث القيمة السوقية اعتبارًا من عام 2021. وهي في المرتبة الثانية بعد بيتكوين (BTC) ، وفقًا للقيمة السوقية. تم إصدار Bitcoin لأول مرة في 3 يناير 2009 ، بينما تم إطلاق blockchain الحية لـ Ethereum في 30 يوليو 2015. على عكس Bitcoin ، لا يوجد حد أقصى للعدد الإجمالي لرموز ether - فهو يتغير وينمو باستمرار وفقًا للطلب. نتيجة لذلك ، فإن سلسلة Ethereum blockchain أكبر بكثير من blockchain للبيتكوين ، ومن المتوقع أن تستمر في تجاوز البيتكوين في المستقبل. الفرق الرئيسي الآخر بين الاثنين هو أنه في حين أن blockchain البيتكوين هو مجرد دفتر حسابات ، يمكن للمساهمين في Ethereum blockchain إنشاء المزيد من التعليمات البرمجية في المعاملات ، وإنشاء ما يسمى "العقود الذكية". لذلك قد تحتوي المعاملات على شبكة Ethereum على رمز قابل للتنفيذ ، بينما يتم استخدام البيانات المتصلة بمعاملات شبكة Bitcoin بشكل عام فقط لحفظ السجلات. يختلف مقدار الوقت الذي يستغرقه إنشاء كتلة جديدة أيضًا بين العملتين الافتراضيتين أيضًا. يمكن تأكيد كتلة جديدة في Ethereum blockchain في ثوانٍ ، بينما يستغرق الأمر دقائق لحدوث مكافئ البيتكوين. والأهم من ذلك ، أن الأهداف العامة للشبكات مختلفة. كنظام دفع لامركزي آمن من نظير إلى نظير ، تم إنشاء Bitcoin ليكون بديلاً للعملات التقليدية. تم إنشاء منصة Ethereum لتسهيل العقود والتطبيقات ، والأثير هو الوسيط الذي يتم من خلاله جعل هذه المعاملات ممكنة. لم يكن القصد من إيثر أبدًا أن تكون عملة بديلة أو أن تحل محل وسائل التبادل الأخرى. بدلاً من ذلك ، الغرض منه هو تسهيل واستثمار عمليات منصة Ethereum. نظريًا ، يجب ألا تتنافس هاتان التقنيتان مع بعضهما البعض ؛ تدعم سلسلة Ethereum blockchain عملة البيتكوين بالفعل. لذلك في حين أنهم لا يتنافسون مع بعضهم البعض من منظور وظيفي - لأنهم تم تطويرهم لأسباب مختلفة ولديهم ديناميكيات داخلية مختلفة - فقد اجتذب كلاهما مبالغ ضخمة من الاستثمار من المستثمرين. لذلك يمكن القول أن التقنيتين تتنافسان على أموال المستثمرين. ## خطط الأثير بدأ مطورو Ethereum العمل على تحويل الشبكة من نظام إثبات العمل (PoW) إلى نظام إثبات الحصة (PoS) في عام 2017. تُعرف الشبكة الأساسية الجديدة باسم Ethereum 2.0. الغرض من الترقية إلى Ethereum 2.0 هو جعل الشبكة الأساسية أسرع وأكثر أمانًا. يقول مؤيدو الترقية المخطط لها إنها سمحت بإجراء آلاف المعاملات الإضافية كل ثانية. في نظام إثبات العمل ، يتنافس ما يسمى ب "عمال المناجم" مع بعضهم البعض لحل المشكلات الرياضية الصعبة من أجل التحقق من صحة المعاملات عبر أجهزة الكمبيوتر الخاصة بهم. مع نظام PoS الجديد ، ستعتمد شبكة Ethereum على "stakers" (بدلاً من عمال المناجم) ، الذين يمتلكون بالفعل بعض رموز ether ، لمعالجة جميع المعاملات الجديدة. من أجل التحقق من صحة معاملة على شبكة Ethereum 2.0 ، يجب على صاحب الحساب إيداع رموز ether في محفظة cryptocurrency. لإيداع الرموز المميزة للإيثر في المحفظة ، يجب أن يستخدم المخترعون عقدًا ذكيًا (عقد على blockchain Ethereum يتم تنفيذه تلقائيًا باستخدام رمز). على عكس نظام إثبات العمل (PoW) ، لا يحتاج المشغلون إلى استخدام كميات كبيرة من القوة الحسابية لأنهم يتم اختيارهم عشوائيًا ولا يتنافسون مع عمال المناجم الآخرين. لا يحتاج المجرمون إلى تعدين الكتل ؛ بدلاً من ذلك ، يقومون بإنشاء كتل عند تحديدها والتحقق من صحة الكتل المقترحة عندما لا تكون كذلك. تُعرف عملية التحقق هذه باسم "التصديق". وفقًا لموقع Ethereum على الويب ، يمكنك التفكير في الشهادة كقولك "هذه الكتلة تبدو جيدة بالنسبة لي". يمكن للمشاركين في هذه العملية ربح مكافآت لاقتراح كتل جديدة وللتصديق على تلك التي رأوها. في 2 ديسمبر 2020 ، قدم مؤسس Ethereum ، Vitalik Buterin ، خارطة طريق لإصدار Ethereum 2.0. وعلى الرغم من إنشاء الكتلة الأولى من سلسلة Ethereum blockchain الجديدة في 1 ديسمبر 2020 ، فقد أوضحت خارطة الطريق أن التنفيذ الكامل لـ Ethereum سيستغرق بعض الوقت. على الرغم من أن النظام الأساسي قد تحول رسميًا إلى الإصدار 2.0 ، إلا أنه لا يزال يعتمد على المعدنين للحصول على قوة الحوسبة. ## يسلط الضوء - بينما يمكن اعتبار الأثير العملة المشفرة لشبكة Ethereum ، بالمعنى المجازي ، فمن الأصح الإشارة إليه على أنه "وقود" الشبكة. - تستخدم تقنية Ethereum تطوير blockchain لاستبدال تخزين بيانات المستهلك ، بما في ذلك السجلات المالية ، من قبل شركات الإنترنت التابعة لجهات خارجية. - إيثر هي ثاني أكبر عملة افتراضية في العالم من حيث القيمة السوقية اعتبارًا من عام 2021 ؛ تأتي في المرتبة الثانية بعد Bitcoin (BTC) ، وفقًا للقيمة السوقية. - بدأ مطورو Ethereum العمل على تحويل الشبكة من نظام إثبات العمل (PoW) إلى نظام إثبات الحصة (PoS) في عام 2017 ؛ تُعرف الشبكة الأساسية الجديدة باسم Ethereum 2.0 ولم يتم إصدارها بالكامل بعد. - الأثير هو رمز المعاملات الذي يسهل العمليات على شبكة إيثريوم.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="images/favicon.png" type="image/x-icon"> <link href="https://cdn.jsdelivr.net/npm/remixicon@2.5.0/fonts/remixicon.css" rel="stylesheet"> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" /> <link rel="stylesheet" href="styles.css"> <title>Island</title> </head> <body> <header class="header" id="header"> <nav class="nav container"> <a href="#" class="nav__logo">Travel</a> <div class="nav__menu" id="nav-menu"> <ul class="nav__list"> <li class="nav__item"> <a href="#" class="nav__link active">Home</a> </li> <li class="nav__item"> <a href="#about" class="nav__link">About</a> </li> <li class="nav__item"> <a href="#discover" class="nav__link">Discover</a> </li> <li class="nav__item"> <a href="#place" class="nav__link">Place</a> </li> </ul> <div class="nav__dark"> <span class="change-theme-name">Dark mode</span> <i class="ri-moon-line mode-change"></i> </div> <i class="ri-close-line nav__close" id="nav-close"></i> </div> <div class="nav__toggle" id="nav-toggle"> <i class="ri-function-line"></i> </div> </nav> </header> <main class="main"> <!-- HOME --> <section class="home" id="home"> <img src="images/home1.jpg" alt="" class="home__img"> <div class="home__container container grid"> <div class="home__data"> <span class="home__data-subtitle">Discover your place</span> <h1 class="home__data-title">Explore The <br> Best <b>Beautiful <br> Beaches</b></h1> <a href="#" class="button">Explore</a> </div> <div class="home__social"> <a href="#" class="home__social-link"> <i class="ri-facebook-fill"></i> </a> <a href="#" class="home__social-link"> <i class="ri-instagram-line"></i> </a> <a href="#" class="home__social-link"> <i class="ri-twitter-line"></i> </a> </div> <div class="home__info"> <div> <span class="home__info-title">5 best places to visit</span> <a href="#" class="home__info--button button button--flex button--link"> More <i class="ri-arrow-right-line"></i> </a> </div> <div class="home__info-overlay"> <img src="images/home2.jpg" alt="" class="home__info-img"> </div> </div> </div> </section> <section class="about section" id="about"> <div class="about__container container grid"> <div class="about__data"> <h2 class="section__title">More Information <br> About The Best Beaches </h2> <p class="about__description"> You can find the most beautiful and pleasant places at the best prices with special discounts, you choose the place we will guide you all the way to wait, get your place now. </p> <a href="#" class="button">Reverse place</a> </div> <div class="about__img"> <div class="about__img-overlay"> <img src="images/about1.jpg" alt="" class="about__img-one"> </div> <div class="about__img-overlay"> <img src="images/about2.jpg" alt="" class="about__img-two"> </div> </div> </div> </section> <!-- DISCOVER --> <section class="discover section" id="discover"> <h2 class="section__title"> Discover The Most <br> Attractive Places </h2> <div class="discover__container container swiper-container"> <div class="swiper-wrapper"> <div class="discover__card swiper-slide"> <img src="images/discover1.jpg" alt="" class="discover__img"> <div class="discover__data"> <h2 class="discover__title">Bali</h2> <span class="discover__description">15 tours available</span> </div> </div> <div class="discover__card swiper-slide"> <img src="images/discover2.jpg" alt="" class="discover__img"> <div class="discover__data"> <h2 class="discover__title">Hawaii</h2> <span class="discover__description">15 tours available</span> </div> </div> <div class="discover__card swiper-slide"> <img src="images/discover3.jpg" alt="" class="discover__img"> <div class="discover__data"> <h2 class="discover__title">Havr</h2> <span class="discover__description">18 tours available</span> </div> </div> <div class="discover__card swiper-slide"> <img src="images/discover4.jpg" alt="" class="discover__img"> <div class="discover__data"> <h2 class="discover__title">Whitehaven</h2> <span class="discover__description">24 tours available</span> </div> </div> </div> </div> </section> <!-- EXPERIENCE --> <section class="experience section"> <h2 class="section__title"> With Our Experience <br> We Will Serve You </h2> <div class="experience__container container grid"> <div class="experience__content grid"> <div class="experience__data"> <h2 class="experience__number">20</h2> <span class="experience__description">Year <br>Experience </span> </div> <div class="experience__data"> <h2 class="experience__number">75</h2> <span class="experience__description">Complete <br>Tour </span> </div> <div class="experience__data"> <h2 class="experience__number">20</h2> <span class="experience__description">Tourist <br>Destination </span> </div> </div> <div class="experience__img grid"> <div class="experience__img-overlay"> <img src="images/experience1.jpg" alt="" class="experience__img-one"> </div> <div class="experience__img-overlay"> <img src="images/experience2.jpg" alt="" class="experience__img-two"> </div> </div> </div> </section> <!-- VIDEO TOUR --> <section class="video section"> <div class="video__container container grid"> <div class="video__data"> <h2 class="section__title">Video Tour</h2> <p class="video__description">Find out more with our video of the most beautiful and pleasant places for you and your family.</p> </div> <div class="video__content"> <video src="video/video.mp4" class="video-id" type='video/mp4'></video> <button class="button button--flex button__video"> <i class="ri-play-line button__video-icon"></i> </button> </div> </div> </section> <!-- CHOOSE place --> <section class="place section" id="place"> <h2 class="section__title">Choose Your Place</h2> <div class="place__container container grid"> <div class="place__card"> <img src="images/place1.jpg" alt=""> <div class="place__card-content"> <span class="place__card-rate"><i class="ri-star-line">4.8 </i></span> <div class="place__card-data"> <h2 class="place__title">Bali</h2> <p class="place__subtitle">Indonesia</p> <h2 class="place__price">$2499</h2> </div> <button class="button button--flex button__place"> <i class="ri-arrow-right-line"></i> </button> </div> </div> <div class="place__card"> <img src="images/place2.jpg" alt=""> <div class="place__card-content"> <span class="place__card-rate"><i class="ri-star-line">4.8 </i></span> <div class="place__card-data"> <h2 class="place__title">Bali</h2> <p class="place__subtitle">Indonesia</p> <h2 class="place__price">$2499</h2> </div> <button class="button button--flex button__place"> <i class="ri-arrow-right-line"></i> </button> </div> </div> <div class="place__card"> <img src="images/place3.jpg" alt=""> <div class="place__card-content"> <span class="place__card-rate"><i class="ri-star-line">4.8 </i></span> <div class="place__card-data"> <h2 class="place__title">Bali</h2> <p class="place__subtitle">Indonesia</p> <h2 class="place__price">$2499</h2> </div> <button class="button button--flex button__place"> <i class="ri-arrow-right-line"></i> </button> </div> </div> <div class="place__card"> <img src="images/place4.jpg" alt=""> <div class="place__card-content"> <span class="place__card-rate"><i class="ri-star-line">4.8 </i></span> <div class="place__card-data"> <h2 class="place__title">Bali</h2> <p class="place__subtitle">Indonesia</p> <h2 class="place__price">$2499</h2> </div> <button class="button button--flex button__place"> <i class="ri-arrow-right-line"></i> </button> </div> </div> <div class="place__card"> <img src="images/place5.jpg" alt=""> <div class="place__card-content"> <span class="place__card-rate"><i class="ri-star-line">4.8 </i></span> <div class="place__card-data"> <h2 class="place__title">Bali</h2> <p class="place__subtitle">Indonesia</p> <h2 class="place__price">$2499</h2> </div> <button class="button button--flex button__place"> <i class="ri-arrow-right-line"></i> </button> </div> </div> </div> </section> <section class="subcribe section"> <div class="subcribe__bg"> <div class="subcribe__container container grid"> <h2 class="section__title section__title-white">Subscribe Our <br> Newsletter</h2> <p class="subcribe__description">Subscribe to our newsletter and get a special 30% discount.</p> <form action="" class="subcribe__form"> <input type="text" placeholder="Enter email"> <button class="button button--flex button__form">Subcribe</button> </form> </div> </div> </section> <section class="sponsor section"> <div class="sponsor__container container grid"> <div class="sponsor__img"> <img src="images/sponsors1.png" alt=""> </div> <div class="sponsor__img"> <img src="images/sponsors2.png" alt=""> </div> <div class="sponsor__img"> <img src="images/sponsors3.png" alt=""> </div> <div class="sponsor__img"> <img src="images/sponsors4.png" alt=""> </div> <div class="sponsor__img"> <img src="images/sponsors5.png" alt=""> </div> </div> </section> </main> <footer class="footer section"> <div class="footer__container container grid"> <div class="footer__content grid"> <div class="footer__data"> <h2 class="footer__title">Travel</h2> <p class="footer__description">Travel you choose the <br> destination, we offer you the <br> experience.</p> <div class="footer__sci"> <span><i class="ri-facebook-box-fill"></i></span> <span><i class="ri-twitter-fill"></i></span> <span><i class="ri-instagram-fill"></i></span> <span><i class="ri-youtube-fill"></i></span> </div> </div> <div class="footer__data"> <h2 class="footer__subtitle">About</h2> <p class="footer__link">About us</p> <p class="footer__link">Features</p> <p class="footer__link">New & Blog</p> </div> <div class="footer__data"> <h2 class="footer__subtitle">Company</h2> <p class="footer__link">Team</p> <p class="footer__link">Plan y Pricing</p> <p class="footer__link">Become a member</p> </div> <div class="footer__data"> <h2 class="footer__subtitle">Support</h2> <p class="footer__link">FAQs</p> <p class="footer__link">Support Center</p> <p class="footer__link">Contact Us </p> </div> </div> <div class="footer__rights grid"> <p class="footer__copy">© 2021 Bedimcode. All rigths reserved.</p> <div class="footer__terms"> <a href="#" class="footer__terms-link">Terms & Agreements</a> <a href="#" class="footer__terms-link">Privacy Policy</a> </div> </div> </div> </footer> <a href="#" class="scroll-up"> <i class="ri-arrow-up-line"></i> </a> <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script> <script src="https://unpkg.com/scrollreveal"></script> <script src="main.js"></script> </body> </html>
import {NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import {AppRoutingModule} from './app-routing.module'; import {AppComponent} from './app.component'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {MatToolbarModule} from "@angular/material/toolbar"; import {AccueilComponent} from './accueil/accueil.component'; import {MatCardModule} from "@angular/material/card"; import {MatIconModule} from "@angular/material/icon"; import {MatButtonModule} from "@angular/material/button"; import {MatSidenavModule} from "@angular/material/sidenav"; import {MatListModule} from "@angular/material/list"; import {HttpClient, HttpClientModule} from "@angular/common/http"; import {MatDialogModule} from "@angular/material/dialog"; import {MatAutocompleteModule} from "@angular/material/autocomplete"; import {MatFormFieldModule} from "@angular/material/form-field"; import {MatInputModule} from "@angular/material/input"; import {FormsModule, ReactiveFormsModule} from "@angular/forms"; import {MatChipsModule} from "@angular/material/chips"; import {MatCheckboxModule} from "@angular/material/checkbox"; import {NgxEchartsModule} from "ngx-echarts"; import {MatRadioModule} from "@angular/material/radio"; import {MatGridListModule} from "@angular/material/grid-list"; import {MatMenuModule} from "@angular/material/menu"; import {TranslateLoader, TranslateModule} from '@ngx-translate/core'; import {TranslateHttpLoader} from "@ngx-translate/http-loader"; import { CarteComponent } from './partage/carte/carte.component'; import { HeaderComponent } from './header/header.component'; import { DrawerComponent } from './drawer/drawer.component'; import { ContactComponent } from './contact/contact.component'; import { LangueBoutonComponent } from './langue-bouton/langue-bouton.component'; import { FormulaireComponent } from './partage/formulaire/formulaire.component'; import { AjoutPopupComponent } from './list-personnel/ajout-popup/ajout-popup.component'; import { ListMusicComponent } from './list-personnel/list-music.component'; import { EditionComponent } from './list-personnel/edition/edition.component'; export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http); } @NgModule({ declarations: [ AppComponent, AccueilComponent, CarteComponent, HeaderComponent, DrawerComponent, ContactComponent, ListMusicComponent, LangueBoutonComponent, FormulaireComponent, AjoutPopupComponent, EditionComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, MatToolbarModule, MatCardModule, MatIconModule, MatButtonModule, MatSidenavModule, MatListModule, HttpClientModule, MatDialogModule, MatAutocompleteModule, MatFormFieldModule, MatInputModule, ReactiveFormsModule, MatChipsModule, MatCheckboxModule, FormsModule, NgxEchartsModule, NgxEchartsModule.forRoot({ echarts: () => import('echarts') }), TranslateModule.forRoot({ defaultLanguage: 'en', loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] } }), MatRadioModule, MatGridListModule, MatMenuModule, // or import('./path-to-my-custom-echarts') ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
import sourceMapSupport from 'source-map-support' sourceMapSupport.install() import arg from 'arg' import colors from 'chalk' import { includes, pick, flatMap } from 'lodash-es' import process from 'process' import { ZodError } from 'zod' declare const VERSION: string const HELP = () => `yeux/${VERSION} ${colors.bold('Usage:')} yeux [options] ${colors.bold('Repository:')} https://github.com/escapace/yeux ${colors.bold('Commands:')} dev start dev server (default) build build for production preview locally preview production build ${colors.bold('Options:')} --host [host] [string] specify hostname (default: "127.0.0.1") --port <port> [number] specify port (default: 3000) -h, --help Display this message -v, --version Display version number ` const help = (message?: string): never => { console.log(HELP()) if (message !== undefined) { console.error(message) process.exit(1) } else { process.exit(0) } } void (async () => { const args = arg({ // types '--help': Boolean, '--host': String, '--port': Number, '--version': Boolean, // aliases '-h': '--help', '-v': '--version' }) if (args['--help'] === true) { help() } if (args['--version'] === true) { console.log(VERSION) process.exit(0) } if (args._.length > 1) { help() } const command = (args._[0] ?? 'dev') as 'build' | 'dev' | 'preview' if (!includes(['build', 'dev', 'preview'], command)) { help(`${command}: unknown command.`) } const directory = process.cwd() const { yeux } = await import('./index') try { await yeux({ command, directory, host: args['--host'], port: args['--port'] }) } catch (e) { if (e instanceof ZodError) { help( flatMap( pick(e.format(), ['host', 'port']) as Record< string, { _errors: string[] } >, (value, key) => flatMap( value._errors, (message) => `${colors.red('Error:')} --${key} ${message}` ) ).join('\n') ) } else if (e instanceof Error) { console.error(`${colors.red('Error:')} ${e.message}`) process.exit(1) } else { console.error('Unknown Error') process.exit(1) } } })()
package postgres import ( "context" "database/sql" "news/internal/models" "news/internal/service/repo" "news/pkg/logger" "news/pkg/utils" "time" ) type newsRepository struct { db *sql.DB logger logger.Logger } func NewNewsRepo(db *sql.DB, logger logger.Logger) repo.INewsRepository { return &newsRepository{ db: db, logger: logger, } } func (r *newsRepository) Create( ctx context.Context, news *models.News, ) (newsID string, err error) { err = r.db.QueryRowContext( ctx, NewsCreate, news.Title, news.Content, news.CreatedBy, news.Category, news.CreatedAt, ).Scan(&newsID) if err != nil { return "", err } return newsID, nil } func (r *newsRepository) GetByID( ctx context.Context, ID string) ( *models.News, error, ) { news := models.News{} err := r.db.QueryRowContext( ctx, NewsGetById, ID, ).Scan( &news.ID, &news.Title, &news.Content, &news.CreatedBy, &news.Category, &news.CreatedAt, ) if err != nil { r.logger.Error("repo.news.GetById Error:", err) return nil, err } return &news, nil } func (r *newsRepository) GetAll( ctx context.Context, query utils.PaginationQuery, ) ( *models.NewsList, error, ) { count := 0 if err := r.db.QueryRowContext(ctx, NewsCount).Scan( &count); err != nil { r.logger.Error("repo.news.GetAll Error:", err) return nil, err } if count == 0 { return &models.NewsList{ TotalCount: count, TotalPages: utils.GetTotalPages(count, query.GetSize()), Page: query.GetPage(), Size: query.GetSize(), HasMore: utils.GetHasMore(query.GetPage(), count, query.GetSize()), News: make([]*models.News, 0), }, nil } rows, err := r.db.QueryContext( ctx, NewsGetAll, query.GetOffset(), query.GetLimit(), ) if err != nil { r.logger.Error("repo.news.GetAll Error: ", err) return nil, err } defer rows.Close() news := make([]*models.News, 0, query.GetSize()) for rows.Next() { new := &models.News{} rows.Scan( &new.ID, &new.Title, &new.Content, &new.CreatedBy, &new.Category, &new.CreatedAt, ) news = append(news, new) } return &models.NewsList{ TotalCount: count, TotalPages: utils.GetTotalPages(count, query.GetSize()), Page: query.GetPage(), Size: query.GetSize(), HasMore: utils.GetHasMore(query.GetPage(), count, query.GetSize()), News: news, }, nil } func (r *newsRepository) Update( ctx context.Context, news *models.News, ) error { tx, err := r.db.BeginTx( context.Background(), &sql.TxOptions{ Isolation: sql.LevelSerializable, }, ) if err != nil { r.logger.Error("repo.news.update error while transaction begin:", err) return err } res, execErr := tx.ExecContext( ctx, NewsUpdate, news.Title, news.Content, news.CreatedBy, news.Category, news.ID, ) if execErr != nil { r.logger.Error( "repo.box.udpate error while insert box:", execErr.Error(), ) _ = tx.Rollback() return execErr } if count, _ := res.RowsAffected(); count == 0 { _ = tx.Rollback() return sql.ErrNoRows } return nil } func (r *newsRepository) Delete( ctx context.Context, id string, ) error { tx, err := r.db.BeginTx( context.Background(), &sql.TxOptions{ Isolation: sql.LevelSerializable, }, ) if err != nil { r.logger.Error("repo.news.update error while transaction begin:", err) return err } res, execErr := tx.ExecContext( ctx, NewsDelete, id, time.Now().Format("2006-01-02"), ) if execErr != nil { r.logger.Error( "repo.box.udpate error while insert box:", execErr.Error(), ) _ = tx.Rollback() return execErr } if count, _ := res.RowsAffected(); count == 0 { _ = tx.Rollback() return sql.ErrNoRows } return nil }
""" @Description: Enrollment App Forms modules @Author: Jobet Casquejo @Group: @Last Modified By: Jobet Casquejo @Last Modifed On: 5/20/2024 Modification Log Ver Date Author Modification 1.0 5/20/2024 Jobet Casquejo Initial Version """ from django import forms from .models import Enrollment, EmergencyContact, Education, Payment class DateInput(forms.DateInput): """ A form class that changes the input type to 'date'. This is used to render input elements with type 'date' in templates. """ input_type = "date" class EnrollmentForms(forms.Form): """ This class represents a form for enrollment data. It contains all necessary fields required for the enrollment process. """ first_name = forms.CharField(label="First Name", max_length=255, widget=forms.TextInput( attrs={"class": "form-control"})) middle_initial = forms.CharField( label="Middle Initial", max_length=255, widget=forms.TextInput(attrs={"class": "form-control"})) last_name = forms.CharField(label="Last Name", max_length=255, widget=forms.TextInput( attrs={"class": "form-control"})) birthdate = forms.DateField( label="Birth Date", widget=forms.DateInput(attrs={"class": "form-control"})) phone = forms.PhoneNumberField( label="Phone", widget=forms.PhoneNumberField(attrs={"class": "form-control"}))
package com.codirect.codiappapi.repository.criteria; import java.util.LinkedList; import java.util.List; import javax.persistence.EntityGraph; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Expression; import javax.persistence.criteria.Join; import javax.persistence.criteria.JoinType; import javax.persistence.criteria.Order; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import javax.persistence.criteria.Subquery; import org.hibernate.query.criteria.internal.OrderImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.util.ObjectUtils; import com.codirect.codiappapi.dto.privates.SearchLeadCriteriaDTO; import com.codirect.codiappapi.model.Account; import com.codirect.codiappapi.model.AccountLead; import com.codirect.codiappapi.model.Lead; import com.codirect.codiappapi.model.TagLeadAccountLead; import com.codirect.codiappapi.service.AccountService; public class AccountLeadCriteriaImpl implements AccountLeadCriteria { @Autowired private AccountService accountService; @PersistenceContext private EntityManager em; private Root<AccountLead> fromAccountLead; private Join<AccountLead, Lead> joinLead; private Join<AccountLead, TagLeadAccountLead> joinTagLeadAccountLead; @Override public Page<AccountLead> searchLead(SearchLeadCriteriaDTO criteria, Pageable pageable) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<AccountLead> query = builder.createQuery(AccountLead.class); fromAccountLead = query.from(AccountLead.class); joinLead = fromAccountLead.join("lead"); query.select(fromAccountLead).distinct(true) .where(searchPredicates(builder, criteria, query)) .orderBy(buildOrder(pageable.getSort())); int firstItem = pageable.getPageNumber() * pageable.getPageSize(); List<AccountLead> result = em.createQuery(query) .setFirstResult(firstItem) .setHint("javax.persistence.fetchgraph", entityGraph()) .setMaxResults(pageable.getPageSize()) .getResultList(); return new PageImpl<AccountLead>(result, pageable, countTotalResult(criteria)); } private List<Order> buildOrder(Sort sort) { List<Order> orders = new LinkedList<>(); if (sort.isEmpty()) return orders; sort.forEach(order -> orders.add(new OrderImpl(buildExpression(order.getProperty()), order.isAscending()))); return orders; } private Expression<?> buildExpression(String field) { String[] fieldSplit = field.split("\\."); if (fieldSplit[0].equals("lead")) return joinLead.get(fieldSplit[1]); else return fromAccountLead.get(fieldSplit[0]); } private EntityGraph<AccountLead> entityGraph() { EntityGraph<AccountLead> entityGraph = em.createEntityGraph(AccountLead.class); entityGraph.addAttributeNodes("lead"); return entityGraph; } private Long countTotalResult(SearchLeadCriteriaDTO searchLeadCriteria) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Long> query = builder.createQuery(Long.class); fromAccountLead = query.from(AccountLead.class); joinLead = fromAccountLead.join("lead"); query.select(builder.countDistinct(fromAccountLead.get("id"))).where(searchPredicates(builder, searchLeadCriteria, query)); return em.createQuery(query).getSingleResult(); } private Predicate[] searchPredicates(CriteriaBuilder builder, SearchLeadCriteriaDTO criteria, CriteriaQuery<?> query) { List<Predicate> predicates = new LinkedList<>(); predicateAccountSelected(predicates, builder, criteria); predicateWordSearch(predicates, builder, criteria); predicateFirstInteraction(predicates, builder, criteria); predicateLastInteraction(predicates, builder, criteria); predicatePostPeriod(predicates, builder, criteria); predicateTagLeadIds(predicates, builder, criteria, query); return predicates.toArray(new Predicate[predicates.size()]); } private void predicateTagLeadIds(List<Predicate> predicates, CriteriaBuilder builder, SearchLeadCriteriaDTO criteria, CriteriaQuery<?> query) { if (ObjectUtils.isEmpty(criteria.getTagLeadIds())) return; joinTagLeadAccountLead = fromAccountLead.join("tagLeadAccountLeads", criteria.getTagLeadsOption().equals("only") ? JoinType.INNER : JoinType.LEFT); if (criteria.getTagLeadIds().size() > 1) { moreThanOneTagLeadIds(predicates, builder, criteria, query); } else { onlyOneTagLeadId(predicates, builder, criteria, query); } } private void moreThanOneTagLeadIds(List<Predicate> predicates, CriteriaBuilder builder, SearchLeadCriteriaDTO criteria, CriteriaQuery<?> query) { if (criteria.getTagLeadsOption().equals("only")) { predicates.add(joinTagLeadAccountLead.get("tagLead").get("id").in(criteria.getTagLeadIds())); return; } Subquery<Integer> subqueryTagLead = query.subquery(Integer.class); Root<TagLeadAccountLead> fromTagLeadAccountLead = subqueryTagLead.from(TagLeadAccountLead.class); subqueryTagLead.select(builder.literal(1)).where(builder.and( fromTagLeadAccountLead.get("tagLead").get("id").in(criteria.getTagLeadIds()), builder.equal(fromAccountLead.get("id"), fromTagLeadAccountLead.get("accountLead").get("id")))); predicates.add(builder.or( builder.isNull(joinTagLeadAccountLead), builder.not(builder.exists(subqueryTagLead)))); } private void onlyOneTagLeadId(List<Predicate> predicates, CriteriaBuilder builder, SearchLeadCriteriaDTO criteria, CriteriaQuery<?> query) { Long tagLeadId = criteria.getTagLeadIds().stream().findFirst().get(); if (criteria.getTagLeadsOption().equals("only")) { predicates.add(builder.equal(joinTagLeadAccountLead.get("tagLead").get("id"), tagLeadId)); return; } Subquery<Integer> subqueryTagLead = query.subquery(Integer.class); Root<TagLeadAccountLead> fromTagLeadAccountLead = subqueryTagLead.from(TagLeadAccountLead.class); subqueryTagLead.select(builder.literal(1)).where(builder.and( builder.equal(fromTagLeadAccountLead.get("tagLead").get("id"), tagLeadId), builder.equal(fromAccountLead.get("id"), fromTagLeadAccountLead.get("accountLead").get("id")))); predicates.add(builder.or( builder.isNull(joinTagLeadAccountLead), builder.notEqual(joinTagLeadAccountLead.get("tagLead").get("id"), tagLeadId))); } private void predicatePostPeriod(List<Predicate> predicates, CriteriaBuilder builder, SearchLeadCriteriaDTO criteria) { if (!(ObjectUtils.isEmpty(criteria.getFromPostDate()) && ObjectUtils.isEmpty(criteria.getToPostDate()))) predicates.add(joinLead.get("id").in(criteria.getLeadIds())); } private void predicateAccountSelected(List<Predicate> predicates, CriteriaBuilder builder, SearchLeadCriteriaDTO criteria) { Account account = accountService.getAccountSelected(); predicates.add(builder.and(builder.equal(fromAccountLead.get("account").get("id"), account.getId()), builder.notEqual(joinLead.get("pk"), account.getPk()))); } private void predicateWordSearch(List<Predicate> predicates, CriteriaBuilder builder, SearchLeadCriteriaDTO criteria) { if (ObjectUtils.isEmpty(criteria.getWord())) return; predicates.add(builder.or(builder.like(joinLead.get("fullName"), "%" + criteria.getWord() + "%"), builder.like(joinLead.get("accountName"), "%" + criteria.getWord() + "%"), builder.like(joinLead.get("biography"), "%" + criteria.getWord() + "%"), builder.like(joinLead.get("publicEmail"), "%" + criteria.getWord() + "%"), builder.like(joinLead.get("contactPhoneNumber"), "%" + criteria.getWord() + "%"), builder.like(fromAccountLead.get("note"), "%" + criteria.getWord() + "%"))); } private void predicateFirstInteraction(List<Predicate> predicates, CriteriaBuilder builder, SearchLeadCriteriaDTO criteria) { if (!ObjectUtils.isEmpty(criteria.getFromFirstInteractionDate())) predicates.add(builder.greaterThanOrEqualTo(fromAccountLead.get("firstInteraction"), criteria.getFromFirstInteractionDate())); if (!ObjectUtils.isEmpty(criteria.getToFirstInteractionDate())) predicates.add(builder.lessThanOrEqualTo(fromAccountLead.get("firstInteraction"), criteria.getToFirstInteractionDate())); } private void predicateLastInteraction(List<Predicate> predicates, CriteriaBuilder builder, SearchLeadCriteriaDTO criteria) { if (!ObjectUtils.isEmpty(criteria.getFromLastInteractionDate())) predicates.add(builder.greaterThanOrEqualTo(fromAccountLead.get("lastInteraction"), criteria.getFromLastInteractionDate())); if (!ObjectUtils.isEmpty(criteria.getToLastInteractionDate())) predicates.add(builder.lessThanOrEqualTo(fromAccountLead.get("lastInteraction"), criteria.getToLastInteractionDate())); } }
import React, { useState } from 'react'; import ListItem from './ListItem.jsx'; import styles from '../styles/app.css'; function App() { const [email, setEmail] = useState(''); const [signUpMessage, setSignUpMessage] = useState('Enter your email to stay in touch!') const HELP = ['1-888-963-8944', '1-814-251-9966 (Text)', 'help@somebirds.com', 'Returns/Exchanges', 'FAQ/Contact Us']; const SHOP = [`Men's Shoes`, `Women's Shoes`, `Men's Apparel`, `Women's Apparel`, 'Socks', 'Gift Cards', 'Download the Somebirds App']; const COMPANY = ['Our Stores', 'Our Story', 'Our Materials', 'Sustainability', 'Partnerships', 'Affiliates', 'Bulk Orders', 'Careers', 'Press', 'California Transparency Act']; const handleEmailChange = (e) => { setEmail(e.target.value); }; const handleSignUp = (e) => { if (email) setSignUpMessage(`Great! You're all set! Cheers!`); } return ( <div className={styles.container}> <div className={styles.rowContainer}> <div className={styles.columnContainer50}> {signUpMessage} {signUpMessage === 'Enter your email to stay in touch!' && <div className={styles.emailForm}> <input className={styles.emailField} type="email" onChange={handleEmailChange} value={email} /> <div className={styles.signUpButton} onClick={handleSignUp}>SIGN UP</div> </div>} </div> </div> <div className={styles.rowContainer}> <div className={styles.columnContainer25}> <div className={styles.colHeader}> HELP </div> { HELP.map(x => <ListItem text={x}/>) } </div> <div className={styles.columnContainer25}> <div className={styles.colHeader}> SHOP </div> { SHOP.map(x => <ListItem text={x}/>) } </div> <div className={styles.columnContainer50}> <div className={styles.colHeader}> COMPANY </div> { COMPANY.map(x => <ListItem text={x}/>) } </div> </div> <div className={styles.rowContainer}> <div className={styles.columnContainer25}> <div className={styles.colHeader2}> FOLLOW THE FLOCK </div> <div className={styles.item}> Exclusive offers, a heads up on new things, and sightings of Somebirds in the wild. Oh, we have cute sheep, too. #wearesomebirds </div> <div className={styles.subRowContainer}> <div> <img className={styles.socialMediaIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/Instagram_Logo.svg"></img> </div> <div> <img className={styles.socialMediaIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/Twitter_Logo.svg"></img> </div> <div> <img className={styles.socialMediaIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/Facebook_Logo.svg"></img> </div> <div> <img className={styles.socialMediaIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/Pinterest_Logo.svg"></img> </div> </div> </div> <div className={styles.columnContainer25}> <div className={styles.horizontalCenter}> <img className={styles.certBLogo} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/CertifiedBCorp_Logo.svg"></img> </div> </div> <div className={styles.columnContainer50}> <div className={styles.subRowContainer}> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/American_Flag.svg"></img> </div> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/NewZealand_Flag.svg"></img> </div> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/Australian_Flag.svg"></img> </div> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/Canadian_Flag.svg"></img> </div> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/UnitedKingdom_Flag.svg"></img> </div> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/Chinese_Flag.svg"></img> </div> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/EuropeanUnion_Flag.svg"></img> </div> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/Japanese_Flag.png"></img> </div> <div> <img className={styles.flagIcon} src="https://somebirds-static-assets.s3.us-east-2.amazonaws.com/assets/SouthKorean_Flag.png"></img> </div> </div> </div> </div> <div className={styles.rowContainer}> <div className={styles.footerText}> <div className={styles.item}> @ 2021 Somebirds, Inc. All Rights Reserved. <span className={styles.link}>Terms</span>, <span className={styles.link}>Privacy</span> & <span className={styles.link}>Accessibility</span> </div> </div> </div> </div> ) } export default App;
<script> import PostCard from "./PostCard.vue"; import { store } from "../store"; import axios from "axios"; export default { data() { return { arrPosts: [], arrTypes: [], page: 1, total: 0, store, }; }, methods: { loadMore() { axios .get(this.store.baseUrl + `api/posts?page=${this.page + 1}`) .then((response) => { this.arrPosts = this.arrPosts.concat(response.data.results.data); this.page++; }); }, resetCard() { axios.get(this.store.baseUrl + "api/posts").then((response) => { this.arrPosts = response.data.results.data; this.total = response.data.results.total; this.page = 1; }); }, getPosts() { axios.get(this.store.baseUrl + "api/posts").then((response) => { this.arrPosts = response.data.results.data; this.total = response.data.results.total; }); }, }, created() { this.getPosts(); }, components: { PostCard, }, }; </script> <template> <div class="container"> <h1 class="mb-4">POST LIST</h1> <!-- CARDS --> <div class="d-flex gap-5 flex-wrap justify-content-center mb-3"> <PostCard v-for="post in arrPosts" :key="post.id" :card="post" /> </div> <!-- LOAD MORE --> <div class="d-flex gap-2 align-items-center justify-content-center"> <button v-if="arrPosts.length != total" @click="loadMore" class="btn btn-primary mb-3" > Carica altri post </button> <button @click="resetCard()" class="btn btn-secondary mb-3">Reset</button> </div> </div> </template> <style lang="scss" scoped></style>
/* eslint-disable react-hooks/exhaustive-deps */ import React, { useEffect, useState } from "react"; import FormInput from "../components/FormInput/FormInput"; import Header from "../components/Header/Header"; import Serie from "../components/Serie/Serie"; import Title from "../components/Title/Title"; import sorting from "../helpers/sorting"; import data from "../mocks/sample.json"; const Series = () => { const [sortMethod, setSortMethod] = useState<string>("yearDescending"); const [searchTerm, setSearchTerm] = useState<string>(""); const [demandedSeries, setDemandedSeries] = useState<ISerie[]>([]); const [initialSeries, setInitialSeries] = useState<ISerie[]>([]); const [error, setError] = useState(null); const [isPending, setIsPending] = useState(false); const [isNotFound, setIsNotFound] = useState(false); const fetchData = async () => { setIsPending(true); if (process.env.NODE_ENV === "development") { try { const res = await fetch("/api/moviesSeries"); if (!res.ok) { throw Error("could not fetch the data for that resource"); } const moviesSeries = await res.json(); const first21SeriesAfter2010 = moviesSeries .filter( (serie: ISerie) => serie.releaseYear >= 2010 && serie.programType === "series" ) .slice(0, 21); setInitialSeries(first21SeriesAfter2010); setIsPending(false); setError(null); } catch (err: any) { setError(err.message); setIsPending(false); } } else { const first21SeriesAfter2010 = data .filter( (serie) => serie.releaseYear >= 2010 && serie.programType === "series" ) .slice(0, 21); setInitialSeries(first21SeriesAfter2010); setIsPending(false); setError(null); } }; useEffect(() => { fetchData(); }, []); useEffect(() => { const sortedAndSearchSeries = sorting(initialSeries, sortMethod).filter( (serie: ISerie) => serie.title.toLocaleLowerCase().includes(searchTerm) ); if (searchTerm.length > 2) { if (sortedAndSearchSeries.length > 0) { setIsNotFound(false); setDemandedSeries(sortedAndSearchSeries); } else { setIsNotFound(true); setDemandedSeries([]); } } else { setIsNotFound(false); setDemandedSeries(initialSeries); } }, [sortMethod, searchTerm, initialSeries]); return ( <> <Header /> <Title title="Popular Series" /> <main> <div className="main-container"> <FormInput setSortMethod={setSortMethod} sortMethod={sortMethod} setSearchTerm={setSearchTerm} /> {isNotFound && ( <h3>{`Could not find any serie matching to ${searchTerm}`}</h3> )} <div className="seriesList"> {error && <h1>{error}</h1>} {isPending && <h1>Loading...</h1>} {demandedSeries.map((serie: ISerie, idx: number) => { return <Serie key={idx} serie={serie} />; })} </div> </div> </main> </> ); }; export default Series;
/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2002 by the OpenSG Forum * * * * www.opensg.org * * * * contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library 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 * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ #ifndef _OSGCGFXMATERIAL_H_ #define _OSGCGFXMATERIAL_H_ #ifdef __sgi #pragma once #endif #include "OSGConfig.h" #include "OSGMaterialChunk.h" #include "OSGTextureChunk.h" #include "OSGTexGenChunk.h" #include "OSGBlendChunk.h" #include "OSGShaderParameterAccess.h" #include "OSGCGFXChunk.h" #include "OSGCGFXMaterialBase.h" OSG_BEGIN_NAMESPACE /*! \brief CGFXMaterial class. See \ref PageKernelCGFXMaterial for a description. */ class OSG_CONTRIBLIB_DLLMAPPING CGFXMaterial : public CGFXMaterialBase { private: typedef CGFXMaterialBase Inherited; public: /*---------------------------------------------------------------------*/ /*! \name Sync */ /*! \{ */ virtual void changed(BitVector whichField, UInt32 origin ); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Output */ /*! \{ */ virtual void dump( UInt32 uiIndent = 0, const BitVector bvFlags = 0) const; virtual StatePtr makeState (void); virtual void rebuildState (void); virtual StatePtr getState (UInt32 index); virtual UInt32 getNPasses (void) const; virtual bool isTransparent (void) const; bool isTextureParameter(const std::string &name); ImagePtr findImage(const std::string &name); Int32 findImage(const ImagePtr &img); std::string getTechniqueString(Int32 index); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Timer */ /*! \{ */ typedef Real64 (*timercbfp) (void); static void setTimerCB(timercbfp fp); static timercbfp getTimerCB(void); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Parameter Access */ /*! \{ */ bool setParameter(const char *name, bool value ); bool setParameter(const char *name, Int32 value ); bool setParameter(const char *name, Real32 value ); bool setParameter(const char *name, const Vec2f &value); bool setParameter(const char *name, const Vec3f &value); bool setParameter(const char *name, const Vec4f &value); bool setParameter(const char *name, const Matrix &value); bool setParameter(const char *name, const std::string &value); bool getParameter(const char *name, bool &value); bool getParameter(const char *name, Int32 &value); bool getParameter(const char *name, Real32 &value); bool getParameter(const char *name, Vec2f &value); bool getParameter(const char *name, Vec3f &value); bool getParameter(const char *name, Vec4f &value); bool getParameter(const char *name, Matrix &value); bool getParameter(const char *name, std::string &value); bool subParameter(const char *name); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Texture specific */ /*! \{ */ /*! \} */ protected: // Variables should all be in CGFXMaterialBase. void onCreate(const CGFXMaterial *source = NULL); void onDestroy(void); /*---------------------------------------------------------------------*/ /*! \name Constructors */ /*! \{ */ CGFXMaterial(void); CGFXMaterial(const CGFXMaterial &source); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Destructors */ /*! \{ */ virtual ~CGFXMaterial(void); /*! \} */ private: friend class FieldContainer; friend class CGFXMaterialBase; static void initMethod(void); static timercbfp _timerFP; CGFXChunkPtr _cgfxChunk; ShaderParameterAccess *_parameter_access; // prohibit default functions (move to 'public' if you need one) void operator =(const CGFXMaterial &source); }; typedef CGFXMaterial *CGFXMaterialP; OSG_END_NAMESPACE #include "OSGCGFXMaterialBase.inl" #include "OSGCGFXMaterial.inl" #define OSGCGFXMATERIAL_HEADER_CVSID "@(#)$Id: OSGCGFXMaterial.h,v 1.3 2006/03/02 17:45:36 a-m-z Exp $" #endif /* _OSGCGFXMATERIAL_H_ */
import {NextIntlClientProvider} from 'next-intl'; import {notFound} from 'next/navigation'; import './globals.css' import { Exo } from '@next/font/google' import Navbar from '@/components/Navbar/Navbar'; import Footer from '@/components/Footer/Footer'; import FoodiesJourney from './foodiesJourney/page'; const exo = Exo({ subsets: ["latin"], variable: "--font-exo" }) export function generateStaticParams() { return [{locale: 'en'}, {locale: 'de'}]; } export default async function RootLayout({ children, params: {locale}}) { let messages; try { messages = (await import(`../../messages/${locale}.json`)).default; } catch (error) { notFound(); } return ( <html lang={locale}> {/* <head /> will contain the components returned by the nearest parent head.js. Find out more at https://beta.nextjs.org/docs/api-reference/file-conventions/head */} <head /> <body className={`${exo.variable} font-exo`}> <NextIntlClientProvider locale={locale} messages={messages}> <Navbar /> <main className='overflow-hidden relative'> {children} </main> <Footer /> </NextIntlClientProvider> </body> </html> ) }
from threading import Thread, Event from typing import Any, Dict import logging import os import signal import queue import redis import boto3 from boto3_type_annotations.s3 import ServiceResource from botocore.config import Config from dotenv import load_dotenv import pika import torch from predict.image.setup import setup as image_setup from predict.voiceover.setup import setup as voiceover_setup from rdqueue.worker import start_redis_queue_worker from rabbitmq_consumer.worker import start_amqp_queue_worker from rabbitmq_consumer.connection import RabbitMQConnection from upload.constants import ( S3_ACCESS_KEY_ID, S3_BUCKET_NAME_UPLOAD, S3_ENDPOINT_URL, S3_REGION, S3_SECRET_ACCESS_KEY, ) from upload.worker import start_upload_worker from clipapi.app import run_clipapi # Logging configuration logging.basicConfig( level=logging.INFO, format="[%(asctime)s] [%(levelname)s] [%(threadName)s] - %(message)s", handlers=[logging.StreamHandler()], ) # Define an event to signal all threads to exit shutdown_event = Event() if __name__ == "__main__": if torch.cuda.is_available() is False: os.environ["CUDA_VISIBLE_DEVICES"] = "0" load_dotenv() WORKER_TYPE = os.environ.get("WORKER_TYPE", "image") amqpUrl = os.environ.get("RABBITMQ_AMQP_URL", None) if amqpUrl is None: raise ValueError("Missing RABBITMQ_AMQP_URL environment variable.") amqpQueueName = os.environ.get("RABBITMQ_QUEUE_NAME", None) if amqpQueueName is None: raise ValueError("Missing RABBITMQ_QUEUE_NAME environment variable.") # Stale redis redisUrl = os.environ.get("REDIS_URL") redisInputQueue = os.environ.get("REDIS_INPUT_QUEUE") redisWorkerId = os.environ.get("WORKER_NAME", None) if redisWorkerId is None: raise ValueError("Missing WORKER_NAME environment variable.") # S3 client s3: ServiceResource = boto3.resource( "s3", region_name=S3_REGION, endpoint_url=S3_ENDPOINT_URL, aws_access_key_id=S3_ACCESS_KEY_ID, aws_secret_access_key=S3_SECRET_ACCESS_KEY, config=Config( retries={"max_attempts": 3, "mode": "standard"}, connect_timeout=5, read_timeout=5, ), ) if WORKER_TYPE == "voiceover": models_pack = voiceover_setup() else: models_pack = image_setup() # Setup redis redisConn = redis.BlockingConnectionPool.from_url(redisUrl) # Create queue for thread communication upload_queue: queue.Queue[Dict[str, Any]] = queue.Queue() # Create redis worker thread redis_worker_thread = Thread( target=lambda: start_redis_queue_worker( worker_type=WORKER_TYPE, redis=redis.Redis( connection_pool=redisConn, socket_keepalive=True, socket_timeout=1000 ), input_queue=redisInputQueue, s3_client=s3, s3_bucket=S3_BUCKET_NAME_UPLOAD, upload_queue=upload_queue, models_pack=models_pack, ) ) # Create rabbitmq connection connection = RabbitMQConnection(amqpUrl) # Setup signal handler for exit def signal_handler(signum, frame): if not shutdown_event.is_set(): print("Signal received, shutting down...") shutdown_event.set() connection.stop_consuming() connection.close() connection.connection.close() signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) # Create rabbitmq worker thread mq_worker_thread = Thread( target=lambda: start_amqp_queue_worker( worker_type=WORKER_TYPE, connection=connection, queue_name=amqpQueueName, upload_queue=upload_queue, models_pack=models_pack, shutdown_event=shutdown_event, ) ) # Create upload thread upload_thread = Thread( target=lambda: start_upload_worker( worker_type=WORKER_TYPE, q=upload_queue, s3=s3, s3_bucket=S3_BUCKET_NAME_UPLOAD, shutdown_event=shutdown_event, ) ) try: mq_worker_thread.start() redis_worker_thread.start() upload_thread.start() if WORKER_TYPE == "image": clipapi_thread = Thread(target=lambda: run_clipapi(models_pack=models_pack)) clipapi_thread.start() clipapi_thread.join() mq_worker_thread.join() redis_worker_thread.join() upload_thread.join() except KeyboardInterrupt: pass # Handle Ctrl+C gracefully. The signal handler already sets the shutdown_event. finally: # Any other cleanup in the main thread you want to perform. print("Main thread cleanup done!")
package com.pagewisegroup.tiredtasks.ui.notifications import android.app.AlertDialog import android.content.DialogInterface import android.os.Bundle import android.text.InputType import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.RadioButton import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.floatingactionbutton.FloatingActionButton import com.pagewisegroup.tiredtasks.R import com.pagewisegroup.tiredtasks.adapters.MessagesAdapter import com.pagewisegroup.tiredtasks.databinding.FragmentNotificationsBinding import com.pagewisegroup.tiredtasks.models.MedicationModel import com.pagewisegroup.tiredtasks.models.MessagesModel import com.pagewisegroup.tiredtasks.ui.medication.AddNewMedication import com.pagewisegroup.tiredtasks.utils.DatabaseHandler class NotificationsFragment : Fragment() { private var _binding: FragmentNotificationsBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! //view list private lateinit var messagesRecycler: RecyclerView private lateinit var messagesAdapter: MessagesAdapter private lateinit var messagesList: ArrayList<MessagesModel> //use db handler group used private lateinit var db: DatabaseHandler override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { //view binding val notificationsViewModel = ViewModelProvider(this).get(NotificationsViewModel::class.java) _binding = FragmentNotificationsBinding.inflate(inflater, container, false) val root: View = binding.root return root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) //get context for db from associated activity db = DatabaseHandler(activity) db.openDatabase() //alert builder's string var m_Text = ""; //bind add button val addButton = _binding!!.root.findViewById<FloatingActionButton>(R.id.templateAdd) addButton.setOnClickListener { val builder: AlertDialog.Builder = android.app.AlertDialog.Builder(activity) builder.setTitle("New Message Template") //user input val input = EditText(activity) input.hint = "Enter Text" input.inputType = InputType.TYPE_CLASS_TEXT builder.setView(input) //builder buttons builder.setPositiveButton("Enter", DialogInterface.OnClickListener { dialog, which -> // get user input m_Text = input.text.toString() if(m_Text != ""){ var temp = MessagesModel() temp.message = m_Text db.addTemplate(temp) messagesList = db.getTemplates() messagesAdapter.setList(messagesList) } }) builder.setNegativeButton("Cancel", DialogInterface.OnClickListener { dialog, which -> dialog.cancel() }) builder.show() } messagesRecycler = _binding!!.root.findViewById(R.id.messageCardView) messagesRecycler.layoutManager = LinearLayoutManager(activity) messagesAdapter = MessagesAdapter(db) messagesRecycler.adapter = messagesAdapter messagesList = db.getTemplates() messagesList.reverse() messagesAdapter.setList(messagesList) } override fun onDestroyView() { super.onDestroyView() _binding = null } }
import { Route, Routes, useNavigate} from "react-router-dom"; import Login from "./component/pages/auth/Login"; import { useAppDispatch } from "./store/store"; import { RestoreLogin, authenSelector } from "./store/slice/authSlice"; import { useEffect } from "react"; import { useSelector } from "react-redux"; import NavBar from "./component/layouts/NavBar"; import Home from "./component/pages/home/Home"; import ProfileEdit from "./component/pages/profile/ProfileEdit"; function App() { const dispatch = useAppDispatch(); const is_login = useSelector(authenSelector).is_login; const navigate = useNavigate(); const checkLogin = async () => { const {payload} = await dispatch(RestoreLogin()); if(payload.sts){ navigate("/home"); }else{ navigate("/"); } } useEffect(() => { checkLogin(); }, [is_login]) return ( <div className="App bg-gradient-to-tr bg-gray-100 h-full"> {is_login && <NavBar/>} <Routes> <Route path="/" element={ <Login/> } /> <Route path="/home" element={ <Home/> } /> <Route path="/profile" element={ <ProfileEdit/> } /> </Routes> </div> ) } export default App
import { Test } from '@nestjs/testing'; import { StripeService } from '../stripe.service'; import { createStripeConfig } from './utils'; const TEST_EMAIL = 'max.putilov@gmail.com'; xdescribe('StripeCustomer', () => { let service: StripeService; beforeAll(async () => { const app = await Test.createTestingModule({ providers: [ { provide: StripeService, useFactory: () => new StripeService(createStripeConfig()), }, ], }).compile(); service = app.get<StripeService>(StripeService); }); describe('Stripe customer', () => { let customerId: string; it('create customer', async () => { const res = await service.createCustomer(TEST_EMAIL); console.log('111', res); expect(res).toBeDefined(); expect(res.id).toBeDefined(); expect(res.email).toEqual(TEST_EMAIL); customerId = res.id; }); it('remove customer', async () => { const res = await service.removeCustomer(customerId); expect(res).toBeDefined(); }); }); });
<template> <v-app> <span v-if="allPlans.length === 0" class="notice text-center"> You currently do not have any study plans set up for any of your notes. </span> <Loading v-if="loading" /> <div v-if="allPlans.length > 0"> <v-row justify="center" align="center"> <span class="notice text-center">Uncompleted Study Plans</span> </v-row> <v-row justify="center" align="center" style="margin-top: 20px;"> <v-card class="modal-list-item" :style="windowWidth < 850 ? 'width: 200px' : null" v-for="(p, i) in allPlans" :key="i" elevation="2" flat > <table> <tr> <td>Note:</td> <td>{{p.notename}}</td> </tr> <tr> <td>Date:</td> <td>{{p.studydate}}</td> </tr> <tr> <td>Time:</td> <td>{{p.time}}</td> </tr> <tr> <td>Duration:</td> <td>{{p.timeamount}} minutes</td> </tr> <tr> <td>Priority Level:</td> <td>{{p.prioritylevel}} / 5</td> </tr> </table> <v-card-actions> <v-spacer /> <v-tooltip bottom> <template v-slot:activator="{ on, attrs }"> <v-btn icon v-bind="attrs" v-on="on" @click="deletePlan(p.planid)" > <v-icon>mdi-delete</v-icon> </v-btn> </template> <span>Delete Plan</span> </v-tooltip> <v-tooltip bottom v-if="!loading || selected != i"> <template v-slot:activator="{ on, attrs }"> <v-btn icon v-bind="attrs" v-on="on" @click="openNote(p.noteid, i)" :disabled="loading" > <v-icon>mdi-chevron-right-circle</v-icon> </v-btn> </template> <span>Study</span> </v-tooltip> <Loading v-if="loading && selected == i" /> </v-card-actions> </v-card> </v-row> </div> </v-app> </template> <script> import Loading from '~/components/Loading.vue' export default { name: 'PlansPage', head() { return { title: 'Study Plans - GOAT Notes', meta: [ { hid: 'plans-description', name: 'description', content: 'See all your study plans in GOAT Notes' }, { hid: 'keywords', name: 'keywords', content: 'goat, notes, study, ai, artificial intelligence, plans, reminder' } ] } }, async mounted () { this.loading = true await this.$store.dispatch('users/getAllPlans') this.loading = false }, created () { window.addEventListener('resize', this.resizeHandler) }, components: { Loading, }, data () { return { windowWidth: window.innerWidth, loading: false, selected: null, } }, methods: { resizeHandler() { this.windowWidth = window.innerWidth }, async deletePlan (planid) { await this.$store.dispatch('users/deletePlan', { planid: planid, noteid: null }) }, async openNote (noteid, i) { this.selected = i this.loading = true await this.$store.dispatch('users/openNote', { noteid }) this.loading = false }, }, computed: { allPlans () { return this.$store.state.users.allPlans } } } </script> <style scoped> @import '~/assets/styles.css'; .modal-list-item { margin-right: 2%; width: 30%; background-color: #fcfcfc; } </style>
import { useEffect, useState } from "react"; function useSemiPersistentState(key, initialState) { const [value, setValue] = useState(localStorage.getItem(key) || initialState); useEffect(() => { localStorage.setItem(key, value); }, [key, value]); return [value, setValue]; } export default useSemiPersistentState;
<?php namespace App\Exports; use App\Models\Customer; use Illuminate\Contracts\Support\Responsable; use Illuminate\Contracts\View\View; use Illuminate\Http\Request; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\FromView; use Maatwebsite\Excel\Concerns\ShouldAutoSize; use Maatwebsite\Excel\Concerns\WithStyles; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class CustomersExport implements ShouldAutoSize, Responsable, FromView, WithStyles { use Exportable; private $fileName = 'customers-report.xls'; public function __construct(private Request $request) {} public function view(): View { $customers = Customer::filter($this->request->only('search'))->get(); return view('excel.customer-report', compact('customers')); } public function styles(Worksheet $sheet) { return [ 1 => [ 'font' => ['bold' => true, 'size' => 12], 'alignment' => ['vertical' => 'center', 'horizontal' => 'center'], ], 3 => [ 'font' => ['bold' => true], ], 'E' => ['alignment' => ['horizontal' => 'left']], ]; } }
# frozen_string_literal: true module AuthConcern extend ActiveSupport::Concern def sign_in(user) session[:user_id] = user.id end def sign_out session.delete(:user_id) session.clear end def signed_in? session[:user_id].present? && current_user.present? end def current_user @current_user ||= User.find_by(id: session[:user_id]) end def authenticate_user! return if signed_in? flash[:warn] = t('web.auth.auth_error') redirect_to root_path end end
#include <TinyGPS++.h> #include <RTClib.h> #include <SoftwareSerial.h> RTC_DS3231 rtc; TinyGPSPlus gps; bool isUpdated; SoftwareSerial ss(4, 3); void setup() { Wire.begin(); Serial.begin(9600); ss.begin(9600); if (!rtc.begin()){ Serial.println("RTC not found"); } if(rtc.lostPower()){ rtc.adjust(DateTime(2000, 01, 01, 0, 0, 0)); } rtc.adjust(DateTime(2000, 01, 01, 0, 0, 0)); rtc.disable32K(); Serial.println("Start"); } void loop(){ DateTime rtcTime = rtc.now(); if(!isUpdated) { while(ss.available() > 0) { if(gps.encode(ss.read())) { Serial.println("GPS sentence received"); if(gps.time.isValid() && gps.date.isValid() && ((rtcTime.second() <= gps.time.second()))) { rtc.adjust(DateTime(gps.date.year(), gps.date.month(), gps.date.day(), gps.time.hour(), gps.time.minute() ,gps.time.second())); Serial.println("Updated"); } } } isUpdated = true; } Serial.println(String(rtcTime.day()) + "/" + String(rtcTime.month()) + "/" + String(rtcTime.year()) + "\t\t" + String(rtcTime.hour()) + ":" + String(rtcTime.minute()) + ":" + String(rtcTime.second()) + "\tGps: " +String(gps.time.value())); delay(1000); }
import React from "react"; import {AppWrap} from "../../wrapper"; import {useTranslation} from "react-i18next"; import {FaRegHandPointRight} from 'react-icons/fa' import {motion} from "framer-motion"; import styles from "./Header.module.scss"; const container = { whileInView: (i = 1) => ({ opacity: [0, 1], transition: {staggerChildren: 0.2, delayChildren: .2 * i} }), }; const child = { whileInView: { opacity: [0, 1], y: [20, 0], transition: {duration: .3} }, }; const Header = () => { const {t} = useTranslation('global') return ( <motion.div variants={container} animate="whileInView" className={styles.container}> <motion.p variants={child} className={styles.intro}>{t('sections.home.header.p1')}</motion.p> <motion.h1 variants={child} className={styles.title}>Michał <span className={styles.titleSecondary}>Stępień</span></motion.h1> <motion.h1 variants={child} className={styles.subtitle}>Junior Web Developer</motion.h1> <motion.div variants={child} className={styles.description}> <p>{t('sections.home.header.p2')}</p> <p> {t('sections.home.header.p3')} <a className={styles.link} href={"#work"}> <FaRegHandPointRight/> {t('sections.home.links.projects')}</a> {t('sections.home.header.p4')} <a className={styles.link} href={"#skills"}> <FaRegHandPointRight/> {t('sections.home.links.skills')}</a> . </p> </motion.div> </motion.div> ); }; export default AppWrap(Header, "home");
// SPDX-License-Identifier: MIT pragma solidity 0.8.19; import {ERC20Upgradeable} from "openzeppelin-upgradeable-contracts/token/ERC20/ERC20Upgradeable.sol"; import {UUPSUpgradeable} from "openzeppelin-upgradeable-contracts/proxy/utils/UUPSUpgradeable.sol"; contract PocProxy is UUPSUpgradeable, ERC20Upgradeable { // keccak256(abi.encode(uint256(keccak256("PocProxy:Storage:V0")) - 1)) & ~bytes32(uint256(0xff)) bytes32 public constant POC_PROXY_STORAGE_SLOT_V0 = 0x16c9df44581e907e6b2370ff2d47dd17c6199f47024750591f3709a54554d200; struct PocProxyStorage { address implementation; string version; } constructor() { _disableInitializers(); } function initialize( string memory name, string memory symbol, string calldata version_ ) external initializer { __ERC20_init(name, symbol); setVersion(version_); } function getStorage() internal pure returns (PocProxyStorage storage s) { assembly { s.slot := POC_PROXY_STORAGE_SLOT_V0 } } function setImplementation(address implementation_) public { getStorage().implementation = implementation_; } function setVersion(string calldata version_) public { getStorage().version = version_; } function getImplementation() public view returns (address) { return getStorage().implementation; } function getVersion() public view returns (string memory) { return getStorage().version; } function _authorizeUpgrade(address newImplementation) internal override {} }
--- title: "\"[New] YouTube Ad-Free Watching Chrome/Firefox/Android/iOS Tutorial\"" date: 2024-06-05T08:12:05.518Z updated: 2024-06-06T08:12:05.518Z tags: - ai video - ai youtube categories: - ai - youtube description: "\"This Article Describes [New] YouTube Ad-Free Watching: Chrome/Firefox/Android/iOS Tutorial\"" excerpt: "\"This Article Describes [New] YouTube Ad-Free Watching: Chrome/Firefox/Android/iOS Tutorial\"" keywords: "\"Ad-Free YouTube Browsing,Chrome AdRemoval Guide,Firefox AdBlocker Tips,Android RemoveAds,IOS AdBlocking Tutorial,YouTube NoAd View,Free Browser Ad Removal\"" thumbnail: https://thmb.techidaily.com/8efb02d1ad78746fe7e04d066e97a30754c0040bd1d393f4b6d528ffbc9df6b1.jpg --- ## YouTube Ad-Free Watching: Chrome/Firefox/Android/iOS Tutorial # How to Block YouTube Ads on Chrome/Firefox/Android/iPhone ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) ##### Richard Bennett Mar 27, 2024• Proven solutions YouTube is unquestionably the world’s most popular video-sharing platform with a massive 2 billion active monthly users. With such a large audience, advertisers are pouring a lot of funds into Google’s video platform that makes up a big portion of the company’s advertising revenue. Unfortunately, according to the [BI Intelligence Digital Trust Survey](https://www.businessinsider.com/facebook-and-youtube-have-the-most-annoying-ads-by-far-2017-4), YouTube serves up the most annoying ads with 43 percent of the respondents considering YouTube ads most irksome. Every now and then you’ll get annoyed with the obtrusive ads and ask **how to block YouTube ads**. Getting away with the un-skippable and plagued 30-second ads during the playback or the onscreen pop-up ads that come suddenly on the playing screen will make your life miserable when watching a show or practicing a dance move. To help you escape the forced ads on YouTube we’ll go through the YouTube ad blocking techniques available. You will learn: * [**Part 1: How to block YouTube ads on the computer (Chrome & Firefox)**](#part1) * [**Part 2: How to block YouTube ads on the mobile phone (Android & iPhone)**](#part2) Here is the video guide to help you block Youtube ads on the computer and mobile phone [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ## Part 1: How to block YouTube ads on the computer (Chrome & Firefox) In case you care about and want to support content creators on YouTube, you can buy the YouTube Premium which will also give you access to exclusive shows and will eliminate ads from your YouTube life. However, as most of us won’t like the idea of paying for a free service, there are possible solutions of how to block YouTube ads in Chrome or Firefox. You will need to install a third-party browser extension proficient in blocking the annoying YouTube ads in Google Chrome or Mozilla Firefox. ### 1.Google Chrome Chrome allows you to have extensions to enhance the browser features and interact more with the content presented to you. These third-party extensions or sometimes called Add-ons can help prevent the irritating YouTube ads to show up on the site. To install them, follow the steps. * 1\. Open Google Chrome browser and go to Menu. * 2\. In the Menu look for “More Tools” and in there tap the “Extensions”. ![more tools](https://images.wondershare.com/filmora/article-images/open-google1.jpg) * 3\. In the Extensions tap the “Main menu” at the left-hand side. It will show the menu here open the Chrome Web Store. Or you can simply open [Chrome Web Store](https://chrome.google.com/webstore/category/extensions?hl=en-GB) ![main menu](https://images.wondershare.com/filmora/article-images/main-menu2.jpg) * 4\. You will need to sign in with your Google account if you’re not already signed in. * 5\. In the search box type “ad blocker YouTube” and tap enter. You’ll see a list of ad blockers available for chrome. * 6\. You will adblocker’s specifically for YouTube ads. Select whichever you like and it will block the YouTube ads on Chrome. ![block ads](https://images.wondershare.com/filmora/article-images/block-ads-3.jpg) ### 2.Mozilla Firefox You can also install third-party extensions to block YouTube ads from popping up in the middle of the playback. To install the extensions, follow the steps. * 1\. Tap the Hamburger Menu on Firefox at the top-right corner and select Add-ons. ![open firefox](https://images.wondershare.com/filmora/article-images/open-firefox4.jpg) * 2\. In the search bar “Find more extensions” type “ad blocker YouTube” and press enter. ![find more extension](https://images.wondershare.com/filmora/article-images/find-more-extension5.jpg) * 3\. Select an appropriate ad blocker and it will protect you from the irritating ads. ![select appropriate ad](https://images.wondershare.com/filmora/article-images/block-add-on6.jpg) * 4\. Tap the “Add to Firefox” to download the extension. ![add to firefox](https://images.wondershare.com/filmora/article-images/add-to-firefox7.jpg) * 5\. It will ask for permission, press “Add” again to grant the permissions. ![grant the permissions](https://images.wondershare.com/filmora/article-images/grant-the-permission8.jpg) ## **Part 2: How to block YouTube ads on the mobile phone (Android & iPhone)** Ads can cause inconvenience and make YouTube watching a sour experience. To protect yourself from the constant nagging ads on mobile platforms both Android and iPhone you can utilize the numerous ad-blocking apps for Android and iOS. Though the simplest method of blocking the ads and watch YouTube content without ads is to use the Adblock Browser available both for both devices at Google Play Store and Apple Store. This technique won’t require you to root your Android phone or jailbreak the iPhone for watching ad-free YouTube videos. [![Download Win Version](https://images.wondershare.com/filmora/guide/download-btn-win.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) [![Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg) ](https://tools.techidaily.com/wondershare/filmora/download/) ### 1.Android Android is pretty flexible and allows you to add many feature-rich third-party apps. Though there might be other options available to get rid of the irksome YouTube ads, the easiest and single app solution to remove ads is downloading an Adblock browser app that will act as your default browser when you try to want to watch YouTube videos. The steps to set up your Android to block YouTube ads are down here. * 1\. Click [**Here**](https://adblockbrowser.org/) to install Adblock Browser on your Android device. ![install adblock](https://images.wondershare.com/filmora/article-images/install-adblock1-min.jpg) * 2\. It is a full-fledged browser and can act as your primary browser for YouTube playback. ![open browser](https://images.wondershare.com/filmora/article-images/open-browser2-min.jpg) * 3\. After installing the Adblock Browser your Android device may still try to play videos in the YouTube app. * 4\. To current that, open the “Settings” on your Android and go to “Apps & notifications” and press See all. In the apps find YouTube, tap in to see app info. ![apps and notifications](https://images.wondershare.com/filmora/article-images/apps-and-notifications3-min.jpg) * 5\. In the App info screen click “Storage & cache”. ![app info](https://images.wondershare.com/filmora/article-images/app-info4-min.jpg) * 6\. Tap on “Clear storage”. This will clear all the cache and data of the app from the operating system. ![clear storage](https://images.wondershare.com/filmora/article-images/clear-storage5-min.jpg) * 7\. Now your YouTube videos will be played in the Adblock Browser. ### 2.iPhone On iOS, you can keep using the default iOS browser and still be able to block YouTube ads in the Safari browser app. You can add third-party ad blocker apps to disable YouTube ads on your iPhone and link it as the Content Blocker in the Safari settings. To activate the ad blocking feature, follow the steps. * 1\. Open Apple Store and download any ad blocker app you like. ![download any blocker](https://images.wondershare.com/filmora/article-images/download-any-blocker6-min.jpg) * 2\. Now come to the iPhone device Settings and go to Safari. ![iphone device settings](https://images.wondershare.com/filmora/article-images/iphone-device-settings7-min.jpg) * 3\. In the Safari settings, you will find a “Block Pop-ups” toggle button, activate it. * 4\. Right below the toggle button, you’ll see the “Content Blockers” tap to configure it. ![content blocker](https://images.wondershare.com/filmora/article-images/content-blocker8-min.jpg) * 5\. The ad blocker app you just downloaded will be displaying under Allow these content blockers, enable it with the toggle button. ![allow blocker](https://images.wondershare.com/filmora/article-images/allow-blocker9-min.jpg) * 6\. Now your Safari browser will block all YouTube ads during playback. ## **Conclusion** Ads can be annoying and time-wasting if you are being forced to watch them every other minute. YouTube is as addictive as its active userbase depict and during that addiction, anyone will not accept an interruption. To do away with the disruptive adds and block YouTube ads on any of your devices from PC to Mac, or mobile devices you need to have an adblocker application that will disable YouTube ads and make your video viewing experience smooth and relishing. ![author avatar](https://images.wondershare.com/filmora/article-images/richard-bennett.jpg) Richard Bennett Richard Bennett is a writer and a lover of all things video. Follow @Richard Bennett <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://facebook-video-footage.techidaily.com/new-earning-potential-in-beauty-blogging-for-2024/"><u>[New] Earning Potential in Beauty Blogging for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-in-2024-boosting-video-quality-utilizing-youtube-studios-features/"><u>[New] In 2024, Boosting Video Quality Utilizing YouTube Studio's Features</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/topics-with-a-twist-for-your-vlog-talks-for-2024/"><u>Topics with a Twist for Your Vlog Talks for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-creating-custom-subscribe-urls-for-online-content/"><u>[Updated] 2024 Approved Creating Custom Subscribe URLs for Online Content</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-2024-approved-captivating-viewers-youtubers-guide-to-dynamic-game-sessions/"><u>[New] 2024 Approved Captivating Viewers YouTubers’ Guide to Dynamic Game Sessions</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-comprehensive-guide-to-embedding-multiple-youtube-playlists-in-websites/"><u>[Updated] 2024 Approved Comprehensive Guide to Embedding Multiple YouTube Playlists in Websites</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-eye-opening-list-of-the-top-12-yt-gamers-intros-freepaid-sessions-for-2024/"><u>[Updated] Eye-Opening List of the Top 12 YT Gamers' Intros (Free/Paid Sessions) for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-the-key-to-infinite-entertainment-master-youtube-video-loops/"><u>[New] The Key to Infinite Entertainment Master Youtube Video Loops</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-bite-sized-content-on-youtube/"><u>[Updated] 2024 Approved Bite-Sized Content on YouTube</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/the-art-of-antiquated-visuals-for-modern-audienciplines-for-2024/"><u>The Art of Antiquated Visuals for Modern Audienciplines for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/binge-on-christmas-classics-enjoy-9-whole-film-flicks-no-charge-in-2024/"><u>Binge on Christmas Classics Enjoy 9 Whole-Film Flicks No Charge, In 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/2024-approved-youtube-and-dailymotion-unveiling-core-variations/"><u>2024 Approved YouTube & Dailymotion Unveiling Core Variations</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-evaluating-mr-beasts-monetary-world-for-2024/"><u>[New] Evaluating Mr. Beast's Monetary World for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-30-must-have-youtube-intros-tools-for-beginners-all-free/"><u>[Updated] 2024 Approved 30 Must-Have YouTube Intros Tools for Beginners, All Free</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-echoes-of-chuckles-parody-playlists/"><u>[Updated] In 2024, Echoes of Chuckles Parody Playlists</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-2024-approved-crescendo-control-secure-sound-sharing-online/"><u>[Updated] 2024 Approved Crescendo Control Secure Sound Sharing Online</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-avoiding-malpractice-how-to-safely-grow-a-million-fanbase-for-2024/"><u>[Updated] Avoiding Malpractice How to Safely Grow a Million Fanbase for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-in-2024-captivate-audiences-unveiling-secrets-for-striking-youtube-banners/"><u>[Updated] In 2024, Captivate Audiences Unveiling Secrets for Striking YouTube Banners</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/updated-stand-out-on-youtube-avoid-common-logo-design-fails/"><u>[Updated] Stand Out on YouTube Avoid Common Logo Design Fails</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-2024-approved-essential-guide-to-mastering-asmr-experience/"><u>[New] 2024 Approved Essential Guide to Mastering ASMR Experience</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-2024-approved-boosting-your-video-income-on-youtube-essentials/"><u>[New] 2024 Approved Boosting Your Video Income on Youtube - Essentials</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/unlock-your-potential-youtube-thumbnail-creation-on-macos-for-2024/"><u>Unlock Your Potential YouTube Thumbnail Creation on macOS for 2024</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-2024-approved-affordable-methods-to-craft-your-own-youtube-intros/"><u>[New] 2024 Approved Affordable Methods to Craft Your Own YouTube Intros</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/new-in-2024-building-a-brand-through-youtube-a-strategic-guide/"><u>[New] In 2024, Building a Brand Through YouTube A Strategic Guide</u></a></li> <li><a href="https://facebook-video-footage.techidaily.com/streamlining-access-to-subscriber-information-for-2024/"><u>Streamlining Access to Subscriber Information for 2024</u></a></li> <li><a href="https://extra-skills.techidaily.com/premiere-seminar-title-assembler-for-2024/"><u>Premiere Seminar Title Assembler for 2024</u></a></li> <li><a href="https://youtube-clips.techidaily.com/updated-customizable-mcb-visuals-for-youtube-banners/"><u>[Updated] Customizable MCB Visuals for YouTube Banners</u></a></li> <li><a href="https://screen-video-capture.techidaily.com/new-in-2024-the-ultimate-companion-for-recording-google-video-calls/"><u>[New] In 2024, The Ultimate Companion for Recording Google Video Calls</u></a></li> <li><a href="https://audio-shaping.techidaily.com/new-essential-unlicensed-melodies-for-picture-sequences/"><u>New Essential Unlicensed Melodies for Picture Sequences</u></a></li> <li><a href="https://tiktok-video-files.techidaily.com/25-popular-tiktok-creators-with-anime-flair-for-2024/"><u>25 Popular TikTok Creators with Anime Flair for 2024</u></a></li> <li><a href="https://visual-screen-recording.techidaily.com/new-crucial-steps-in-archiving-lol-matchups/"><u>[New] Crucial Steps in Archiving LOL Matchups</u></a></li> <li><a href="https://tiktok-clips.techidaily.com/updated-20-popular-tiktok-rap-songs-you-probably-have-listened-to/"><u>[Updated] 20 Popular TikTok Rap Songs You Probably Have Listened To</u></a></li> <li><a href="https://location-social.techidaily.com/in-2024-how-to-sharefake-location-on-whatsapp-for-apple-iphone-7-drfone-by-drfone-virtual-ios/"><u>In 2024, How to Share/Fake Location on WhatsApp for Apple iPhone 7 | Dr.fone</u></a></li> <li><a href="https://fix-guide.techidaily.com/in-2024-simple-and-effective-ways-to-change-your-country-on-youtube-app-of-your-vivo-y36i-drfone-by-drfone-virtual-android/"><u>In 2024, Simple and Effective Ways to Change Your Country on YouTube App Of your Vivo Y36i | Dr.fone</u></a></li> <li><a href="https://location-social.techidaily.com/in-2024-why-your-whatsapp-live-location-is-not-updating-and-how-to-fix-on-your-vivo-s17-pro-drfone-by-drfone-virtual-android/"><u>In 2024, Why Your WhatsApp Live Location is Not Updating and How to Fix on your Vivo S17 Pro | Dr.fone</u></a></li> <li><a href="https://screen-activity-recording.techidaily.com/updated-2024-approved-innovative-strategies-for-capturing-live-lectures-a-mac-centric-approach/"><u>[Updated] 2024 Approved Innovative Strategies for Capturing Live Lectures A Mac-Centric Approach</u></a></li> <li><a href="https://ai-topics.techidaily.com/easy-guide-how-to-make-talking-head-videos-for-2024/"><u>Easy Guide How To Make Talking Head Videos for 2024</u></a></li> <li><a href="https://some-tips.techidaily.com/in-2024-streamline-caption-insertion-photos-app-tutorials-for-win-11/"><u>In 2024, Streamline Caption Insertion Photos App Tutorials for WIN 11</u></a></li> <li><a href="https://extra-resources.techidaily.com/comparing-bites-new-insights-on-hero5-and-yi-4k-cameras/"><u>Comparing Bites New Insights on Hero5 & Yi 4K Cameras</u></a></li> <li><a href="https://howto.techidaily.com/app-wont-open-on-your-nubia-red-magic-8s-proplus-here-are-all-fixes-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>App Wont Open on Your Nubia Red Magic 8S Pro+? Here Are All Fixes | Dr.fone</u></a></li> <li><a href="https://ai-video-editing.techidaily.com/updated-if-you-are-into-gifs-and-want-to-know-a-great-extent-of-information-about-it-then-we-have-got-you-covered-in-this-article-here-is-what-we-have-learn/"><u>Updated If You Are Into GIFs and Want to Know a Great Extent of Information About It Then We Have Got You Covered in This Article. Here Is What We Have Learned so Far About It</u></a></li> <li><a href="https://tiktok-video-recordings.techidaily.com/navigate-to-tiktok-world-installation-for-macbook/"><u>Navigate to TikTok World Installation for MacBook</u></a></li> <li><a href="https://unlock-android.techidaily.com/in-2024-best-xiaomi-13-ultra-pattern-lock-removal-tools-remove-android-pattern-lock-without-losing-data-by-drfone-android/"><u>In 2024, Best Xiaomi 13 Ultra Pattern Lock Removal Tools Remove Android Pattern Lock Without Losing Data</u></a></li> </ul></div> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins>
from app import mysql from app.models.user import User from app.models.medecin import Medecin class Avis: def __init__(self, user_id, medecin_id, note, libelle, dateAvis, descriptionAvis, avis_id=None): self.user_id = user_id self.medecin_id = medecin_id self.note = note self.libelle = libelle self.dateAvis = dateAvis self.descriptionAvis = descriptionAvis self.avis_id = avis_id def save(self): conn = mysql.connect() cursor = conn.cursor() cursor.execute( "CALL sp_createAvis(%s, %s, %s, %s, %s, %s)", (self.user_id, self.medecin_id, self.note, self.libelle, self.dateAvis, self.descriptionAvis) ) conn.commit() cursor.close() conn.close() @staticmethod def getById(id_avis): conn = mysql.connect() cursor = conn.cursor() cursor.execute( "select * from avis where avis_id=%s", (id_avis,) ) avis_data = cursor.fetchone() cursor.close() conn.close() if avis_data: avis_id = avis_data[0] user_id = avis_data[1] medecin_id = avis_data[2] note = avis_data[3] libelle = avis_data[4] dateAvis = avis_data[5] descriptionAvis = avis_data[6] return Avis(user_id, medecin_id, note, libelle, dateAvis, descriptionAvis, avis_id) else: return None @staticmethod def getAll(): conn = mysql.connect() cursor = conn.cursor() cursor.execute( "select * from avis" ) avis_datas = cursor.fetchall() cursor.close() conn.close() avis = [] if avis_datas: for avis_data in avis_datas: avis_id = avis_data[0] user_id = avis_data[1] medecin_id = avis_data[2] note = avis_data[3] libelle = avis_data[4] dateAvis = avis_data[5] descriptionAvis = avis_data[6] avis.append( Avis(user_id, medecin_id, note, libelle, dateAvis, descriptionAvis, avis_id) ) return avis else: return None @staticmethod def getAllByUser(user_id): conn = mysql.connect() cursor = conn.cursor() cursor.execute( "select * from avis where user_id=%s", (user_id,) ) avis_datas = cursor.fetchall() cursor.close() conn.close() avis = [] if avis_datas: for avis_data in avis_datas: avis_id = avis_data[0] user_id = avis_data[1] medecin_id = avis_data[2] note = avis_data[3] libelle = avis_data[4] dateAvis = avis_data[5] descriptionAvis = avis_data[6] avis.append( Avis(user_id, medecin_id, note, libelle, dateAvis, descriptionAvis, avis_id) ) return avis else: return None @staticmethod def getAllByMedecin(medecin_id): conn = mysql.connect() cursor = conn.cursor() cursor.execute( "select * from avis where medecin_id=%s", (medecin_id,) ) avis_datas = cursor.fetchall() cursor.close() conn.close() avis = [] if avis_datas: for avis_data in avis_datas: avis_id = avis_data[0] user_id = avis_data[1] medecin_id = avis_data[2] note = avis_data[3] libelle = avis_data[4] dateAvis = avis_data[5] descriptionAvis = avis_data[6] avis.append( Avis(user_id, medecin_id, note, libelle, dateAvis, descriptionAvis, avis_id) ) return avis else: return None def update(self, note, libelle, dateAvis, descriptionAvis): conn = mysql.connect() cursor = conn.cursor() cursor.execute( "update avis set note=%s, libelle=%s, dateAvis=%s, descriptionAvis=%s where avis_id=%s", (note, libelle, dateAvis, descriptionAvis, self.avis_id) ) conn.commit() cursor.close() conn.close() def delete(self): conn = mysql.connect() cursor = conn.cursor() cursor.execute( "delete from avis where avis_id=%s", (self.avis_id,) ) conn.commit() cursor.close() conn.close()
import { useState, useRef} from 'react'; import { TextField, Tooltip } from '@mui/material'; import Box from '@mui/material/Box'; import UploadFileIcon from '@mui/icons-material/UploadFile'; import FolderOpenIcon from '@mui/icons-material/FolderOpen'; import { Fab, Button } from '@mui/material'; import { useValue } from '../../../context/ContextProvider'; import { v4 as uuidv4 } from 'uuid'; import { register } from '../../../actions/tapeStation'; // import { register as registerSeqRun } from '../../../actions/seqRun'; import { getTapeStations } from '../../../actions/tapeStation'; import { uploadFile } from '../../../actions/utils/s3'; import { useNavigate } from 'react-router-dom'; export default function ActionToolbar(props) { const { state: { currentUser, selectedTapeStations }, dispatch, } = useValue(); const [file, setFile] = useState() const navigate = useNavigate() const handleClickFile = async(e) => { const inputfile = e.target.files[0] setFile(inputfile) dispatch({ type: 'UPDATE_ALERT', payload: { open: true, severity: 'info', message: inputfile.name + ' is ready to upload !!' }, }); }; const handleUploadInfo = async(e) => { e.preventDefault(); let fileNameParts = file.name.split('.') let fileName = fileNameParts[0] if (selectedTapeStations.length === 0) return dispatch({ type: 'UPDATE_ALERT', payload: { open: true, severity: 'error', message: 'Please select libraries related to the uploaded file', }, }); let newFileName = 'TapeStation-'+uuidv4()+'-'+file.name try { const uploadResult = await uploadFile(file, newFileName, file.type) } catch (error) { const {httpStatusCode } = error.$metadata console.log({ httpStatusCode }) return dispatch({ type: 'UPDATE_ALERT', payload: { open: true, severity: 'error', message: 'HttpStatusCode: '+httpStatusCode, }, }); } for (let aItem of selectedTapeStations) { let tapeStationId = uuidv4() aItem.libType.toUpperCase() === 'DNA' ? await register({"id":tapeStationId, "name": fileName, "libType":aItem.libType, "dnaLibraryId":aItem.libId, "resultFile": newFileName, "operator":currentUser.email, },dispatch) : await register({"id":tapeStationId, "name": fileName, "libType":aItem.libType, "rnaLibraryId":aItem.libId, "resultFile": newFileName, "operator":currentUser.email, },dispatch) } navigate('/qcresult/tapeStation') } return ( <Box sx={{mt:1, mr:5, display:"flex", justifyContent:"flex-end", alignItems:"center"}}> <Fab size="small" color="primary" aria-label="add" sx={{ml:2}} component="label"> <Tooltip title="Browse Files"> <FolderOpenIcon/> </Tooltip> <input hidden type="file" onChange={handleClickFile} /> </Fab> <Fab size="small" color="primary" aria-label="add" sx={{ml:2}} component="label"> <Tooltip title="Submit"> <UploadFileIcon onClick={handleUploadInfo}/> </Tooltip> </Fab> </Box> ); }
<div class="row"> <div class="col-sm-6 offset-sm-3"> <%= form_with(model: @recipe, local: true) do |f| %> <%= render 'layouts/error_messages', model: f.object %> <div class="form-group"> <%= f.label :title, 'レシピ名' %> <%= f.text_field :title, class: 'form-control' %> </div> <div class="form-group"> <%= f.label :comment, 'レシピへのコメント' %> <%= f.text_area :comment, class: 'form-control' %> </div> <div class="form-group"> <%= f.label :image, '完成写真' %> <%= f.file_field :image, class: 'form-control' %> </div> <div class="form-group"> <%= f.label :cooking_time, '調理時間' %> <%= f.text_field :cooking_time, class: 'form-control' %> </div> <div class="form-group"> <%= f.label :material, '材料と分量' %> <%= f.text_area :material, class: 'form-control' %> </div> <div class="form-group"> <%= f.label :process, '作り方' %> <%= f.text_area :process, class: 'form-control' %> </div> <%= f.submit '投稿', class: 'btn btn-primary btn-block' %> <% end %> </div> </div>
import PropTypes from 'prop-types'; const ButtonProjects = ({ link, icon, text }) => { return ( <a href={link} target="_blank" rel="noreferrer" className="backgroundGradient flex items-center gap-1 rounded-full px-4 py-2 border-white cursor-pointer" > {icon} {text} </a> ); }; ButtonProjects.propTypes = { text: PropTypes.string.isRequired, icon: PropTypes.element.isRequired, link: PropTypes.string.isRequired, }; export default ButtonProjects;
class Api::UsersController < ApplicationController skip_before_action :verify_authenticity_token before_action :require_logged_in!, only:[:show] def create @user = User.new(user_params) if @user.save login!(@user) render "api/users/show" else render json: @user.errors.full_messages, status: 422 end end def show @user = User.find(params[:id]) if @user # render "/api/reservations/show" render :show else render json: @user.errors.full_messages, status: 404 end end private def user_params params.require(:user).permit(:email, :username, :password) end end