text
stringlengths
184
4.48M
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import reportWebVitals from './reportWebVitals'; import {BrowserRouter} from "react-router-dom"; /** * 리덕스 적용 */ import {Provider} from 'react-redux'; import {createStore} from 'redux'; import rootReducer from './modules'; import {persistStore} from "redux-persist"; import {PersistGate} from "redux-persist/integration/react"; const store = createStore(rootReducer); const persistor = persistStore(store); ReactDOM.render( <BrowserRouter> <Provider store={store}> <PersistGate loading={null} persistor={persistor}> <App/> </PersistGate> </Provider> </BrowserRouter>, document.getElementById('root') ); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();
"use client"; import MatchResultsItem from "@app/components/listItem/MatchResultsItem"; import getAllUserGameResults from "@app/hooks/game/getAllUserGameResults"; import { Divider, Spinner, User } from "@nextui-org/react"; import Link from "next/link"; type AllUserGameResult = { game_result_id: number; user_id: number; user_image: { url: string; }; user_name: string; user_user_id: string; match_result: any[]; pitching_result: any[]; plate_appearances: any[]; }; export default function AllUserGameResultItem() { const { allUserGameResults, isError, isLoading } = getAllUserGameResults(); if (isLoading) { return ( <div className="flex justify-center pb-6 pt-14"> <Spinner color="primary" /> </div> ); } if (isError) { return ( <p className="text-sm text-white text-center"> 成績の読み込みに失敗しました。 </p> ); } return ( <> <div className="mt-6 grid gap-y-6"> {allUserGameResults.map( (gameResult: AllUserGameResult, index: number) => ( <div key={index}> <div className="grid grid-cols-[1fr_auto] items-center "> <Link href={`/mypage/${gameResult.user_user_id}/`} className="block mb-2" > <User name={gameResult.user_name} description={`@${gameResult.user_user_id}`} avatarProps={{ src: process.env.NODE_ENV === "production" ? gameResult.user_image.url : `${process.env.NEXT_PUBLIC_API_URL}${gameResult.user_image.url}`, }} /> </Link> </div> <MatchResultsItem gameResult={[gameResult]} plateAppearance={[gameResult.plate_appearances]} /> <Divider className="mt-6" /> </div> ) )} </div> </> ); }
--- title: 'Factorial ANOVA - The omnibus ANOVA and Main effects' --- Note that this week's vignette assumes you have the following packages: ```{r} pacman::p_load(emmeans, ez, # get info on design of ANOVA, also can run ezANOVA Rmisc, # getting summary data cowplot, tidyverse) ``` ## TLDR; To run a factorial ANOVA we can use the `lm()` method we are familiar with. In this walkthrough we only focus on what can be done with the omnibus ANOVA assuming no interactions: The general steps for running a factorial ANOVA: 1. construct your ANOVA model using `lm` 2. use the residuals of the model to test for normality and heteroscadicity 3. test the model, checking for the presence of an interaction, and any main effects. 4. If no interaction proceed with any necessary post hoc analyses on the main effects. This week we will be focusing on Steps 1, 2, and 4, i.e., we won't be formally looking at potential interaction effects. However, as we will see next week, analyzing and interpreting interaction effects is a critical part of factorial ANOVA. For now, I want you focused on building intuitions about dealing with main effects. ### Example ```{r} # Preliminaries ## load in data dataset <- read_csv("http://tehrandav.is/PSYC7014/practice_dataSets/factorial_ANOVA_dataset_no_interactions.csv") ## in this case, fixing IV columns... dataset$Lecture <- recode_factor(dataset$Lecture, "1"="Phys","2"="Soc","3"="Hist") dataset$Presentation <- recode_factor(dataset$Presentation, "1"="Comp","2"="Stand") # Step 1: create the additive ANOVA model # note that this is not a full factorial model, but what we are focusing on this week: aov_model <- lm(Score~Lecture + Presentation,data = dataset) # Step 2a: test normalty / heteroscadicity using model visually, best to run from your console: performance::check_model(aov_model) # Step 2b: check normality and homogeneity assumptions using tests: # test residuals of model for normality: aov_model %>% resid() %>% shapiro.test() # test homogeneity: # note we are using a test from the performance package due to (somewhat) artificial limitations of the instruction method (see below) aov_model %>% performance::check_homogeneity() # Step 3: check the F-ratio for significance # note I'm only slecting columns from the anova table that are relevant to us: aov_model %>% sjstats::anova_stats() %>% dplyr::select(c("term","df","statistic","p.value","partial.etasq")) # Step 4: Post hoc analyses on main effects emmeans(aov_model, specs = pairwise~Lecture, adjust="tukey") emmeans(aov_model, specs = pairwise~Presentation, adjust="tukey") ``` ## Analysis of Variance: Factorial ANOVA In this week's vignette we are simply building upon the previous two weeks coverage of One-way ANOVA and multiple comparisons. I'm assuming you've taken a look at all of the assigned material related to these topics. This week we up the ante by introducing more complex ANOVA models, aka factorial design. As we discussed in class, a factorial ANOVA design is required (well, for the purposes of this course) when your experimental design has more than one IV. Our examples this week focus on situations involving two IVs, however, what is said here applies for more complex designs involving 3, 4, 5, or however many IV's you want to consider. Well, maybe not however many... as we we'll see this week and the next, the more IVs you include in your analysis, the more difficult interpreting your results becomes. This is especially true if you have interaction effects running all over the place. But perhaps I'm getting a little bit ahead of myself. Let's just way I wouldn't recommend including more than 3 or 4 IVs in your ANOVA at a single time and for now leave it at that. ## Main effect, main effect, and interactions... oh my! When we are performing a factorial ANOVA we are performing a series of independent comparisons of means as a function of our IVs (this assumption of independence is one of the reasons that we don't typically concern ourselves with adjusting our p-values in the omnibus factorial ANOVA). For any given number of IVs, or **factors**, we test for a **main effect** of that factor on the data---that is "do means grouped by levels within that factor differ from one another **not taking into consideration the influence of any of the other IVs"**. Our tests for interactions **do** consider the possibility that our factors influence one another---that is, "do the differences that are observed in one factor depend on the intersecting level of another?" For the sake of simplicity, we will start with a 2 × 2 ANOVA and work our way up by extending the data set. Given our naming conventions, saying that we have a 2 × 2 ANOVA indicates that there are 2 IVs and each has 2 levels. A 2 × 3 ANOVA indicates that there are 2 IVs, and that the first IV has 2 levels and the second has 3 levels; a 2 × 3 × 4 ANOVA indicates that we have 3 IVs, the first has 2 levels, the second has 3 levels, and the third has 4 levels. Our example ANOVA comes from a study testing the effects of smoking on performance in different types of *putatively* (perhaps I'm showing my theoretical biases here) information processing tasks. There were 3 types of cognitive tasks: - **1** = a pattern recognition task where participants had to locate a target on a screen; - **2** = a cognitive task where participants had to read a passage and recall bits of information from that passage later; - **3** = participants performed a driving simulation. Additionally, 3 groups of smokers were recruited - **1** = those that were actively smoking prior to and during the experiment; - **2 =** those that were smokers, but did not smoke 3 hours prior to the experiment; - **3 =** non-smokers. As this is a between design, each participants only completed one of the cognitive tasks. ## Example 1: a 2×2 ANOVA Let's grab the data from from the web. Note that for now we are going to ignore the `covar` column. ```{r} dataset <- read_delim("https://www.uvm.edu/~dhowell/methods8/DataFiles/Sec13-5.dat", "\t", escape_double = FALSE, trim_ws = TRUE) dataset ``` Looking at this data, the first think that we need to do is recode the factors. Recall that we can do this using `recode_factor`... ### Ninja-up As an alternative to `mutate()`, you can add a new column to a data frame by invoking `dataframe$new_column.` This saves us a bit of typing. Also, for weeks I've told you not to overwrite existing columns, and I maintain that is best practice for beginners. However, in this example we will overwrite. ```{r} dataset$Task <- recode_factor(dataset$Task, "1" = "Pattern Recognition", "2" = "Cognitive", "3" = "Driving Simulation") dataset$Smkgrp <- recode_factor(dataset$Smkgrp, "3" = "Nonsmoking", "2" = "Delayed", "1" = "Active") ``` To get a quick view of our data structure we can use two kinds of calls: `summary()` provides us with info related to each column in the data frame. If a column contains a factor it provides frequency counts of each level. It the column is numeric it provides summary stats: ```{r} summary(dataset) ``` In addition, I like to use the `ezDesign()` function from the `ez` package to get a feel for counts in each cell. This is useful for identifying conditions that may have missing data. ```{r} ez::ezDesign(data = dataset, x=Task, # what do you want along the x-axis y=Smkgrp, # what do you want along the y-axis row = NULL, # are we doing any sub-divisions by row... col = NULL) # or column ``` This provides us with a graphic representation of cell counts. In this case, every condition (cell) has 15 participants. As you can see right now this is a 3 x 3 ANOVA. To start, let's imagine that we are only comparing the active smokers to the nonsmokers, and that we are only concerned with the pattern recognition v driving simulation. In this circumstance we are running a 2 (smoking group: active v. passive) × 2 (task: pattern recognition v. driving simulation) ANOVA. We can do a quick subsetting of this data using the `filter()` command. For our sake, let's create a new object with this data, `dataset_2by2`: ```{r} # subsetting the data. Remember that "!=" means "does not equal"; "&" suggests that both cases must be met, so dataset_2by2 <- filter(dataset, Smkgrp!="Delayed" & Task!="Cognitive") ``` To get a quick impression of what this dataset looks like, we can use the `summary()` function, or `ezDesign()`: ```{r} # getting a summary of dataset_2by2: summary(dataset_2by2) ez::ezDesign(data = dataset_2by2, x=Task, # what do you want along the x-axis y=Smkgrp, # what do you want along the y-axis row = NULL, # are we doing any sub-divisions by row... col = NULL) # or column ``` You may notice from the summary above that the groups that were dropped "Delayed" smokers and "Cognitive" task still show up in the `summary`, albeit now with 0 instances (you'll also notice that the remaining groups decreased in number, can you figure out why?). In most cases, `R` notices this an will automatically drop these factors in our subsequent analyses. However, if needed (i.e. it's causing errors), these factors can be dropped by invoking the `droplevels()`function like so: ```{r} dataset_2by2 <- dataset_2by2 %>% droplevels() summary(dataset_2by2) ``` And to see the cell counts: ```{r} ez::ezDesign(data = dataset_2by2, x=Task,y=Smkgrp,row = NULL,col = NULL) ``` ## Making sense of plots Let's go ahead and plot the data using a line plot with 95% CI error bars. Note that these plots (up until the last section) are not APA-complete!!!! ### Interaction plots Interaction plots take into consideration the influence of each of the IVs on one another---in this case the mean and CI of each smoking group (Active v. Nonsmoking) as a function of Task (Driving Simulation v. Pattern Recognition). There is an additional consideration when plotting multiple predictors. That said, all we are doing is extending the plotting methods that you have been using for the past few weeks. The important addition here is the addition of `group=` in the first line the `ggplot`. For example: ```{r eval=FALSE} ggplot2::ggplot(data = dataset, mapping=aes(x=Smkgrp,y=score,group=Task)) ``` indicates that we are: - using the `dataset` data set - putting first IV, `Smkgrp`, on the x-axis - putting our dv, `score` on the y-axis - and grouping our data by our other IV, `Task` This last bit is important as it makes clear that the resulting mean plots should be of the cell means related to `Smkgrp` x `Task` For example, a line plot might look like this. Note that I am assigning a different `shape` and `linetype` to each level of `Task`: ```{r} # line plot ggplot(data = dataset_2by2, mapping=aes(x=Smkgrp, y=score, group=Task, shape = Task)) + stat_summary(geom="pointrange", fun.data = "mean_se") + stat_summary(geom = "line", fun = "mean", aes(linetype = Task)) + theme_cowplot() ``` One thing you may have noticed is that is very difficult to distinguish between my Task groups at the Non-smoking level, the points and error bars are overlapping one another. One way to fix this is to use the `position_dodge()` function. This effectively shifts the data points to the left and right to separate them from one another. You need to perform an identical `position_dodge()` for each element you intend to shift. In this case, we need to include it in both the `pointrange` and `line` parts of our both. Rewriting the above (while also getting rid of color per APA format) ```{r} # line plot with dodging ggplot(data = dataset_2by2, mapping=aes(x=Smkgrp, y=score, group=Task, shape = Task) ) + stat_summary(geom="pointrange", fun.data = "mean_se", position = position_dodge(0.25), ) + stat_summary(geom = "line", fun = "mean", aes(linetype = Task), position = position_dodge(0.25) ) + theme_cowplot() ``` A brief inspection of the plot can be quite informative. Let's start with the interaction, in fact: **you should always start with the interaction**. Since this is an "interaction" plot, often a quick visual inspection will allow us to predict whether our subsequent ANOVA will likely yield an interaction effect (it's good practice to plot your data *before* running your ANOVA). A simple rule of thumb is that if you see the lines converging or intersecting then more than likely an interaction is present. However, whether it's statistically significant is another question. You might think that this rule of thumb is useful if you use a line plot, and well, you'd be right. What about a bar plot, you ask? \* **Note that when generating a grouped barplot, you may need to position dodge to ensure your bars don't overlap. Typically selecting a value of 0.9 ensures they do not overlap, but also that your grouped bars are touching one another with no gap between. For practice try changing the position_dodge values in the plot below to see how that effects the plot.** ```{r} # barplot ggplot(data = dataset_2by2, mapping=aes(x=Smkgrp,y=score,group=Task)) + stat_summary(geom = "bar", fun = "mean", color="black", aes(fill=Task), position=position_dodge(.9)) + stat_summary(geom="errorbar", width=.3, fun.data = "mean_se", position = position_dodge(.9)) + theme(legend.position="none") + scale_fill_manual(values = c("light grey", "white")) ``` Note that the grey fills above are the "Driving Simulation" group and the white are the "Pattern Recognition". Take a look at the means. If the relative difference between grouped means changes as you move from one category on the x-axis to the next, you likely have an interaction. Note that this is a general rule of thumb and applies to the line plots as well (the reason that the lines intersect is because of these sorts of changes). In this case, the bar (cell) means on the "Active" grouping are nearly identical, while the bar means in the "Nonsmoking" grouping are much further apart. So we likely have interaction. ### Plotting main effects If we wanted we could also create separate plots related to our mean effects. Remember that a main effect takes a look at the difference in means for one IV **independent** of the other IV(s). For example, consider `Smkgrp`, we are looking at the means of `Nonsmoking` and `Active` indifferent to `Task`. These plots would look something like this: ```{r} Smoke_main_effect_plot <- ggplot2::ggplot(data = dataset_2by2, mapping=aes(x=Smkgrp,y=score, group=1)) + stat_summary(geom="pointrange", fun.data = "mean_se", position=position_dodge(0)) + stat_summary(geom = "line", fun = "mean", position=position_dodge(0)) + coord_cartesian(ylim=c(4,12)) + theme_cowplot() show(Smoke_main_effect_plot) ``` ```{r} Task_main_effect_plot <- ggplot2::ggplot(data = dataset_2by2, mapping=aes(x=Task,y=score, group=1)) + stat_summary(geom="pointrange", fun.data = "mean_se", position=position_dodge(0)) + stat_summary(geom = "line", fun = "mean", position=position_dodge(0)) + coord_cartesian(ylim=c(4,12)) + theme_cowplot() show(Task_main_effect_plot) ``` and would take a look at changes due to each IV without considering the other. Here we might infer that there is a main effect for both of our IVs. That said, the original interaction plot is useful as well in assessing main effects as well. In this case, to infer whether there might be main effects we can imagine where the means would be if we collapsed our grouped plots (this is exactly what the main effects take a look at). To help with your imagination I'm going to plot our main effect means on the interaction plot. Here the grey-filled triangles represent the the collapsed Smoking Group means indifferent to task. To get these, just imagine finding the midpoint of the two circles in each level of Smoking group. The slope suggests the possibility a main effect. ```{r echo=FALSE} # line plot ggplot(data = dataset_2by2, mapping=aes(x=Smkgrp,y=score,group=Task, shape = Task)) + stat_summary(geom="pointrange",fun.data = "mean_se", position=position_dodge(.5)) + stat_summary(geom = "line", fun = "mean", position=position_dodge(.5), aes(linetype=Task)) + stat_summary(aes(x=Smkgrp, y=score, group=1), geom = "point", fun = "mean", color="dark grey", size=3, shape=18) + stat_summary(aes(x=Smkgrp, y=score, group=1), geom = "line", fun = "mean", color="dark grey", size=1) + theme_cowplot() ``` To imagine the collapsed Task means, we can just find the y-values that intersect with the midpoints of each line (note the red line is the mean value of the Driving Simulation group): ```{r echo=FALSE} # to pull this plot off I first need to get the means for each level of Task. I'm going to use a function that we will discuss later on. # it might be useful to take a quick look at what task_main_effect_means look like task_main_effect_means <- Rmisc::summarySE(dataset_2by2,measurevar = "score", groupvars = "Task") # taking individual means pattern_scores_mean <- task_main_effect_means$score[1] driving_scores_mean <- task_main_effect_means$score[2] # finaly, plot ggplot(data = dataset_2by2, mapping=aes(x=Smkgrp,y=score,group=Task, shape = Task)) + stat_summary(geom="pointrange",fun.data = "mean_se", position=position_dodge(.5)) + stat_summary(geom = "line", fun = "mean", position=position_dodge(.5), aes(linetype=Task)) + geom_hline(yintercept = pattern_scores_mean, color="red", lty="dashed") + geom_hline(yintercept = driving_scores_mean, color="blue", lty="dashed") + theme_cowplot() ``` The difference in y-intercepts suggests the possibility of a main effect. So in summary, I'm guessing from plot I've got 2 main effects and an interaction. For this week, we are only going to focus on the main effects. In the future, you'll see that we would need to test for the interaction as well, and if it was present we would need to "deal" with that first. For now, let's focus on testing the main effects. ## Running the ANOVA `lm()` method Now we can run the using the `lm()` method as we have previously done with the One-way ANOVA. The new wrinkle is simply adding our additional IV terms to the the formula equation: $$y=IV_1+IV_2+...+IV_n$$ where the first and second terms capture our main effects and the third is our interaction. Using our data in `R` this formula becomes: ```{r eval=FALSE} aov_model <- lm(score~Smkgrp+Task,data = dataset_2by2) ``` ## Assumption testing ### visual inspection Let's quickly assess whether the prescribed model satisfies the assumptions for general linear models. Visually we may call upon the `performance::check_model().` to get a series of visual inspection checks in a single plot. **Note that you encounter errors in your `.qmd`, you may try to run this directly from your Console** ```{r} aov_model %>% performance::check_model() ``` Alternatively, running the above with **`panel = FALSE`** allows you to see each plot individually. ```{r} aov_model %>% performance::check_model(panel = FALSE) ``` For our purposes this semester, the **Homogeneity of Variance** and **Normality of Residuals** plots are most important. Visual inspection suggests that while normality may not be and issue, there is potentially something awry with the homogeneity of variance. ### test for assessing normality If we want to check the normality of residuals we may use the **Shapiro-Wilkes Test**. We can call it directly using `shapiro.test()` or from the `performance` library. I show both methods below (you only need to choose ONE. In week's past you've been using the `shapiro.test()`: ```{r} aov_model$residuals %>% shapiro.test() aov_model %>% performance::check_normality() ``` Keep in mind that the Shapiro-Wilkes test for normality is notoriously conservative. In week's past we discussed an alternative based on this method from Kim (2013) "Statistical notes for clinical researchers: assessing normal distribution using skewness and kurtosis": ```{r} # recommendation from Kim (2013) source("http://tehrandav.is/psyc7014/custom_functions/skew_kurtosis_z.R") aov_model$residuals %>% skew_kurtosis_z() ``` Based on what you see what conclusions might you make? ### test for assessing homogeneity of variance Typically, we can submit our `aov_model` to `car::leveneTest` to test for homogeneity. However, for this week only, this will produce an error. This is because the `car::leveneTest()` demands that the IVs in a factorial ANOVA be crossed. That is, the **Levene's test** requires that we include the interaction term in our model. This week, we are NOT looking at interactions, nor am I asking you to include the terms in our model. Because of this, we will us an alternate method, **the Bartlet test** while noting that in future weeks, and under most practical circumstances this will not be an issue. FWIW, the `performance` method works as a reliable alternative to `car::leveneTest` in most circumstances, so you could elect to just use this instead using `method = "levene"`. ```{r} aov_model %>% performance::check_homogeneity(method = "bartlet") ``` Our test says we have a violation (which is consistent with our visual inspection above. Let's take a look at the 3x time rule. To do this we need to get a feel for the variance within each cell. While we are at it we might as well get the means too. Which leads to the next section (don't worry we'll come back to this) ## Getting cell means and sd Up until this point we've used `psych::describeBy()` to generate summary stats. This becomes a little more difficult as the designs become more complex. Alternatively you might elect to build a data table yourself. You learned how to do this a few weeks ago using the summarise function: ```{r} dataset_2by2 %>% group_by(Task, Smkgrp) %>% summarise(mean = mean(score), # get group means var = var(score)) # get group variances ``` Another alternative, that I would recommend over the `psych` package is to use `summarySE()` from the `Rmisc` package: ```{r} Rmisc::summarySE(data = dataset_2by2, # your dataset measurevar = "score", # your dv groupvars = c("Task","Smkgrp")) # your between-groups IV(s) ``` Recalling that we had an issue with heteroscadicity, we can now use the obtained `sd` values to assess whether our violation is too great. Let's save our summary table: ```{r} cell_summary_table <- Rmisc::summarySE(data = dataset_2by2, # your dataset measurevar = "score", # your dv groupvars = c("Task","Smkgrp")) ``` from this we can call the `sd` values and square them to get our variance: ```{r} # varience is sd-squared: cell_summary_table$sd^2 ``` Houston we have a problem! The largest variance there is definitely greater than 3x the smallest. What to do? For now nothing, I don't want you to go down that rabbit hole just yet. But look for info on dealing with this later. ## getting marginal means for main effects We can also use this function to report the means related to the main effects (irrespective of interaction). For example, Smoking effect I can re-write the call above, simply dropping `Task` from `groupvars`: ```{r} Rmisc::summarySE(data = dataset_2by2,measurevar = "score",groupvars = "Smkgrp") ``` and for the Task effect: ```{r} Rmisc::summarySE(data = dataset_2by2,measurevar = "score",groupvars = "Task") ``` Note that If you are reporting means related to the main effects, you need to report these marginal means! HOWEVER... this data has an interaction, and remember what I said above, if the data has an interaction, you need to deal with that first. We'll show how to work with data that has interactions next week. ## Testing the ANOVA Ok. Now let's look at our ANOVA table. Note that instead of the full print out, I'm asking `sjstats` to only give me the values I'm interested in: the **term** (effect), **df**, (F) **statistic**, p-**value**, and effect size, in this case **partial.eta** ```{r} sjstats::anova_stats(aov_model) %>% select("term","df","statistic","p.value","partial.etasq") ``` You'll note that both main effects are significant, meaning that we would need to perform pairwise, post-hoc comparisions for each effect. **BUT** **you'll also note that each of our factors ONLY HAD TWO LEVELS, meaning that the F-test in the ANOVA table *IS* a pairwise comparison.** In cases like this, when the effect only has 2 levels, we are done (any post hoc analysis would be redundant). Assuming you feel comfortable with everything in this walkthrough, let's proceed to the next, which includes cases where our factors have three (or more) levels.
import {Trans, Plural} from '@lingui/react' import {DataLink} from 'components/ui/DbLink' import {BASE_GCD} from 'data/CONSTANTS' import {Event, Events} from 'event' import {filter} from 'parser/core/filter' import {dependency} from 'parser/core/Injectable' import {Actors} from 'parser/core/modules/Actors' import {TieredSuggestion, SEVERITY} from 'parser/core/modules/Suggestions' import {Weaving, Weave} from 'parser/core/modules/Weaving' import React from 'react' import {DISPLAY_ORDER} from './DISPLAY_ORDER' const MAX_CAST_TIME_FOR_SINGLE_WEAVE = 1500 const SINGLE_WEAVE_MS = 1000 const MAX_SURPANAKHA_CHARGES = 4 const MAX_ALLOWED_MULTIWEAVE_DURING_MOON_FLUTE = 6 // Surpanakha has four charges, and each it is pressed, it gives // a buff that increases the damage of the next Surpanakha, but // ONLY if no other action is used. // That "no other action" is EXTREMELY strict. No GCD, no oGCDs, // no items, no sprint. // // Each Surpanakha cast is *roughly* ~850ms, assuming little latency; // this module uses a flat 1000ms to accommodate for typical latency. // // Additionally, the standard opener has us doing a very // funny HEXAWEAVE (Swift, Glass Dance, Surpanakha x4) so // we need to except that specific situation too. // export class BLUWeaving extends Weaving { static override displayOrder = DISPLAY_ORDER.WEAVING private badSurpanakhaSequence = 0 @dependency private actors!: Actors override initialise() { super.initialise() this.addEventHook(filter<Event>().type('complete'), this.onCompleteExtra) } override getMaxWeaves(weave: Weave) { let surpanakhas = 0 let foundBadSurpanakhaSequence = false const weaves: Array<Events['action']> = weave.weaves weaves.forEach(weave => { if (weave.action === this.data.actions.SURPANAKHA.id) { surpanakhas++ } else if (surpanakhas >=1 && surpanakhas < MAX_SURPANAKHA_CHARGES) { foundBadSurpanakhaSequence = true } }) if (foundBadSurpanakhaSequence || (surpanakhas && surpanakhas !== MAX_SURPANAKHA_CHARGES)) { this.badSurpanakhaSequence++ } // It is expected and intentional to clip GCDs during Moon Flute windows. if (this.actors.current.hasStatus(this.data.statuses.WAXING_NOCTURNE.id)) { // The big case is multi-weaving with Surpanakha: if (surpanakhas && !foundBadSurpanakhaSequence && weaves.length > surpanakhas && weaves.length <= MAX_ALLOWED_MULTIWEAVE_DURING_MOON_FLUTE) { // We got four Surpanakhas, they were correctly used in sequence, but there's // more to this weave window. // If the weave happened after the final Surpanakha then they're unnecessarily // clipping their next GCD, so we'll fall through and give them a suggestion // based on that if (weaves[weaves.length - 1].action === this.data.actions.SURPANAKHA.id) { // ...but here's the other alternative. They did the four Surpanakhas at // the end of the weave slot. IF they are following the standard opener, // then they did something like this: // Bristle (Swiftcast, Glass Dance, Surpanakha x4) // So let's be understanding. During a Moon Flute window, single or // double weaving *before* the Surpanakhas is potentially fine. // Continue the handwavey assumption that any weave takes 1000ms const extraWeaveTimeMs = SINGLE_WEAVE_MS * (weaves.length + 1) if (weave.gcdTimeDiff < extraWeaveTimeMs) { return weaves.length } } } // And the second case: To fit all the oGCDs we have, we hard-clip // 2s cast time GCDs during Moon Flute windows: if (weaves.length === 1 && weave.leadingGcdEvent !== undefined) { const castTime = this.castTime.forEvent(weave.leadingGcdEvent) ?? BASE_GCD const allowedWeaveClippingDuringMF = castTime + SINGLE_WEAVE_MS if (weave.gcdTimeDiff < allowedWeaveClippingDuringMF) { return weaves.length } } } // Otherwise, we only accept Surpanakha when it is not weaved with anything else. if (surpanakhas && weaves.length === surpanakhas && weave.gcdTimeDiff < (surpanakhas + 1) * SINGLE_WEAVE_MS) { return surpanakhas } // The default weaving module allows a single-weave after any spell with // a cast time between 1.5 and 2.5 -- But here we want to disallow weaving // after a 2s cast time GCD: if (weave.leadingGcdEvent !== undefined) { const castTime = this.castTime.forEvent(weave.leadingGcdEvent) ?? BASE_GCD if (castTime > MAX_CAST_TIME_FOR_SINGLE_WEAVE) { // 2s cast time spell, possibly a bit lower due to SpS; no weaves allowed return 0 } } return super.getMaxWeaves(weave) } private onCompleteExtra() { // Give a suggestion for people who didn't use Surpanakha x4, losing the buff and // a bunch of damage. // // There's an edge case here -- Some fights you may want to delay your Moon Flute window by // 30 seconds, at which point you might as well use a single charge of Surpanakha rather than // having it go to waste. // // But if people are clever & skilled enough to do that kind of optimization, then they're // clever enough to understand that they can disregarding the misfiring message. this.suggestions.add(new TieredSuggestion({ icon: this.data.actions.SURPANAKHA.icon, content: <Trans id="blu.weaving.bad_surpanakha.content"> Use all four <DataLink action="SURPANAKHA" /> charges at the same time, with no other actions in-between. Even <DataLink action="SPRINT" showIcon={false} /> or using an item will cancel the buff. </Trans>, why: <Trans id="blu.weaving.bad_surpanakha.why"> <Plural value={this.badSurpanakhaSequence} one="# Surpanakha chain" other="# Surpanakha chains" /> dropped the buff early. </Trans>, tiers: {1: SEVERITY.MAJOR}, value: this.badSurpanakhaSequence, })) } }
/** * Takes all the line items and adds them up * @param {Array | undefined} lineItems * @returns {number} */ export const sumLineItems = (lineItems: LineItem[] | undefined): number => { if (!lineItems) return 0; return lineItems.reduce((prevValue, curValue) => prevValue + curValue.amount, 0); }; /** * Takes and returns a dollar amount (USD), formatted with commas and 2 decimal places * @param {number} cents * @returns {string} */ export const centsToDollars = (cents: number): string => { const dollars = cents / 100; const addDecimals = twoDecimals(dollars); return addThousandsSeperator(addDecimals); }; /** * Takes a dollar amount and converts it to cents * @param {number} dollars * @returns {number} */ export const dollarsToCents = (dollars: number): number => { return dollars * 100; }; /** * Takes a number and returns a number with two decimal places * @param {number} myNum * @returns {string} */ export const twoDecimals = (myNum: number): string => { return myNum.toFixed(2); }; /** * Adds a thousands seperator * @param {string} myNum * @returns {string} */ export const addThousandsSeperator = (myNum: string): string => { return myNum.replace(/\B(?=(\d{3})+(?!\d))/g, ','); }; /** * Takes all the invoices and finds the total * @param {Invoice} invoices * @returns {number} */ export const sumInvoices = (invoices: Invoice[] | undefined): number => { if (!invoices) return 0; return invoices.reduce((prevValue, curValue) => { const invoiceSum = sumLineItems(curValue.lineItems); return prevValue + invoiceSum; }, 0); };
/* * Copyright 2017 - 2023 the original author or authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see [http://www.gnu.org/licenses/] */ package cn.taketoday.transaction.reactive; import java.util.function.Function; import cn.taketoday.context.ApplicationEvent; import cn.taketoday.context.ApplicationEventPublisher; import cn.taketoday.context.PayloadApplicationEvent; import reactor.core.publisher.Mono; /** * A delegate for publishing transactional events in a reactive setup. * Includes the current Reactor-managed {@link TransactionContext} as * a source object for every {@link ApplicationEvent} to be published. * * <p>This delegate is just a convenience. The current {@link TransactionContext} * can be directly included as the event source as well, and then published * through an {@link ApplicationEventPublisher} such as the Infra * {@link cn.taketoday.context.ApplicationContext}: * * <pre>{@code * TransactionContextManager.currentContext() * .map(source -> new PayloadApplicationEvent&lt;&gt;(source, "myPayload")) * .doOnSuccess(this.eventPublisher::publishEvent) * }</pre> * * @author Juergen Hoeller * @author <a href="https://github.com/TAKETODAY">Harry Yang</a> * @see #publishEvent(Function) * @see #publishEvent(Object) * @see ApplicationEventPublisher * @since 4.0 */ public class TransactionalEventPublisher { private final ApplicationEventPublisher eventPublisher; /** * Create a new delegate for publishing transactional events in a reactive setup. * * @param eventPublisher the actual event publisher to use, * typically a Infra {@link cn.taketoday.context.ApplicationContext} */ public TransactionalEventPublisher(ApplicationEventPublisher eventPublisher) { this.eventPublisher = eventPublisher; } /** * Publish an event created through the given function which maps the transaction * source object (the {@link TransactionContext}) to the event instance. * * @param eventCreationFunction a function mapping the source object to the event instance, * e.g. {@code source -> new PayloadApplicationEvent&lt;&gt;(source, "myPayload")} * @return the Reactor {@link Mono} for the transactional event publication */ public Mono<Void> publishEvent(Function<TransactionContext, ApplicationEvent> eventCreationFunction) { return TransactionContextManager.currentContext().map(eventCreationFunction) .doOnSuccess(this.eventPublisher::publishEvent).then(); } /** * Publish an event created for the given payload. * * @param payload the payload to publish as an event * @return the Reactor {@link Mono} for the transactional event publication */ public Mono<Void> publishEvent(Object payload) { if (payload instanceof ApplicationEvent) { return Mono.error(new IllegalArgumentException("Cannot publish ApplicationEvent with transactional " + "source - publish payload object or use publishEvent(Function<Object, ApplicationEvent>")); } return publishEvent(source -> new PayloadApplicationEvent<>(source, payload)); } }
package main import ( "fmt" ) type ListNode struct { Val int Next *ListNode } func detectCycle(head *ListNode) *ListNode { if head == nil { return nil } slow := head fast := head for slow != nil { // fmt.Printf("slow = %v, fast = %v\n", slow, fast) if fast == nil || fast.Next == nil { return nil } slow = slow.Next fast = fast.Next.Next if slow == fast { fast = head for slow != fast { // fmt.Printf("after has cycle: slow = %v, fast = %v\n", slow, fast) slow = slow.Next fast = fast.Next } return fast } } return nil } func makeList1() *ListNode { root := &ListNode{Val: 3} root.Next = &ListNode{Val: 2} root.Next.Next = &ListNode{Val: 0} root.Next.Next.Next = &ListNode{Val: -4} root.Next.Next.Next.Next = root.Next return root } func makeList2() *ListNode { root := &ListNode{Val: 1} root.Next = &ListNode{Val: 2} root.Next.Next = root.Next return root } func makeList3() *ListNode { root := &ListNode{Val: 1} return root } func makeList4() *ListNode { root := &ListNode{Val: 3} root.Next = &ListNode{Val: 2} root.Next.Next = &ListNode{Val: 0} root.Next.Next.Next = &ListNode{Val: -4} root.Next.Next.Next.Next = &ListNode{Val: -5} root.Next.Next.Next.Next.Next = &ListNode{Val: 9} root.Next.Next.Next.Next.Next.Next = &ListNode{Val: 100} root.Next.Next.Next.Next.Next.Next.Next = root.Next.Next.Next.Next return root } func main() { // result: indexed 1 node // head := makeList1() // result: indexed 0 node // head := makeList2() // result: nil // head := makeList3() // result: indexed 4 node head := makeList4() // result: // head := makeList() result := detectCycle(head) fmt.Printf("result = %v\n", result) }
require_relative '../fastlane/readme_api/api' require_relative '../fastlane/code_blocks/code_blocks' require 'rspec' RSpec.describe 'Fastfile' do before do # Set the current working directory to the spec folder so it behaves the same as fastlane current_dir = File.dirname(File.expand_path(__FILE__)) Dir.chdir(current_dir) Dir.rmdir('spec/test_files/rendered_docs') if Dir.exist?('spec/test_files/rendered_docs') end context 'code_blocks' do it 'embed_code_blocks' do embed_code_blocks('spec/test_files/rendered_docs', 'spec/test_files/docs_source') check_rendered_docs end it 'clean images' do file_contents = get_file_contents('spec/test_files/file_with_two_block_images.md') expected_clean_file_contents = get_file_contents('spec/test_files/clean_file_with_two_block_images.md') cleaned = clean_images_in_file_contents(file_contents) expect(cleaned).to eq(expected_clean_file_contents) end end end def check_rendered_docs Dir.chdir(root_dir) do rendered_docs = Dir.glob("spec/test_files/rendered_docs/**/*.md") expected_docs = Dir.glob('spec/test_files/expected_rendered_docs/**/*.md') expect(rendered_docs.size).to be > 0 expect(rendered_docs.size).to eq(expected_docs.size) rendered_docs.each_with_index do |rendered_doc, index| expected_doc = expected_docs[index] rendered_doc_content = File.read(rendered_doc) expected_doc_content = File.read(expected_doc) expect(expected_doc_content.size).to be > 0 expect(expected_doc_content).to eq(rendered_doc_content) end end end
// // DynamicFilteredView.swift // Task Manager // // Created by Can on 29.10.2022. // import SwiftUI import CoreData struct DynamicFilteredView<Content: View, T>: View where T: NSManagedObject { // MARK: - Core Data Request @FetchRequest var request: FetchedResults<T> let content: (T) -> Content // MARK: - Building Custom ForEach which will give CoreData object to build View init(currentTab: String, @ViewBuilder content: @escaping (T) -> Content) { // MARK: - Predicate to filter current date Tasks let calendar = Calendar.current var predicate: NSPredicate! if currentTab == "Today" { let today = calendar.startOfDay(for: Date()) let tomorrow = calendar.date(byAdding: .day, value: 1, to: today)! // Filter key let filterKey = "deadline" // Below predicate will fetch tasks between today and tomorrow. // 0-false, 1-true predicate = NSPredicate(format: "\(filterKey) >= %@ AND \(filterKey) < %@ AND isCompleted == %i", argumentArray: [today, tomorrow, 0]) } else if currentTab == "Upcoming" { let tomorrow = calendar.date(byAdding: .day, value: 1, to: Date())! let future = Date.distantFuture // Filter key let filterKey = "deadline" // Below predicate will fetch tasks between today and tomorrow. // 0-false, 1-true predicate = NSPredicate(format: "\(filterKey) >= %@ AND \(filterKey) < %@ AND isCompleted == %i", argumentArray: [tomorrow, future, 0]) } else if currentTab == "Failed" { let today = calendar.startOfDay(for: Date()) let past = Date.distantPast // Filter key let filterKey = "deadline" // Below predicate will fetch tasks between today and tomorrow. // 0-false, 1-true predicate = NSPredicate(format: "\(filterKey) >= %@ AND \(filterKey) < %@ AND isCompleted == %i", argumentArray: [past, today, 0]) } else { predicate = NSPredicate(format: "isCompleted == %i", argumentArray: [1]) } // Initialize request with NSPredicate _request = FetchRequest(entity: T.entity(), sortDescriptors: [.init(keyPath: \Task.deadline, ascending: false)], predicate: predicate) self.content = content } var body: some View { Group { if request.isEmpty { Text("No task found!") } else { ForEach(request, id: \.objectID) { object in self.content(object) } } } } }
package ua.nure.andreiko.airline.web.command.dispatcherCommands; import org.apache.log4j.Logger; import ua.nure.andreiko.airline.Path; import ua.nure.andreiko.airline.db.DBManager; import ua.nure.andreiko.airline.db.entity.Application; import ua.nure.andreiko.airline.db.entity.Flights; import ua.nure.andreiko.airline.db.entity.Workers; import ua.nure.andreiko.airline.exception.AppException; import ua.nure.andreiko.airline.exception.DBException; import ua.nure.andreiko.airline.web.command.Command; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Create application command. * * @author E.Andreiko */ public class CreateAppCommand extends Command { private static final Logger LOG = Logger.getLogger(CreateAppCommand.class); DBManager dbManager; String subject; String message; @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException, AppException { LOG.debug("Command start"); dbManager = DBManager.getInstance(); subject = request.getParameter("subject"); message = request.getParameter("message"); dbManager.createApp(subject, message); LOG.trace("Create new message in DB"); fillingTables(request); LOG.trace("Set the request attribute all lists"); LOG.debug("Commands finished"); return Path.PAGE_DISPATCHER_FUNC; } /** * Filling tables in dispatcher_menu.jsp * * @param request Http request. * @throws DBException */ private void fillingTables(HttpServletRequest request) throws DBException { List<Flights> flightsListFormationBrigade = dbManager.findFlights(); List<Flights> flightsList = dbManager.findFlights(); List<Application> applicationList = dbManager.findApp(); List<Workers> workersList = dbManager.findWorkers(); List<Workers> pilotsList = dbManager.getPilots(); List<Workers> navigatorList = dbManager.getNavigator(); List<Workers> operatorList = dbManager.getOperator(); List<Workers> stewardessList = dbManager.getStewardess(); flightsListFormationBrigade.removeIf(flight -> flight.getBrigade() != 0); pilotsList.removeIf(workers -> workers.getBrigade_id() != 0); navigatorList.removeIf(workers -> workers.getBrigade_id() != 0); operatorList.removeIf(workers -> workers.getBrigade_id() != 0); stewardessList.removeIf(workers -> workers.getBrigade_id() != 0); request.setAttribute("flightsList", flightsList); request.setAttribute("flightsListFormationBrigade", flightsListFormationBrigade); request.setAttribute("applicationList", applicationList); request.setAttribute("workersList", workersList); request.setAttribute("pilotsList", pilotsList); request.setAttribute("navigatorList", navigatorList); request.setAttribute("operatorList", operatorList); request.setAttribute("stewardessList", stewardessList); } }
from unittest import mock import sklearn.preprocessing as pp import pandas as pd import pytest from src.enum.scaling_methods_enum import ScalingMethodEnum from src.scaling.standard_scaler import StandardScaler DATA = pd.DataFrame({'col': ['value0', 'value1'], 'col1': ['value2', 'value3']}) COLUMNS = ['col1'] def test_attributes(): scaler = StandardScaler() assert scaler.method == ScalingMethodEnum.STANDARD_SCALER assert isinstance(scaler.base_scaler, pp.StandardScaler) assert scaler.scaler is None @mock.patch('sklearn.preprocessing.StandardScaler.fit_transform') def test_fit_scale(mock_scaler_fit_transform): return_scaler = pd.DataFrame({'col1': ['value4', 'value5']}) expected_output = pd.DataFrame({'col': ['value0', 'value1'], 'col1': ['value4', 'value5']}) mock_scaler_fit_transform.return_value = return_scaler actual_output = StandardScaler().fit_scale(DATA, COLUMNS) mock_scaler_fit_transform.assert_called_once() assert actual_output.equals(expected_output) @mock.patch('sklearn.preprocessing.StandardScaler.transform') def test_scale(mock_scaler_fit_transform): return_scaler = pd.DataFrame({'col1': ['value4', 'value5']}) expected_output = pd.DataFrame({'col': ['value0', 'value1'], 'col1': ['value4', 'value5']}) mock_scaler_fit_transform.return_value = return_scaler scaler = StandardScaler() scaler.scaler = scaler.base_scaler actual_output = scaler.scale(DATA, COLUMNS) mock_scaler_fit_transform.assert_called_once() assert actual_output.equals(expected_output) def test_scale_none_scaler(): with pytest.raises(Exception) as e_info: StandardScaler().scale(DATA, COLUMNS) assert str(e_info.value) == "You must train the scaler before calling scale method" @mock.patch('sklearn.preprocessing.StandardScaler.inverse_transform') def test_descale(mock_scaler_inverse_transform): return_scaler = pd.DataFrame({'col1': ['value4', 'value5']}) expected_output = pd.DataFrame({'col': ['value0', 'value1'], 'col1': ['value4', 'value5']}) mock_scaler_inverse_transform.return_value = return_scaler scaler = StandardScaler() scaler.scaler = scaler.base_scaler actual_output = scaler.descale(DATA, COLUMNS) mock_scaler_inverse_transform.assert_called_once() assert actual_output.equals(expected_output) def test_constructor_descale_empty_columns(): with pytest.raises(Exception) as e_info: StandardScaler().descale(DATA, COLUMNS) assert str(e_info.value) == "You must train the scaler before calling descale method"
package com.example.tobyspringboot; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.client.RestTemplate; public class HelloApiTest { @Test void helloApi(){ // http localhost:8080/hello?name=Spring // HTTPie TestRestTemplate rest =new TestRestTemplate(); ResponseEntity<String> res = rest.getForEntity("http://localhost:8080/hello?name={name}", String.class, "Spring"); // status code 200 Assertions.assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK); // header (content-type) text/plain //equalto하면 인코딩정보까지 헤더에 있기 때문에 오류가 난다. //startsWith를 써서 앞부분이 같은지 비교한다. Assertions.assertThat(res.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE)).startsWith(MediaType.TEXT_PLAIN_VALUE); //body Hello Spring Assertions.assertThat(res.getBody()).isEqualTo("Hello Spring"); //이 세가지를 왔는지 검증해야된다. } }
Day 2 ASSIGNMENT Q1 public static int smallestNumber(int x, int y, int z) { int min = y; if (y > x) { min = x; } if (z < x) { min = z; } return min; } Q2 public static String middleChar(String find) { char[] str = find.toCharArray(); String middle = ""; int index = str.length / 2; if (str.length % 2 == 0) { middle = Character.toString(str[index - 1]) + Character.toString(str[index]); } else { middle = Character.toString(str[index]); } return middle; } Q3 public static void countVowels(String str) { char[] st = str.toLowerCase().toCharArray(); char[] vls = { 'a', 'e', 'i', 'o', 'u' }; int count = 0; for (Character c : st) { for (Character v : vls) { if (c == v) { count++; } } } System.out.println("Number of Vowels in the string: " + count); } Q4 public class Room { private int roomNo; private String roomType; private double roomArea; private int ACMachine; public Room(int roomNo, String roomType, double roomArea, int ACMachine) { this.setRoomNo(roomNo); this.setACMachine(ACMachine); this.setRoomArea(roomArea); this.setRoomType(roomType); } public static void main(String[] args) { } public int displayACMachine() { return ACMachine; } public void setACMachine(int aCMachine) { ACMachine = aCMachine; } public double displayRoomArea() { return roomArea; } public void setRoomArea(double roomArea) { this.roomArea = roomArea; } public String displayRoomType() { return roomType; } public void setRoomType(String roomType) { this.roomType = roomType; } public int displayRoomNo() { return roomNo; } public void setRoomNo(int roomNo) { this.roomNo = roomNo; } } Q5 public class A { int a = 100; public void display() { System.out.printf("a in A = %d\n", a); } } class B extends A { private int a = 123; public void display() { System.out.printf("a in B = %d\n", a); } } class C extends B { private int a = 543; public void display() { System.out.printf("a in C = %d\n", a); } } Q6 import java.util.ArrayList; import java.util.List; import java.util.Random; public class Addition { public static void main(String[] args) { Random rd = new Random(); List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { int x = rd.nextInt(20); list.add(x); } addition(list); } public static void addition(List<Integer> i) { String str = i.get(0).toString(); Integer sum = i.get(0); for (int n = 1; n < i.size(); n++) { sum += n; str += " + " + i.get(n).toString(); String end = " = " + sum.toString(); System.out.println(str + end); } } } Q7 public class InheritenceExample { public static void main(String[] args) { Bike M = new Bike(); } } class Bike extends Cycle { String define_me() { return "a cycle with an engine."; } Bike() { Cycle cyc = new Cycle(); System.out.println("Hello I am a motorcycle I am " + define_me()); String temp = cyc.define_me(); System.out.println("My ancestor is a cycle who is " + temp); } } class Cycle { String define_me() { return "a vehicle with pedals."; } } Q8 class Animal { void walk() { System.out.println("I am walking"); } } class Dog extends Animal { void eat() { System.out.println("I am eating"); } void bark() { System.out.println("I am barking"); } } public class InheritenceExample { public static void main(String[] args) { Dog dog = new Dog(); dog.walk(); dog.eat(); dog.bark(); } } Q9 class Child1 extends Parent { } class Child2 extends Parent { } public class D2Q9 { public static void main(String[] args) { Parent p = new Parent(); Child1 c1 = new Child1(); Child2 c2 = new Child2(); System.out.println(c1 instanceof Parent); System.out.println(c2 instanceof Parent); System.out.println(p instanceof Child1); System.out.println(p instanceof Child2); p = c1; System.out.println(p instanceof Child1); System.out.println(p instanceof Child2); p = c2; System.out.println(p instanceof Child1); System.out.println(p instanceof Child2); } } class Parent { }
package com.flightbooking.service; import com.flightbooking.model.Flight; import org.springframework.stereotype.Service; import java.time.LocalDateTime; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; @Service public class FlightService { private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); private List<Flight> flights = Arrays.asList( new Flight("FL101", "JFK", "LAX", LocalDateTime.parse("2024-03-15 08:00", formatter), LocalDateTime.parse("2024-03-15 11:00", formatter), 120, LocalDate.parse("2024-03-15")), new Flight("FL102", "LAX", "JFK", LocalDateTime.parse("2024-03-16 13:00", formatter), LocalDateTime.parse("2024-03-16 21:00", formatter), 120, LocalDate.parse("2024-03-16")), new Flight("FL103", "LHR", "CDG", LocalDateTime.parse("2024-03-17 09:30", formatter), LocalDateTime.parse("2024-03-17 10:30", formatter), 80, LocalDate.parse("2024-03-17")), new Flight("FL104", "CDG", "LHR", LocalDateTime.parse("2024-03-18 15:00", formatter), LocalDateTime.parse("2024-03-18 16:00", formatter), 80, LocalDate.parse("2024-03-18")), new Flight("FL105", "HND", "LAX", LocalDateTime.parse("2024-03-19 17:00", formatter), LocalDateTime.parse("2024-03-20 03:00", formatter), 200, LocalDate.parse("2024-03-19")) ); public List<Flight> findAllFlights() { return flights; } public List<Flight> searchFlights(String departureAirport, String arrivalAirport, LocalDate departureDate) { return flights.stream() .filter(flight -> (departureAirport == null || flight.getDepartureAirport().equalsIgnoreCase(departureAirport)) || (arrivalAirport == null || flight.getArrivalAirport().equalsIgnoreCase(arrivalAirport)) || (departureDate == null || flight.getDepartureDate().equals(departureDate)) ) .collect(Collectors.toList()); } }
import tkinter as tk class HomePage(tk.Frame): def __init__(self, root, app): tk.Frame.__init__(self, root) self.root = root self.app = app self.create_widgets() def create_widgets(self): self.categories = [ "Home appliances", "Electronics", "Fashion", "Books", "Sports" ] self.category_label = tk.Label(self, text="Categories:") self.category_label.grid(row=0, column=0, columnspan=2) for i, category in enumerate(self.categories): row = i // 2 + 1 column = i % 2 category_button = tk.Button(self, text=category, command=lambda cat=category: self.category_clicked(cat), width=20, height=2, bg="purple", fg="white") category_button.grid(row=row, column=column, padx=5, pady=5) self.back_button = tk.Button(self, text="Back", command=self.go_back, width=10, height=1, bg="red", fg="white") self.back_button.grid(row=len(self.categories) // 2 + 2, column=0, columnspan=1, padx=5, pady=5) def category_clicked(self, category): self.app.show_page("CategoryPage") # Show the generic "CategoryPage" def go_back(self): self.app.show_previous_page()
/** * Class for managing actions based on element data attributes. */ export class Action { #element; #apiURL; #description; #libUrl; #id; /** * Initializes the Actions object with a DOM element and its data attributes. * * @param {HTMLElement} element - The DOM element containing data attributes. */ constructor(element) { if (!(element instanceof HTMLElement)) { throw new Error("triggerElement must be an instance of HTMLElement."); } this.#element = element; this.#id = element.id; this.#apiURL = element.dataset.apiUrl; this.#description = element.dataset.description; this.#libUrl = element.dataset.url; } /** * Retrieves the id/key. * * @returns {string} The element key. */ get id() { return this.#id; } /** * Retrieves the api URL. * * @returns {string} The library API url to get the version data. */ get api() { return this.#apiURL; } /** * Retrieves the library description. * * @returns {string} The library description. */ get description() { return this.#description; } /** * Retrieves the Library URL. * * @returns {string} The library url to include. */ get libUrl() { return this.#libUrl; } /** * Retrieves the DOM element. * * @returns {HTMLElement} The DOM element associated with this object. */ get element() { return this.#element; } }
{% extends 'base.html' %} {% load static %} {% block title %}Songs{% endblock %} {% block content %} <div class="grey_container" data-bs-theme="dark"> <div class="container mt-5 mb-5 w-50"> <div class="bd-masthead mt-5" id="content"> <div class="d-flex mb-4"> <div class="dropdown me-auto"> <button class="btn btn btn-outline-danger dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false"> Sort </button> <ul class="dropdown-menu"> <li><a href="{% url 'player:songs' %}?order_by=title" class="dropdown-item">Name</a></li> <li><a href="{% url 'player:songs' %}?order_by=artist" class="dropdown-item">Artist</a></li> <li><a href="{% url 'player:songs' %}?order_by=-pk" class="dropdown-item">New First</a></li> <li><a href="{% url 'player:songs' %}?order_by=pk" class="dropdown-item">Old First</a></li> </ul> </div> <form method="GET" action="{% url 'player:songs' %}" class="input-group w-25"> <input type="text" name="search_val" class="form-control" placeholder="Name" aria-label="Name" aria-describedby="button-addon2"> <button class="btn btn-danger" type="submit" id="button-addon2"><i class="fa-solid fa-magnifying-glass"></i> Search</button> </form> </div> <div class="list-group mb-5 mt-5"> {% for song in songs %} <div class="list-group-item"> <div class="d-flex align-middle"> <img id="image{{ song.pk }}" src="{{ song.image.url }}" width="60" height="60" class="me-3 song_image" alt="song_image"> <div class="me-auto"> <a class="text-decoration-none link-light" href="{{ song.get_absolute_url }}"> <h5 id="title{{ song.pk }}" class="mb-1 mt-1 text-light"> {{ song.title }} <a href="{% url 'player:save_song' song.pk %}">{% if song.is_saved %}<i class="fa-solid fa-heart text-danger"></i>{% else %}<i class="fa-regular fa-heart text-danger"></i>{% endif %}</a> </h5> </a> <a class="text-decoration-none" href="{{ song.artist.get_absolute_url }}"> <h6 id="artist{{ song.pk }}" class="text-muted">{{ song.artist }}</h6> </a> <audio id="{{ song.pk }}" style="width: 100%;"> <source src="{% if song.audio_link %}{{ song.audio_link }}{% else %}{{ song.audio_file.url }}{% endif %}" type="audio/mp3"> </audio> </div> <h5 class="mt-3 me-3"><a href='#' id="playButton{{ song.pk }}" class='link link-danger' onclick="playPauseAudio('{{ song.pk }}', this)"><i class="fa-solid fa-play"></i></a></h5> </div> </div> {% empty %} <h4 class="text-danger mt-3 mb-3 text-center">No results found</h4> {% endfor %} </div> </div> {% include 'bottom_audio.html' %} </div> </div> {% include 'pagination.html' %} {% endblock %}
#### [1015. 可被 K 整除的最小整数](https://leetcode.cn/problems/smallest-integer-divisible-by-k/) 给定正整数 `k` ,你需要找出可以被 `k` 整除的、仅包含数字 **1** 的最 **小** 正整数 `n` 的长度。 返回 `n` 的长度。如果不存在这样的 `n` ,就返回-1。 **注意:** `n` 可能不符合 64 位带符号整数。 **示例 1:** ``` 输入:k = 1 输出:1 解释:最小的答案是 n = 1,其长度为 1。 ``` **示例 2:** ``` 输入:k = 2 输出:-1 解释:不存在可被 2 整除的正整数 n 。 ``` **示例 3:** ``` 输入:k = 3 输出:3 解释:最小的答案是 n = 111,其长度为 3。 ``` ![[image-20230528171921027.png]] ![[image-20230528171959411.png]] ![[1683680206-OGDZGf-1015-3.png]] ### 算法一(无优化) ```python class Solution: def smallestRepunitDivByK(self, k: int) -> int: seen = set() x = 1 % k while x and x not in seen: seen.add(x) x = (x * 10 + 1) % k return -1 if x else len(seen) + 1 ``` ### 算法二+优化 ```python class Solution: def smallestRepunitDivByK(self, k: int) -> int: if k % 2 == 0 or k % 5 == 0: return -1 x = 1 % k for i in count(1): # 一定有解 if x == 0: return i x = (x * 10 + 1) % k ``` ### 算法三 附:[欧拉定理]([欧拉定理 & 费马小定理 - OI Wiki (oi-wiki.org)](https://oi-wiki.org/math/number-theory/fermat/#欧拉定理)) ```python # 计算欧拉函数(n 以内的与 n 互质的数的个数) def phi(n: int) -> int: res = n i = 2 while i * i <= n: if n % i == 0: res = res // i * (i - 1) while n % i == 0: n //= i i += 1 if n > 1: res = res // n * (n - 1) return res class Solution: def smallestRepunitDivByK(self, k: int) -> int: if k % 2 == 0 or k % 5 == 0: return -1 m = phi(k * 9) # 从小到大枚举不超过 sqrt(m) 的因子 i = 1 while i * i <= m: if m % i == 0 and pow(10, i, k * 9) == 1: return i i += 1 # 从小到大枚举不低于 sqrt(m) 的因子 i -= 1 while True: if m % i == 0 and pow(10, m // i, k * 9) == 1: return m // i i -= 1 ``` ```c++ class Solution { // 计算欧拉函数(n 以内的与 n 互质的数的个数) int phi(int n) { int res = n; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { res = res / i * (i - 1); while (n % i == 0) n /= i; } } if (n > 1) res = res / n * (n - 1); return res; } // 快速幂,返回 pow(x, n) % mod long long pow(long long x, int n, long long mod) { long long res = 1; for (; n; n /= 2) { if (n % 2) res = res * x % mod; x = x * x % mod; } return res; } public: int smallestRepunitDivByK(int k) { if (k % 2 == 0 || k % 5 == 0) return -1; int m = phi(k * 9); // 从小到大枚举不超过 sqrt(m) 的因子 int i = 1; for (; i * i <= m; i++) if (m % i == 0 && pow(10, i, k * 9) == 1) return i; // 从小到大枚举不低于 sqrt(m) 的因子 for (i--; ; i--) if (m % i == 0 && pow(10, m / i, k * 9) == 1) return m / i; } }; ```
import React from 'react' import PropTypes from 'prop-types' function SelectInput(props) { var i=0; let wrapperClass = "form-group" if (props.error.length > 0) { wrapperClass += " has-error" } return ( <div className={wrapperClass}> <label htmlFor={props.id}>{props.label}</label> <div className="field"> <select id={props.id} name={props.name} value={props.value || ''} onChange={props.onChange} className="form-control"> <option value=""/> { props.options.map( option => { i++ return ( <option key={i} value={i}>{option}</option> )}) } </select> </div> { props.error && <div className="alert alert-danger">{props.error}</div>} </div> ) } SelectInput.propTypes = { id : PropTypes.string.isRequired, label: PropTypes.string.isRequired, name: PropTypes.string.isRequired, value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, error: PropTypes.string, options: PropTypes.array.isRequired } SelectInput.defaultProps = { error: "" } export default SelectInput
/* * Copyright (c) 2016 ab2005@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.camino.lib.provider; import android.app.Application; import android.content.SharedPreferences; import android.net.Uri; import android.preference.PreferenceManager; import android.support.annotation.NonNull; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.core.ImagePipelineConfig; import com.facebook.stetho.Stetho; import com.camino.lib.provider.dropbox.DbxProvider; import com.camino.lib.provider.imagepipeline.ConfigFactory; import com.camino.lib.provider.local.MediaProvider; import com.camino.lib.provider.lyve.LyveCloudProvider; /** * The collection of available providers. */ public enum Providers { DROPBOX(new DbxProvider()), SEAGATE(new LyveCloudProvider()), LOCAL(new MediaProvider()); private static Application sApplication; public final Provider provider; Providers(Provider provider) { this.provider = provider; } // TODO: add option to provide config public static Application getContext() { return sApplication; } /** * A single initialization step which occurs once in your Application class {@link Application#onCreate()}. * * @param context */ public static void initWithDefaults(@NonNull Application context) { sApplication = context; ImagePipelineConfig config = ConfigFactory.getDefaultConfig(context); Fresco.initialize(context, config); //FLog.setMinimumLoggingLevel(FLog.VERBOSE); Stetho.initializeWithDefaults(context); applyStoredTokens(); } public static Provider providerForUri(Uri uri) { String authority = uri.getAuthority(); switch(authority) { case "seagate": return SEAGATE.provider; case "dropbox": return DROPBOX.provider; } return null; } /** * Load access tokens stored in the context and set providers. */ public static void applyStoredTokens() { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(sApplication); for (Providers p : Providers.values()) { String key = "Providers.access.token." + p.provider.getDomain(); String token = prefs.getString(key, null); if (token != null) { p.provider.setAccessToken(token); } } } /** * Save access tokens from provider. */ public static void storeTokens(Provider provider) { SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(sApplication).edit(); edit.commit(); String key = "Providers.access.token." + provider.getDomain(); String token = provider.getAccessToken(); edit.putString(key, token); edit.commit(); } /** * Save access tokens from providers. */ public static void storeTokens() { SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(sApplication).edit(); edit.commit(); for (Providers p : Providers.values()) { String key = "Providers.access.token." + p.provider.getDomain(); String token = p.provider.getAccessToken(); edit.putString(key, token); } edit.commit(); } }
# Internal from ouigo.types_class import Station_FR, Station_ES # From python from dataclasses import dataclass import json # External import requests stations_fr = None stations_es = None URL_API_STATIONS_ES = "https://mdw02.api-es.ouigo.com/api/Data/GetStations" URL_API_STATIONS_FR = "https://mdw.api-fr.ouigo.com/api/Data/GetStations" class DateProcessingError(Exception): pass def load_stations(country: str): """ This method call the API for get the stations of France or Spain, save the stations for futures call of this method Example of use: load_stations("ES") Response:[Station_ES(_u_i_c_station_code='MT1', name='Madrid - Todas las estaciones', connected_stations=[ '7160600','7160911', '7171801', '7104040', '7104104', '7103216'], synonyms=['Madrid'], hidden=False), Station_ES( _u_i_c_station_code='7171801',..... """ global stations_fr global stations_es try: # If not loaded, call the API if country == "FR": if stations_fr is not None: # check if the stations are already loaded return stations_fr # Create the list to save the stations stations_fr = {} response_stations = requests.get(URL_API_STATIONS_FR, timeout=10) # Call the API to get the stations else: # If the search is not in France, make the search for Spain if stations_es is not None: # check if the stations are already loaded return stations_es stations_es = {} response_stations = requests.get(URL_API_STATIONS_ES, timeout=10) # Call the API to get the stations # If the response is OK (for Spain o France) if response_stations.status_code == 200: stations_json = response_stations.json() # Convert the list of dictionaries to a list of Station objects if country == "FR": stations_fr = [Station_FR(**station) for station in stations_json] return stations_fr else: # Convert the list of dictionaries to a list of Station objects stations_es = [Station_ES(**station) for station in stations_json] return stations_es else: # If the response is not ok raise DateProcessingError(f"API call error load_stations, {response_stations.status_code}") except Exception as e: raise DateProcessingError(f"API call exception load_stations, {e}")
import React from 'react' import "./Education.css" import { VerticalTimeline, VerticalTimelineElement } from 'react-vertical-timeline-component'; import 'react-vertical-timeline-component/style.min.css'; import { FcGraduationCap } from "react-icons/fc"; function Education() { const data = [ { name: "Adama Science And Technology University", degree: "Software Engineering", year: "2021 - 2025", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis molestie a iaculis at erat. Sagittis nisl rhoncus mattis rhoncus urna. Malesuada fames ac turpis egestas integer eget aliquet nibh praesent. Sodales neque sodales ut etiam sit.", }, { name: "AlxEthiopia", degree: "Software Engineering", year: "2023 - 2024", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis molestie a iaculis at erat. Sagittis nisl rhoncus mattis rhoncus urna. Malesuada fames ac turpis egestas integer eget aliquet nibh praesent. Sodales neque sodales ut etiam sit.", }, { name: "ALXEthiopia", degree: "AiCE", year: "2024 - 2025", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis molestie a iaculis at erat. Sagittis nisl rhoncus mattis rhoncus urna. Malesuada fames ac turpis egestas integer eget aliquet nibh praesent. Sodales neque sodales ut etiam sit." }, { name: "Huawei", degree: "Data Communication and networking", year: "2023 - 2024", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis molestie a iaculis at erat. Sagittis nisl rhoncus mattis rhoncus urna. Malesuada fames ac turpis egestas integer eget aliquet nibh praesent. Sodales neque sodales ut etiam sit." }, { name: "ALXEthiopia", degree: "AiCE", year: "2024 - 2025", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis molestie a iaculis at erat. Sagittis nisl rhoncus mattis rhoncus urna. Malesuada fames ac turpis egestas integer eget aliquet nibh praesent. Sodales neque sodales ut etiam sit." }, { name: "Huawei", degree: "Data Communication and networking", year: "2023 - 2024", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Mattis molestie a iaculis at erat. Sagittis nisl rhoncus mattis rhoncus urna. Malesuada fames ac turpis egestas integer eget aliquet nibh praesent. Sodales neque sodales ut etiam sit." } ] const colors = [ "#B30000", "#006699", "#CC8800", "#009999", "#4D0099", "#1A9900", ] return ( <div className='Eduction-section' id='education'> <div class="flex flex-col items-center justify-center mb-4 text-2xl font-bold"> <h5>Education</h5> <span class="block h-2 bg-gray-400 flex-grow w-12 rounded-full"></span> </div> <div className='timeline-section'> <VerticalTimeline lineColor='tomato'> { data.map((item, index) => ( <VerticalTimelineElement key={index} className="vertical-timeline-element--work" contentStyle={{ background: colors[index], color: '#fff' }} contentArrowStyle={{ borderRight: `7px solid black` }} date={item.year} dateClassName='date-my-project' iconStyle={{ background: colors[index], color: '#fff' }} icon={<FcGraduationCap />} > <h3 className="vertical-timeline-element-title">{item.name}</h3> <h4 className="vertical-timeline-element-subtitle" style={{ color: "yellow" }}>{item.degree}</h4> <p style={{ color: "white", fontFamily: "monospace" }}> {item.description} </p> </VerticalTimelineElement> )) } </VerticalTimeline> </div> </div> ) } export default Education
/* * net/tipc/name_distr.c: TIPC name distribution code * * Copyright (c) 2000-2006, Ericsson AB * Copyright (c) 2005, 2010-2011, Wind River Systems * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "core.h" #include "link.h" #include "name_distr.h" #define ITEM_SIZE sizeof(struct distr_item) /** * struct distr_item - publication info distributed to other nodes * @type: name sequence type * @lower: name sequence lower bound * @upper: name sequence upper bound * @ref: publishing port reference * @key: publication key * * ===> All fields are stored in network byte order. <=== * * First 3 fields identify (name or) name sequence being published. * Reference field uniquely identifies port that published name sequence. * Key field uniquely identifies publication, in the event a port has * multiple publications of the same name sequence. * * Note: There is no field that identifies the publishing node because it is * the same for all items contained within a publication message. */ struct distr_item { __be32 type; __be32 lower; __be32 upper; __be32 ref; __be32 key; }; /** * struct publ_list - list of publications made by this node * @list: circular list of publications * @list_size: number of entries in list */ struct publ_list { struct list_head list; u32 size; }; static struct publ_list publ_zone = { .list = LIST_HEAD_INIT(publ_zone.list), .size = 0, }; static struct publ_list publ_cluster = { .list = LIST_HEAD_INIT(publ_cluster.list), .size = 0, }; static struct publ_list publ_node = { .list = LIST_HEAD_INIT(publ_node.list), .size = 0, }; static struct publ_list *publ_lists[] = { NULL, &publ_zone, /* publ_lists[TIPC_ZONE_SCOPE] */ &publ_cluster, /* publ_lists[TIPC_CLUSTER_SCOPE] */ &publ_node /* publ_lists[TIPC_NODE_SCOPE] */ }; /** * publ_to_item - add publication info to a publication message */ static void publ_to_item(struct distr_item *i, struct publication *p) { i->type = htonl(p->type); i->lower = htonl(p->lower); i->upper = htonl(p->upper); i->ref = htonl(p->ref); i->key = htonl(p->key); } /** * named_prepare_buf - allocate & initialize a publication message */ static struct sk_buff *named_prepare_buf(u32 type, u32 size, u32 dest) { struct sk_buff *buf = tipc_buf_acquire(INT_H_SIZE + size); struct tipc_msg *msg; if (buf != NULL) { msg = buf_msg(buf); tipc_msg_init(msg, NAME_DISTRIBUTOR, type, INT_H_SIZE, dest); msg_set_size(msg, INT_H_SIZE + size); } return buf; } static void named_cluster_distribute(struct sk_buff *buf) { struct sk_buff *buf_copy; struct tipc_node *n_ptr; list_for_each_entry(n_ptr, &tipc_node_list, list) { if (tipc_node_active_links(n_ptr)) { buf_copy = skb_copy(buf, GFP_ATOMIC); if (!buf_copy) break; msg_set_destnode(buf_msg(buf_copy), n_ptr->addr); tipc_link_send(buf_copy, n_ptr->addr, n_ptr->addr); } } kfree_skb(buf); } /** * tipc_named_publish - tell other nodes about a new publication by this node */ void tipc_named_publish(struct publication *publ) { struct sk_buff *buf; struct distr_item *item; list_add_tail(&publ->local_list, &publ_lists[publ->scope]->list); publ_lists[publ->scope]->size++; if (publ->scope == TIPC_NODE_SCOPE) return; buf = named_prepare_buf(PUBLICATION, ITEM_SIZE, 0); if (!buf) { pr_warn("Publication distribution failure\n"); return; } item = (struct distr_item *)msg_data(buf_msg(buf)); publ_to_item(item, publ); named_cluster_distribute(buf); } /** * tipc_named_withdraw - tell other nodes about a withdrawn publication by this node */ void tipc_named_withdraw(struct publication *publ) { struct sk_buff *buf; struct distr_item *item; list_del(&publ->local_list); publ_lists[publ->scope]->size--; if (publ->scope == TIPC_NODE_SCOPE) return; buf = named_prepare_buf(WITHDRAWAL, ITEM_SIZE, 0); if (!buf) { pr_warn("Withdrawal distribution failure\n"); return; } item = (struct distr_item *)msg_data(buf_msg(buf)); publ_to_item(item, publ); named_cluster_distribute(buf); } /* * named_distribute - prepare name info for bulk distribution to another node */ static void named_distribute(struct list_head *message_list, u32 node, struct publ_list *pls, u32 max_item_buf) { struct publication *publ; struct sk_buff *buf = NULL; struct distr_item *item = NULL; u32 left = 0; u32 rest = pls->size * ITEM_SIZE; list_for_each_entry(publ, &pls->list, local_list) { if (!buf) { left = (rest <= max_item_buf) ? rest : max_item_buf; rest -= left; buf = named_prepare_buf(PUBLICATION, left, node); if (!buf) { pr_warn("Bulk publication failure\n"); return; } item = (struct distr_item *)msg_data(buf_msg(buf)); } publ_to_item(item, publ); item++; left -= ITEM_SIZE; if (!left) { list_add_tail((struct list_head *)buf, message_list); buf = NULL; } } } /** * tipc_named_node_up - tell specified node about all publications by this node */ void tipc_named_node_up(unsigned long nodearg) { struct tipc_node *n_ptr; struct tipc_link *l_ptr; struct list_head message_list; u32 node = (u32)nodearg; u32 max_item_buf = 0; /* compute maximum amount of publication data to send per message */ read_lock_bh(&tipc_net_lock); n_ptr = tipc_node_find(node); if (n_ptr) { tipc_node_lock(n_ptr); l_ptr = n_ptr->active_links[0]; if (l_ptr) max_item_buf = ((l_ptr->max_pkt - INT_H_SIZE) / ITEM_SIZE) * ITEM_SIZE; tipc_node_unlock(n_ptr); } read_unlock_bh(&tipc_net_lock); if (!max_item_buf) return; /* create list of publication messages, then send them as a unit */ INIT_LIST_HEAD(&message_list); read_lock_bh(&tipc_nametbl_lock); named_distribute(&message_list, node, &publ_cluster, max_item_buf); named_distribute(&message_list, node, &publ_zone, max_item_buf); read_unlock_bh(&tipc_nametbl_lock); tipc_link_send_names(&message_list, node); } /** * named_purge_publ - remove publication associated with a failed node * * Invoked for each publication issued by a newly failed node. * Removes publication structure from name table & deletes it. */ static void named_purge_publ(struct publication *publ) { struct publication *p; write_lock_bh(&tipc_nametbl_lock); p = tipc_nametbl_remove_publ(publ->type, publ->lower, publ->node, publ->ref, publ->key); if (p) tipc_nodesub_unsubscribe(&p->subscr); write_unlock_bh(&tipc_nametbl_lock); if (p != publ) { pr_err("Unable to remove publication from failed node\n" " (type=%u, lower=%u, node=0x%x, ref=%u, key=%u)\n", publ->type, publ->lower, publ->node, publ->ref, publ->key); } kfree(p); } /** * tipc_named_recv - process name table update message sent by another node */ void tipc_named_recv(struct sk_buff *buf) { struct publication *publ; struct tipc_msg *msg = buf_msg(buf); struct distr_item *item = (struct distr_item *)msg_data(msg); u32 count = msg_data_sz(msg) / ITEM_SIZE; write_lock_bh(&tipc_nametbl_lock); while (count--) { if (msg_type(msg) == PUBLICATION) { publ = tipc_nametbl_insert_publ(ntohl(item->type), ntohl(item->lower), ntohl(item->upper), TIPC_CLUSTER_SCOPE, msg_orignode(msg), ntohl(item->ref), ntohl(item->key)); if (publ) { tipc_nodesub_subscribe(&publ->subscr, msg_orignode(msg), publ, (net_ev_handler) named_purge_publ); } } else if (msg_type(msg) == WITHDRAWAL) { publ = tipc_nametbl_remove_publ(ntohl(item->type), ntohl(item->lower), msg_orignode(msg), ntohl(item->ref), ntohl(item->key)); if (publ) { tipc_nodesub_unsubscribe(&publ->subscr); kfree(publ); } else { pr_err("Unable to remove publication by node 0x%x\n" " (type=%u, lower=%u, ref=%u, key=%u)\n", msg_orignode(msg), ntohl(item->type), ntohl(item->lower), ntohl(item->ref), ntohl(item->key)); } } else { pr_warn("Unrecognized name table message received\n"); } item++; } write_unlock_bh(&tipc_nametbl_lock); kfree_skb(buf); } /** * tipc_named_reinit - re-initialize local publications * * This routine is called whenever TIPC networking is enabled. * All name table entries published by this node are updated to reflect * the node's new network address. */ void tipc_named_reinit(void) { struct publication *publ; int scope; write_lock_bh(&tipc_nametbl_lock); for (scope = TIPC_ZONE_SCOPE; scope <= TIPC_NODE_SCOPE; scope++) list_for_each_entry(publ, &publ_lists[scope]->list, local_list) publ->node = tipc_own_addr; write_unlock_bh(&tipc_nametbl_lock); }
package org.example.lambda; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; public class MethodReferenceTypes { public static void main(String[] args) { boundMethodReferences(); unboundMethodReferences(); staticMethodReferences(); constructorMethodReferences(); } public static void boundMethodReferences() { String name = "Mr. Joe Bloggs"; // Supplier<T> // T get() Supplier<String> lowerL = () -> name.toLowerCase(); Supplier<String> lowerMR = name::toLowerCase; // no need to say which instance to call it on - the supplier is bound to name System.out.println(lowerL.get()); // mr. joe bloggs System.out.println(lowerMR.get()); // mr. joe bloggs // Predicate<T> // boolean test(T t) Predicate<String> titleL = (title) -> name.startsWith(title); Predicate<String> titleMR = name::startsWith; // Even though startsWith is overloaded, there are two versions of this method: // boolean startsWith(String) and // boolean startsWith(String, int), because we are creating a Predicate which // has a functional method od test(T t), the startsWith(String) is used. // This is where "context" is important. System.out.println(titleL.test("Mr."));//true System.out.println(titleMR.test("Mrs."));//false } public static void unboundMethodReferences() { // Function<T, R> // R apply(T) // String apply(String) Function<String, String> upperL = s -> s.toUpperCase(); Function<String, String> upperMR = String::toUpperCase; // the function is unbound, so you need to specify which instance to call it on System.out.println(upperL.apply("larissa")); // LARISSA System.out.println(upperMR.apply("larissa")); // LARISSA // BiFunction<T, U, R> // R apply(T t, U u) // String apply(String, String) BiFunction<String, String, String> concatL = (s1, s2) -> s1.concat(s2); BiFunction<String, String, String> concatMR = String::concat; System.out.println(concatL.apply("Larissa ", "Evaldt")); //Larissa Evaldt // 1st parameter is used for executing the instance method // "Larissa ".concat("Evaldt") System.out.println(concatMR.apply("Larissa ", "Evaldt")); //Larissa Evaldt } public static void staticMethodReferences() { // Static method references are considered UNBOUND also. An example static method // is Collections.sort(List) // Consumer<T> // void accept(T t) // NB: Consumer takes one parameter => sort(List) is used, as opposed to sort(List, Comparator) Consumer<List<Integer>> sortL = list -> Collections.sort(list); Consumer<List<Integer>> sortMR = Collections::sort; List<Integer> listOfNumbers = Arrays.asList(2,1,5,4,9); sortL.accept(listOfNumbers); // execution System.out.println(listOfNumbers); // [1, 2, 4, 5, 9] listOfNumbers = Arrays.asList(8,12,4,3,7); sortMR.accept(listOfNumbers); // execution System.out.println(listOfNumbers); // [3, 4, 7, 8, 12] } public static void constructorMethodReferences() { // Supplier<T> // T get() Supplier<StringBuilder> sbL = () -> new StringBuilder(); //lambda Supplier<StringBuilder> sbMR = StringBuilder::new; //method reference // Function<T, R> // R apply(T) // List<String> apply(Integer) // ArrayList(int initialCapacity) Function<Integer, List<String>> alL = x -> new ArrayList(x); Function<Integer, List<String>> alMR = ArrayList::new; List<String> ls1 = alL.apply(10); // size 10 ls1.add("21"); System.out.println(ls1); // [21] List<String> ls2 = alMR.apply(5); // size 5 ls2.add("88"); System.out.println(ls2); // [88] } }
import { CiImageOn } from "react-icons/ci"; import { BsEmojiSmileFill } from "react-icons/bs"; import { useRef, useState } from "react"; import { IoCloseSharp } from "react-icons/io5"; import useAuthUser from "../../hooks/useAuthUser"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import toast from "react-hot-toast"; import { MdClose } from "react-icons/md"; import EmojiPicker from "emoji-picker-react"; const CreatePost = () => { const [showPicker, setShowPicker] = useState(false); const [text, setText] = useState(""); const [img, setImg] = useState(null); const imgRef = useRef(null); const { data: authUser } = useAuthUser(); const queryClient = useQueryClient(); const { mutate: createPost, isPending, isError, error, } = useMutation({ mutationFn: async ({ text, img }) => { try { const res = await fetch("/api/post/create", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ text, img }), }); const data = await res.json(); if (!res.ok) { throw new Error(data.message); } return data; } catch (error) { throw error; } }, onSuccess: () => { setText(""); setImg(null); queryClient.invalidateQueries({ queryKey: ["posts"] }); toast.success("Post created successfully"); }, }); const handleSubmit = (e) => { e.preventDefault(); createPost({ text, img }); }; // Function to render the selected image on the client const handleImgChange = (e) => { const file = e.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = () => { setImg(reader.result); }; reader.readAsDataURL(file); } }; const addEmoji = (emojiData, event) => { if (emojiData) { console.log("went here"); setText((prevText) => prevText + emojiData.emoji); } }; return ( <div className="flex p-4 items-start gap-4 border-b border-gray-700"> <div className="avatar"> <div className="w-8 rounded-full"> <img src={authUser?.profileImg || "/avatar-placeholder.png"} /> </div> </div> <form className="flex flex-col gap-2 w-full" onSubmit={handleSubmit}> <textarea className="textarea w-full p-0 text-lg resize-none border-none focus:outline-none border-gray-800" placeholder="What is happening?!" value={text} onChange={(e) => setText(e.target.value)} /> {img && ( <div className="relative w-72 mx-auto"> <IoCloseSharp className="absolute top-0 right-0 text-white bg-gray-800 rounded-full w-5 h-5 cursor-pointer" onClick={() => { setImg(null); imgRef.current.value = null; }} /> <img src={img} className="w-full mx-auto h-72 object-contain rounded" /> </div> )} <div className="flex justify-between border-t py-2 border-t-gray-700"> <div className="flex gap-1 items-center"> <CiImageOn className="fill-primary w-6 h-6 cursor-pointer" onClick={() => imgRef.current.click()} /> <div onClick={() => setShowPicker(!showPicker)}> {showPicker ? ( <MdClose className="w-5 h-5 cursor-pointer" /> ) : ( <BsEmojiSmileFill className="fill-primary w-5 h-5 cursor-pointer" /> )} </div> {showPicker && <EmojiPicker onEmojiClick={addEmoji} />} </div> <input type="file" accept="image/*" hidden ref={imgRef} onChange={handleImgChange} /> <button disabled={isPending} className="btn btn-primary rounded-full btn-sm text-white px-4 disabled:opacity-80" > {isPending ? "Posting..." : "Post"} </button> </div> {isError && <div className="text-red-500">{error.message}</div>} </form> </div> ); }; export default CreatePost;
import React, { useState, useEffect } from 'react'; import { View, Text, TextInput, TouchableOpacity, ScrollView, StyleSheet, ActivityIndicator, } from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; import { useNavigation } from '@react-navigation/native'; import { CommonActions } from '@react-navigation/native'; import * as SecureStore from 'expo-secure-store'; import Spinner from '../../../components/Spinner'; const LoginScreen = () => { const navigation = useNavigation(); const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [isValidEmail, setIsValidEmail] = useState(true); const [isValidPassword, setIsValidPassword] = useState(true); const [formError, setFormError] = useState(null); const [passwordVisible, setPasswordVisible] = useState(false); const [loading, setLoading] = useState(true); const [isStoringToken, setIsStoringToken] = useState(false); useEffect(() => { const checkAuthentication = async () => { try { const storedToken = await SecureStore.getItemAsync('authToken'); setLoading(false); if (storedToken) { navigation.dispatch( CommonActions.reset({ index: 0, routes: [{ name: 'PrivatesRoutes' }], }) ); } } catch (error) { console.log('Error:', error); setFormError( `Une erreur s'est produite lors de l'authentification : ${error.message}` ); setLoading(false); } }; checkAuthentication(); }, [navigation]); const validateEmail = (text) => { const emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; setIsValidEmail(emailPattern.test(text)); setEmail(text); }; const validatePassword = (text) => { setIsValidPassword(text.length >= 8); setPassword(text); }; const storeAuthToken = async (token) => { try { setIsStoringToken(true); await SecureStore.setItemAsync('authToken', token); navigation.dispatch( CommonActions.reset({ index: 0, routes: [{ name: 'PrivatesRoutes' }], }) ); } catch (error) { setFormError( `Une erreur s'est produite lors de la tentative de stockage du jeton d'authentification : ${error.message}` ); } finally { setIsStoringToken(false); } }; const handleSignIn = async () => { if (email.trim() === '' || password.trim() === '') { setFormError('Tous les champs sont obligatoires.'); return; } if (!isValidEmail || !isValidPassword) { setFormError('Veuillez corriger les champs invalides.'); return; } const authToken = 'votre-jeton-d-authentification'; await storeAuthToken(authToken); }; return ( <ScrollView contentContainerStyle={styles.container} keyboardShouldPersistTaps="handled"> <Text style={styles.title}>Connexion</Text> {formError && <Text style={styles.errorText}>{formError}</Text>} <View style={[ styles.inputContainer, !isValidEmail && styles.invalidInputContainer, ]}> <Icon name="envelope" size={20} color="black" style={styles.icon} /> <TextInput style={[styles.input, !isValidEmail && styles.invalidInput]} placeholder="Adresse e-mail" onChangeText={(text) => validateEmail(text)} value={email} keyboardType="email-address" autoCapitalize="none" /> </View> <View style={[ styles.inputContainer, !isValidPassword && styles.invalidInputContainer, ]}> <Icon name="lock" size={20} color="black" style={styles.icon} /> <TextInput style={[styles.input, !isValidPassword && styles.invalidInput]} placeholder="Mot de passe" onChangeText={(text) => validatePassword(text)} value={password} secureTextEntry={!passwordVisible} /> <TouchableOpacity onPress={() => setPasswordVisible(!passwordVisible)} style={styles.visibilityIcon}> <Icon name={passwordVisible ? 'eye-slash' : 'eye'} size={20} color="#2E8B57" /> </TouchableOpacity> </View> <TouchableOpacity style={styles.button} onPress={handleSignIn}> {isStoringToken ? ( <ActivityIndicator color="#fff" /> ) : ( <Text style={styles.buttonText}>Se connecter</Text> )} </TouchableOpacity> <TouchableOpacity style={styles.secondaryButton} onPress={() => navigation.navigate('Register')}> <Text style={styles.secondaryButtonText}>Créer un compte</Text> </TouchableOpacity> <TouchableOpacity style={styles.resetPasswordButton} onPress={() => navigation.navigate('ResetPassword')}> <Text style={styles.resetPasswordButtonText}> Mot de passe oublié ? </Text> </TouchableOpacity> </ScrollView> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', padding: 20, }, title: { fontSize: 28, marginBottom: 20, color: '#2E8B57', fontWeight: 'bold', }, inputContainer: { flexDirection: 'row', alignItems: 'center', width: '100%', borderBottomWidth: 2, borderBottomColor: '#2E8B57', paddingVertical: 10, marginBottom: 15, }, invalidInputContainer: { borderBottomColor: 'red', }, icon: { marginRight: 10, }, input: { flex: 1, fontSize: 18, color: '#333', }, invalidInput: { color: 'red', }, button: { backgroundColor: '#2E8B57', padding: 15, borderRadius: 25, width: '100%', alignItems: 'center', marginTop: 20, }, buttonText: { color: '#fff', fontSize: 18, fontWeight: 'bold', }, secondaryButton: { backgroundColor: 'black', padding: 15, borderRadius: 25, width: '100%', alignItems: 'center', marginTop: 10, borderWidth: 1, borderColor: 'green', }, secondaryButtonText: { color: 'green', fontSize: 18, fontWeight: 'bold', }, errorText: { color: 'red', fontSize: 16, marginTop: 10, }, resetPasswordButton: { marginTop: 10, }, resetPasswordButtonText: { color: 'green', fontSize: 16, }, visibilityIcon: { position: 'absolute', right: 10, top: '80%', transform: [{ translateY: -10 }], }, }); export default LoginScreen;
#pragma once #include"Core/Parallel.h" namespace GEngine::GridBasedContainer { template<typename T> class ArrayAccessor<T, 3> final { public: ArrayAccessor() :m_Data{ nullptr } {}; ArrayAccessor(const Dim3d& size, T* const data) { Reset(size, data); } ArrayAccessor(size_t width, size_t height, size_t depth, T* const data) { Reset(width, height, depth, data); } //! Copy constructor. ArrayAccessor(const ArrayAccessor& other) { Set(other); } //! Replaces the content with given \p other array accessor. void Set(const ArrayAccessor& other) { Reset(other.m_Size, other.m_Data); } //! Resets the array. void Reset(const Dim3d& size, T* const data) { m_Data = data; m_Size = size; } //! Resets the array. void Reset(size_t width, size_t height, size_t depth, T* const data) { m_Data = data; m_Size = Dim3d{ width, height, depth }; } //! Returns the reference to the i-th element. T& At(size_t i) { ASSERT(i >= 0 && i < m_Size.m_Width* m_Size.m_Height* m_Size.m_Depth); return m_Data[i]; } //! Returns the const reference to the i-th element. const T& At(size_t i) const { ASSERT(i >= 0 && i < m_Size.m_Width* m_Size.m_Height* m_Size.m_Depth); return m_Data[i]; } //! Returns the reference to the element at (i, j, k). T& At(size_t i, size_t j, size_t k) { ASSERT(i >= 0 && i < m_Size.m_Width&& j >= 0 && j < m_Size.m_Height&& k >= 0 && k < m_Size.m_Depth); return m_Data[i + m_Size.m_Width * (j + m_Size.m_Height * k)]; } //! Returns the const reference to the element at (i, j, k). const T& At(size_t i, size_t j, size_t k) const { ASSERT(i >= 0 && i < m_Size.m_Width&& j >= 0 && j < m_Size.m_Height&& k >= 0 && k < m_Size.m_Depth); return m_Data[i + m_Size.m_Width * (j + m_Size.m_Height * k)]; } //! Returns the begin iterator of the array. T* const begin() const { return m_Data; } //! Returns the end iterator of the array. T* const end() const { return m_Data + m_Size.m_Width * m_Size.m_Height * m_Size.m_Depth; } //! Returns the begin iterator of the array. T* begin() { return m_Data; } //! Returns the end iterator of the array. T* end() { return m_Data + m_Size.m_Width * m_Size.m_Height * m_Size.m_Depth; } //! Returns the size of the array. Dim3d Size() const { return m_Size; } //! Returns the width of the array. size_t Width() const { return m_Size.m_Width; } //! Returns the height of the array. size_t Height() const { return m_Size.m_Height; } //! Returns the depth of the array. size_t Depth() const { return m_Size.m_Depth; } //! Returns the raw pointer to the array data. T* const Data() const { return m_Data; } template <typename Callback> void ForEach(Callback func) { for (size_t k = 0; k < m_Size.m_Depth; ++k) { for (size_t j = 0; k < m_Size.m_Height; ++j) { for (size_t i = 0; k < m_Size.m_Width; ++i) { func((*this)(i, j, k)); } } } } template <typename Callback> void ForEachIndex(Callback func) { for (size_t k = 0; k < m_Size.m_Depth; ++k) { for (size_t j = 0; k < m_Size.m_Height; ++j) { for (size_t i = 0; k < m_Size.m_Width; ++i) { func(i, j, k); } } } } template <typename Callback> void ParallelForEach(Callback func) { ParallelFor((size_t)0, m_Size.m_Width, (size_t)0, m_Size.m_Height, (size_t)0, m_Size.m_Depth, [&](size_t i, size_t j, size_t k) { func((*this)(i, j, k)); }); } template <typename Callback> void ParallelForEachIndex(Callback func) { ParallelFor((size_t)0, m_Size.m_Width, (size_t)0, m_Size.m_Height, (size_t)0, m_Size.m_Depth, func); } template <typename Callback> void ParallelForIndexRange(Callback func) { ParallelRangeFor((size_t)0, m_Size.m_Width, (size_t)0, m_Size.m_Height, (size_t)0, m_Size.m_Depth, func); } template <typename Callback, typename Partitioner = tbb::auto_partitioner> void ParallelForIndexRange(const RangeParams<size_t>& xRange, const RangeParams<size_t>& yRange, const RangeParams<size_t>& zRange, Callback func, const Partitioner& partitioner = tbb::auto_partitioner{}) { ParallelRangeFor(xRange, yRange, zRange, func, partitioner); } //! Returns the linear index of the given =3-D coordinate (i, j, k). size_t Index(size_t i, size_t j, size_t k) const { return i + m_Size.m_Width * (j + m_Size.m_Height * k); } //! Returns the reference to the i-th element. T& operator[](size_t i) { return m_Data[i]; } //! Returns the const reference to the i-th element. const T& operator[](size_t i) const { return m_Data[i]; } //! Returns the reference to the element at (i, j, k). T& operator()(size_t i, size_t j, size_t k) { return m_Data[i + m_Size.m_Width * (j + m_Size.m_Height * k)]; } //! Returns the const reference to the element at (i, j, k). const T& operator()(size_t i, size_t j, size_t k) const { return m_Data[i + m_Size.m_Width * (j + m_Size.m_Height * k)]; } //! Swaps the content of with \p other array accessor. void Swap(ArrayAccessor& other) { std::swap(other.m_Data, m_Data); std::swap(other.m_Size, m_Size); } //! Copies given array \p other to this array. ArrayAccessor& operator=(const ArrayAccessor& other) { Set(other); return *this; } //! Casts type to ConstArrayAccessor. operator ConstArrayAccessor<T, 3>() const { return ConstArrayAccessor<T, 3>(*this); } private: Dim3d m_Size; T* m_Data; }; //! Type alias for 3-D array accessor. template <typename T> using WriteAccessor3D = ArrayAccessor<T, 3>; template <typename T> class ConstArrayAccessor<T, 3> { public: //! Constructs empty 3-D read-only array accessor. ConstArrayAccessor(): m_Data{ nullptr }{} //! Constructs a read-only array accessor that wraps given array. //! \param size Size of the 3-D array. //! \param data Raw array pointer. ConstArrayAccessor(const Dim3d& size, const T* const data) { m_Size = size; m_Data = data; } //! Constructs a read-only array accessor that wraps given array. //! \param width Width of the 3-D array. //! \param height Height of the 3-D array. //! \param depth Depth of the 3-D array. //! \param data Raw array pointer. ConstArrayAccessor( size_t width, size_t height, size_t depth, const T* const data) { m_Size = { width, height, depth }; m_Data = data; } //! Constructs a read-only array accessor from read/write accessor. explicit ConstArrayAccessor(const ArrayAccessor<T, 3>& other) { m_Size = other.Size(); m_Data = other.Data(); } //! Copy constructor. ConstArrayAccessor(const ConstArrayAccessor& other) { m_Size = other.m_Size; m_Data = other.m_Data; } //! Returns the const reference to the i-th element. const T& At(size_t i) const { ASSERT(i >= 0 && i < m_Size.m_Width* m_Size.m_Height* m_Size.m_Depth); return m_Data[i]; } //! Returns the const reference to the element at (i, j, k). const T& At(size_t i, size_t j, size_t k) const { ASSERT(i >= 0 && i < m_Size.m_Width&& j >= 0 && j < m_Size.m_Height&& k >= 0 && k < m_Size.m_Depth); return m_Data[i + m_Size.m_Width * (j + m_Size.m_Height * k)]; } //! Returns the begin iterator of the array. const T* const begin() const { return m_Data; } //! Returns the end iterator of the array. const T* const end() const { return m_Data + m_Size.m_Width * m_Size.m_Height * m_Size.m_Depth; } //! Returns the size of the array. Dim3d Size() const { return m_Size; } //! Returns the width of the array. size_t Width() const { return m_Size.m_Width; } //! Returns the height of the array. size_t Height() const { return m_Size.m_Height; } //! Returns the depth of the array. size_t Depth() const { return m_Size.m_Depth; } //! Returns the raw pointer to the array data. const T* const Data() const { return m_Data; } template <typename Callback> void ForEach(Callback func) const { for (size_t k = 0; k < m_Size.m_Depth; ++k) { for (size_t j = 0; k < m_Size.m_Height; ++j) { for (size_t i = 0; k < m_Size.m_Width; ++i) { func((*this)(i, j, k)); } } } } template <typename Callback> void ForEachIndex(Callback func) const { for (size_t k = 0; k < m_Size.m_Depth; ++k) { for (size_t j = 0; k < m_Size.m_Height; ++j) { for (size_t i = 0; k < m_Size.m_Width; ++i) { func(i, j, k); } } } } template <typename Callback> void ParallelForEach(Callback func) const { ParallelFor((size_t)0, m_Size.m_Width, (size_t)0, m_Size.m_Height, (size_t)0, m_Size.m_Depth, [&](size_t i, size_t j, size_t k) { func((*this)(i, j, k)); }); } template <typename Callback> void ParallelForEachIndex(Callback func) const { ParallelFor((size_t)0, m_Size.m_Width, (size_t)0, m_Size.m_Height, (size_t)0, m_Size.m_Depth, func); } template <typename Callback> void ParallelForIndexRange(Callback func)const { ParallelRangeFor((size_t)0, m_Size.m_Width, (size_t)0, m_Size.m_Height, (size_t)0, m_Size.m_Depth, func); } template <typename Callback, typename Partitioner = tbb::auto_partitioner> void ParallelForIndexRange(const RangeParams<size_t>& xRange, const RangeParams<size_t>& yRange, const RangeParams<size_t>& zRange, Callback func, const Partitioner& partitioner = tbb::auto_partitioner{})const { ParallelRangeFor(xRange, yRange, zRange, func, partitioner); } //! Returns the linear index of the given =3-D coordinate (i, j, k). size_t Index(size_t i, size_t j, size_t k) const { return i + m_Size.m_Width * (j + m_Size.m_Height * k); } //! Returns the const reference to the i-th element. const T& operator[](size_t i) const { return m_Data[i]; } //! Returns the reference to the element at (i, j, k). const T& operator()(size_t i, size_t j, size_t k) const { return m_Data[i + m_Size.m_Width * (j + m_Size.m_Height * k)]; } private: Dim3d m_Size; const T* m_Data; }; //! Type alias for 3-D const array accessor. template <typename T> using ReadAccessor3D = ConstArrayAccessor<T, 3>; }
import React from "react"; import "./Home.css"; import HomeNavigation from "./../../components/home_navigation/HomeNavigation"; import DisplayMessage from "./../../components/display_message/DisplayMessage"; import Quiz from "./../../components/quiz/Quiz"; import { UserActionContext } from "../../contexts/userContext"; import { httpAgent, getFromLocalStorage } from "./../../utils/util"; function Home() { const userActionContext = React.useContext(UserActionContext); const [isFetching, setIsFetching] = React.useState(true); const [quizzes, setQuizzes] = React.useState([]); React.useEffect(() => { const fetchQuiz = async () => { try { const access_token = getFromLocalStorage("access_token"); const url = `http://localhost:4000/api/v1/quiz?access_token=${access_token}`; const method = "GET"; const response = await httpAgent(url, method, {}); if (response.ok) { const results = await response.json(); setIsFetching(false); setQuizzes(results["quizzes"]); } } catch (error) { setIsFetching(false); userActionContext.setMessage({ visible: true, type: "error", message: "Unable to fetch quizzes." }); console.log(error); } }; fetchQuiz(); }, []); return ( <div className="Home"> <DisplayMessage /> <HomeNavigation /> <div className="Home-mahoot">{isFetching ? <p>Fetching quizzes...</p> : quizzes.map(quiz => <Quiz quiz={quiz} key={quiz._id} />)}</div> </div> ); } export default Home;
<?php namespace App\Models; use DateTimeInterface; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Subscriber extends Model { use SoftDeletes, HasFactory; public $table = 'subscribers'; protected $dates = [ 'created_at', 'updated_at', 'deleted_at', ]; protected $fillable = [ 'full_name', 'email_address', 'phone_number', 'provided_phone', 'signed_up', 'read_page_contents', 'landing_page_id', 'created_at', 'updated_at', 'deleted_at', ]; protected function serializeDate(DateTimeInterface $date) { return $date->format('Y-m-d H:i:s'); } public function landing_page() { return $this->belongsTo(LandingPage::class, 'landing_page_id'); } }
<?php /* * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2015 PrestaShop SA * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ /** * @property Attachment $object */ class AdminAttachmentsControllerCore extends AdminController { public $bootstrap = true ; protected $product_attachements = array(); public function __construct() { $this->table = 'attachment'; $this->className = 'Attachment'; $this->lang = true; $this->addRowAction('edit'); $this->addRowAction('view'); $this->addRowAction('delete'); $this->_select = 'IFNULL(virtual.products, 0) as products'; $this->_join = 'LEFT JOIN (SELECT id_attachment, COUNT(*) as products FROM '._DB_PREFIX_.'product_attachment GROUP BY id_attachment) virtual ON a.id_attachment = virtual.id_attachment'; $this->_use_found_rows = false; $this->fields_list = array( 'id_attachment' => array( 'title' => $this->l('ID'), 'align' => 'center', 'class' => 'fixed-width-xs' ), 'name' => array( 'title' => $this->l('Name') ), 'file' => array( 'title' => $this->l('File') ), 'file_size' => array( 'title' => $this->l('Size'), 'callback' => 'displayHumanReadableSize' ), 'products' => array( 'title' => $this->l('Associated with'), 'suffix' => $this->l('product(s)'), 'filter_key' => 'virtual!products', ), ); $this->bulk_actions = array( 'delete' => array( 'text' => $this->l('Delete selected'), 'icon' => 'icon-trash', 'confirm' => $this->l('Delete selected items?') ) ); parent::__construct(); } public function setMedia() { parent::setMedia(); $this->addJs(_PS_JS_DIR_.'/admin/attachments.js'); Media::addJsDefL('confirm_text', $this->l('This attachment is associated with the following products, do you really want to delete it?', null, true, false)); } public static function displayHumanReadableSize($size) { return Tools::formatBytes($size); } public function initPageHeaderToolbar() { if (empty($this->display)) { $this->page_header_toolbar_btn['new_attachment'] = array( 'href' => self::$currentIndex.'&addattachment&token='.$this->token, 'desc' => $this->l('Add new attachment', null, null, false), 'icon' => 'process-icon-new' ); } parent::initPageHeaderToolbar(); } public function renderView() { if (($obj = $this->loadObject(true)) && Validate::isLoadedObject($obj)) { $link = $this->context->link->getPageLink('attachment', true, null, 'id_attachment='.$obj->id); Tools::redirectLink($link); } return $this->displayWarning($this->l('File not found')); } public function renderForm() { if (($obj = $this->loadObject(true)) && Validate::isLoadedObject($obj)) { /** @var Attachment $obj */ $link = $this->context->link->getPageLink('attachment', true, null, 'id_attachment='.$obj->id); if (file_exists(_PS_DOWNLOAD_DIR_.$obj->file)) { $size = round(filesize(_PS_DOWNLOAD_DIR_.$obj->file) / 1024); } } $this->fields_form = array( 'legend' => array( 'title' => $this->l('Attachment'), 'icon' => 'icon-paper-clip' ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Filename'), 'name' => 'name', 'required' => true, 'lang' => true, 'col' => 4 ), array( 'type' => 'textarea', 'label' => $this->l('Description'), 'name' => 'description', 'lang' => true, 'col' => 6 ), array( 'type' => 'file', 'file' => isset($link) ? $link : null, 'size' => isset($size) ? $size : null, 'label' => $this->l('File'), 'name' => 'file', 'required' => true, 'col' => 6 ), ), 'submit' => array( 'title' => $this->l('Save'), ) ); return parent::renderForm(); } public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false) { parent::getList((int)$id_lang, $order_by, $order_way, $start, $limit, $id_lang_shop); if (count($this->_list)) { $this->product_attachements = Attachment::getProductAttached((int)$id_lang, $this->_list); $list_product_list = array(); foreach ($this->_list as $list) { $product_list = ''; if (isset($this->product_attachements[$list['id_attachment']])) { foreach ($this->product_attachements[$list['id_attachment']] as $product) { $product_list .= $product.', '; } $product_list = rtrim($product_list, ', '); } $list_product_list[$list['id_attachment']] = $product_list; } // Assign array in list_action_delete.tpl $this->tpl_delete_link_vars = array( 'product_list' => $list_product_list, 'product_attachements' => $this->product_attachements ); } } public function postProcess() { if (_PS_MODE_DEMO_) { $this->errors[] = Tools::displayError('This functionality has been disabled.'); return; } if (Tools::isSubmit('submitAdd'.$this->table)) { $id = (int)Tools::getValue('id_attachment'); if ($id && $a = new Attachment($id)) { $_POST['file'] = $a->file; $_POST['mime'] = $a->mime; } if (!count($this->errors)) { if (isset($_FILES['file']) && is_uploaded_file($_FILES['file']['tmp_name'])) { if ($_FILES['file']['size'] > (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024 * 1024)) { $this->errors[] = sprintf( $this->l('The file is too large. Maximum size allowed is: %1$d kB. The file you are trying to upload is %2$d kB.'), (Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE') * 1024), number_format(($_FILES['file']['size'] / 1024), 2, '.', '') ); } else { do { $uniqid = sha1(microtime()); } while (file_exists(_PS_DOWNLOAD_DIR_.$uniqid)); if (!move_uploaded_file($_FILES['file']['tmp_name'], _PS_DOWNLOAD_DIR_.$uniqid)) { $this->errors[] = $this->l('Failed to copy the file.'); } $_POST['file_name'] = $_FILES['file']['name']; @unlink($_FILES['file']['tmp_name']); if (!sizeof($this->errors) && isset($a) && file_exists(_PS_DOWNLOAD_DIR_.$a->file)) { unlink(_PS_DOWNLOAD_DIR_.$a->file); } $_POST['file'] = $uniqid; $_POST['mime'] = $_FILES['file']['type']; } } elseif (array_key_exists('file', $_FILES) && (int)$_FILES['file']['error'] === 1) { $max_upload = (int)ini_get('upload_max_filesize'); $max_post = (int)ini_get('post_max_size'); $upload_mb = min($max_upload, $max_post); $this->errors[] = sprintf( $this->l('The file %1$s exceeds the size allowed by the server. The limit is set to %2$d MB.'), '<b>'.$_FILES['file']['name'].'</b> ', '<b>'.$upload_mb.'</b>' ); } elseif (!isset($a) || (isset($a) && !file_exists(_PS_DOWNLOAD_DIR_.$a->file))) { $this->errors[] = $this->l('Upload error. Please check your server configurations for the maximum upload size allowed.'); } } $this->validateRules(); } $return = parent::postProcess(); if (!$return && isset($uniqid) && file_exists(_PS_DOWNLOAD_DIR_.$uniqid)) { unlink(_PS_DOWNLOAD_DIR_.$uniqid); } return $return; } }
// // HomeTableViewCell.swift // VeroCaseStudy // // Created by Adem Burak Cevizli on 31.03.2023. // import UIKit class HomeTableViewCell: UITableViewCell { static let identifier = "HomeTableViewCell" private let taskLabel = UILabel() private let titleLabel = UILabel() private let descriptionLabel = UILabel() private var colorCode: String = "" override func layoutSubviews() { super.layoutSubviews() contentView.frame = contentView.frame.inset(by: UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 0)) } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.layer.cornerRadius = 6 createCell() } required init?(coder: NSCoder) { fatalError() } private func createCell() { contentView.addSubview(taskLabel) taskLabel.numberOfLines = 0 taskLabel.anchor(top: contentView.topAnchor, left: contentView.leftAnchor, bottom: nil, right: nil, padding: UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 0), size: CGSize(width: self.contentView.frame.width - 20, height: 50)) contentView.addSubview(titleLabel) titleLabel.numberOfLines = 0 titleLabel.anchor(top: taskLabel.bottomAnchor, left: contentView.leftAnchor, bottom: nil, right: nil, padding: UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 0), size: CGSize(width: self.contentView.frame.width - 20, height: 50)) contentView.addSubview(descriptionLabel) descriptionLabel.numberOfLines = 0 descriptionLabel.anchor(top: titleLabel.bottomAnchor, left: contentView.leftAnchor, bottom: nil, right: nil, padding: UIEdgeInsets(top: 10, left: 10, bottom: 0, right: 0), size: CGSize(width: self.contentView.frame.width - 20, height: 50)) } func updateCell(with model: Items) { taskLabel.attributedText = makeBoldString(string: "Task: \(model.task)", length: 5) titleLabel.attributedText = makeBoldString(string: "Title: \(model.title)", length: 6) descriptionLabel.attributedText = makeBoldString(string: "Description: \(model.desc)", length: 12) contentView.backgroundColor = colorFromHex(hex: model.colorCode) } private func makeBoldString(string: String, length: Int) -> NSMutableAttributedString { let tasksString = NSMutableAttributedString(string: string) tasksString.addAttribute(.font, value: UIFont.systemFont(ofSize: 18, weight: .bold), range: NSRange(location: 0, length: length)) return tasksString } private func colorFromHex(hex: String) -> UIColor { let colorCode = hex.replacingOccurrences(of: "#", with: "") let convertedColor = UInt64(colorCode, radix: 16) ?? 0 let red = CGFloat((convertedColor & 0xFF0000) >> 16) / 255.0 let green = CGFloat((convertedColor & 0x00FF00) >> 8) / 255.0 let blue = CGFloat(convertedColor & 0x0000FF) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 0.6) } }
import { IsArray, IsNotEmpty, IsString } from 'class-validator'; import { Expose, Type } from 'class-transformer'; export class CoffeeCardResponseDto { @Expose({ name: '_id' }) @Type(() => String) @IsNotEmpty() id: string; @Expose() @IsString() @IsNotEmpty() uid: string; @Expose() @IsString() @IsNotEmpty() blendName: string; @Expose({ name: '_coffeeImage' }) @Type(() => String) @IsNotEmpty() image: string; @Expose() @IsString() @IsNotEmpty() intensifier: string; @Expose() @IsString({ each: true }) @IsArray() @IsNotEmpty() notes: string[]; @Expose() @IsString() @IsNotEmpty() origin: string; @Expose() @IsString() @IsNotEmpty() variety: string; }
import { shallowMount, createLocalVue } from '@vue/test-utils' import { mockUserDataFixture } from '@/api/mocs/api-user-mock' import Vuex from 'vuex' import { getters as realUserModuleGetters } from '@/store/user' import SAlert from '@/components/ui-system/s-alert' import AppStaticMessages from '@/components/base/app-static-messages' const localVue = createLocalVue() localVue.use(Vuex) describe('@/components/base/app-static-messages', () => { let store let state beforeEach(() => { state = { userData: { mockUserDataFixture, profile: { ...mockUserDataFixture.profile, companyId: null, }, }, } store = new Vuex.Store({ modules: { user: { state, getters: realUserModuleGetters, namespaced: true, }, }, }) }) it('Отображается только сообщение об отсутствии организации', () => { const wrapper = shallowMount(AppStaticMessages, { store, localVue, stubs: { SAlert, }, mocks: { $auth: { isAdminAsUser: false, }, }, }) expect(wrapper.html()).toMatchSnapshot() }) it('Отображается сообщение об заходе под админом и об отсутствии организации', () => { const wrapper = shallowMount(AppStaticMessages, { store, localVue, stubs: { SAlert, }, mocks: { $auth: { fromUserId: true, }, }, }) expect(wrapper.html()).toMatchSnapshot() }) it('Закрытие сообщения при клике на кнопку его закрытия', async () => { const wrapper = shallowMount(AppStaticMessages, { store, localVue, stubs: { SAlert, }, mocks: { $auth: { isAdminAsUser: false, }, }, }) const alert = wrapper.findComponent(SAlert) expect(alert.classes()).toEqual(expect.arrayContaining(['company-alert'])) expect(alert.exists()).toBe(true) await alert.vm.$emit('close') expect(alert.exists()).toBe(false) }) }) describe('@/components/base/app-static-message', () => { let store let state beforeEach(() => { state = { userData: { profile: {}, }, } store = new Vuex.Store({ modules: { user: { state, getters: realUserModuleGetters, namespaced: true, }, }, }) }) it('Не отображать сообщение, если данных пользователя нету', () => { const wrapper = shallowMount(AppStaticMessages, { store, localVue, stubs: { SAlert, }, mocks: { $auth: { isAdminAsUser: false, }, }, }) const alert = wrapper.findComponent(SAlert) expect(alert.exists()).toBe(false) }) })
import React, { useEffect, useState } from 'react'; import styles from './BoardPage.module.css' import { Link, useLocation } from 'react-router-dom'; import Search from '../component/Search/Search'; export default function SearchResultPage() { const location = useLocation(); const searchParams = new URLSearchParams(location.search); const query = searchParams.get('q'); // 이렇게 쿼리 문자열에서 'q' 파라미터를 얻을 수 있음 const [searchResults, setSearchResults] = useState([]); const [currentPage, setCurrentPage] = useState(1); const [resultsPerPage] = useState(10); useEffect(() => { // 검색 결과를 가져오는 비동기 함수를 호출 fetchSearchResults(); // 이 함수를 구현해야 함 }, []); const fetchSearchResults = async() => { // 여기에서 검색 결과를 가져오는 비동기 요청을 수행 // 결과를 setSearchResults로 설정 await fetch('http://localhost:3001/post/search', { method: 'POST', // POST 메서드를 사용 headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ title: query }), // 검색어를 서버로 보내기 }) .then((response) => response.json()) .then((data) => setSearchResults(data)) .catch((error) => console.log(error)) }; const indexOfLastResult = currentPage * resultsPerPage; const indexOfFirstResult = indexOfLastResult - resultsPerPage; const currentResults = searchResults.slice(indexOfFirstResult, indexOfLastResult); const paginate = (pageNumber) => { setCurrentPage(pageNumber); }; return ( <div className={styles.container}> <div className={styles.content}> <h1 className={styles.title}> 검색결과</h1> <div className="post-list"> {currentResults.map((searchResult) => ( <Link key={searchResult.id} to={`/board/${searchResult.id}`} className={styles.postlink}> <div className={styles.postContent}> <div> <h2>{searchResult.title}</h2> <span>작성자: {searchResult.nickname}</span> </div> <div className={styles.postinfo}> <span>게시일: {searchResult.p_date} 추천: {searchResult.recommend}</span> </div> </div> </Link> ))} </div> {/* 페이지네이션 */} <ul className={styles.pagination}> {Array.from({ length: Math.ceil(searchResults.length / resultsPerPage) }, (_, index) => ( <li key={index} className={currentPage === index + 1 ? styles.active : ''} onClick={() => paginate(index + 1)} > <span >{index + 1}</span> </li> ))} </ul> <Search></Search> </div> </div> ); }
# # Copyright (c) 2021, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import transformers from merlin.models.utils.doc_utils import docstring_parameter from merlin.models.utils.registry import Registry transformer_registry: Registry = Registry("transformers") TRANSFORMER_CONFIG_PARAMETER_DOCSTRING = """ d_model: int The hidden dimension of the transformer layer. n_head: int The number of attention heads in each transformer layer. n_layer: int The number of transformer layers to stack. total_seq_length: int The maximum sequence length. hidden_act: str, optional The activation function in the hidden layers. By default 'gelu' initializer_range: float, optional The standard deviation of the `truncated_normal_initializer` for initializing all transformer's weights parameters. By default 0.01 layer_norm_eps: float, optional The epsilon used by the layer normalization layers. By default 0.03 dropout: float, optional The dropout probability. By default 0.3 pad_token: int, optional The padding token ID. By default 0 log_attention_weights: bool, optional Whether to log attention weights. By default False """ class T4RecConfig: """A class responsible for setting the configuration of the transformers class from Hugging Face and returning the corresponding T4Rec model. """ def to_huggingface_torch_model(self): """ Instantiate a Hugging Face transformer model based on the configuration parameters of the class. Returns ------- transformers.PreTrainedModel The Hugging Face transformer model. """ model_cls = transformers.MODEL_MAPPING[self.transformers_config_cls] return model_cls(self) def to_torch_model( self, input_features, *prediction_task, task_blocks=None, task_weights=None, loss_reduction="mean", **kwargs ): """Links the Hugging Face transformer model to the given input block and prediction tasks, and returns a T4Rec model. Parameters ---------- input_features: torch4rec.TabularSequenceFeatures The sequential block that represents the input features and defines the masking strategy for training and evaluation. prediction_task: torch4rec.PredictionTask One or multiple prediction tasks. task_blocks: list, optional List of task-specific blocks that we apply on top of the HF transformer's output. task_weights: list, optional List of the weights to use for combining the tasks losses. loss_reduction: str, optional The reduction to apply to the prediction losses, possible values are: 'none': no reduction will be applied, 'mean': the weighted mean of the output is taken, 'sum': the output will be summed. By default: 'mean'. Returns ------- torch4rec.Model The T4Rec torch model. Raises ------ ValueError If input block or prediction task is of the wrong type. """ from .. import torch as torch4rec if not isinstance(input_features, torch4rec.TabularSequenceFeatures): raise ValueError("`input_features` must an instance of SequentialTabularFeatures") if not all(isinstance(t, torch4rec.PredictionTask) for t in prediction_task): raise ValueError( "`task` is of the wrong type, please provide one or multiple " "instance(s) of PredictionTask" ) body = torch4rec.SequentialBlock( input_features, torch4rec.TransformerBlock(self, masking=input_features.masking) ) return torch4rec.Head( body, *prediction_task, task_blocks=task_blocks, task_weights=task_weights, loss_reduction=loss_reduction, ).to_model(**kwargs) @property def transformers_config_cls(self): return self.__class__.__bases__[1] @classmethod def build(cls, *args, **kwargs): raise NotImplementedError @transformer_registry.register("reformer") class ReformerConfig(T4RecConfig, transformers.ReformerConfig): """Subclass of T4RecConfig and transformers.ReformerConfig from Hugging Face. It handles configuration for Reformer layers in the context of T4Rec models. """ @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length, hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, axial_pos_shape_first_dim=4, **kwargs ): """ Creates an instance of ReformerConfig with the given parameters. Parameters ---------- {transformer_cfg_parameters} axial_pos_shape_first_dim: int, optional The first dimension of the axial position encodings. During training, the product of the position dims has to be equal to the sequence length. Returns ------- ReformerConfig An instance of ReformerConfig. """ # To account for target positions at inference mode, we extend the maximum sequence length. total_seq_length = total_seq_length + 2 return cls( hidden_size=d_model, attention_head_size=d_model, attn_layers=["local", "lsh"] * (n_layer // 2) if n_layer > 2 else ["local"], num_hidden_layers=n_layer, feed_forward_size=d_model * 4, num_attention_heads=n_head, hidden_act=hidden_act, initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, hidden_dropout_prob=dropout, lsh_attention_probs_dropout_prob=dropout, pad_token_id=pad_token, output_attentions=log_attention_weights, max_position_embeddings=total_seq_length, axial_pos_embds_dim=[ d_model // 2, d_model // 2, ], axial_pos_shape=[ axial_pos_shape_first_dim, total_seq_length // axial_pos_shape_first_dim, ], vocab_size=1, **kwargs, ) @transformer_registry.register("gtp2") @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) class GPT2Config(T4RecConfig, transformers.GPT2Config): """Subclass of T4RecConfig and transformers.GPT2Config from Hugging Face. It handles configuration for GPT2 layers in the context of T4Rec models. """ @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length, hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, **kwargs ): """ Creates an instance of GPT2Config with the given parameters. Parameters ---------- {transformer_cfg_parameters} Returns ------- GPT2Config An instance of GPT2Config. """ return cls( n_embd=d_model, n_inner=d_model * 4, n_layer=n_layer, n_head=n_head, activation_function=hidden_act, initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, resid_pdrop=dropout, embd_pdrop=dropout, attn_pdrop=dropout, n_positions=total_seq_length, n_ctx=total_seq_length, output_attentions=log_attention_weights, vocab_size=1, **kwargs, ) @transformer_registry.register("longformer") class LongformerConfig(T4RecConfig, transformers.LongformerConfig): """Subclass of T4RecConfig and transformers.LongformerConfig from Hugging Face. It handles configuration for LongformerConfig layers in the context of T4Rec models. """ @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length, hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, **kwargs ): """ Creates an instance of LongformerConfig with the given parameters. Parameters ---------- {transformer_cfg_parameters} Returns ------- LongformerConfig An instance of LongformerConfig. """ # To account for target positions at inference mode, we extend the maximum sequence length. total_seq_length = total_seq_length + 2 return cls( hidden_size=d_model, num_hidden_layers=n_layer, num_attention_heads=n_head, hidden_act=hidden_act, attention_window=total_seq_length, initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, dropout=dropout, pad_token_id=pad_token, output_attentions=log_attention_weights, vocab_size=1, **kwargs, ) @transformer_registry.register("electra") class ElectraConfig(T4RecConfig, transformers.ElectraConfig): """Subclass of T4RecConfig and transformers.ElectraConfig from Hugging Face. It handles configuration for ElectraConfig layers in the context of T4Rec models. """ @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length, hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, **kwargs ): """ Creates an instance of ElectraConfig with the given parameters. Parameters ---------- {transformer_cfg_parameters} Returns ------- ElectraConfig An instance of ElectraConfig. """ # To account for target positions at inference mode, we extend the maximum sequence length. total_seq_length = total_seq_length + 2 return cls( hidden_size=d_model, embedding_size=d_model, num_hidden_layers=n_layer, num_attention_heads=n_head, intermediate_size=d_model * 4, hidden_act=hidden_act, initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, hidden_dropout_prob=dropout, max_position_embeddings=total_seq_length, pad_token_id=pad_token, output_attentions=log_attention_weights, vocab_size=1, **kwargs, ) @transformer_registry.register("albert") class AlbertConfig(T4RecConfig, transformers.AlbertConfig): """Subclass of T4RecConfig and transformers.AlbertConfig from Hugging Face. It handles configuration for AlbertConfig layers in the context of T4Rec models. """ @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length, hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, **kwargs ): """ Creates an instance of AlbertConfig with the given parameters. Parameters ---------- {transformer_cfg_parameters} Returns ------- AlbertConfig An instance of AlbertConfig. """ # To account for target positions at inference mode, we extend the maximum sequence length. total_seq_length = total_seq_length + 2 return cls( hidden_size=d_model, num_attention_heads=n_head, num_hidden_layers=n_layer, hidden_act=hidden_act, intermediate_size=d_model * 4, hidden_dropout_prob=dropout, attention_probs_dropout_prob=dropout, max_position_embeddings=total_seq_length, embedding_size=d_model, # should be same as dimension of the input to ALBERT initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, output_attentions=log_attention_weights, vocab_size=1, **kwargs, ) @transformer_registry.register("xlnet") @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) class XLNetConfig(T4RecConfig, transformers.XLNetConfig): """Subclass of T4RecConfig and transformers.XLNetConfig from Hugging Face. It handles configuration for XLNetConfig layers in the context of T4Rec models. """ @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length=None, attn_type="bi", hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, mem_len=1, **kwargs ): """ Creates an instance of XLNetConfig with the given parameters. Parameters ---------- {transformer_cfg_parameters} mem_len: int, The number of tokens to be cached. Pre-computed key/value pairs from a previous forward pass are stored and won't be re-computed. This parameter is especially useful for long sequence modeling where different batches may truncate the entire sequence. Tasks like user-aware recommendation could benefit from this feature. By default, this parameter is set to 1, which means no caching is used. Returns ------- XLNetConfig An instance of XLNetConfig. """ return cls( d_model=d_model, d_inner=d_model * 4, n_layer=n_layer, n_head=n_head, attn_type=attn_type, ff_activation=hidden_act, initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, dropout=dropout, pad_token_id=pad_token, output_attentions=log_attention_weights, vocab_size=1, mem_len=mem_len, **kwargs, ) @transformer_registry.register("bert") class BertConfig(T4RecConfig, transformers.BertConfig): """Subclass of T4RecConfig and transformers.BertConfig from Hugging Face. It handles configuration for BertConfig layers in the context of T4Rec models. """ @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length, hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, **kwargs ): """ Creates an instance of BertConfig with the given parameters. Parameters ---------- {transformer_cfg_parameters} Returns ------- BertConfig An instance of BertConfig. """ # To account for target positions at inference mode, we extend the maximum sequence length. total_seq_length = total_seq_length + 2 return cls( hidden_size=d_model, num_hidden_layers=n_layer, num_attention_heads=n_head, hidden_act=hidden_act, initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, dropout=dropout, pad_token_id=pad_token, output_attentions=log_attention_weights, max_position_embeddings=total_seq_length, vocab_size=1, **kwargs, ) @transformer_registry.register("roberta") class RobertaConfig(T4RecConfig, transformers.RobertaConfig): """Subclass of T4RecConfig and transformers.RobertaConfig from Hugging Face. It handles configuration for RobertaConfig layers in the context of T4Rec models. """ @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length, hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, **kwargs ): """ Creates an instance of RobertaConfig with the given parameters. Parameters ---------- {transformer_cfg_parameters} Returns ------- RobertaConfig An instance of RobertaConfig. """ # To account for target positions at inference mode, we extend the maximum sequence length. total_seq_length = total_seq_length + 2 return cls( hidden_size=d_model, num_hidden_layers=n_layer, num_attention_heads=n_head, hidden_act=hidden_act, initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, dropout=dropout, pad_token_id=pad_token, output_attentions=log_attention_weights, max_position_embeddings=total_seq_length, vocab_size=1, **kwargs, ) @transformer_registry.register("transfo-xl") class TransfoXLConfig(T4RecConfig, transformers.TransfoXLConfig): """Subclass of T4RecConfig and transformers. TransfoXLConfig from Hugging Face. It handles configuration for TransfoXLConfig layers in the context of T4Rec models. """ @docstring_parameter(transformer_cfg_parameters=TRANSFORMER_CONFIG_PARAMETER_DOCSTRING) @classmethod def build( cls, d_model, n_head, n_layer, total_seq_length, hidden_act="gelu", initializer_range=0.01, layer_norm_eps=0.03, dropout=0.3, pad_token=0, log_attention_weights=False, **kwargs ): """ Creates an instance of TransfoXLConfig with the given parameters. Parameters ---------- {transformer_cfg_parameters} Returns ------- TransfoXLConfig An instance of TransfoXLConfig. """ return cls( d_model=d_model, d_embed=d_model, n_layer=n_layer, n_head=n_head, d_inner=d_model * 4, hidden_act=hidden_act, untie_r=True, attn_type=0, initializer_range=initializer_range, layer_norm_eps=layer_norm_eps, dropout=dropout, pad_token_id=pad_token, output_attentions=log_attention_weights, vocab_size=1, # As the input_embeds will be fed in the forward function, limits the memory reserved by the internal input embedding table, which will not be used mem_len=1, # We do not use mems, because we feed the full sequence to the Transformer models and not sliding segments (which is useful for the long sequences in NLP. As setting mem_len to 0 leads to NaN in loss, we set it to one, to minimize the computing overhead) div_val=1, # Disables adaptative input (embeddings), because the embeddings are managed by TabularFeatures **kwargs, )
import { useEffect, useReducer, useState } from "react"; import { onValue, ref, set } from "firebase/database"; import { auth, db } from "../../utils/firebase"; import { useNavigate } from "react-router-dom"; import { onAuthStateChanged } from "firebase/auth"; export default function useNewBlog(originalPost) { const navigate = useNavigate(); const [username, setUsername] = useState(null); useEffect(() => { onAuthStateChanged(auth, user => { if (user === null) navigate("/login?continue=/blog/create&message=Sign+in+to+create+post"); else { const userRef = ref(db, "users/" + user.uid); onValue(userRef, snapshot => { setUsername(snapshot.val().username) }) } }) }, [navigate]) function createPost(e) { e.preventDefault(); console.log(post) const id = post.title.toLowerCase().replace(/\s/g, '-'); const newPostRef = ref(db, "posts/" + id); set(newPostRef, { ...post, id: id, author: username, date: (originalPost && originalPost.date) || Date.now() }); navigate("/blog/" + id); } function reducer(state, action) { if (action.type === "TITLE") return { ...state, title: action.value }; if (action.type === "DESCRIPTION") return { ...state, description: action.value }; if (action.type === "CONTENT") return { ...state, content: action.value }; return state; } const [post, dispatch] = useReducer(reducer, originalPost || { title: "", description: "", content: "**bold** \n*italic* \n- Bullet 1 \n- Bullet 2 \n\n[Link](https://www.a.com) \n![Image](/favicon.ico)" }) function changePostContent(e) { const height = document.getElementsByClassName("preview")[0].scrollHeight; const contents = document.getElementsByClassName("content"); for (var i = 0; i < contents.length; i++) { contents[i].style.height = height + "px"; }; if (e) dispatch({ type: "CONTENT", value: e.target.value }) } return { post, dispatch, changePostContent, createPost }; }
<template> <Carousel :i18n="{ ariaNextSlide: 'Zur nächsten Slide', ariaPreviousSlide: 'Zur vorherigen Slide', ariaNavigateToSlide: 'Springe zu Slide {slideNumber}', ariaGallery: 'Galerie', itemXofY: 'Slide {currentSlide} von {slidesCount}', iconArrowUp: 'Pfeil nach oben', iconArrowDown: 'Pfeil nach unten', iconArrowRight: 'Pfeil nach rechts', iconArrowLeft: 'Pfeil nach links', }" > <Slide v-for="slide in 10" :key="slide"> <div class="carousel__item">{{ slide }}</div> </Slide> <template #addons> <Navigation /> <Pagination /> </template> </Carousel> </template> <script> import { defineComponent } from 'vue' import { Carousel, Pagination, Navigation, Slide } from '../../dist/carousel.es' import '../../dist/carousel.css' export default defineComponent({ name: 'Basic', components: { Carousel, Slide, Pagination, Navigation, }, }) </script>
// // Shapes.swift // Bullseye // // Created by Matthew Lewis on 7/23/21. // import SwiftUI struct Shapes: View { @State private var wideShapes = true var body: some View { VStack { if !wideShapes { Circle() .strokeBorder(Color.blue, lineWidth: 20.0) .frame(width: 200, height: 100) .transition(.opacity) } RoundedRectangle(cornerRadius: 20.0) .fill(Color.blue) .frame(width: wideShapes ? 200 : 100, height: 100) Capsule() .fill(Color.blue) .frame(width: wideShapes ? 200 : 100, height: 100) Ellipse() .fill(Color.blue) .frame(width: wideShapes ? 200 : 100, height: 100) Button(action: { withAnimation{ wideShapes.toggle() } }, label: { Text("Animate!") }) } .background(Color.green) } } struct Shapes_Previews: PreviewProvider { static var previews: some View { Shapes() } }
--- title: "Как сделать пулреквест на GitHub" description: "Создайте свой первый запрос на изменение GitHub пулреквеста." authors: - igsekor related: - tools/version-control - tools/git-cli - tools/github-actions tags: - article --- ## Задача Сделать пулреквест в существующий репозиторий на GitHub. ## Готовое решение Суть пулреквеста — создать запрос на внесение изменений в репозиторий. Обычно такой запрос сопровождается отзывом (ревью) со стороны других пользователей репозитория, обладающих правами на внесение изменений. Для того, чтобы сделать пулреквест, нужно создать отдельную ветку и внести все правки именно в неё. Название ветки можно выбрать произвольным образом, но лучше отразить суть изменений в нескольких английских словах, перечисленных через знак переноса (`-`). Например, чтобы внести изменения (пофиксить), можно использовать слово `fix` или `hotfix` (для срочных изменений) в качестве первого слова: ```bash git checkout -b hotfix ``` Эта команда создаст ветку с именем `hotfix`, и Git переключит репозиторий на новую ветку. Теперь можно вносить изменения с помощью коммитов, например: ```bash git commit -m 'Вносит правки в описание' ``` Когда все правки внесены, необходимо отправить изменения на GitHub. Для этого нужно выполнить команду: ```bash git push -u origin hotfix ``` После этого нужно перейти на сайт GitHub и зайти там в репозиторий. Сверху появится сообщение на жёлтом фоне, в котором вам предложат создать пулреквест: ![Сообщение «hotfix had recent pushes less than a minute ago». После него кнопка «Compare and pull request.»](images/compare-and-pull-request.png) Можно нажать кнопку «Compare & pull request» в этом сообщении или создать пулреквест «вручную» на странице со списком пулреквестов с помощью кнопки «New pull request»: ![Кнопка «New pull request» для создания пулреквеста на странице со списком пулреквестов. Находится после поля для поиска по проекту с фильтрами.](images/new-pull-request.png) Далее вас перекинет на страницу с настройками будущего пулреквеста. На ней можете добавить название и описать изменения, выбрать ветку, в которую хотите внести изменения (по умолчанию выбирается ветка, из которой создавали текущую ветку с изменениями) или связать ваш запрос с текущими нуждами. Обычно они находятся в списке ишью. Также можете добавить ревьюеров для проверки изменений и тестирования: ![Страница с настройками пулреквеста](images/open-pull-request.png) Внизу страницы будут перечислены коммиты с изменениями. Когда будете уверены, что заполнили необходимые поля и выбрали подходящие настройки, нажмите кнопку «Create pull request».
import Indecision from '@/components/Indecision.vue'; <template> <!-- Hacemos binding con image --> <img v-if="image" :src="image" alt="bg" /> <div class="bg-dark"></div> <div class="indecision-container"> <h1>{{ titulo }}</h1> <input type="text" placeholder="Hazme una pregunta" v-model.trim="question" /> <p>Recuerda terminar con un signo de interrogación (?)</p> <div> <h2 v-if="isValidQuestion">{{ question }}</h2> <h1>{{ answer }}</h1> </div> </div> </template> <script> export default { name: 'Indecision', // Mis propiedades props: { titulo: { type: String, default: 'Indecision', }, }, // eventos que emito emits: ['question-response'], // Mi estado data() { return { question: '', answer: null, image: null, isValidQuestion: false, } }, // Mis métodos methods: { async getAnswer() { try { this.answer = 'Pensando...' // Obtenemos una respuesta y desestructuramos const { answer, image } = await fetch('https://yesno.wtf/api').then((res) => res.json()) this.answer = answer === 'yes' ? 'Sí' : 'No' this.image = image // Mandamos el evento y su parámetro, si lo hay this.$emit('question-response', { respuesta: this.answer }) } catch (error) { this.answer = 'No se pudo cargar de la API la respuesta' this.image = null } }, }, // Mis watchers watch: { // Observamos question question(newQuestion) { // Si la pregunta cambia console.log(newQuestion) // Si la pregunta termina con un signo de interrogación y tiene más que eso :) this.isValidQuestion = false if (newQuestion.endsWith('?') && newQuestion.length > 1) { this.isValidQuestion = true this.getAnswer() } }, }, } </script> <style scoped> img, .bg-dark { height: 100vh; left: 0px; max-height: 100%; max-width: 100%; position: fixed; top: 0px; width: 100vw; } .bg-dark { background-color: rgba(0, 0, 0, 0.4); } .indecision-container { position: relative; z-index: 99; } input { width: 250px; padding: 10px 15px; border-radius: 5px; border: none; margin: 1rem; } input:focus { outline: none; } p { color: white; font-size: 20px; margin-top: 0px; } h1, h2 { color: white; } h2 { margin-top: 150px; } </style>
# from flask import Flask, request, render_template # from search_model import search_book_tfidf, search_book_w2v, search_book_fuzzy # # app = Flask(__name__) # # # @app.route('/') # def home(): # return render_template('index.html') # # # @app.route('/search', methods=['POST']) # def search(): # query = request.form['query'] # # # Set the similarity threshold # tfidf_threshold = 0.1 # w2v_threshold = 0.1 # fuzzy_threshold = 80 # # results_tfidf = search_book_tfidf(query, threshold=tfidf_threshold) # results_w2v = search_book_w2v(query, threshold=w2v_threshold) # results_fuzzy = search_book_fuzzy(query, threshold=fuzzy_threshold) # # return render_template('results.html', query=query, results_tfidf=results_tfidf, results_w2v=results_w2v, # results_fuzzy=results_fuzzy) # # # if __name__ == "__main__": # app.run(debug=True) from flask import Flask, request, render_template from search_model import search_book_combined import re app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') @app.route('/search', methods=['POST']) def search(): query = request.form['query'] # Kiểm tra nếu từ khóa chứa ký tự số if re.search(r'\d', query): message = "Không tìm thấy sách" results_combined = [] else: # Đặt ngưỡng tối thiểu cho điểm số threshold = 0.4 results_combined = search_book_combined(query, threshold=threshold) # Kiểm tra xem có kết quả tìm kiếm hay không if not results_combined: message = "Không tìm thấy sách" else: message = None return render_template('results.html', query=query, results_combined=results_combined, message=message) if __name__ == "__main__": app.run(debug=True)
import { Link } from 'react-router-dom'; import { useEffect, useState } from 'react'; import CartWidget from './CartWidget/CartWidget'; import './NavBar.css'; import FirebaseService from '../services/FirebaseService'; import { FirebaseCollections } from '../helpers/FirebaseUtil'; const NavBar = () => { const [categories, setCategories ] = useState([]); const drawCategoriesMenu = () => { return ( categories.map(data => ( <li className="nav-item" key={data.id}> <Link to={`/category/${data.key}`} className="nav-link active" aria-current="page">{data.description}</Link> </li> )) ); }; useEffect(() => { const { getAllDocs } = FirebaseService(FirebaseCollections.categories); getAllDocs().then(resp => (resp.sort( (prev, next) => (prev.key > next.key)?1:((prev.key < next.key)?-1:0) ))) .then(data => setCategories(data)) .catch(err => { console.error('ERROR:',err); }); }, []); return ( <header> <nav className="navbar navbar-expand-lg bg-light"> <div id="container-nav" className="container-fluid"> <div className="container head-title"> <section className="head-title-1"> {/* Titulo de la tienda */} <h1><Link to={"/"}><span>Book Shop</span></Link></h1> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> </section> <section className="head-title-2"> {/* Tipo de usuario invitado */} <b>[</b> Invitado <b>]</b> </section> </div> <hr id="sep-nav" className="sep-nav" /> <div className="collapse navbar-collapse" id="navbarSupportedContent"> <div className="container barra-menu"> {/* Menu principal de la tienda */} <ul className="navbar-nav me-auto mb-2 mb-lg-0"> <li className="nav-item"> <Link to={"/"} className="nav-link active" aria-current="page">Inicio</Link> </li> { drawCategoriesMenu() } </ul> <ul className="navbar-nav user pull-right"> <li className="dropdown menu"> {/* Carrito de compras */} <CartWidget /> </li> </ul> </div> </div> </div> </nav> </header> ); } export default NavBar;
import { useRef, useState } from 'react'; import { useHistory } from 'react-router-dom'; import './project_4.scss'; const Project_4 = () => { const history = useHistory(); const [user, setUser] = useState({}); const [errorMessage, setErrorMessage] = useState({}); const usernameRef = useRef(); const emailRef = useRef(); const passwordRef = useRef(); const conPasswordRef = useRef(); const handleUser = (e) => { setUser({ ...user, [e.target.name]: e.target.value }); }; const handleSubmit = (e) => { const errors = {}; e.preventDefault(); if (!user.username) { usernameRef.current.className = 'form-control error'; errors['username'] = "Username can't be empty"; } else { usernameRef.current.className = 'form-control success'; } if (!user.email) { emailRef.current.className = 'form-control error'; errors['email'] = "Email Field can't Empty"; } else { if (checkEmailPattern(user.email)) { emailRef.current.className = 'form-control success'; } else { emailRef.current.className = 'form-control error'; errors['email'] = 'Email invalid'; } } if (!user.password) { passwordRef.current.className = 'form-control error'; errors['password'] = "Password Field can't Empty"; } else { passwordRef.current.className = 'form-control success'; } if (!user.confirmPassword) { conPasswordRef.current.className = 'form-control error'; errors['confirmPassword'] = "Confirm password Cant't be blank"; } else { if (user.password !== user.confirmPassword) { conPasswordRef.current.className = 'form-control error'; errors['confirmPassword'] = `Password can't match`; } else { conPasswordRef.current.className = 'form-control success'; } } setErrorMessage(errors); // console.log(errorMessage); if (Object.keys(errors).length === 0) { history.push('/project/4/success'); } }; function checkEmailPattern(email) { const res = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test( String(email.trim()).toLowerCase() ); return res; } return ( <div className="project_4"> <div className="container"> <div className="title">Sign up</div> <div className="form-container"> <form onSubmit={handleSubmit}> <div className="form-control" ref={usernameRef}> <label htmlFor="username">Username</label> <input name="username" id="username" type="text" placeholder="Enter username" onChange={handleUser} /> <i className="fas fa-check-circle"></i> <i className="fas fa-times-circle"></i> <small>{errorMessage.username}</small> </div> <div className="form-control" ref={emailRef}> <label htmlFor="email">Email</label> <input name="email" id="email" type="email" placeholder="Enter email" onChange={handleUser} /> <i className="fas fa-check-circle"></i> <i className="fas fa-times-circle"></i> <small>{errorMessage.email}</small> </div> <div className="form-control" ref={passwordRef}> <label htmlFor="pass">Password</label> <input name="password" id="pass" type="password" placeholder="Enter password" onChange={handleUser} /> <i className="fas fa-check-circle"></i> <i className="fas fa-times-circle"></i> <small>{errorMessage.password}</small> </div> <div className="form-control" ref={conPasswordRef}> <label htmlFor="con">Confirm Password</label> <input name="confirmPassword" id="con" type="password" placeholder="Enter confirm password" onChange={handleUser} /> <i className="fas fa-check-circle"></i> <i className="fas fa-times-circle"></i> <small>{errorMessage.confirmPassword}</small> </div> <button>submit</button> </form> </div> </div> </div> ); }; export default Project_4;
/* Write a solution to calculate 3-day rolling averages of steps for each user. We calculate the n-day rolling average this way: For each day, we calculate the average of n consecutive days of step counts ending on that day if available, otherwise, n-day rolling average is not defined for it. Output the user_id, steps_date, and rolling average. Round the rolling average to two decimal places. Return the result table ordered by user_id, steps_date in ascending order. */ WITH NewSteps AS ( SELECT *, COALESCE(lead_steps_date-steps_date, 0) AS steps_date_difference FROM ( SELECT user_id, steps_count, steps_date, LEAD(steps_date) OVER(PARTITION BY user_id ORDER BY steps_date) AS lead_steps_date FROM Steps ) S ), RollingAverages AS ( SELECT user_id, steps_count, steps_date, ROUND(AVG(steps_count) OVER(PARTITION BY user_id ORDER BY steps_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW), 2) AS rolling_average, ROW_NUMBER() OVER(PARTITION BY user_id ORDER BY steps_date) AS row_num FROM NewSteps WHERE steps_date_difference IN (0, 1) ) SELECT user_id, steps_date, rolling_average FROM RollingAverages WHERE row_num >= 3 ORDER BY user_id, steps_date;
<!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>Age Calculator</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" 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=Oswald&family=Roboto&display=swap" rel="stylesheet"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link rel="icon" type="image/x-icon" href="fevicon.png"> <link href="https://fonts.googleapis.com/css2?family=Creepster&display=swap" rel="stylesheet"> <style> *{ /* background-color: #E6E6E6; */ font-family: 'Roboto', sans-serif; } .title{ font-size: 4.5rem; text-transform: capitalize; color: #1488e7; font-family: 'Creepster', cursive; } .text{ font-size: 1.7rem; } .dobtext, .currtext{ font-size: 2rem; text-transform: capitalize; font-weight:500; } .display{ text-transform: capitalize; font-size: 1.4rem; } input[type="date"] { font-size: 1.4rem; padding: 8px; border-radius: 5px; border-radius: 5px; text-align: center; } input[type="button"]{ font-size: 1.4rem; border-radius: 5px; border: 1px solid black; background-color: #AED5F5; text-transform: capitalize; } input[type="button"]:hover{ cursor: pointer; box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.292); } .display{ font-family: 'Roboto', sans-serif; font-size: 1.6rem; } </style> </head> <body style="background-color: #f4f4f4"> <!-- title --> <div class="container"> <div class="row"> <div class="col-12"> <div class="text-center title"> age calculator </div> </div> </div> </div> <!-- text --> <div class="container "> <div class="row"> <div class="col-12 pt-3"> <p class="text-center text"> To calculate age, you need to enter the birthdate of the person and the current date, and the age calculator will do the rest. </p> </div> </div> </div> <!-- calculator --> <div class="container" id="backcolor"> <div class="row pt-4 "> <div class="col-12 text-center"> <p class=" dobtext"> enter the date of birth </p> <input type="date" name="" id="dob"> <p class="currtext pt-3"> enter the current date </p> <input type="date" name="" id="curd"> </div> </div> <div class="row py-4"> <div class="col-12 text-center"> <input type="button" name="" id="" value="calculate" onclick="calculateage()"> </div> </div> <div class="row"> <div class="col-12"> <pre class="display mx-3"> Age : <span id="years"></span> Total months : <span id="months"></span> Total days : <span id="days"></span> Total hours : <span id="hours"></span> Total minutes : <span id="minutes"></span> Total seconds : <span id="seconds"></span> </pre> </div> </div> </div> <script> function calculateage(){ var birthdate = new Date(document.getElementById('dob').value); var currentdate = new Date(document.getElementById('curd').value); var ageInMilliseconds = currentdate - birthdate; var ageInSeconds = ageInMilliseconds / 1000; var ageInMinutes = ageInSeconds / 60; var ageInHours = ageInMinutes / 60; var ageInDays = ageInHours / 24; var ageInMonths = ageInDays / 30.44; var ageInYears = ageInMonths / 12; document.getElementById("years").innerHTML = Math.floor(ageInYears)+" Years"; document.getElementById("months").innerHTML = Math.floor(ageInMonths ); document.getElementById("days").innerHTML = Math.floor(ageInDays ); document.getElementById("hours").innerHTML = Math.floor(ageInHours ); document.getElementById("minutes").innerHTML = Math.floor(ageInMinutes ); document.getElementById("seconds").innerHTML = Math.floor(ageInSeconds ); } </script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script> </body> </html>
import React from 'react' import SignUp from '../pages/SignUp' import frameImage from "../assets/frame.png" import SignUpForm from '../Component/SignUpForm' import LoginForm from "../Component/LoginForm" import {FcGoogle} from "react-icons/fc" export const Template = ({ title, desc1, desc2, image, formtype, setIsLoggedIn }) => { return ( <div className='flex justify-between w-11/12 max-w-[1160px] py-12 mx-auto gap-y-0'> <div className='w-11/12 max-w-[450px]'> <h1 className='text-richblack-5 font-semibold text-[1.875rem] leading-[2.375rem]'>{title}</h1> <p className='text-[1.125rem] leading-[1.625rem] mt-4'> <span className='text-richblack-100'>{desc1}</span> <br/> <span className='text-blue-100 italic'>{desc2}</span> </p> {formtype =="signup" ? (<SignUpForm setIsLoggedIn={setIsLoggedIn} />):(<LoginForm setIsLoggedIn={setIsLoggedIn} />)} <div className='flex flex-row w-full items-center my-4 gap-x-2 '> <div className='h-[1px] w-full bg-richblack-700'></div> <p className='text-richblack-700 font-medium leading-[1.375rem]'>OR</p> <div className='h-[1px] w-full bg-richblack-700'></div> </div> <button className='w-full flex justify-center items-center rounded-[8px] font-medium text-richblack-100 border border-richblack-700 px-[12px] py-[8px] gap-x-2 mt-2'> <FcGoogle/> <p>SignUp with Google</p> </button> </div> <div className='relative w-11/12 max-w-[450px]'> <img src={frameImage} alt='pattern' width={558} height={504} loading='lazy' /> <img className='absolute -top-4 right-4' src={image} alt='students' width={558} height={490} loading='lazy' /> </div> </div> ) }
<?php declare(strict_types=1); namespace Flow\ETL\Extractor; use Flow\ETL\Exception\InvalidArgumentException; trait Limitable { private ?int $limit = null; private int $yieldedRows = 0; public function changeLimit(int $limit) : void { if ($limit <= 0) { throw new InvalidArgumentException('Limit must be greater than 0'); } $this->limit = $limit; } public function countRow() : void { $this->yieldedRows++; } public function isLimited() : bool { return $this->limit !== null; } public function limit() : ?int { return $this->limit; } public function reachedLimit() : bool { if ($this->limit === null) { return false; } return $this->yieldedRows >= $this->limit; } public function resetLimit() : void { $this->limit = null; $this->yieldedRows = 0; } }
// // ConfirmationView.swift // SwiftUI-Supabase-Calendly-Clone // // Created by Micah Hodge on 10/6/23. // import SwiftUI struct ConfirmationView: View { @Binding var path: NavigationPath var currentDate: Date var body: some View { ScrollView { VStack { Image("micah") .resizable() .scaledToFill() .frame(width: 128, height: 128) .clipShape(/*@START_MENU_TOKEN@*/Circle()/*@END_MENU_TOKEN@*/) Text("Confirmed") .font(.title) .bold() .padding() Text("You are schedule with Micah Hodge.") Divider() .padding() VStack(alignment: .leading, spacing: 32) { HStack { Circle() .frame(width: 20, height: 20) .foregroundStyle(.blue) Text("Calendly Course") } HStack(alignment: .firstTextBaseline) { Image(systemName: "calendar") Text(currentDate.bookingViewDateFormat()) } HStack(alignment: .firstTextBaseline) { Image(systemName: "video") Text("FaceTime") } } Spacer() } .padding() .frame(maxHeight: .infinity, alignment: .top) } .overlay( Button { path = NavigationPath() } label: { Text("Done") .bold() .foregroundStyle(.white) .padding() .frame(maxWidth: .infinity) .background(RoundedRectangle(cornerRadius: 10).foregroundStyle(.blue)) } .padding() , alignment: .bottom ) .navigationBarBackButtonHidden() } } #Preview { NavigationStack { ConfirmationView(path: .constant(NavigationPath()), currentDate: Date()) } }
### Reto #1: EL "LENGUAJE HACKER"” ### """ https://retosdeprogramacion.com/ Escribe un programa que reciba un texto y transforme lenguaje natural a "lenguaje hacker" (conocido realmente como "leet" o "1337"). Este lenguaje se caracteriza por sustituir caracteres alfanuméricos. - Utiliza esta tabla (https://www.gamehouse.com/blog/leet-speak-cheat-sheet/) con el alfabeto y los números en "leet". (Usa la primera opción de cada transformación. Por ejemplo "4" para la "a") """ leet_dict = {"a": "4", "b": "I3", "c": "[", "d": ")", "e": "3", "f": "|=", "g": "&", "h": "#", "i": "1", "j": ",_|", "k": ">|", "l": "1", "m": "/\/\\", "n": "^/", "o": "0", "p": "|*", "q": "(_,)", "r": "|2", "s": "5", "t": "7", "u": "(_)", "v": "\/", "w": "\/\/", "x": "><", "y": "j", "z": "2", "1": "L", "2": "R", "3": "E", "4": "A", "5": "S", "6": "b", "7": "T", "8": "B", "9": "g", "0": "o" } # using for loop :) def to_leet(text): leet ="" for i in text: leet += leet_dict.get(i,i) return leet # using list comprehension :)) def to_leet_list_com(text:str)-> str: return ''.join([leet_dict.get(x,x) for x in text ]) text = input("Enter text to transform to LEET: \n").lower() print(to_leet(text)) print(to_leet_list_com(text))
--> Services local ReplicatedStorage = game:GetService("ReplicatedStorage") --> Overhead Object local OverheadObject = ReplicatedStorage:WaitForChild("Overhead") --> Gradients local GradientsFolder = ReplicatedStorage:WaitForChild("Gradients") --> Packages local Packages = script:WaitForChild("Packages") local Class = require(Packages:WaitForChild("class")) --> Create Class local Overhead = Class("Overhead") --> Methods function Overhead:__init(player) self.Overhead = OverheadObject:Clone() local Character = player.Character self.Overhead.Parent = Character self.Overhead.Adornee = Character:FindFirstChild("Head") local UsernameString = "" if player.Name == player.DisplayName then UsernameString = player.Name else UsernameString = string.format("%s(@%s)", player.DisplayName, player.Name) end self.Overhead.Main.Username.Text = UsernameString self.Overhead.Main.LevelUI.Label.Text = string.format("LEVEL: %s", tostring(player:GetAttribute("Level"))) end function Overhead:ApplyGradient(player, GradientName) local Overhead = self.Overhead if GradientsFolder:FindFirstChild(GradientName) then local Gradient = GradientsFolder:FindFirstChild(GradientName):Clone() Gradient.Parent = Overhead.Main.Username Gradient:Clone().Parent = Overhead.Main.Rank end end function Overhead:UpdateStats(player) local Overhead = self.Overhead if (player:GetAttribute("SwordFight") == nil) or (player:GetAttribute("SwordFight") ~= nil and player:GetAttribute("SwordFight") == false) then Overhead.Main.LevelUI.Label.Text = string.format("LEVEL: %s", tostring(player:GetAttribute("Level"))) elseif (player:GetAttribute("SwordFight") ~= nil and player:GetAttribute("SwordFight") == true) then Overhead.Main.LevelUI.Label.Text = string.format("KILLS: %s", tostring(player:GetAttribute("Kills"))) end end --> Return Class return Overhead
package com.yedam.web.common; import lombok.Getter; @Getter //내부값 변경이 필요한 경우가 잘 없어서 생성자에서만 값을 변경시키고 읽어들이기만 하기 위해 getter만 설정 public class PagingVO { private final static int defaultVal = 10; private int totalData; //현재 총 데이터 수 private int nowPage; //현재 페이지 private int cntPage = 10; //View 안에서 보여줄 페이지 수 -> 시작 페이지와 끝 페이지 발생 (직접 결정하는 값) private int startPage; //시작 페이지 = (끝 페이지-5)+1 private int endPage; //끝 페이지 = (올림)(현재 페이지/5)*5 private int cntPerPage; //한 페이지 안에 보여줄 데이터 수 private int lastPage; //마지막 페이지 = 총 데이터수/한 페이지에 보여줄 데이터 수 private int start; //현재 페이지 안에 보여줄 첫번째 데이터 private int end; //현재 페이지 안에 보여줄 마지막 데이터 //생성자를 통해서만 값을 넘김 public PagingVO(int totalData, int nowPage, int cntPerPage) { this.totalData = totalData; this.nowPage = nowPage; this.cntPerPage= cntPerPage; //생성하는 순간 모든 필드에 값이 들어가야함 -> 연산작업이 필요 calcLastPage(); calcStartEndPage(); calcStartEnd(); } public PagingVO(int totalData, int nowPage) { //보여줄 데이터 개수를 정해놓을 때 this(totalData, nowPage, defaultVal); } //제일 마지막 페이지 계산 private void calcLastPage() { //소수점 필요하므로 double로 강제변환 반드시 할 것 -> 올림처리 -> 올림처리하면 double로 반환됨 -> 다시 int로 변환 this.lastPage = (int)Math.ceil((double)this.totalData / (double)this.cntPerPage); } //현재 view안에서 시작, 끝 페이지 계산 //선택 사항-> 데이터의 개수가 정해져있는 경우엔 필요 없을때가 있기 때문 private void calcStartEndPage() { this.endPage = (int)Math.ceil((double)this.nowPage / (double)this.cntPage) * this.cntPage; //끝 페이지는 마지막 페이지보다 작아야함 if(this.endPage > this.lastPage) { this.endPage = this.lastPage; } //시작 페이지 마이너스 값이 나오는지 확인 this.startPage = (this.endPage - this.cntPage) + 1; if(this.startPage < 1) { this.startPage = 1; } } //현재 페이지 안에서 보여질 첫번째 데이터와 마지막 데이터 -> DB쿼리 안에 사용할 start, end private void calcStartEnd() { this.start = ((this.nowPage - 1) * this.cntPerPage)+1; this.end = this.nowPage * this.cntPerPage; //end는 totalData보다 작아야함 if(this.end > this.totalData) { this.end = this.totalData; } } }
import { Component, Inject } from '@angular/core'; import { MatDialog, MAT_DIALOG_DATA, MatDialogRef, MatDialogModule, MatDialogConfig } from '@angular/material/dialog'; import { MatButtonModule } from '@angular/material/button'; import { FormsModule } from '@angular/forms'; import { MatInputModule } from '@angular/material/input'; import { MatFormFieldModule } from '@angular/material/form-field'; import { Product } from '../products'; import { ProductsService } from "../products.service"; @Component({ selector: 'app-dialog-data', templateUrl: './dialog-data.component.html', styleUrls: ['./dialog-data.component.css'] }) export class DialogDataComponent { name: string; price: number; description: string; discount: number; stock: number; category: string; constructor(public dialog: MatDialog) { } openDialog(): void { const dialogRef = this.dialog.open(DialogOverviewExampleDialog, { data: { name: this.name, price: this.price, description: this.description, discount: this.discount, stock: this.stock, category: this.category, }, width: '500px', height: '800px', }); } } @Component({ selector: 'dialog-overview-example-dialog', templateUrl: 'dialog-overview-example-dialog.html', standalone: true, imports: [MatDialogModule, MatFormFieldModule, MatInputModule, FormsModule, MatButtonModule], }) export class DialogOverviewExampleDialog { product: Product; constructor( public dialogRef: MatDialogRef<DialogOverviewExampleDialog>, private productsService: ProductsService, @Inject(MAT_DIALOG_DATA) public data: Product, ) { } onNoClick(): void { this.dialogRef.close(); } createProduct() { this.dialogRef.afterClosed().subscribe(result => { console.log('The dialog was closed'); console.log("Result: ", result); this.product = result; console.log("This ", this.product); this.productsService.createProduct(this.product).subscribe(response => { console.log("Product created ", response.body); }); }); } }
using MoneyManager.Models; using MoneyManager.Data.Repositories.Concrete; using System.ComponentModel; using System.Windows.Input; using System.Threading.Tasks; using System; using System.Collections.ObjectModel; using System.Windows; namespace MoneyManager.ViewModels.Deposits { public class AddDepositViewModel : INotifyPropertyChanged { private readonly DepositRepository _depositRepository; private readonly CurrencyRepository _currencyRepository; private Deposit _newDeposit; private ObservableCollection<Currency> _currencies; public ObservableCollection<Currency> Currencies { get => _currencies; set { _currencies = value; OnPropertyChanged(nameof(Currencies)); } } public Deposit NewDeposit { get => _newDeposit; set { _newDeposit = value; OnPropertyChanged(nameof(NewDeposit)); } } public ICommand AddDepositCommand { get; } public AddDepositViewModel(DepositRepository depositRepository, CurrencyRepository currencyRepository) { _depositRepository = depositRepository; _currencyRepository = currencyRepository; _newDeposit = new Deposit { StartDate = DateTime.Today, EndDate = DateTime.Today }; AddDepositCommand = new RelayCommand(async _ => await AddDeposit()); LoadData(); } private async Task AddDeposit() { if (NewDeposit.Currency != null) { NewDeposit.CurrencyId = NewDeposit.Currency.CurrencyId; NewDeposit.Status = true; // Активируем вклад при добавлении await _depositRepository.AddAsync(NewDeposit); DepositAdded?.Invoke(this, NewDeposit); } else { // Обработка случая, когда валюта не выбрана MessageBox.Show("Пожалуйста, выберите валюту.", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error); } } private async void LoadData() { var currencies = await _currencyRepository.GetAllAsync(); Currencies = new ObservableCollection<Currency>(currencies); } public event EventHandler<Deposit> DepositAdded; public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
# %% import numpy as np from dataclasses import dataclass import scipy.stats as ss import pandas as pd from typing import Optional, Any, List # %% # a class to store parameters @dataclass class Parameter: input_model: List[float] transition_model: List[float] observation_model: List[float] initial_state: np.ndarray # %% class ModelInterface: """Customize necessary model functionalities here Methods: _parse_config: parse configurations _set_observed_made_each_step: set observation interval _set_fluxes: set fluxes and observations using info from config _parse_theta_init: parse initial values of parameters _set_parameter_distribution: set parameter distribution using info from theta_init update_model: update model using the new theta values transition_model: transition model for/to link user-defined model observation_model: observation model for/to link user-defined model observation_model_likelihood: observation model likelihood for/to link user-defined model input_model: input model for/to link user-defined model state_as_model: state model for/to link user-defined model """ def __init__( self, df: pd.DataFrame, customized_model: Optional[Any] = None, theta_init: Optional[dict[str, Any]] = None, config: Optional[dict[str, Any]] = None, num_input_scenarios: Optional[int] = 10, ) -> None: """Initialize the model interface, and parse any parameters Args: df (pd.DataFrame): dataframe of input data customized_model (Optional, Any): any model structure that is necessary to import info. Refer to Linear_reservoir for example. theta_init (Optional, dict): initial values of parameters config (Optional, dict): configurations of the model num_input_scenarios (Optional, int): number of input scenarios Set: df (pd.DataFrame): dataframe of input data model (Any): any model structure that pass through customized_model. Refer to Linear_reservoir for example. config (dict): configurations of the model N (int): number of input scenarios T (int): length of the dataframe """ self.df = df self.model = customized_model # pass your own model here self.N = num_input_scenarios self.T = len(self.df) # set T to be the length of the dataframe # Set configurations according your own need here self.config = config self._parse_config() # Set parameters to be estimated here self._parse_theta_init(theta_init=theta_init) # initialize theta self.update_theta() def _parse_config(self) -> None: """Parse config and set default values Set: dt (float): time step config (dict): configurations of the model """ _default_config = { "dt": 1.0 / 24 / 60 * 15, "influx": "J_obs", "outflux": "Q_obs", "observed_made_each_step": True, } if self.config is None: self.config = _default_config elif not isinstance(self.config, dict): raise ValueError("Error: Please check the input format!") else: # make sure all keys are valid for key in self.config.keys(): if key not in _default_config.keys(): raise ValueError(f"Invalid config key: {key}") # replace default config with input configs for key in _default_config.keys(): if key not in self.config: self.config[key] = _default_config[key] # set delta_t------------------------ self.dt = self.config["dt"] # get observation interval set self._set_observed_made_each_step() # get fluxes set self._set_fluxes() return def _set_observed_made_each_step(self) -> None: """Set observation interval based on config Set: K (int): number of observed timesteps observed_ind (np.ndarray): indices of observed timesteps """ obs_made = self.config["observed_made_each_step"] # if giving a single bool val if isinstance(obs_made, bool): # if bool val is True if obs_made: self.K = self.T self.observed_ind = np.arange(self.T) # if bool val is False, request to give a int val to give observation interval else: raise ValueError("Error: Please specify the observation interval!") # give observation interval as a list elif isinstance(obs_made, np.ndarray) or isinstance(obs_made, list): # convert np.ndarray to list if isinstance(obs_made, np.ndarray): obs_made = obs_made.tolist() # check if the length of the list is the same as the length of the time series if len(obs_made) == self.T: # if is all bool and all True if all(isinstance(entry, bool) and entry for entry in obs_made): self.K = self.T self.observed_ind = np.arange(self.T) # if is all bool and some are not True elif all(isinstance(entry, bool) for entry in obs_made): self.K = sum(obs_made) self.observed_ind = np.arange(self.T)[obs_made] else: raise ValueError( "Error: Check the format of your observation indicator!" ) # give observation interval as a int - how many timesteps elif isinstance(obs_made, int): # in this case K is still equal to T self.K = self.T self.config["dt"] *= obs_made # update dt to account for the interval self.observed_ind = np.arange(self.K) else: raise ValueError("Error: Input format not supported!") def _set_fluxes(self) -> None: """Set influx and outflux Set: influx (np.ndarray): influx outflux (np.ndarray): outflux """ # TODO: flexible way to insert multiple influx and outflux if self.config["influx"] is not None: self.influx = self.df[self.config["influx"]] else: print("Warning: No influx is given!") if self.config["outflux"] is not None: self.outflux = self.df[self.config["outflux"]] else: print("Warning: No outflux is given!") return def _parse_theta_init(self, theta_init: Optional[dict[str, Any]] = None) -> None: """Parse theta from theta_init new theta_init can overwrite the default theta_init default theta_init can fill in the missing keys in new theta_init Args: theta_init (Optional, dict): initial values of parameters Set: theta_init (dict): initial values of parameters """ _default_theta_init = { "to_estimate": { "k": { "prior_dis": "normal", "prior_params": [1.0, 0.0001], "is_nonnegative": True, }, "initial_state": { "prior_dis": "normal", "prior_params": [self.df[self.config["outflux"]][0], 0.0001], "is_nonnegative": True, }, "input_uncertainty": { "prior_dis": "normal", "prior_params": [ self.df[self.config["influx"]].std(ddof=1), 0.0005, ], "is_nonnegative": True, }, "obs_uncertainty": { "prior_dis": "normal", "prior_params": [ self.df[self.config["outflux"]].std(ddof=1), 0.000005, ], "is_nonnegative": True, }, }, "not_to_estimate": {}, } self._theta_init = theta_init # set default theta if theta_init == None: self._theta_init = _default_theta_init elif not isinstance(theta_init, dict): raise ValueError("Error: Please check the input format!") else: # make sure all keys are valid for key in self._theta_init["to_estimate"].keys(): if key not in _default_theta_init["to_estimate"].keys(): print(f"key: {key} not in default config!") # raise ValueError(f'Invalid config key: {key}') # replace default config with input configs for key in _default_theta_init["to_estimate"].keys(): if key not in self._theta_init["to_estimate"]: self._theta_init["to_estimate"][key] = _default_theta_init[ "to_estimate" ][key] # find params to update self._theta_to_estimate = list(self._theta_init["to_estimate"].keys()) self._num_theta_to_estimate = len(self._theta_to_estimate) # Set parameter constraints and distributions self._set_parameter_constraints() self._set_parameter_distribution() return def _set_parameter_constraints(self) -> None: """Get parameter constraints: nonnegative or not Set: param_constraints (dict): whether this parameter is nonnegative """ # save models self.param_constraints = {} for key in self._theta_to_estimate: current_theta = self._theta_init["to_estimate"][key] if "is_nonnegative" in current_theta: self.param_constraints[key] = current_theta["is_nonnegative"] else: self.param_constraints[key] = False return def _set_parameter_distribution( self, update: Optional[bool] = False, theta_new: Optional[dict] = None ) -> None: """Set parameter distribution model and update the model object Args: update (Optional, bool): whether to update the model object theta_new (Optional, float): new theta to initialize/update the model Set: dist_model (dict): parameter distribution model """ if not update: # save models self.dist_model = {} for key in self._theta_to_estimate: # grab theta current_theta = self._theta_init["to_estimate"][key] is_nonnegative = self.param_constraints[key] # set parameters for prior distribution: [first param: mean, second param: std] if current_theta["prior_dis"] == "normal": # update or not if not update: mean = current_theta["prior_params"][0] else: mean = theta_new[key] std = current_theta["prior_params"][1] # truncate or not if is_nonnegative: a = (0 - mean) / std self.dist_model[key] = ss.truncnorm( a=a, b=np.inf, loc=mean, scale=std ) else: self.dist_model[key] = ss.norm(loc=mean, scale=std) elif current_theta["prior_dis"] == "uniform": # first param: lower bound, second param: upper bound # Note: uniform distribution is non-informative prior, so we don't update it lower_bound = current_theta["prior_params"][0] interval_length = ( current_theta["prior_params"][1] - current_theta["prior_params"][0] ) self.dist_model[key] = ss.uniform( loc=lower_bound, scale=interval_length ) else: raise ValueError("This prior distribution is not implemented yet") return def update_theta(self, theta_new: Optional[List[float]] = None) -> None: """Set/update the model object with a new parameter set Args: theta_new (Optional, Theta): new theta to initialize/update the model Set: Parameter: update parameter object for later """ # initialize theta to the order of self._theta_to_estimate if theta_new is None: theta_new = np.zeros(self._num_theta_to_estimate) for i, key in enumerate(self._theta_to_estimate): theta_new[i] = self.dist_model[key].rvs() # if a set of theta is given, update the current theta to the new theta for i, key in enumerate(self._theta_to_estimate): self._theta_init["to_estimate"][key]["current_value"] = theta_new[i] # update parameters to be passed into the model # transition model transition_param = [ self._theta_init["to_estimate"]["k"][ "current_value" ], # param [0] is k to estimate self.config["dt"], # param [1] is delta_t (fixed) ] # observation model obs_param = self._theta_init["to_estimate"]["obs_uncertainty"]["current_value"] # input uncertainty param is to estimate input_param = self._theta_init["to_estimate"]["input_uncertainty"][ "current_value" ] # initial state param is to estimate init_state = self._theta_init["to_estimate"]["initial_state"]["current_value"] # update model object theta self.theta = Parameter( input_model=input_param, transition_model=transition_param, observation_model=obs_param, initial_state=init_state, ) return def input_model(self, start_ind: int, end_ind: int) -> None: """Input model for linear reservoir Ut: influx at time t Rt = N(Ut, theta_r) Args: start_ind (int): start index of the input time series end_ind (int): end index of the input time series Returns: np.ndarray: Rt """ sig_r = self.theta.input_model theta_dt = self.theta.transition_model[1] R = np.zeros((self.N, end_ind - start_ind)) U = self.influx[start_ind:end_ind] for n in range(self.N): R[n] = ss.norm(U, scale=sig_r).rvs() return R def transition_model( self, Xtm1: np.ndarray, Rt: Optional[np.ndarray] = None ) -> np.ndarray: """State estimaton model f_theta(Xt-1, Rt) Currently set up for linear reservoirmodel: Xt = (1 - k * delta_t) * X_{t-1} + delta_t * Rt, where Rt = N(Ut, theta_r) from input model Args: Xtm1 (np.ndarray): state X at t = k-1 Rt (np.ndarray, Optional): input signal at t = k-1:k Returns: np.ndarray: state X at t """ # Get parameters theta = self.theta.transition_model theta_k = theta[0] theta_dt = theta[1] # update from last observation num_iter = Rt.shape[1] Xt = np.ones((self.N, num_iter + 1)) * Xtm1.reshape(-1, 1) for i in range(1, num_iter + 1): Xt[:, i] = (1 - theta_k * theta_dt) * Xt[:, i - 1] + theta_dt * Rt[:, i - 1] return Xt[:, 1:] # return w/out initial state def transition_model_probability(self, X_1toT: np.ndarray) -> np.ndarray: """State estimaton model f_theta(Xt-1, Rt) Currently set up for linear reservoirmodel: p(Xt|Xtm1) = (1 - k * delta_t) * Xtm1 + delta_t * Rt, where Rt = N(Ut, theta_r) from input model p(Xt|Xtm1) = N((1 - k * delta_t) * Xtm1 + delta_t * Ut, delta_t * theta_r) Args: X_1toT (np.ndarray): state X at t = 1:T Returns: np.ndarray: p(X_{1:T}|theta) """ # Get parameters theta = self.theta.transition_model theta_k = theta[0] theta_dt = theta[1] theta_r = self.theta.input_model # set all params prob = np.ones((self.N, self.T - 1)) Ut = self.influx[1:].to_numpy() Xtm1 = X_1toT[:-1] Xt = X_1toT[1:] # calculate prob prob = ss.norm( (1 - theta_k * theta_dt) * Xtm1 + theta_dt * Ut, theta_r * (theta_dt) ).logpdf(Xt) return prob.sum() def observation_model(self, Xk: np.ndarray) -> np.ndarray: """Observation probability g_theta Current setup for linear reservoir: y_hat(k) = x(k) Current general model setting: y(t) = y_hat(t) - N(0, theta_v), where y_hat(t) = x(t) Args: Xk (np.ndarray): state X at time k yhk (np.ndarray): estimated y_hat at time k Returns: np.ndarray: y_hat at time k """ return Xk def observation_model_probability( self, yhk: np.ndarray, yk: np.ndarray ) -> np.ndarray: """get observation probability p(y|y_hat, sig_v) Args: yhk (np.ndarray): estimated y_hat at time k yk (np.ndarray): observation y at time k Returns: np.ndarray: the likelihood of observation """ theta = self.theta.observation_model return ss.norm(yhk, theta).logpdf(yk) def initial_state_model(self, num: int) -> np.ndarray: """Initial state model Args: num (int): number of initial states to generate Returns: np.ndarray: initial state """ return self.dist_model["initial_state"].rvs(num) def state_as_probability(self, offset: np.ndarray, std: float): """State model probability p(xk'|xk) Args: offset (np.ndarray): offset of state model (xk - xk') sd (float): standard deviation of state model, set to be adaptive for now Returns: np.ndarray: probability of estimated state around ref trajectory """ return ss.norm(0, std).logpdf(offset) # %%
import { Component, OnInit, ElementRef, ViewChild, AfterViewInit, ChangeDetectorRef } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { AuthService } from '../../core/auth/auth.service' import { PlataformDetectorService } from '../../core/plataform-detector/plataform-detector.service'; @Component({ selector: 'app-signin', templateUrl: './signin.component.html', styleUrls: ['./signin.component.css'] }) export class SignInComponent implements OnInit, AfterViewInit { loginForm: FormGroup; @ViewChild('userNameInput') userNameInput: ElementRef<HTMLInputElement>; constructor( private formBuilder: FormBuilder, private authService: AuthService, private router: Router, private platformDetectorService: PlataformDetectorService, private cdRef: ChangeDetectorRef) { } ngAfterViewInit(): void { this.platformDetectorService.isPlatformBrowser() && this.userNameInput.nativeElement.focus(); this.cdRef.detectChanges(); } ngOnInit(): void { this.loginForm = this.formBuilder.group({ userName: ['', Validators.required], password: ['', Validators.required] }); } login() { const userName = this.loginForm.get('userName').value; const password = this.loginForm.get('password').value; this.authService.autenticate(userName, password).subscribe( () => //user/flavio this.router.navigate(['user', userName]), err => { console.log(err); this.loginForm.reset(); // Se a plataforma for no navegador ele vai executar o focus no campo, se não nem irá executar por isso está utilizando o && this.platformDetectorService.isPlatformBrowser() && this.userNameInput.nativeElement.focus(); alert('User name or pasword is incorrect!'); } ); } }
import React, { useEffect, useState } from "react"; type CountdownTimerProps = { time: number; start_date?: string; className?: string; precisionDigit?: number; }; export default function CountdownTimer({ time, start_date, className, precisionDigit = 1, }: CountdownTimerProps) { const [countdown, setCountdown] = useState(time); useEffect(() => { const end_date = start_date ? new Date(new Date(start_date).getTime() + time * 1000) : new Date(Date.now() + time * 1000); setCountdown(time); const timerId = setInterval(() => { setCountdown((_) => { const time_left = end_date.getTime() - Date.now(); if (time_left <= 0) { clearInterval(timerId); return 0; } else { return time_left / 1000; } }); }, 1000 / 10 ** precisionDigit); // Return a cleanup function that clears the interval return () => clearInterval(timerId); }, [time, start_date, precisionDigit]); return <div className={className}>{countdown.toFixed(precisionDigit)}</div>; }
import java.util.Arrays; public class ClimbStairsFib { // recursions -O(2^n) public static int ways(int n){ if(n == 0){ return 1; } if(n < 0){ return 0; } return ways(n-1) + ways(n-2); } // dp - memo ->O(n) public static int waysdp(int n, int dp[]){ if( n == 0){ return 1; } if( n < 0){ return 0; } if( dp[n] != -1){ return dp[n]; } return dp[n] = waysdp(n-1,dp) + waysdp(n-2, dp); } //for three steps allowed 1,2,3 public static int waysdp3(int n, int dp3[]){ if( n == 0){ return 1; } if( n < 0){ return 0; } if( dp3[n] != -1){ return dp3[n]; } return dp3[n] = waysdp3(n-1,dp3) + waysdp3(n-2, dp3) + waysdp3(n-3,dp3); } //intialization -> O(n) public static int waysinit(int n){ int waysdp[] = new int[n+1]; waysdp[0] = 1; for(int i=1;i<=n;i++){ if( i == 1){ waysdp[i] = waysdp[ i-1]; }else{ waysdp[i] = waysdp[i-1] + waysdp[i-2]; } } int ans = waysdp[n]; return ans; } public static int waysinit3(int n){ int waysdp3[] = new int[n+1]; waysdp3[0] = 1; for(int i=1;i<=n;i++){ if( i == 1){ waysdp3[i] = waysdp3[ i-1]; } else if( i == 2){ waysdp3[i] = waysdp3[i-1] + waysdp3[i-2]; }else{ waysdp3[i] = waysdp3[i-1] + waysdp3[i-2] + waysdp3[i-3]; } } int ans = waysdp3[n]; return ans; } public static void main(String[] args) { int n = 4; System.out.println(ways(n)); int dp[] = new int[n+1]; Arrays.fill(dp, -1); System.out.println(waysdp(n,dp)); // 3 steps int dp3[] = new int[n+1]; Arrays.fill(dp3, -1); System.out.println(waysdp3(n,dp3)); //tabulation System.out.println(waysinit(n)); //tabulation -> 3steps System.out.println(waysinit3(n)); } }
<?php /** * Template part for displaying posts * * @link https://codex.wordpress.org/Template_Hierarchy * * @package pastelinterior */ ?> <article <?php post_class('blog_item'); ?> > <?php if( is_sticky() ){ echo '<span class="sticky_label">'. esc_html__( 'Sticky', 'pastel-interior' ) .'</span>'; } if( has_post_thumbnail() ){ ?> <div class="blog_item_img"> <?php the_post_thumbnail( 'pastelinterior_blog_750x375', array( 'class' => 'card-img rounded-0' ) ); echo '<a href="'. esc_url( pastelinterior_blog_date_permalink() ) .'" class="blog_item_date"><h3>'. get_the_time( 'd' ) .'</h3><p>'. get_the_time('M') .'</p></a>'; ?> </div> <?php } ?> <div class="blog_details"> <a class="d-inline-block" href="<?php the_permalink(); ?>"> <h2 class="p_title"><?php the_title(); ?></h2> </a> <?php echo wpautop( wp_trim_words( get_the_content(), 28, '' ) ); if( pastelinterior_opt( 'pastelinterior_blog_meta' ) == 1 ) { ?> <ul class="blog-info-link"> <li class="cat_list"><i class="fa fa-tags"></i> <?php echo pastelinterior_featured_post_cat(); ?></li> <li><?php echo pastelinterior_posted_comments(); ?></li> </ul> <?php } ?> </div> </article>
const express = require('express'); const app = express(); // req ==> middleware ==> res const logger = (req,res,next)=>{ const method = req.method; const url = req.url; const time = new Date().getFullYear(); console.log(method, url, time); // this is an example of terminating your code in the middleware // res.send('testing') next() // without next, the process will never finish and will never make it to the response } app.get('/', logger, (req, res, next)=>{ res.send("Home"); }) app.listen(5000, ()=>{ console.log('Listening on port 5000'); });
const faker = require('faker'); const boom = require('@hapi/boom'); class ProductsServices { constructor() { this.products = []; this.generate(); } generate() { const limit = 100; for (let i = 0; i < limit; i++) { this.products.push({ id: this.products.length.toString(), name: faker.commerce.productName(), price: parseInt(faker.commerce.price()), image: faker.image.imageUrl(), isBlock: faker.datatype.boolean(), }); } } async create(data) { const newProduct = { id: ( parseInt(this.products[this.products.length - 1].id) + 1 ).toString(), ...data, }; this.products.push(newProduct); return newProduct; } async find() { return this.products; } async findOne(id) { const product = this.products.find((item) => item.id === id); if (!product) { throw boom.notFound('Product not fount'); } if (product.isBlock) { throw boom.conflict('Product is block'); } return product; } async update(id, changes) { const index = this.products.findIndex((item) => item.id === id); if (index === -1) { throw boom.notFound('Product not fount'); } const product = this.products[index]; this.products[index] = { ...product, ...changes, }; return this.products[index]; } async delete(id) { const index = this.products.findIndex((item) => item.id === id); if (index === -1) { throw boom.notFound('Product not fount'); } this.products.splice(index, 1); return { id }; } } module.exports = ProductsServices;
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { TweetComponent } from './tweet.component'; describe('TweetComponent', () => { let component: TweetComponent; let fixture: ComponentFixture<TweetComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [HttpClientTestingModule], declarations: [TweetComponent] }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(TweetComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have addNewTweet function defined', () => { expect(component.addNewTweet).toBeDefined(); }); it('should have editTweetButton function defined', () => { expect(component.editTweetButton).toBeDefined(); component.editTweetButton(0); expect(component.editTweetFlag[0]).toBeTrue(); }); it('should have updateTweet function defined', () => { expect(component.updateTweet).toBeDefined(); }); it('should have cancelEditTweet function defined', () => { expect(component.cancelEditTweet).toBeDefined(); component.cancelEditTweet(0); expect(component.editTweetFlag[0]).toBeFalse(); }); it('should have deleteTweet function defined', () => { expect(component.deleteTweet).toBeDefined(); }); it('should have toggleTweetLike function defined', () => { expect(component.toggleTweetLike).toBeDefined(); }); it('should have toggleComments function defined', () => { expect(component.toggleComments).toBeDefined(); }); it('should have addComment function defined', () => { expect(component.addComment).toBeDefined(); }); it('should have clearCommentInput function defined', () => { expect(component.clearCommentInput).toBeDefined(); component.clearCommentInput(0); expect(component.newComment[0]).toBe(''); }); it('should have editComment function defined', () => { expect(component.editComment).toBeDefined(); }); it('should have editCommentConfirm function defined', () => { expect(component.editCommentConfirm).toBeDefined(); }); it('should have deleteComment function defined', () => { expect(component.deleteComment).toBeDefined(); }); it('should have toggleCommentLike function defined', () => { expect(component.toggleCommentLike).toBeDefined(); }); it('should have handleKeyboardEvent function defined', () => { expect(component.handleKeyboardEvent).toBeDefined(); }); it('should have userNameClickEvent to be defined', () => { expect(component.userNameClickEvent).toBeDefined(); }); });
Shader "Custom/Terrain" { Properties { _Color("Color", Color) = (1,1,1,1) _MainTex("Terrain Texture Array", 2DArray) = "white" {} _GridTex("Grid Texture", 2D) = "white" {} _Glossiness("Smoothness", Range(0,1)) = 0.5 _Metallic("Metallic", Range(0,1)) = 0.0 } SubShader { Tags { "RenderType" = "Opaque" } LOD 200 CGPROGRAM #pragma surface surf Standard fullforwardshadows vertex:vert #pragma target 3.5 // conditional shader compilation #pragma multi_compile _ GRID_ON #include "HexCellData.cginc" UNITY_DECLARE_TEX2DARRAY(_MainTex); sampler2D _GridTex; half _Glossiness; half _Metallic; fixed4 _Color; struct Input { float4 color : COLOR; float3 worldPos; float3 terrain; float3 visibility; // we're passing through three separate terrain indices }; // we add a float3 terrain field to the input structure and copy v.texcoord2.xyz to it void vert(inout appdata_full v, out Input data) { UNITY_INITIALIZE_OUTPUT(Input, data); // old way //data.terrain = v.texcoord2.xyz; float4 cell0 = GetCellData(v, 0); float4 cell1 = GetCellData(v, 1); float4 cell2 = GetCellData(v, 2); data.terrain.x = cell0.w; data.terrain.y = cell1.w; data.terrain.z = cell2.w; // A visibility of 0 means that a cell is currently not visible and 1 if the cell is visible. data.visibility.x = cell0.x; data.visibility.y = cell1.x; data.visibility.z = cell2.x; data.visibility = lerp(0.3, 1, data.visibility); // we don't want to have complete darkness } // We have to sample the texture array three times per fragment. // So let's create a convenient function to construct the texture coordinates, sample the array, // and modulate the sample with the splat map for one index. float4 GetTerrainColor(Input IN, int index) { float3 uvw = float3(IN.worldPos.xz * 0.02, IN.terrain[index]); float4 c = UNITY_SAMPLE_TEX2DARRAY(_MainTex, uvw); return c * (IN.color[index] * IN.visibility[index]); } void surf(Input IN, inout SurfaceOutputStandard o) { fixed4 c = GetTerrainColor(IN, 0) + GetTerrainColor(IN, 1) + GetTerrainColor(IN, 2); fixed4 grid = 1; #if defined(GRID_ON) // scale the grid so it fits the hex float2 gridUV = IN.worldPos.xz; gridUV.x *= 1 / (4 * 8.66025404); gridUV.y *= 1 / (2 * 15.0); grid = tex2D(_GridTex, gridUV); #endif o.Albedo = c.rgb * grid * _Color; o.Metallic = _Metallic; o.Smoothness = _Glossiness; o.Alpha = c.a; } ENDCG } FallBack "Diffuse" }
import Head from "next/head"; import Link from "next/link"; import type { NextPage } from "next"; import { useState, useEffect } from "react"; import { motion, MotionConfig } from "framer-motion"; import Nav from "~/components/nav"; import { Button } from "~/elements/button"; import CollectionCard from "~/components/collection-card"; const Home: NextPage = () => { return ( <> <Head> <title>Cathedra | Gundam Tracker</title> <meta name="description" content="Gundam collection and backlog tracker" /> <link rel="icon" href="/favicon.ico" /> </Head> <Nav /> <main className="flex min-h-screen flex-col items-center justify-center"> <HeroSection /> <AboutSection /> </main> </> ); }; const HeroSection = () => { const [activeIndex, setActiveIndex] = useState(0); useEffect(() => { const interval = setInterval( () => setActiveIndex((activeIndex) => activeIndex + 1 >= KITS.length ? 0 : activeIndex + 1 ), 5000 ); return () => clearInterval(interval); }, []); return ( <section className="w-full py-16"> <div className="container relative"> <div className="lg:flex lg:justify-between"> <div className="lg:w-1/2"> <motion.h1 initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.5 }} className="mb-8 text-5xl font-bold leading-tight text-white lg:text-7xl" > Track your Gundam Models with ease. </motion.h1> <motion.p initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.5, delay: 0.2 }} className="mb-8 text-xl text-gray-400 lg:text-2xl" > Say goodbye to forgetting which models you&apos;e purchased and which ones you&apos;ve built. With our tracking app, you can keep track of your collection with ease. </motion.p> <motion.div initial={{ opacity: 0, x: -20 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.5, delay: 0.4 }} > <Button asChild> <Link href="/collection">Get Started </Link> </Button> </motion.div> </div> <div className="relative lg:w-1/2"> <div className="ml-auto h-[419px] w-[350px]"> <MotionConfig transition={{ duration: 0.7, ease: [0.32, 0.72, 0, 1] }} > <div> <div className="mx-auto flex h-full max-w-7xl flex-col justify-center"> <div className="relative overflow-hidden"> <motion.div animate={{ x: `-${activeIndex * 100}%` }} className="flex" > {KITS.map((kit) => ( <div key={kit.id} className="w-[350px] flex-shrink-0"> <CollectionCard kit={kit} /> </div> ))} </motion.div> </div> </div> </div> </MotionConfig> </div> </div> </div> </div> </section> ); }; const AboutSection = () => { return ( <section className="w-full bg-muted py-16"> <div className="container"> <div className="flex flex-col lg:flex-row lg:justify-between"> <div className="lg:w-1/2 lg:pr-10"> <motion.h2 initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5, delay: 0.2 }} className="mb-4 text-4xl font-bold text-primary" > Keep Track of Your Gundam Model Collection </motion.h2> <motion.p initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5, delay: 0.4 }} className="mb-8 text-lg leading-relaxed" > Our Gundam model tracking website is the perfect tool for any Gundam model builder looking to organize their collection. With our simple and intuitive interface, you can keep track of which models you own, which ones you&apos;ve built, and much more. </motion.p> <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.5, delay: 0.6 }} > <Button asChild> <Link href="/collection">Get Started</Link> </Button> </motion.div> </div> <div className="mt-12 lg:mt-0 lg:w-1/2"> <CollectionDemo /> </div> </div> </div> </section> ); }; const CollectionDemo = () => { return ( <div className="grid grid-cols-1 gap-8 md:grid-cols-2"> <CollectionCard kit={{ id: "3", userId: "1", name: "RG ZGMF-X20A Strike Freedom Gundam", image: "/images/rg_strike_freedom_gundam.jpeg", grade: "RG", scale: "1/144", series: "SEED", status: "ORDERED", type: "MODEL", link: null, releaseDate: null, orderedDate: null, backlogOrder: null, createdAt: new Date("1/1/23"), updatedAt: new Date("1/1/23"), }} /> <CollectionCard kit={{ id: "3", userId: "1", name: "HG Sinanju Stein [Narrative Ver.]", image: "/images/hg_sinanju_stein.png", grade: "HF", scale: "1/144", series: "UC", status: "ASSEMBLED", type: "MODEL", link: null, releaseDate: null, orderedDate: null, backlogOrder: null, createdAt: new Date("1/1/23"), updatedAt: new Date("1/1/23"), }} /> </div> ); }; const KITS = [ { id: "1", userId: "1", name: "HG Gundam Aerial", image: "/images/hg_gundam_aerial.jpeg", grade: "HG", scale: "1/144", series: "G-Witch", status: "ASSEMBLED", type: "MODEL", link: null, releaseDate: null, orderedDate: null, backlogOrder: null, createdAt: new Date("1/1/23"), updatedAt: new Date("1/1/23"), }, { id: "2", userId: "1", name: "MG Sazabi Ver. Ka", image: "/images/mg_sazabi_verka.jpeg", grade: "MG", scale: "1/100", series: "UC", status: "OWNED", type: "MODEL", link: null, releaseDate: null, orderedDate: null, backlogOrder: null, createdAt: new Date("1/1/23"), updatedAt: new Date("1/1/23"), }, { id: "3", userId: "1", name: "PG Unicorm Gundam", image: "/images/pg_unicorn_gundam.jpeg", grade: "PG", scale: "1/60", series: "UC", status: "WISHLIST", type: "MODEL", link: null, releaseDate: null, orderedDate: null, backlogOrder: null, createdAt: new Date("1/1/23"), updatedAt: new Date("1/1/23"), }, ] as const; export default Home;
package com.example.oppawtunity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QuerySnapshot; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; public class adminViewUserPets extends AppCompatActivity { Button goBack, addPet, signOut; TextView name, phone; ListView viewPets; ArrayList<Pets> petList; FirebaseFirestore db = FirebaseFirestore.getInstance(); DocumentReference docRef, getAdmin; FirebaseAuth mAuth; Boolean admin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admin_view_user_pets); String fName, uPhone, userName; goBack = findViewById(R.id.goBackFromViewUserPet); viewPets = findViewById(R.id.viewUserPetList); name = findViewById(R.id.viewPetUser); phone = findViewById(R.id.viewUserPetPhone); addPet = findViewById(R.id.adminAddPet); signOut = findViewById(R.id.signOutUser); Bundle extras = getIntent().getExtras(); fName = extras.getString("uName"); uPhone = extras.getString("uPhone"); userName = extras.getString("uUser"); name.setText(fName); phone.setText(uPhone); petList = new ArrayList<Pets>(); db = FirebaseFirestore.getInstance(); loadDataInListview(userName); mAuth = FirebaseAuth.getInstance(); FirebaseUser currentUser = mAuth.getCurrentUser(); getAdmin = db.collection("users").document(currentUser.getUid()); getAdmin.get() .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() { @Override public void onSuccess(DocumentSnapshot documentSnapshot) { admin = documentSnapshot.getBoolean("isAdmin"); if(!admin){ addPet.setVisibility(View.GONE); goBack.setVisibility(View.GONE); } else { signOut.setVisibility(View.GONE); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { } }); addPet.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(adminViewUserPets.this, adminAddPet.class); i.putExtra("uName",fName); i.putExtra("uPhone",uPhone); i.putExtra("uUser",userName); startActivity(i); finish(); } }); signOut.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(adminViewUserPets.this, "User signed out", Toast.LENGTH_SHORT).show(); mAuth.signOut(); startActivity(new Intent(adminViewUserPets.this , MainActivity.class)); finish(); } }); goBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(adminViewUserPets.this, admin_viewUsers.class)); finish(); } }); } private void loadDataInListview(String userName) { db.collection("users").document(userName).collection("pets").get() .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() { @Override public void onSuccess(QuerySnapshot queryDocumentSnapshots) { if (!queryDocumentSnapshots.isEmpty()) { List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments(); for (DocumentSnapshot d : list) { Pets pet = new Pets(); pet.setName(d.getString("name")); pet.setWeight(d.getString("weight")); pet.setAge(d.getString("age")); pet.setImgURL(d.getString("imgURL")); pet.setBreed(d.getString("breed")); pet.setuPhone(d.getString("uPhone")); pet.setuName(d.getString("uName")); pet.setuUser(userName); pet.setPetID(d.getId().toString()); petList.add(pet); } PetAdapter adapter = new PetAdapter(adminViewUserPets.this, petList); viewPets.setAdapter(adapter); } else { Toast.makeText(adminViewUserPets.this, "No data found in Database", Toast.LENGTH_SHORT).show(); } } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(adminViewUserPets.this, "User has no pet record", Toast.LENGTH_SHORT).show(); } }); } }
import React from 'react'; import { connect, useDispatch, useSelector } from "react-redux"; import { filterCards, orderCards } from '../../redux/actions'; import Card from '../Card/Card'; import styles from "./Favorites.module.css"; const Favorites = () => { const favorites = useSelector(state => state.filterFavorites); const dispatch = useDispatch(); const order = (event) => { dispatch(orderCards(event.target.value)) } const filter = (event) => { dispatch(filterCards(event.target.value)) } return ( <> <div> <select name="" onChange={order}> <option value="Ascendente">Ascendente</option> <option value="Descendente">Descendente</option> </select> <select name="" onChange={filter}> <option value="All">All</option> <option value="Male">Male</option> <option value="Female">Female</option> <option value="Genderless">Genderless</option> <option value="unknown">unknown</option> </select> </div> <div className={styles.contenedor}> {favorites.map((fav) => { return <Card key={fav.id} id={fav.id} name={fav.name} species={fav.species} gender={fav.gender} image={fav.image} />; })} </div> </> ) } // const mapStateToProps = (state) => { // return { // myFavorites: state.myFavorites // } // } //export default connect(mapStateToProps, null)(Favorites); export default Favorites;
import React, { useContext, useEffect, useState } from "react"; import { Button, Card, Container, FormControl, InputGroup, Modal, } from "react-bootstrap"; import { AuthContext } from "../../services/auth/context/AuthContext"; import { getOrdenes, getOrdenesUsuario, removeOrden, } from "../../services/ordenes/ordenesService"; import VerElementosOrden from "./VerElementosOrden"; export const HistorialOrdenes = () => { const { userInfo } = useContext(AuthContext); const [loading, setLoading] = useState(false); const [ordenes, setOrdenes] = useState([]); const [refreshing, setRefreshing] = useState(false); const [showModal, setShowModal] = useState(false); const [renderComponent, setRenderComponent] = useState(null); const openClose = () => setShowModal((prevState) => !prevState); const fetchOrdenes = async () => { setLoading(true); if (userInfo.user.usuario.id_rol === 1) { const ordenes = await getOrdenes(); setOrdenes(ordenes); } else { const ordenes = await getOrdenesUsuario(userInfo.user.usuario.id_usuario); setOrdenes(ordenes); } setLoading(false); }; useEffect(() => { fetchOrdenes(); }, []); const [searchText, setSearchText] = useState(""); const handleSearchTextChange = (text) => { setSearchText(text); }; const filteredOrdenes = ordenes.filter((ordenes) => ordenes.fecha_creacion.toLowerCase().includes(searchText.toLowerCase()) ); const onRefresh = React.useCallback(() => { setRefreshing(true); fetchOrdenes().then(() => setRefreshing(false)); }, []); return ( <Container style={styles.container}> <div style={styles.searchBarContainer}> <InputGroup> <FormControl placeholder="Buscar por fecha..." onChange={(e) => handleSearchTextChange(e.target.value)} value={searchText} /> </InputGroup> </div> {filteredOrdenes.length > 0 ? ( <div className="d-flex flex-wrap flex-row justify-content-center mt-2"> {filteredOrdenes.map((item) => ( <Card style={styles.ordenesContainer} key={item.id_orden} className="m-2" > <Card.Body> <div style={styles.ordenesInfo}> <div> <p style={styles.ordenesName}> Fecha creado: {item.fecha_creacion} </p> </div> <div> {item.estatus === true ? ( <p style={styles.ordenesText}>Activa</p> ) : ( <p style={styles.ordenesText}>Pagado</p> )} </div> </div> <div style={styles.multipleButtons}> <Button className="m-2" variant="primary" onClick={() => { setRenderComponent( <VerElementosOrden orden={item} /> ); openClose(); }} > Ver elementos de la orden </Button> {item.estatus === true ? ( <Button variant={item.estatus === true ? "danger" : "success"} onClick={() => { setRenderComponent( <div> <p>¿Estás seguro que deseas pagar esta orden?</p> <div style={styles.multipleButtons}> <Button variant="secondary" onClick={() => openClose()} > Cancelar </Button> <Button className="m-2" variant="success" onClick={async () => { await removeOrden(item.id_orden); onRefresh(); openClose(); }} > Pagar </Button> </div> </div> ); openClose(); }} > Pagar </Button> ) : null} </div> </Card.Body> </Card> ))} </div> ) : ( <div style={styles.body}> <p style={styles.noOrdenesText}>No hay ordenes para mostrar</p> </div> )} <Modal show={showModal} onHide={openClose}> <Modal.Body>{renderComponent}</Modal.Body> </Modal> </Container> ); }; const styles = { container: { flex: 1, }, searchBarContainer: { backgroundColor: "#fff", flexDirection: "column", justifyContent: "space-between", padding: 10, borderBottom: "1px solid #ccc", }, ordenesContainer: { padding: 10, marginBottom: "3%", borderBottom: "1px solid #ccc", borderRadius: 20, }, ordenesName: { fontSize: 16, }, ordenesInfo: { flexDirection: "column", justifyContent: "space-between", alignItems: "flex-start", }, ordenesText: { fontSize: 14, color: "#000", }, multipleButtons: { flexDirection: "column", justifyContent: "space-evenly", marginTop: 15, }, noOrdenesText: { textAlign: "center", fontSize: 20, fontWeight: "bold", marginBottom: 16, color: "#000", }, body: { marginTop: 20, padding: 24, }, }; export default HistorialOrdenes;
import React, { useCallback, useMemo, useState } from 'react'; import { isDefined } from '@togglecorp/fujs'; import { Modal, Button, useAlert, TextInput, NumberInput, } from '@the-deep/deep-ui'; import { ObjectSchema, PartialForm, useForm, getErrorObject, requiredCondition, requiredStringCondition, createSubmitHandler, removeNull, internal, } from '@togglecorp/toggle-form'; import { gql, useMutation } from '@apollo/client'; import { InstitutionCreateInputType, UpdateInstitutionMutation, UpdateInstitutionMutationVariables, } from '#generated/types'; import NonFieldError from '#components/NonFieldError'; import ErrorMessage from '#components/ErrorMessage'; import { transformToFormError, ObjectError, } from '#base/utils/errorTransform'; import LocationInput, { MunicipalityOption } from '#components/LocationInput'; import { InstitutionItemType } from '../index'; import styles from './styles.css'; const UPDATE_INSTITUTION = gql` mutation UpdateInstitution($data: InstitutionCreateInputType!, $id: ID!) { updateInstitution(id: $id, data: $data) { errors ok result { id name panNumber vatNumber wardNumber localAddress municipality { id name district { id name province { id name } } } } } } `; type FormType = UpdateInstitutionMutationVariables['data']; type PartialFormType = PartialForm<FormType>; type FormSchema = ObjectSchema<PartialFormType>; type FormSchemaFields = ReturnType<FormSchema['fields']>; const schema: FormSchema = { fields: (): FormSchemaFields => ({ name: [requiredStringCondition], municipality: [requiredStringCondition], localAddress: [], panNumber: [], wardNumber: [requiredCondition], }), }; interface Props { institution: NonNullable<InstitutionItemType['institution']>; onModalClose: () => void; } function UpdateInstitutionModal(props: Props) { const { institution, onModalClose, } = props; const [ municipalityOptions, setMunicipalityOptions, ] = useState<MunicipalityOption[] | undefined | null>([institution.municipality]); const initialValue: PartialFormType = useMemo(() => (institution ? ({ name: institution.name, municipality: institution.municipality.id, localAddress: institution.localAddress ?? '', panNumber: institution.panNumber, wardNumber: institution.wardNumber, }) : {}), [institution]); const { pristine, value, error: riskyError, setFieldValue, validate, setError, } = useForm(schema, initialValue); const alert = useAlert(); const error = getErrorObject(riskyError); const [ updateInstitution, { loading: updateInstitutionPending }, ] = useMutation<UpdateInstitutionMutation, UpdateInstitutionMutationVariables>( UPDATE_INSTITUTION, { onCompleted: (response) => { if (!response.updateInstitution) { return; } const { ok, errors, } = response.updateInstitution; if (ok) { onModalClose(); alert.show( 'Institution updated successfully!', { variant: 'success' }, ); } else if (errors) { const formErrorFromServer = transformToFormError( removeNull(errors) as ObjectError[], ); setError(formErrorFromServer); alert.show( <ErrorMessage header="Failed to update institution." description={ isDefined(formErrorFromServer) ? formErrorFromServer[internal] : undefined } />, { variant: 'error' }, ); } }, onError: (errors) => { alert.show( <ErrorMessage header="Failed to update institution." description={errors.message} />, { variant: 'error' }, ); }, }, ); const handleSubmit = useCallback(() => { const submit = createSubmitHandler( validate, setError, (val) => { updateInstitution({ variables: { data: val as InstitutionCreateInputType, id: institution.id }, }); }, ); submit(); }, [setError, validate, updateInstitution, institution.id]); return ( <Modal className={styles.updateInstitutionModal} heading="Edit Institution" headingSize="small" onCloseButtonClick={onModalClose} headingDescription={institution.name} size="small" freeHeight bodyClassName={styles.content} footerActions={( <> <Button name={undefined} onClick={onModalClose} variant="secondary" > Cancel </Button> <Button name={undefined} variant="primary" onClick={handleSubmit} disabled={pristine || updateInstitutionPending} > Save </Button> </> )} > <NonFieldError error={error} /> <TextInput name="name" label="Institution Name" value={value?.name} error={error?.name} onChange={setFieldValue} disabled={updateInstitutionPending} /> <LocationInput name="municipality" label="Municipality" error={error?.municipality} value={value?.municipality} onChange={setFieldValue} options={municipalityOptions} onOptionsChange={setMunicipalityOptions} disabled={updateInstitutionPending} /> <NumberInput name="wardNumber" label="Ward Number" value={value?.wardNumber} error={error?.wardNumber} onChange={setFieldValue} disabled={updateInstitutionPending} min={1} max={99} /> <TextInput name="localAddress" label="Local Address" value={value?.localAddress} error={error?.localAddress} onChange={setFieldValue} disabled={updateInstitutionPending} /> <TextInput name="panNumber" label="PAN Number" value={value?.panNumber} error={error?.panNumber} onChange={setFieldValue} disabled={updateInstitutionPending} /> </Modal> ); } export default UpdateInstitutionModal;
import 'package:equatable/equatable.dart'; import '../../../../const/app_enums.dart'; class Travel extends Equatable { final String? travelTitle; final String? travelDescription; final String? travelAddress; final String? travelPrice; final String? travelPhone1; final String? travelPhone2; final String? travelPhone3; final String? travelFacebook; final String? travelWhatsApp; final String? travelLocation; final String? travelCategory; final String? travelRating; final DateTime? travelCreated; final DateTime? lastUpdate; final String? travelId; final List<String>? travelImages; const Travel({ this.travelTitle, this.travelDescription, this.travelAddress, this.travelPrice, this.travelPhone1, this.travelPhone2, this.travelPhone3, this.travelFacebook, this.travelWhatsApp, this.travelLocation, this.travelCategory, this.travelRating, this.travelCreated, this.lastUpdate, this.travelId, this.travelImages, }); @override List<Object?> get props => [ travelTitle, travelDescription, travelAddress, travelPrice, travelPhone1, travelPhone2, travelPhone3, travelFacebook, travelWhatsApp, travelLocation, travelCategory, travelRating, travelCreated, lastUpdate, travelId, travelImages, ]; }
;;; core-ui.el -*- lexical-binding: t; -*- ;; ;;; Variables (defvar doom-theme nil "A symbol representing the Emacs theme to load at startup. Set to `nil' to load no theme at all. This variable is changed by `load-theme'.") (defvar doom-font nil "The default font to use. Must be a `font-spec', a font object, an XFT font string, or an XLFD string. This affects the `default' and `fixed-pitch' faces. Examples: (setq doom-font (font-spec :family \"Fira Mono\" :size 12)) (setq doom-font \"Terminus (TTF):pixelsize=12:antialias=off\") (setq doom-font \"Fira Code-14\")") (defvar doom-variable-pitch-font nil "The default font to use for variable-pitch text. Must be a `font-spec', a font object, an XFT font string, or an XLFD string. See `doom-font' for examples. An omitted font size means to inherit `doom-font''s size.") (defvar doom-serif-font nil "The default font to use for the `fixed-pitch-serif' face. Must be a `font-spec', a font object, an XFT font string, or an XLFD string. See `doom-font' for examples. An omitted font size means to inherit `doom-font''s size.") (defvar doom-unicode-font nil "Fallback font for Unicode glyphs. Must be a `font-spec', a font object, an XFT font string, or an XLFD string. See `doom-font' for examples. The defaults on macOS and Linux are Apple Color Emoji and Symbola, respectively. WARNING: if you specify a size for this font it will hard-lock any usage of this font to that size. It's rarely a good idea to do so!") (defvar doom-emoji-fallback-font-families '("Apple Color Emoji" "Segoe UI Emoji" "Noto Color Emoji" "Noto Emoji") "A list of fallback font families to use for emojis.") (defvar doom-symbol-fallback-font-families '("Segoe UI Symbol" "Apple Symbols") "A list of fallback font families for general symbol glyphs.") ;; ;;; Custom hooks (defvar doom-init-ui-hook nil "List of hooks to run when the UI has been initialized.") (defvar doom-load-theme-hook nil "Hook run after the theme is loaded with `load-theme' or reloaded with `doom/reload-theme'.") (defvar doom-switch-buffer-hook nil "A list of hooks run after changing the current buffer.") (defvar doom-switch-window-hook nil "A list of hooks run after changing the focused windows.") (defvar doom-switch-frame-hook nil "A list of hooks run after changing the focused frame.") (defun doom-run-switch-buffer-hooks-h (&optional _) (let ((gc-cons-threshold most-positive-fixnum) (inhibit-redisplay t)) (run-hooks 'doom-switch-buffer-hook))) (defvar doom--last-frame nil) (defun doom-run-switch-window-or-frame-hooks-h (&optional _) (let ((gc-cons-threshold most-positive-fixnum) (inhibit-redisplay t)) (unless (equal (old-selected-frame) (selected-frame)) (run-hooks 'doom-switch-frame-hook)) (unless (or (minibufferp) (equal (old-selected-window) (minibuffer-window))) (run-hooks 'doom-switch-window-hook)))) (defun doom-protect-fallback-buffer-h () "Don't kill the scratch buffer. Meant for `kill-buffer-query-functions'." (not (eq (current-buffer) (doom-fallback-buffer)))) (defun doom-highlight-non-default-indentation-h () "Highlight whitespace at odds with `indent-tabs-mode'. That is, highlight tabs if `indent-tabs-mode' is `nil', and highlight spaces at the beginnings of lines if `indent-tabs-mode' is `t'. The purpose is to make incorrect indentation in the current buffer obvious to you. Does nothing if `whitespace-mode' or `global-whitespace-mode' is already active or if the current buffer is read-only or not file-visiting." (unless (or (eq major-mode 'fundamental-mode) (bound-and-true-p global-whitespace-mode) (null buffer-file-name)) (require 'whitespace) (set (make-local-variable 'whitespace-style) (cl-union (if indent-tabs-mode '(indentation) '(tabs tab-mark)) (when whitespace-mode (remq 'face whitespace-active-style)))) (cl-pushnew 'face whitespace-style) ; must be first (whitespace-mode +1))) ;; ;;; General UX ;; A simple confirmation prompt when killing Emacs. But only prompt when there ;; are real buffers open. (setq confirm-kill-emacs #'doom-quit-p) ;; Prompt for confirmation when deleting a non-empty frame; a last line of ;; defense against accidental loss of work. (global-set-key [remap delete-frame] #'doom/delete-frame-with-prompt) ;; Don't prompt for confirmation when we create a new file or buffer (assume the ;; user knows what they're doing). (setq confirm-nonexistent-file-or-buffer nil) (setq uniquify-buffer-name-style 'forward ;; no beeping or blinking please ring-bell-function #'ignore visible-bell nil) ;; middle-click paste at point, not at click (setq mouse-yank-at-point t) ;; Larger column width for function name in profiler reports (after! profiler (setf (caar profiler-report-cpu-line-format) 80 (caar profiler-report-memory-line-format) 80)) ;; ;;; Scrolling (setq hscroll-margin 2 hscroll-step 1 ;; Emacs spends too much effort recentering the screen if you scroll the ;; cursor more than N lines past window edges (where N is the settings of ;; `scroll-conservatively'). This is especially slow in larger files ;; during large-scale scrolling commands. If kept over 100, the window is ;; never automatically recentered. scroll-conservatively 101 scroll-margin 0 scroll-preserve-screen-position t ;; Reduce cursor lag by a tiny bit by not auto-adjusting `window-vscroll' ;; for tall lines. auto-window-vscroll nil ;; mouse mouse-wheel-scroll-amount '(2 ((shift) . hscroll)) mouse-wheel-scroll-amount-horizontal 2) ;; ;;; Cursor ;; The blinking cursor is distracting, but also interferes with cursor settings ;; in some minor modes that try to change it buffer-locally (like treemacs) and ;; can cause freezing for folks (esp on macOS) with customized & color cursors. (blink-cursor-mode -1) ;; Don't blink the paren matching the one at point, it's too distracting. (setq blink-matching-paren nil) ;; Don't stretch the cursor to fit wide characters, it is disorienting, ;; especially for tabs. (setq x-stretch-cursor nil) ;; ;;; Buffers ;; Make `next-buffer', `other-buffer', etc. ignore unreal buffers. (push '(buffer-predicate . doom-buffer-frame-predicate) default-frame-alist) (defadvice! doom--switch-to-fallback-buffer-maybe-a (&rest _) "Switch to `doom-fallback-buffer' if on last real buffer. Advice for `kill-current-buffer'. If in a dedicated window, delete it. If there are no real buffers left OR if all remaining buffers are visible in other windows, switch to `doom-fallback-buffer'. Otherwise, delegate to original `kill-current-buffer'." :before-until #'kill-current-buffer (let ((buf (current-buffer))) (cond ((window-dedicated-p) (delete-window) t) ((eq buf (doom-fallback-buffer)) (message "Can't kill the fallback buffer.") t) ((doom-real-buffer-p buf) (let ((visible-p (delq (selected-window) (get-buffer-window-list buf nil t)))) (unless visible-p (when (and (buffer-modified-p buf) (not (y-or-n-p (format "Buffer %s is modified; kill anyway?" buf)))) (user-error "Aborted"))) (let ((inhibit-redisplay t) buffer-list-update-hook) (when (or ;; if there aren't more real buffers than visible buffers, ;; then there are no real, non-visible buffers left. (not (cl-set-difference (doom-real-buffer-list) (doom-visible-buffers))) ;; if we end up back where we start (or previous-buffer ;; returns nil), we have nowhere left to go (memq (switch-to-prev-buffer nil t) (list buf 'nil))) (switch-to-buffer (doom-fallback-buffer))) (unless visible-p (with-current-buffer buf (restore-buffer-modified-p nil)) (kill-buffer buf))) (run-hooks 'buffer-list-update-hook) t))))) ;; ;;; Fringes ;; Reduce the clutter in the fringes; we'd like to reserve that space for more ;; useful information, like git-gutter and flycheck. (setq indicate-buffer-boundaries nil indicate-empty-lines nil) ;; ;;; Windows/frames ;; A simple frame title (setq frame-title-format '("%b – Doom Emacs") icon-title-format frame-title-format) ;; Don't resize the frames in steps; it looks weird, especially in tiling window ;; managers, where it can leave unseemly gaps. (setq frame-resize-pixelwise t) ;; But do not resize windows pixelwise, this can cause crashes in some cases ;; when resizing too many windows at once or rapidly. (setq window-resize-pixelwise nil) ;; Disable tool, menu, and scrollbars. Doom is designed to be keyboard-centric, ;; so these are just clutter (the scrollbar also impacts performance). Whats ;; more, the menu bar exposes functionality that Doom doesn't endorse. ;; ;; I am intentionally not calling `menu-bar-mode', `tool-bar-mode', and ;; `scroll-bar-mode' because they do extra and unnecessary work that can be more ;; concisely and efficiently expressed with these six lines: (push '(menu-bar-lines . 0) default-frame-alist) (push '(tool-bar-lines . 0) default-frame-alist) (push '(vertical-scroll-bars) default-frame-alist) ;; And set these to nil so users don't have to toggle the modes twice to ;; reactivate them. (setq menu-bar-mode nil tool-bar-mode nil scroll-bar-mode nil) ;; The native border "consumes" a pixel of the fringe on righter-most splits, ;; `window-divider' does not. Available since Emacs 25.1. (setq window-divider-default-places t window-divider-default-bottom-width 1 window-divider-default-right-width 1) (add-hook 'doom-init-ui-hook #'window-divider-mode) ;; GUIs are inconsistent across systems and themes (and will rarely match our ;; active Emacs theme). They impose inconsistent shortcut key paradigms too. ;; It's best to avoid them altogether and have Emacs handle the prompting. (setq use-dialog-box nil) (when (bound-and-true-p tooltip-mode) (tooltip-mode -1)) (when IS-LINUX (setq x-gtk-use-system-tooltips nil)) ;; Favor vertical splits over horizontal ones. Monitors are trending toward ;; wide, rather than tall. (setq split-width-threshold 160 split-height-threshold nil) ;; ;;; Minibuffer ;; Allow for minibuffer-ception. Sometimes we need another minibuffer command ;; while we're in the minibuffer. (setq enable-recursive-minibuffers t) ;; Show current key-sequence in minibuffer ala 'set showcmd' in vim. Any ;; feedback after typing is better UX than no feedback at all. (setq echo-keystrokes 0.02) ;; Expand the minibuffer to fit multi-line text displayed in the echo-area. This ;; doesn't look too great with direnv, however... (setq resize-mini-windows 'grow-only) ;; Typing yes/no is obnoxious when y/n will do (if EMACS28+ (setq use-short-answers t) ;; DEPRECATED Remove when we drop 27.x support (advice-add #'yes-or-no-p :override #'y-or-n-p)) ;; Try to keep the cursor out of the read-only portions of the minibuffer. (setq minibuffer-prompt-properties '(read-only t intangible t cursor-intangible t face minibuffer-prompt)) (add-hook 'minibuffer-setup-hook #'cursor-intangible-mode) ;; ;;; Built-in packages ;;;###package ansi-color (setq ansi-color-for-comint-mode t) (after! comint (setq comint-prompt-read-only t comint-buffer-maximum-size 2048)) ; double the default (after! compile (setq compilation-always-kill t ; kill compilation process before starting another compilation-ask-about-save nil ; save all buffers on `compile' compilation-scroll-output 'first-error) ;; Handle ansi codes in compilation buffers (add-hook 'compilation-filter-hook #'ansi-color-compilation-filter) ;; Automatically truncate compilation buffers so they don't accumulate too ;; much data and bog down the rest of Emacs. (autoload 'comint-truncate-buffer "comint" nil t) (add-hook 'compilation-filter-hook #'comint-truncate-buffer)) (after! ediff (setq ediff-diff-options "-w" ; turn off whitespace checking ediff-split-window-function #'split-window-horizontally ediff-window-setup-function #'ediff-setup-windows-plain) (defvar doom--ediff-saved-wconf nil) ;; Restore window config after quitting ediff (add-hook! 'ediff-before-setup-hook (defun doom-ediff-save-wconf-h () (setq doom--ediff-saved-wconf (current-window-configuration)))) (add-hook! '(ediff-quit-hook ediff-suspend-hook) :append (defun doom-ediff-restore-wconf-h () (when (window-configuration-p doom--ediff-saved-wconf) (set-window-configuration doom--ediff-saved-wconf))))) (use-package! hl-line ;; Highlights the current line :hook (doom-first-buffer . global-hl-line-mode) :init (defvar global-hl-line-modes '(prog-mode text-mode conf-mode special-mode org-agenda-mode dired-mode) "What modes to enable `hl-line-mode' in.") :config ;; HACK I reimplement `global-hl-line-mode' so we can white/blacklist modes in ;; `global-hl-line-modes' _and_ so we can use `global-hl-line-mode', ;; which users expect to control hl-line in Emacs. (define-globalized-minor-mode global-hl-line-mode hl-line-mode (lambda () (and (cond (hl-line-mode nil) ((null global-hl-line-modes) nil) ((eq global-hl-line-modes t)) ((eq (car global-hl-line-modes) 'not) (not (derived-mode-p global-hl-line-modes))) ((apply #'derived-mode-p global-hl-line-modes))) (hl-line-mode +1)))) ;; Temporarily disable `hl-line' when selection is active, since it doesn't ;; serve much purpose when the selection is so much more visible. (defvar doom--hl-line-mode nil) (add-hook! 'hl-line-mode-hook (defun doom-truly-disable-hl-line-h () (unless hl-line-mode (setq-local doom--hl-line-mode nil)))) (add-hook! '(evil-visual-state-entry-hook activate-mark-hook) (defun doom-disable-hl-line-h () (when hl-line-mode (hl-line-mode -1) (setq-local doom--hl-line-mode t)))) (add-hook! '(evil-visual-state-exit-hook deactivate-mark-hook) (defun doom-enable-hl-line-maybe-h () (when doom--hl-line-mode (hl-line-mode +1))))) (use-package! winner ;; undo/redo changes to Emacs' window layout :preface (defvar winner-dont-bind-my-keys t) ; I'll bind keys myself :hook (doom-first-buffer . winner-mode) :config (appendq! winner-boring-buffers '("*Compile-Log*" "*inferior-lisp*" "*Fuzzy Completions*" "*Apropos*" "*Help*" "*cvs*" "*Buffer List*" "*Ibuffer*" "*esh command on file*"))) (use-package! paren ;; highlight matching delimiters :hook (doom-first-buffer . show-paren-mode) :config (setq show-paren-delay 0.1 show-paren-highlight-openparen t show-paren-when-point-inside-paren t show-paren-when-point-in-periphery t)) ;;;###package whitespace (setq whitespace-line-column nil whitespace-style '(face indentation tabs tab-mark spaces space-mark newline newline-mark trailing lines-tail) whitespace-display-mappings '((tab-mark ?\t [?› ?\t]) (newline-mark ?\n [?¬ ?\n]) (space-mark ?\ [?·] [?.]))) ;; ;;; Third party packages (use-package! all-the-icons :commands (all-the-icons-octicon all-the-icons-faicon all-the-icons-fileicon all-the-icons-wicon all-the-icons-material all-the-icons-alltheicon) :preface (add-hook! 'after-setting-font-hook (defun doom-init-all-the-icons-fonts-h () (when (fboundp 'set-fontset-font) (dolist (font (list "Weather Icons" "github-octicons" "FontAwesome" "all-the-icons" "file-icons" "Material Icons")) (set-fontset-font t 'unicode font nil 'append))))) :config (cond ((daemonp) (defadvice! doom--disable-all-the-icons-in-tty-a (fn &rest args) "Return a blank string in tty Emacs, which doesn't support multiple fonts." :around '(all-the-icons-octicon all-the-icons-material all-the-icons-faicon all-the-icons-fileicon all-the-icons-wicon all-the-icons-alltheicon) (if (or (not after-init-time) (display-multi-font-p)) (apply fn args) ""))) ((not (display-graphic-p)) (defadvice! doom--disable-all-the-icons-in-tty-a (&rest _) "Return a blank string for tty users." :override '(all-the-icons-octicon all-the-icons-material all-the-icons-faicon all-the-icons-fileicon all-the-icons-wicon all-the-icons-alltheicon) "")))) ;; Hide the mode line in completion popups and MAN pages because they serve ;; little purpose there, and is better hidden. ;;;###package hide-mode-line-mode (add-hook! '(completion-list-mode-hook Man-mode-hook) #'hide-mode-line-mode) ;; Many major modes do no highlighting of number literals, so we do it for them (use-package! highlight-numbers :hook ((prog-mode conf-mode) . highlight-numbers-mode) :config (setq highlight-numbers-generic-regexp "\\_<[[:digit:]]+\\(?:\\.[0-9]*\\)?\\_>")) ;;;###package image (setq image-animate-loop t) ;;;###package rainbow-delimiters ;; Helps us distinguish stacked delimiter pairs, especially in parentheses-drunk ;; languages like Lisp. I reduce it from it's default of 9 to reduce the ;; complexity of the font-lock keyword and hopefully buy us a few ms of ;; performance. (setq rainbow-delimiters-max-face-count 4) ;; ;;; Line numbers ;; Explicitly define a width to reduce the cost of on-the-fly computation (setq-default display-line-numbers-width 3) ;; Show absolute line numbers for narrowed regions to make it easier to tell the ;; buffer is narrowed, and where you are, exactly. (setq-default display-line-numbers-widen t) ;; Enable line numbers in most text-editing modes. We avoid ;; `global-display-line-numbers-mode' because there are many special and ;; temporary modes where we don't need/want them. (add-hook! '(prog-mode-hook text-mode-hook conf-mode-hook) #'display-line-numbers-mode) ;; Fix #2742: cursor is off by 4 characters in `artist-mode' ;; REVIEW Reported upstream https://debbugs.gnu.org/cgi/bugreport.cgi?bug=43811 ;; DEPRECATED Fixed in Emacs 28; remove when we drop 27 support (unless EMACS28+ (add-hook 'artist-mode-hook #'doom-disable-line-numbers-h)) ;; ;;; Theme & font ;; User themes should live in $DOOMDIR/themes, not ~/.emacs.d (setq custom-theme-directory (concat doom-private-dir "themes/")) ;; Third party themes add themselves to `custom-theme-load-path', but the themes ;; living in $DOOMDIR/themes should always have priority. (setq custom-theme-load-path (cons 'custom-theme-directory (delq 'custom-theme-directory custom-theme-load-path))) (defun doom--make-font-specs (face font &optional base-specs) (let* ((base-specs (cadr (assq 'user (get face 'theme-face)))) (base-specs (or base-specs '((t nil)))) (attrs '(:family :foundry :slant :weight :height :width)) (new-specs nil)) (dolist (spec base-specs) ;; Each SPEC has the form (DISPLAY ATTRIBUTE-PLIST) (let ((display (car spec)) (plist (copy-tree (nth 1 spec)))) ;; Alter only DISPLAY conditions matching this frame. (when (or (memq display '(t default)) (face-spec-set-match-display display this-frame)) (dolist (attr attrs) (setq plist (plist-put plist attr (face-attribute face attr))))) (push (list display plist) new-specs))) (nreverse new-specs))) (defun doom-init-fonts-h (&optional reload) "Loads `doom-font'." (dolist (map `((default . ,doom-font) (fixed-pitch . ,doom-font) (fixed-pitch-serif . ,doom-serif-font) (variable-pitch . ,doom-variable-pitch-font))) (when-let* ((face (car map)) (font (cdr map))) (dolist (frame (frame-list)) (when (display-multi-font-p frame) (set-face-attribute face frame :width 'normal :weight 'normal :slant 'normal :font font))) (let ((new-specs (doom--make-font-specs face font))) ;; Don't save to `customized-face' so it's omitted from `custom-file' ;;(put face 'customized-face new-specs) (custom-push-theme 'theme-face face 'user 'set new-specs) (put face 'face-modified nil)))) (when (fboundp 'set-fontset-font) (let ((fn (doom-rpartial #'member (font-family-list)))) (when-let (font (cl-find-if fn doom-symbol-fallback-font-families)) (set-fontset-font t 'symbol font)) (when-let (font (cl-find-if fn doom-emoji-fallback-font-families)) (set-fontset-font t 'unicode font)) (when doom-unicode-font (set-fontset-font t 'unicode doom-unicode-font)))) ;; Users should inject their own font logic in `after-setting-font-hook' (run-hooks 'after-setting-font-hook)) (defun doom-init-theme-h (&rest _) "Load the theme specified by `doom-theme' in FRAME." (when (and doom-theme (not (custom-theme-enabled-p doom-theme))) (load-theme doom-theme t))) (defadvice! doom--load-theme-a (fn theme &optional no-confirm no-enable) "Record `doom-theme', disable old themes, and trigger `doom-load-theme-hook'." :around #'load-theme ;; Run `load-theme' from an estranged buffer, where we can ensure that ;; buffer-local face remaps (by `mixed-pitch-mode', for instance) won't ;; interfere with recalculating faces in new themes. (with-temp-buffer (let ((last-themes (copy-sequence custom-enabled-themes))) ;; Disable previous themes so there are no conflicts. If you truly want ;; multiple themes enabled, then use `enable-theme' instead. (mapc #'disable-theme custom-enabled-themes) (prog1 (funcall fn theme no-confirm no-enable) (when (and (not no-enable) (custom-theme-enabled-p theme)) (setq doom-theme theme) (put 'doom-theme 'previous-themes (or last-themes 'none)) ;; DEPRECATED Hook into `enable-theme-functions' when we target 29 (doom-run-hooks 'doom-load-theme-hook)))))) ;; ;;; Bootstrap (defun doom-init-ui-h (&optional _) "Initialize Doom's user interface by applying all its advice and hooks. These should be done as late as possible, as to avoid/minimize prematurely triggering hooks during startup." (doom-run-hooks 'doom-init-ui-hook) (add-hook 'kill-buffer-query-functions #'doom-protect-fallback-buffer-h) (add-hook 'after-change-major-mode-hook #'doom-highlight-non-default-indentation-h 'append) ;; Initialize `doom-switch-window-hook' and `doom-switch-frame-hook' (add-hook 'window-selection-change-functions #'doom-run-switch-window-or-frame-hooks-h) ;; Initialize `doom-switch-buffer-hook' (add-hook 'window-buffer-change-functions #'doom-run-switch-buffer-hooks-h) ;; `window-buffer-change-functions' doesn't trigger for files visited via the server. (add-hook 'server-visit-hook #'doom-run-switch-buffer-hooks-h) ;; Only execute this function once. (remove-hook 'window-buffer-change-functions #'doom-init-ui-h)) ;; Apply fonts and theme (let ((hook (if (daemonp) 'server-after-make-frame-hook 'after-init-hook))) (add-hook hook #'doom-init-fonts-h -100) (add-hook hook #'doom-init-theme-h -90)) ;; Initialize UI as late as possible. `window-buffer-change-functions' runs ;; once, when the scratch/dashboard buffer is first displayed. (add-hook 'window-buffer-change-functions #'doom-init-ui-h -100) ;; ;;; Fixes/hacks ;; Doom doesn't support `customize' and it never will. It's a clumsy interface ;; that sets variables at a time where it can be easily and unpredictably ;; overwritten. Configure things from your $DOOMDIR instead. (dolist (sym '(customize-option customize-browse customize-group customize-face customize-rogue customize-saved customize-apropos customize-changed customize-unsaved customize-variable customize-set-value customize-customized customize-set-variable customize-apropos-faces customize-save-variable customize-apropos-groups customize-apropos-options customize-changed-options customize-save-customized)) (put sym 'disabled "Doom doesn't support `customize', configure Emacs from $DOOMDIR/config.el instead")) (put 'customize-themes 'disabled "Set `doom-theme' or use `load-theme' in $DOOMDIR/config.el instead") ;; Doesn't exist in terminal Emacs, but some Emacs packages (internal and ;; external) use it anyway, leading to a void-function error, so define a no-op ;; substitute to suppress them. (unless (fboundp 'define-fringe-bitmap) (fset 'define-fringe-bitmap #'ignore)) (after! whitespace (defun doom-is-childframes-p () "`whitespace-mode' inundates child frames with whitespace markers, so disable it to fix all that visual noise." (null (frame-parameter nil 'parent-frame))) (add-function :before-while whitespace-enable-predicate #'doom-is-childframes-p)) (provide 'core-ui) ;;; core-ui.el ends here
# This file is part of NIT ( http://www.nitlanguage.org ). # # 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. # Server-side network services for games and such # # The following code creates a server that continuously listen for new clients, # and exchange with them briefly before disconnecting. # # ~~~nitish # redef fun handshake_app_name do return "nitwork_test" # redef fun handshake_app_version do return "1.0" # # Open a server on port 4444 # var server = new Server(4444) # # loop # # Accept new clients # var new_clients = server.accept_clients # for client in new_clients do # # A client is connected, communicate! # print "" # print client.reader.deserialize.as(Object) # client.writer.serialize "Goodbye client" # # # Done, close socket # client.socket.close # end # # # `accept_clients` in non-blocking, # # sleep before tying again, or do something else. # 0.5.sleep # printn "." # end # ~~~ module server intrude import common # Game server controller class Server # Port for the `listening_socket` var port: Int # All connected `RemoteClient` var clients = new Array[RemoteClient] # TCP socket accepting new connections # # Opened on the first call to `accept_clients`. var listening_socket: TCPServer is lazy do var socket = new TCPServer(port) socket.listen 8 socket.blocking = false return socket end # Accept currently waiting clients and return them as an array # # If `add_to_clients`, the default, the new clients are added to `clients`. # Otherwise, the return value of `accept_clients` may be added to `clients` # explicitly by the caller after an extra verification or sorting. fun accept_clients(add_to_clients: nullable Bool): Array[RemoteClient] do add_to_clients = add_to_clients or else true assert not listening_socket.closed var new_clients = new Array[RemoteClient] loop var client_socket = listening_socket.accept if client_socket == null then break var rc = new RemoteClient(client_socket) var handshake_success = rc.handshake if handshake_success then new_clients.add rc print "Server: Client at {client_socket.address} passed the handshake" else print_error "Server Error: Client at {client_socket.address} failed the handshake" client_socket.close end end if add_to_clients then clients.add_all new_clients return new_clients end # Broadcast a `message` to all `clients`, then flush the connection # # The client `except` is skipped and will not receive the `message`. fun broadcast(message: Serializable, except: nullable RemoteClient) do for client in clients do if client != except then client.writer.serialize(message) client.socket.flush end end # Respond to pending discovery requests by sending the TCP listening address and port # # Returns the number of valid requests received. # # The response messages includes the TCP listening address and port # for remote clients to connect with TCP using `connect`. # These connections are accepted by the server with `accept_clients`. fun answer_discovery_requests: Int do var count = 0 loop var ptr = new Ref[nullable SocketAddress](null) var read = discovery_socket.recv_from(1024, ptr) # No sender means there is no discovery request var sender = ptr.item if sender == null then break var words = read.split(" ") if words.length != 2 or words[0] != discovery_request_message or words[1] != handshake_app_name then print "Server Warning: Rejected discovery request '{read}' from {sender.address}:{sender.port}" continue end var msg = "{discovery_response_message} {handshake_app_name} {self.port}" discovery_socket.send_to(sender.address, sender.port, msg) count += 1 end return count end # UDP socket responding to discovery requests # # Usually opened on the first call to `answer_discovery_request`. var discovery_socket: UDPSocket is lazy do var s = new UDPSocket s.blocking = false s.bind(null, discovery_port) return s end end # Reference to a remote client connected to this server class RemoteClient # Communication socket with the client var socket: TCPStream # Is this client connected? fun connected: Bool do return socket.connected # `MsgPackSerializer` used to send data to this client through `socket` var writer: MsgPackSerializer is noinit # `MsgPackDeserializer` used to receive data from this client through `socket` var reader: MsgPackDeserializer is noinit init do # Setup serialization writer = new MsgPackSerializer(socket) writer.cache = new AsyncCache(true) reader = new MsgPackDeserializer(socket) writer.link reader end # Check for compatibility with the client fun handshake: Bool do print "Server: Handshake initiated by {socket.address}" # Make sure it is the same app var server_app = sys.handshake_app_name var client_app = socket.deserialize_msgpack if server_app != client_app then print_error "Server Error: Client app name is '{client_app or else "<invalid>"}'" # Send an empty string so the client read it and give up socket.serialize_msgpack "" socket.close return false end socket.serialize_msgpack server_app # App version var app_version = sys.handshake_app_version var client_version = socket.deserialize_msgpack if client_version != app_version then print_error "Handshake Error: client version is different '{client_version or else "<invalid>"}'" socket.serialize_msgpack "" socket.close return false end socket.serialize_msgpack app_version return true end end
package Pinwheel::Cache; use strict; use warnings; use Pinwheel::Cache::Null; use Exporter; our @ISA = qw(Exporter); our @EXPORT_OK = qw(cache cache_clear cache_get cache_remove cache_set); # By default use the Null backend my $backend = new Pinwheel::Cache::Null; sub cache_clear { return $backend->clear(); } sub cache_get { my ($key) = @_; return $backend->get($key); } sub cache_remove { my ($key, $time) = @_; return $backend->remove($key, $time); } sub cache_set { my ($key, $value, $expires) = @_; return $backend->set($key, $value, $expires); } sub cache { my $valuefn = pop @_; my ($key, $expires) = @_; my ($value); $value = $backend->get($key); if (!defined($value)) { $value = $valuefn->(); $expires = $expires->($value) if ref($expires) eq 'CODE'; $backend->set($key, $value, $expires); } return $value; } sub set_backend { my ($b) = @_; $b = new Pinwheel::Cache::Null unless defined($b); $backend = $b; } 1; __DATA__ =head1 NAME Pinwheel::Cache =head1 SYNOPSIS use Pinwheel::Cache qw(cache cache_get cache_set); Pinwheel::Cache::set_backend(new Pinwheel::Cache::Hash); cache_set('key', 'value'); $value = cache_get('get'); cache('key', sub { 'result of complex operation' }); =head1 DESCRIPTION Procedural caching API. =head1 ROUTINES =over 4 =item cache_clear() Remove all objects from the cache. =item cache_get( $key ) Returns the data associated with *$key*. =item cache_set( $key, $data, [$expires_in] ) Associates *$data* with *$key* in the cache. *$expires_in* indicates the time in seconds until this data should be erased. =item cache_remove( $key ) Delete the data associated with the *$key* from the cache. =item cache( $key, [$expires_in], $subroutine ) Call subroutine and store the result in the cache with *$key*. If there is already data in the cache associated with *$key* then it is returned and the subroutine is not called. =item set_backend( $backend ) Set the caching backend to use. The backend should implement the Cache::Cache API. =back =head1 AUTHOR A&M Network Publishing <DLAMNetPub@bbc.co.uk> =cut
import random def get_user_choice(): while True: user_choice = input("Enter your choice (rock/paper/scissors): ").lower() if user_choice in ["rock", "paper", "scissors"]: return user_choice else: print("Invalid choice. Please choose rock, paper, or scissors.") def get_computer_choice(): return random.choice(["rock", "paper", "scissors"]) def determine_winner(user_choice, computer_choice): if user_choice == computer_choice: return "tie" elif ( (user_choice == "rock" and computer_choice == "scissors") or (user_choice == "scissors" and computer_choice == "paper") or (user_choice == "paper" and computer_choice == "rock") ): return "user" else: return "computer" def main(): user_score = 0 computer_score = 0 print("Welcome to Rock-Paper-Scissors Game!") while True: user_choice = get_user_choice() computer_choice = get_computer_choice() print(f"Your choice: {user_choice}") print(f"Computer's choice: {computer_choice}") result = determine_winner(user_choice, computer_choice) if result == "tie": print("It's a tie!") elif result == "user": print("You win!") user_score += 1 else: print("Computer wins!") computer_score += 1 print(f"Your score: {user_score} | Computer's score: {computer_score}") play_again = input("Do you want to play again? (yes/no): ") if play_again.lower() != "yes": break print("Thanks for playing!") if __name__ == "__main__": main()
from dataclasses import dataclass from itertools import chain, repeat from pprint import pformat from string import Template from textwrap import dedent from typing import ( AbstractSet, Iterable, Iterator, MutableMapping, MutableSequence, Optional, Sequence, Tuple, ) from uuid import uuid4 from pynvim import Nvim from pynvim.api import Buffer, Window from pynvim.api.common import NvimError from pynvim_pp.api import ( buf_get_extmarks, buf_get_lines, buf_set_text, create_ns, cur_win, win_get_buf, win_get_cursor, win_set_cursor, ) from pynvim_pp.lib import decode, encode, write from pynvim_pp.logging import log from std2.types import never from ..consts import DEBUG from ..lang import LANG from ..shared.runtime import Metric from ..shared.trans import trans_adjusted from ..shared.types import ( UTF8, UTF16, Completion, Context, ContextualEdit, Edit, Mark, NvimPos, RangeEdit, SnippetEdit, ) from ..snippets.parse import ParsedEdit, parse from ..snippets.parsers.types import ParseError from .mark import mark from .rt_types import Stack from .state import State NS = uuid4() @dataclass(frozen=True) class EditInstruction: primary: bool begin: NvimPos end: NvimPos cursor_yoffset: int cursor_xpos: int new_lines: Sequence[str] @dataclass(frozen=True) class _Lines: lines: Sequence[str] b_lines8: Sequence[bytes] b_lines16: Sequence[bytes] len8: Sequence[int] def _lines(lines: Sequence[str]) -> _Lines: b_lines8 = tuple(map(encode, lines)) return _Lines( lines=lines, b_lines8=b_lines8, b_lines16=tuple(encode(line, encoding=UTF16) for line in lines), len8=tuple(len(line) for line in b_lines8), ) def _rows_to_fetch(ctx: Context, edit: Edit, *edits: Edit) -> Tuple[int, int]: row, _ = ctx.position def cont() -> Iterator[int]: for e in chain((edit,), edits): if isinstance(e, ContextualEdit): lo = row - (len(e.old_prefix.split(ctx.linefeed)) - 1) hi = row + (len(e.old_suffix.split(ctx.linefeed)) - 1) yield from (lo, hi) elif isinstance(e, RangeEdit): (lo, _), (hi, _) = e.begin, e.end yield from (lo, hi) elif isinstance(e, Edit): yield row else: never(e) line_nums = tuple(cont()) return min(line_nums), max(line_nums) + 1 def _contextual_edit_trans( ctx: Context, lines: _Lines, edit: ContextualEdit ) -> EditInstruction: row, col = ctx.position old_prefix_lines = edit.old_prefix.split(ctx.linefeed) old_suffix_lines = edit.old_suffix.split(ctx.linefeed) r1 = row - (len(old_prefix_lines) - 1) r2 = row + (len(old_suffix_lines) - 1) c1 = ( lines.len8[r1] - len(encode(old_prefix_lines[0])) if len(old_prefix_lines) > 1 else col - len(encode(old_prefix_lines[0])) ) c2 = ( len(encode(old_suffix_lines[-1])) if len(old_prefix_lines) > 1 else col + len(encode(old_suffix_lines[0])) ) begin = r1, c1 end = r2, c2 new_lines = edit.new_text.split(ctx.linefeed) new_prefix_lines = edit.new_prefix.split(ctx.linefeed) cursor_yoffset = -len(old_prefix_lines) + len(new_prefix_lines) cursor_xpos = ( len(encode(new_prefix_lines[-1])) if len(new_prefix_lines) > 1 else len(encode(ctx.line_before)) - len(encode(old_prefix_lines[-1])) + len(encode(new_prefix_lines[0])) ) inst = EditInstruction( primary=True, begin=begin, end=end, cursor_yoffset=cursor_yoffset, cursor_xpos=cursor_xpos, new_lines=new_lines, ) return inst def _edit_trans( unifying_chars: AbstractSet[str], ctx: Context, lines: _Lines, edit: Edit, ) -> EditInstruction: adjusted = trans_adjusted(unifying_chars, ctx=ctx, edit=edit) inst = _contextual_edit_trans(ctx, lines=lines, edit=adjusted) return inst def _range_edit_trans( unifying_chars: AbstractSet[str], ctx: Context, primary: bool, lines: _Lines, edit: RangeEdit, ) -> EditInstruction: new_lines = edit.new_text.split(ctx.linefeed) if ( primary and not isinstance(edit, ParsedEdit) and len(new_lines) <= 1 and edit.begin == edit.end ): return _edit_trans(unifying_chars, ctx=ctx, lines=lines, edit=edit) else: (r1, ec1), (r2, ec2) = sorted((edit.begin, edit.end)) if edit.encoding == UTF16: c1 = len(encode(decode(lines.b_lines16[r1][: ec1 * 2], encoding=UTF16))) c2 = len(encode(decode(lines.b_lines16[r2][: ec2 * 2], encoding=UTF16))) elif edit.encoding == UTF8: c1 = len(lines.b_lines8[r1][:ec1]) c2 = len(lines.b_lines8[r2][:ec2]) else: raise ValueError(f"Unknown encoding -- {edit.encoding}") begin = r1, c1 end = r2, c2 lines_before = ( edit.new_prefix.split(ctx.linefeed) if isinstance(edit, ParsedEdit) else new_lines ) cursor_yoffset = (r2 - r1) + (len(lines_before) - 1) cursor_xpos = ( ( len(encode(lines_before[-1])) if len(lines_before) > 1 else len(lines.b_lines8[r2][:c1]) + len(encode(lines_before[0])) ) if primary else -1 ) inst = EditInstruction( primary=primary, begin=begin, end=end, cursor_yoffset=cursor_yoffset, cursor_xpos=cursor_xpos, new_lines=new_lines, ) return inst def _instructions( ctx: Context, unifying_chars: AbstractSet[str], lines: _Lines, primary: Edit, secondary: Sequence[RangeEdit], ) -> Iterator[EditInstruction]: if isinstance(primary, RangeEdit): inst = _range_edit_trans( unifying_chars, ctx=ctx, primary=True, lines=lines, edit=primary, ) yield inst elif isinstance(primary, ContextualEdit): inst = _contextual_edit_trans(ctx, lines=lines, edit=primary) yield inst elif isinstance(primary, Edit): inst = _edit_trans(unifying_chars, ctx=ctx, lines=lines, edit=primary) yield inst else: never(primary) for edit in secondary: yield _range_edit_trans( unifying_chars, ctx=ctx, primary=False, lines=lines, edit=edit, ) def _consolidate( instruction: EditInstruction, *instructions: EditInstruction ) -> Sequence[EditInstruction]: edits = sorted(chain((instruction,), instructions), key=lambda i: (i.begin, i.end)) pivot = 0, 0 stack: MutableSequence[EditInstruction] = [] for edit in edits: if edit.begin >= pivot: stack.append(edit) pivot = edit.end elif edit.primary: while stack: conflicting = stack.pop() if conflicting.end <= edit.begin: break stack.append(edit) pivot = edit.end else: pass return stack def _shift(instructions: Iterable[EditInstruction]) -> Iterator[EditInstruction]: row_shift = 0 col_shift: MutableMapping[int, int] = {} for inst in instructions: (r1, c1), (r2, c2) = inst.begin, inst.end yield EditInstruction( primary=inst.primary, begin=(r1 + row_shift, c1 + col_shift.get(r1, 0)), end=(r2 + row_shift, c2 + col_shift.get(r2, 0)), cursor_yoffset=inst.cursor_yoffset, cursor_xpos=inst.cursor_xpos, new_lines=inst.new_lines, ) row_shift += (r2 - r1) + len(inst.new_lines) - 1 f_length = len(encode(inst.new_lines[-1])) if inst.new_lines else 0 col_shift[r2] = -(c2 - c1) + f_length if r1 == r2 else -c2 + f_length def apply(nvim: Nvim, buf: Buffer, instructions: Iterable[EditInstruction]) -> None: for inst in _shift(instructions): try: buf_set_text( nvim, buf=buf, begin=inst.begin, end=inst.end, text=inst.new_lines ) except NvimError as e: tpl = """ ${e} ${inst} """ msg = Template(dedent(tpl)).substitute(e=e, inst=inst) log.warn(f"%s", msg) def _cursor(cursor: NvimPos, instructions: Iterable[EditInstruction]) -> NvimPos: row, _ = cursor col = -1 for inst in instructions: row += inst.cursor_yoffset col = inst.cursor_xpos if inst.primary: break assert col != -1 return row, col def _parse(stack: Stack, state: State, comp: Completion) -> Tuple[Edit, Sequence[Mark]]: if isinstance(comp.primary_edit, SnippetEdit): visual = "" return parse( stack.settings.match.unifying_chars, context=state.context, snippet=comp.primary_edit, visual=visual, ) else: return comp.primary_edit, () def _restore(nvim: Nvim, win: Window, buf: Buffer, pos: NvimPos) -> Tuple[str, int]: row, _ = pos ns = create_ns(nvim, ns=NS) marks = tuple(buf_get_extmarks(nvim, buf=buf, id=ns)) if len(marks) != 2: return "", 0 else: m1, m2 = marks after, *_ = buf_get_lines(nvim, buf=buf, lo=row, hi=row + 1) cur_row, cur_col = win_get_cursor(nvim, win=win) (_, lo), (_, hi) = m1.end, m2.begin binserted = encode(after)[lo:hi] inserted = decode(binserted) if inserted and cur_row == row and lo <= cur_col <= hi: movement = cur_col - lo else: movement = len(binserted) if inserted: buf_set_text(nvim, buf=buf, begin=m1.end, end=m2.begin, text=("",)) return inserted, movement def edit( nvim: Nvim, stack: Stack, state: State, metric: Metric, synthetic: bool ) -> Optional[Tuple[int, int]]: win = cur_win(nvim) buf = win_get_buf(nvim, win=win) if buf.number != state.context.buf_id: log.warn("%s", "stale buffer") return None else: nvim.options["undolevels"] = nvim.options["undolevels"] if synthetic: inserted, movement = "", 0 else: inserted, movement = _restore( nvim, win=win, buf=buf, pos=state.context.position ) try: primary, marks = _parse(stack, state=state, comp=metric.comp) except ParseError as e: primary, marks = metric.comp.primary_edit, () write(nvim, LANG("failed to parse snippet")) log.info("%s", e) lo, hi = _rows_to_fetch( state.context, primary, *metric.comp.secondary_edits, ) if lo < 0 or hi > state.context.line_count + 1: log.warn("%s", pformat(("OUT OF BOUNDS", (lo, hi), metric))) return None else: limited_lines = buf_get_lines(nvim, buf=buf, lo=lo, hi=hi) lines = [*chain(repeat("", times=lo), limited_lines)] view = _lines(lines) instructions = _consolidate( *_instructions( state.context, unifying_chars=stack.settings.match.unifying_chars, lines=view, primary=primary, secondary=metric.comp.secondary_edits, ) ) n_row, p_col = _cursor( state.context.position, instructions=instructions, ) n_col = p_col + movement if not synthetic: stack.idb.inserted(metric.instance.bytes, sort_by=metric.comp.sort_by) apply(nvim, buf=buf, instructions=instructions) if inserted: try: buf_set_text( nvim, buf=buf, begin=(n_row, p_col), end=(n_row, p_col), text=(inserted,), ) except NvimError as e: log.warn("%s", e) try: win_set_cursor(nvim, win=win, row=n_row, col=n_col) except NvimError as e: log.warn("%s", e) if marks: mark(nvim, settings=stack.settings, buf=buf, marks=marks) if DEBUG: log.debug( "%s", pformat( ( (metric.comp.primary_edit, *metric.comp.secondary_edits), instructions, ) ), ) return n_row, n_col
import { expect } from 'chai'; import { projectName } from '../dist/index.js'; import { setup } from './utils.js'; describe('project name', async () => { const fixture = setup(); it('pass in name', async () => { const context = { projectName: '', cwd: './foo/bar/baz', prompt: () => {} }; await projectName(context); expect(context.cwd).to.eq('./foo/bar/baz'); expect(context.projectName).to.eq('baz'); }); it('dot', async () => { const context = { projectName: '', cwd: '.', prompt: () => ({ name: 'foobar' }) }; await projectName(context); expect(fixture.hasMessage('"." is not empty!')).to.be.true; expect(context.projectName).to.eq('foobar'); }); it('dot slash', async () => { const context = { projectName: '', cwd: './', prompt: () => ({ name: 'foobar' }) }; await projectName(context); expect(fixture.hasMessage('"./" is not empty!')).to.be.true; expect(context.projectName).to.eq('foobar'); }); it('empty', async () => { const context = { projectName: '', cwd: './test/fixtures/empty', prompt: () => ({ name: 'foobar' }), }; await projectName(context); expect(fixture.hasMessage('"./test/fixtures/empty" is not empty!')).to.be.false; expect(context.projectName).to.eq('empty'); }); it('not empty', async () => { const context = { projectName: '', cwd: './test/fixtures/not-empty', prompt: () => ({ name: 'foobar' }), }; await projectName(context); expect(fixture.hasMessage('"./test/fixtures/not-empty" is not empty!')).to.be.true; expect(context.projectName).to.eq('foobar'); }); it('basic', async () => { const context = { projectName: '', cwd: '', prompt: () => ({ name: 'foobar' }) }; await projectName(context); expect(context.cwd).to.eq('foobar'); expect(context.projectName).to.eq('foobar'); }); it('blank space', async () => { const context = { projectName: '', cwd: '', prompt: () => ({ name: 'foobar ' }) }; await projectName(context); expect(context.cwd).to.eq('foobar'); expect(context.projectName).to.eq('foobar'); }); it('normalize', async () => { const context = { projectName: '', cwd: '', prompt: () => ({ name: 'Invalid Name' }) }; await projectName(context); expect(context.cwd).to.eq('Invalid Name'); expect(context.projectName).to.eq('invalid-name'); }); it('remove leading/trailing dashes', async () => { const context = { projectName: '', cwd: '', prompt: () => ({ name: '(invalid)' }) }; await projectName(context); expect(context.projectName).to.eq('invalid'); }); it('handles scoped packages', async () => { const context = { projectName: '', cwd: '', prompt: () => ({ name: '@astro/site' }) }; await projectName(context); expect(context.cwd).to.eq('@astro/site'); expect(context.projectName).to.eq('@astro/site'); }); it('--yes', async () => { const context = { projectName: '', cwd: './foo/bar/baz', yes: true, prompt: () => {}, }; await projectName(context); expect(context.projectName).to.eq('baz'); }); it('dry run with name', async () => { const context = { projectName: '', cwd: './foo/bar/baz', dryRun: true, prompt: () => {}, }; await projectName(context); expect(context.projectName).to.eq('baz'); }); it('dry run with dot', async () => { const context = { projectName: '', cwd: '.', dryRun: true, prompt: () => ({ name: 'foobar' }), }; await projectName(context); expect(context.projectName).to.eq('foobar'); }); it('dry run with empty', async () => { const context = { projectName: '', cwd: './test/fixtures/empty', dryRun: true, prompt: () => ({ name: 'foobar' }), }; await projectName(context); expect(context.projectName).to.eq('empty'); }); });
# User stories Dit document zal de user stories voor de benodigde onderdelen en features bevatten. Gezien dit voor mij de eerste keer is dat ik deze maak zal ik eerst volgens een voorbeeld een standaard opmaak aanmaken en vanuit daar werken. ## Standaard opmaak. In de eerdere versie van deze opdracht (versie 1.0) kregen wij de benodigde user stories aangeleverd, ik zal deze opmaak toevoegen als voorbeeld en gebruiken als opmaak voor de user stories van deze opdracht. ![Een voorbeeld van een User Story](/project_documentation/images/example_user_story.png) # Epics ### Omschrijving van wat Epics zijn Voor de User stories zijn meerdere "epics" nodig; dit zijn unieke periodes met een eigen functie; bijvoorbeeld het aanmaken van documentatie. Elke periode bestaat uit een aantal deliverables; dit zijn bijvoorbeeld documenten of werkende code. ![voorbeeld van een overzicht van de Epics](/images/example_epics.png) ## De Epics die in dit project gebruikt gaan worden Voor dit project worden er 2 Epics aangemaakt: Epic 1: *Exploration* Epic 2 *Bouw* # Epic 1: Exploration --- **User Story:** *Er is een duidelijke omschrijving nodig van de eisen* **Epic:** *Exploration* **Beschrijving:** Het ontwerp document beschrijft een aantal onderdelen. Al deze onderdelen moeten worden beschreven in een puntsgewijze omschrijving. **deliverable 1** Een korte omschrijving van alle eisen. --- --- **User Story** *Er moet een overzicht komen van de gemaakte aannames* **Epic** *Exploration* **Beschrijving** Veel informatie staat al in het ontwerpdocument maar lang niet alle benodigde onderdelen worden er in vermeld. Er zullen dus een aantal aannames worden gedaan. Al deze aannames moeten worden geschreven. **Deliverable 2** Een beschrijving van alle aannames. --- --- **User Story** *Er zijn nog niet beschreven diensten, die wel beschreven moeten worden* **Epic** *exploration* **Beschrijving** Naast alle onderdelen die er gebruikt gaan worden, zijn er ook diensten die nodig zijn maar welke niet in het ontwerp document worden vermeld en/of in de architectuur vermeld worden. Deze moeten beschreven worden. **Deliverable 3** Een beschrijving van alle diensten die er gebruikt gaan worden. --- --- **User Story** *Er is een architectuur tekening nodig* **Epic** *exploration* **Beschrijving** De eisen moeten leiden tot een werkende architectuur welke opgetekend wordt. **Deliverable 4** De architectuur tekening. --- --- **User Story** *Er is een volledige omschrijving nodig van het gehele systeem* **Epic** *exploration* **Beschrijving** Nadat alle onderdelen puntsgewijs beschreven zijn moeten deze ook uitgebreid omschreven worden inclusief elke aanname en dienst. **Deliverable** Een uitgebreide omschrijving van het systeem. --- --- # Epic 2: Bouw **User Story** *Er is een load balancer nodig* **Epic** *bouw* **Beschrijving** Het systeem heeft een application gateway nodig die de VM scale set beheert. Deze load balancer/gateway heeft zelf een IP adres nodig. **Deliverable** Werkende IaC code. --- --- **User Story** *IaC code voor een VM scale set* **Epic** *bouw* **Beschrijving** Er is werkende code nodig voor een VM scale set waarbij er altijd minimaal 1 VM met webserver role actief is, en deze geschaald kan worden naar maximaal 3 instances. Deze scale set moet achter een load balancer staan en zodoende niet meer "naakt" vanaf het internet bereikbaar zijn maar alleen via de adminVM via ssh. **Deliverable** Werkende IaC code voor een VM scale set. --- --- **User Story** *De scale set heeft health checks nodig die bij eventueel falen de VMs automatisch kan herstellen* **Epic** *bouw* **Beschrijving** De scale set moet stabiel blijven werken en heeft daarvoor regelmatige health checks nodig en een automatisch systeem van herstel mochten de health checks problemen constateren. **Deliverable** Werkende IaC code voor health checks voor de VM scale set. --- --- **User story** *Het systeem mag alleen via HTTPS bereikt worden* **Epic** *bouw* **Beschrijving** Er is een self signed certificaat nodig om elke connectie met de load balancer/gateway via HTTPS te kunnen laten verlopen. **Deliverable** Een self signed certificate dat de load balancer gebruikt. Hierbij moet ook direct het gebruik van TLS 1.2 verplicht gesteld worden. --- --- **User Story** *Er moeten aanpassingen komen aan meerdere onderdelen van de V1.0 app* **Epic** *bouw* **Beschrijving** Hoewel bijna alles gelijk blijft op de webserverVM na, het is wel nodig om een aantal kleine aanpassingen door te voeren op de backup, NSG en adminVM code. **Deliverable** Aangepaste code voor backup, NSG en adminVM.
const Header = (props) => { return ( <h1>{props.course}</h1> ) } const Part = (props) => { const part = props.part; return ( <p> {part.name} {part.exercises} </p> ) } const Content = (props) => { return ( <div> <Part part={props.parts[0]} /> <Part part={props.parts[1]} /> <Part part={props.parts[2]} /> </div> ) } const Total = (props) => { return ( <p>Number of exercises {props.parts.reduce((sum, part) => sum + part.exercises, 0)}</p> ) } const App = () => { const course = { name: 'Half Stack application development', parts: [ { name: 'Fundamentals of React', exercises: 10 }, { name: 'Using props to pass data', exercises: 7 }, { name: 'State of a component', exercises: 14 } ] } return ( <div> <Header course={course.name} /> <Content parts={course.parts} /> <Total parts={course.parts} /> </div> ) } export default App
import "./_game.scss"; import Header from "../../Layouts/Header"; import Footer from "../../Layouts/Footer"; import { axiosJWT, gameQuestions } from "../../utils/axios"; import { useEffect, useState } from "react"; import Timer from "../../Components/Timer/Timer"; import ProgressBar from "../../Components/ProgressBar/ProgressBar"; import { useParams } from "react-router-dom"; //? set FOCUS sur le champ de réponse (inputRef.current.focus()) const Game = () => { // on récupère gameId des paramètres de la route const { gameId } = useParams(); const [questions, setQuestions] = useState([]); const [selectedQuestion, setSelectedQuestion] = useState(0); const [noMoreTime, setNoMoreTime] = useState(false); const [thisQuestion, setThisQuestion] = useState(null); // const isLastQuestion = selectedQuestion === questions.length - 1; //!calculer % complétion pour progressBar // récuperer les questions de cette partie + le temps de chacune + le niveau useEffect(() => { let isMounted = true; const controller = new AbortController(); const getQuestions = async () => { try { const { data: gameQuestion } = await axiosJWT.get( `${gameQuestions}?game=${gameId}`, { signal: controller.signal, } ); if (isMounted && gameQuestion) { // console.log(gameQuestion); setQuestions(gameQuestion["hydra:member"]); } } catch (error) { console.log(error); } }; getQuestions(); return () => { isMounted = false; controller.abort(); }; }, [gameId]); useEffect(() => { questions && setThisQuestion(questions[`${selectedQuestion}`]); }, [questions, selectedQuestion]); useEffect(() => { if (noMoreTime && selectedQuestion <= questions.length) { setNoMoreTime((prev) => !prev); return setSelectedQuestion((prev) => prev + 1); } }, [noMoreTime]); const getParseMedia = () => { if (thisQuestion.question.media.length > 0) { const media = thisQuestion.question.media[0].contentUrl; if (media.includes("mp4")) { return ( <video width="750" height="500" controls autoPlay muted> <source src={media} type="video/mp4" /> </video> ); } else if (media.includes("png")) { return <img src={media} alt="image" />; } } return; }; return ( <> <Header /> <main> <p style={{ color: "white" }}>{selectedQuestion}</p> {thisQuestion && ( <div className="game-content"> <Timer time={thisQuestion.question.timer} setNoMoreTime={setNoMoreTime} noMoreTime={noMoreTime} /> <div className="game-box"> <div className="media">{getParseMedia()}</div> <div className="question"> <p>{thisQuestion.question.question}</p> </div> <div className="answer"> <form action=""> <input type="text" name="" id="" /> </form> </div> </div> <ProgressBar level={thisQuestion.question.level} progress={50} /> </div> )} </main> <Footer /> </> ); }; export default Game;
import React from 'react'; import { Container } from 'react-bootstrap'; import Chart from "react-apexcharts"; import { userData } from '../../../dummyData'; const ServiceSales = () => { const names = userData.map((user) => (user.name)); const data = userData.map((user) => (user['Active User'])); return ( <Container className="my-4" > <h3>Sales Month Wise For Service </h3> <Chart type='line' width={"100%"} height={300} series={[ { name: "serviceName-1", data: data } ]} options={{ // colors:["#333","#ff0000"], theme: { mode: "day" }, xaxis: { tickPlacement: "on", categories: names, title: { text: "Months", style: { color: "#0f0", fontSize: 20 } } }, chart: { stacked: false }, dataLabels: { formatter: (val) => { return `$${val}` }, style: { fontSize: 18 } }, yaxis: { labels: { formatter: (val) => { return `$${val}` }, style: { fontSize: 18 } }, title: { text: "Sales", style: { color: "#ff0", fontSize: 20 } } }, legend: { show: true, position: 'bottom' }, stroke: { show: true, curve: 'smooth', lineCap: 'round', colors: undefined, width: 2, dashArray: 0, } }} > </Chart> </Container> ) } export default ServiceSales;
package main import ( "context" "database/sql" "fmt" "net/netip" "k8s.io/klog/v2" "source.monogon.dev/cloud/bmaas/bmdb" "source.monogon.dev/cloud/bmaas/bmdb/model" "source.monogon.dev/cloud/shepherd" ) // provider represents a shepherd.Provider that works entirely on a // static device list. It requires a provider type and a device list. type provider struct { providerType model.Provider machines map[shepherd.ProviderID]machine } type machine struct { ProviderID shepherd.ProviderID `json:"ID"` Address netip.Addr `json:"Addr"` Location string `json:"Location"` } func (d machine) ID() shepherd.ProviderID { return d.ProviderID } func (d machine) Addr() netip.Addr { return d.Address } func (d machine) State() shepherd.State { return shepherd.StatePossiblyUsed } func (p *provider) ListMachines(ctx context.Context) ([]shepherd.Machine, error) { machines := make([]shepherd.Machine, 0, len(p.machines)) for _, m := range p.machines { machines = append(machines, m) } return machines, nil } func (p *provider) GetMachine(ctx context.Context, id shepherd.ProviderID) (shepherd.Machine, error) { // If the provided machine is not inside our known machines, // bail-out early as this is unsupported. if _, ok := p.machines[id]; !ok { return nil, fmt.Errorf("unknown provided machine requested") } return p.machines[id], nil } func (p *provider) CreateMachine(ctx context.Context, session *bmdb.Session, request shepherd.CreateMachineRequest) (shepherd.Machine, error) { if request.UnusedMachine == nil { return nil, fmt.Errorf("parameter UnusedMachine is missing") } //TODO: Do we just trust the implementation to be correct? m, ok := request.UnusedMachine.(machine) if !ok { return nil, fmt.Errorf("invalid type for parameter UnusedMachine") } if err := p.assimilate(ctx, session, m); err != nil { klog.Errorf("Failed to provision machine %s: %v", m.ProviderID, err) return nil, err } return m, nil } func (p *provider) assimilate(ctx context.Context, sess *bmdb.Session, machine machine) error { return sess.Transact(ctx, func(q *model.Queries) error { // Create a new machine record within BMDB. m, err := q.NewMachine(ctx) if err != nil { return fmt.Errorf("while creating a new machine record in BMDB: %w", err) } // Link the new machine with the device, and tag it "provided". addParams := model.MachineAddProvidedParams{ MachineID: m.MachineID, ProviderID: string(machine.ProviderID), Provider: p.providerType, } klog.Infof("Setting \"provided\" tag (ID: %s, PID: %s, Provider: %s).", addParams.MachineID, addParams.ProviderID, addParams.Provider) if err := q.MachineAddProvided(ctx, addParams); err != nil { return fmt.Errorf("while tagging machine active: %w", err) } upParams := model.MachineUpdateProviderStatusParams{ ProviderID: string(machine.ProviderID), Provider: p.providerType, ProviderIpAddress: sql.NullString{ String: machine.Address.String(), Valid: true, }, ProviderLocation: sql.NullString{ String: machine.Location, Valid: machine.Location != "", }, ProviderStatus: model.NullProviderStatus{ ProviderStatus: model.ProviderStatusUnknown, Valid: true, }, } klog.Infof("Setting \"provided\" tag status parameter (ID: %s, PID: %s, Provider: %s).", addParams.MachineID, upParams.ProviderID, upParams.Provider) if err := q.MachineUpdateProviderStatus(ctx, upParams); err != nil { return fmt.Errorf("while setting machine params: %w", err) } return nil }) } func (p *provider) Type() model.Provider { return p.providerType }
package controllers import ( "cofin/models" "net/http" "strconv" "github.com/gin-gonic/gin" "go.uber.org/zap" "gorm.io/gorm" ) type CompaniesController struct { DB *gorm.DB Logger *zap.SugaredLogger } func (cc CompaniesController) GetCompany(c *gin.Context) { companyID, err := strconv.ParseUint(c.Param("company_id"), 10, 32) if err != nil { RespondBadRequestErr(c, []error{err}) return } company, err := models.GetCompanyByID(cc.DB, uint(companyID)) if err != nil { cc.Logger.Errorf("Error querying company: %w", err) RespondInternalErr(c) return } else if company == nil { RespondCustomStatusErr(c, http.StatusNotFound, []error{ErrUnknownCompany}) return } RespondOK(c, company) } func (cc CompaniesController) GetCompanies(c *gin.Context) { if ticker := c.Query("ticker"); ticker != "" { company, err := models.GetCompanyByTicker(cc.DB, ticker) if err != nil { cc.Logger.Errorf("Error querying company: %w", err) RespondInternalErr(c) return } if company == nil { RespondCustomStatusErr(c, http.StatusNotFound, []error{ErrUnknownCompany}) return } RespondOK(c, company) return } limit, err := strconv.Atoi(c.Query("limit")) if err != nil { RespondBadRequestErr(c, []error{err}) return } offset, err := strconv.Atoi(c.Query("offset")) if err != nil { RespondBadRequestErr(c, []error{err}) return } query := c.Query("query") companies, err := models.FindCompanies(cc.DB, query, offset, limit) if err != nil { cc.Logger.Errorf("Error querying companies: %w", err) RespondInternalErr(c) return } RespondOK(c, companies) } func (cc CompaniesController) GetCompanyDocuments(c *gin.Context) { companyID, err := strconv.ParseUint(c.Param("company_id"), 10, 32) if err != nil { RespondBadRequestErr(c, []error{err}) return } company, err := models.GetCompanyByID(cc.DB, uint(companyID)) if err != nil { cc.Logger.Errorf("Error querying company: %w", err) RespondInternalErr(c) return } else if company == nil { RespondCustomStatusErr(c, http.StatusNotFound, []error{ErrUnknownCompany}) return } limit, err := strconv.Atoi(c.Query("limit")) if err != nil { RespondBadRequestErr(c, []error{err}) return } offset, err := strconv.Atoi(c.Query("offset")) if err != nil { RespondBadRequestErr(c, []error{err}) return } documents, err := models.GetCompanyDocumentsInverseChronological(cc.DB, company.ID, offset, limit) if err != nil { cc.Logger.Errorf("Error querying company documents: %w", err) RespondInternalErr(c) return } RespondOK(c, documents) }
import React, {useState, useRef, useEffect} from 'react'; import TodoList from './TodoList' import {uuid} from 'uuidv4' const LOCAL_STORAGE_KEY = 'todoApp.todos' function App() { const [todos, setTodos] = useState([]) const todoNameRef = useRef() console.log(todos) useEffect(() => { const localStorageData = localStorage.getItem(LOCAL_STORAGE_KEY) console.log(localStorageData === undefined) if(localStorageData) { const storedTodos = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY)) setTodos(storedTodos) } setTodos([]) }, []) useEffect(() => { localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos)) }, [todos]) function toggleTodo(id) { const newTodos = [...todos] const todo = newTodos.find(todo => todo.id === id) todo.complete = !todo.complete setTodos(newTodos) } function handleAddTodo(e) { const name = todoNameRef.current.value if (!name) { return } console.log(todos) setTodos([...todos, { id: uuid(), name: name, complete:false}]) todoNameRef.current.value = null } function handleClearTodos() { const newTodos = todos.filter(todo => !todo.complete) setTodos(newTodos) } return ( <> <TodoList todos={todos} toggleTodo={toggleTodo} /> <input ref={todoNameRef} type="text" /> <button onClick={handleAddTodo}> Add Todo</button> <button onClick={handleClearTodos}> Clear Completed</button> <div>{todos.filter(todo => !todo.complete).length} left to do</div> </> ) } export default App;
import { Todo } from '@/types' import { TodoService } from './TodoService' const defaultTodos: Todo[] = [ { id: 1, title: 'Item1', checked: true }, { id: 2, title: 'Item2', checked: true }, { id: 3, title: 'Item3', checked: true }, { id: 4, title: 'Item4', checked: true }, { id: 5, title: 'Item5', checked: true } ] function delay(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)) } export interface LocalStorage { setItem(key: string, value: string): void getItem(key: string): string | null } export default class TodoLocalStorageService implements TodoService { latestID: number get todos(): Todo[] { const savedTodos = this.getTodosFromLocalStorage() if (savedTodos.length === 0) { return defaultTodos } return savedTodos } set todos(todos: Todo[]) { this.saveTodosToLocalStorage(todos) } localStorage: LocalStorage constructor(localStorage: LocalStorage) { this.localStorage = localStorage this.latestID = (this.todos.at(-1)?.id ?? 0) + 1 } getTodosFromLocalStorage(): Todo[] { const todosString = this.localStorage.getItem('todos') if (!todosString) { return [] } const todos = JSON.parse(todosString) return todos } saveTodosToLocalStorage(todos: Todo[]) { const todosJSON = JSON.stringify(todos) this.localStorage.setItem('todos', todosJSON) } getNewTodoItem(): Todo { const newTodo: Todo = { id: this.latestID, title: '', checked: false } this.latestID += 1 return newTodo } async getTodos(): Promise<Todo[]> { await delay(1000) return this.todos } async createTodo(): Promise<Todo> { await delay(1000) const newTodo = this.getNewTodoItem() this.todos = [...this.todos, newTodo] return newTodo } async updateTodo(todo: Todo): Promise<Todo> { await delay(1000) const updatedTodo = todo const updatedIndex = this.todos.findIndex((todo) => todo.id === updatedTodo.id) const updatedTodos = [...this.todos] updatedTodos.splice(updatedIndex, 1, updatedTodo) this.todos = updatedTodos return updatedTodo } async deleteTodo(todo: Todo): Promise<Todo> { await delay(1000) const deletedTodo = todo const deleteIndex = this.todos.findIndex((todo) => todo.id === deletedTodo.id) const updatedTodos = [...this.todos] updatedTodos.splice(deleteIndex, 1) this.todos = updatedTodos return deletedTodo } }
// // ContentUnavailableView.swift // CleanPad // // Created by Uriel Ortega on 10/10/23. // // Inspired by ContentUnavailableView (iOS 17+) import SwiftUI /// View meant to be used when a list is empty, inviting the user to add an item. /// Can be personalized modifying its default parameters values. struct EmptyListView: View { var imageSystemName: String = "questionmark" var label: String = "No Items" var description: String = "Start adding items to your list." var buttonLabel: String = "Add item" var buttonActions: () -> Void var body: some View { VStack(alignment: .center) { Image(systemName: imageSystemName) .foregroundStyle(.secondary) .font(.system(size: 50)) .padding(.bottom) Text(label) .font(.system(size: 20)) .fontWeight(.bold) .padding(.bottom, 3) Text(description) .font(.system(size: 18)) .fontWeight(.semibold) .foregroundStyle(.secondary) .padding(.bottom, 15) Button(buttonLabel) { buttonActions() } } } } struct EmptyListView_Previews: PreviewProvider { static var previews: some View { EmptyListView() { } } }
<template> <v-container class="hasBgColor"> <v-progress-linear v-if="isLoading || checkLoading" indeterminate></v-progress-linear> <h3> {{ textFilter('balance') }}<b class="red--text">{{ this.balanceSum }}</b> </h3> <v-btn-toggle v-if="withdrawalsCurrencyList && withdrawalsCurrencyList.length" tile group v-model="payId" class="d-flex flex-wrap"> <v-btn :color="payId == 0 ? 'success' : 'primary'" class="mr-3 mb-3 py-1 payment d-flex elevation-0" outlined small :value="0"> <v-icon class="clip" :class="{ success: payId == 0, primary: payId != 0 }">payment</v-icon> CNY </v-btn> <v-btn v-for="(item, i) in withdrawalsCurrencyList" :key="i" :color="payId == item.PayID ? 'success' : 'primary'" class="mr-3 mb-3 py-1 payment d-flex elevation-0" outlined small :value="item.PayID" > <v-icon class="clip" :class="{ success: payId == item.PayID, primary: payId != item.PayID }">payment</v-icon> {{ item.PayName }} </v-btn> </v-btn-toggle> <v-text-field v-if="payId == 0" v-model.number="withdraw" type="number" :label="textFilter('withdrawLabel')"> <template v-slot:prepend> <v-icon class="transparent primary--text">currency_yuan</v-icon> </template> </v-text-field> <template v-else> <div class="d-flex"> <v-card class="align-center d-flex height-35px elevation-0"> <v-icon class="grey--text">calculate</v-icon> <span class="grey--text">{{ textFilter('withdrawalExchangeRateLabel') }}:</span> <span class="pr-5 primary--text">{{ pay.Drate }}</span> </v-card> <v-card class="align-center d-flex elevation-0"> <span class="pl-2 grey--text font-size-14 align-self-bottom">{{ textFilter('withdrawalCNYAmountLabel') }}:</span> <span class="primary--text font-size-18 d-block line-height-18px">{{ withdraw || 0 }}</span> <v-icon class="grey--text pr-2 font-size-14 align-self-bottom" small>currency_yuan</v-icon> </v-card> </div> <v-text-field v-model.number="unit" @input="withdraw = unit * pay.Drate" type="number" :label="`${textFilter('withdrawLabel')}(${pay && pay.CurrencyCode})`" > <template v-slot:prepend> <v-icon class="transparent primary--text">currency_exchange</v-icon> </template> </v-text-field> <v-autocomplete v-if="/USDT/gi.test(pay && pay.CurrencyCode)" v-model="usdtAccount" :items="usdtWallets" item-value="Card" :label="textFilter('usdtAccountLabel')" :placeholder="textFilter('usdtAccountPlaceholder')" :rules="[v => !!v || textFilter('usdtAccountPlaceholder')]" > <template v-slot:selection="{ item }">{{ cardStarText(item.Card) }} </template> <template v-slot:item="{ item }">{{ cardStarText(item.Card) }} </template> <!-- <template v-slot:prepend><img width="20" src="./assets/icon/bank.png" /></template> --> <template slot="append"> <v-btn @dragover.prevent icon color="primary" @click.prevent="$refs.qrInput.$el.click()"><v-icon>cloud_upload</v-icon></v-btn> <image-barcode-reader v-show="false" ref="qrInput" @decode="onDecode" @error="qrError"></image-barcode-reader> </template> </v-autocomplete> </template> <v-select v-if="payId == 0" return-object :hint="textFilter('accountHint')" :noDataText="textFilter('noBankCard')" v-model="select" :items="bankCards" :label="textFilter('accountLabel')" :item-text="changeStar" outline > </v-select> <v-text-field v-model="userProfileData.username" readonly :label="$t('g_layout_userCentre_default_bankCard_nameLabel')"></v-text-field> <v-text-field v-model="withdrawPass" :type="visibility ? 'text' : 'password'" :append-icon="visibility ? 'visibility' : 'visibility_off'" @click:append="visibility = !visibility" :label="textFilter('withdrawPassLabel')" :placeholder="textFilter('withdrawPassPlaceholder')" ></v-text-field> <v-btn v-if="!(config.Hide_WithdrawalBtn === '1')" :disabled="isLoading || checkLoading" @click.stop="postWithdrawal" block depressed color="primary" >{{ textFilter('submitBtn') }}</v-btn > <v-btn color="primary" block outlined class="mt-3" @click="$router.go(-1)">{{ textFilter('cancelBtn') }}</v-btn> <v-list class="mt-5"> <v-list-item> <v-list-item-content> <h4 class="mb-3">{{ textFilter('descriptionTitle') }}</h4> <div v-html="config.withdrawals_descriptionContents" /> </v-list-item-content> </v-list-item> </v-list> <!-- 提現成功 --> <v-dialog v-if="dialog" v-model="dialog" max-width="290"> <v-card> <v-card-title class="headline">{{ textFilter('success') }}</v-card-title> <v-card-text> {{ textFilter('successContent1') }} <code color="red">{{ textFilter('successContent2') }}</code> {{ textFilter('successContent3') }} </v-card-text> <v-card-actions> <v-spacer></v-spacer> <v-btn color="green darken-1" depressed @click="routerPush('/record')"> {{ textFilter('confirmBtn') }} </v-btn> </v-card-actions> </v-card> </v-dialog> <!-- 流水任務 --> <v-dialog v-model="withdrawalError.show"> <v-card> <v-card-title class="justify-center">{{ $t('g_com_login_default_tipTitle') }}</v-card-title> <v-card-text>{{ withdrawalError.text }}</v-card-text> <v-card-actions class="d-flex justify-center"> <v-btn color="error" @click="withdrawalError.show = false">{{ $t('g_layout_userCentre_default_deposit_closeBtn') }}</v-btn> <v-btn color="primary" depressed @click="SHOW_LIVE_CHAT(0)" class="px-5">{{ $t('g_com_login_default_contactCustomerService') }}</v-btn> </v-card-actions> </v-card> </v-dialog> <WithdrawalOverTime /> </v-container> </template> <script> import { mapActions, mapGetters, mapMutations } from 'vuex'; import { textFilter } from '@UTILS/i18n'; import { MOBILE_WITHDRAWALS_DESCRIPTIONCONTENTS } from '@G/consts'; import { textReplacer, cardStarText } from '@G/utils'; import { ImageBarcodeReader } from 'vue-barcode-reader'; import WithdrawalOverTime from '@G/components/WithdrawalOverTime.vue'; export default { name: 'Withdrawals', components: { ImageBarcodeReader, WithdrawalOverTime, }, data() { return { visibility: false, checkLoading: true, showUSDT: false, select: {}, Password: '', dialog: false, withdrawPass: '', withdraw: '', unit: 0, usdtAccount: '', // usdt 錢包地址 originalUsdtAccount: '', // usdt 錢包地址初始值 editUsdtAcc: false, timerSaver: null, descriptionContents: MOBILE_WITHDRAWALS_DESCRIPTIONCONTENTS.split(',').map(i => `descriptionContent${i}`), withdrawalError: { text: '', show: false, }, payId: 0, }; }, computed: { ...mapGetters([ 'isLoading', 'config', 'userProfileData', 'userInfo', 'userBankList', 'balanceAllInfo', 'balanceSum', 'postWithdrawalsStatus', 'putPasswordStatus', 'virtualUsdtInfo', 'usdtWallets', 'isWithdrawHideUsdt', 'withdrawalsCurrencyList', ]), withdrawal_limited() { let arr = this.config.withdrawal_limited.split(','); const [lower = '', higher = ''] = arr; return { lower, higher, day: this.config.withdrawal_day }; }, bankCards() { return this.userBankList.filter(item => item.Bank != 'USDT'); }, pay() { return this.withdrawalsCurrencyList.find(item => item.PayID === this.payId); }, }, watch: { postWithdrawalsStatus(info) { if (info === 'success') { this.select = {}; this.withdraw = ''; this.withdrawPass = ''; this.dialog = true; } this.POST_WITHDRAWALS_STATUS(''); }, // usdt 資訊 // virtualUsdtInfo(info) { // console.log(this.usdtWallets); // info.account && this.usdtHandler(); // }, // usdt 預選定入款用錢包 usdtWallets(wallets) { if (wallets.length) { this.usdtAccount = wallets[0].Card; } }, payId(v) { return (this.payId = v ?? 0); }, }, async created() { this.SET_CURRENT_MENU_TITLE(this.textFilter('withdrawal')); // 進入頁面前檢查 try { const profile = await this.GET_USER_PROFILE(); if (!profile.username) throw { route: 'profile', key: 'msgName' }; // 1.檢查姓名 if (!profile.cards || profile.cards.length < (this.config.ID_pic_check || 0)) throw { route: 'profile', key: 'msgCards' }; // 2.檢查身份證 if (!this.userInfo.w) throw { route: 'withdrawalsPass', key: 'msgPassword' }; // 3.檢查取款密碼 const bankList = await this.GET_USER_BANK_LIST(); if (!bankList.length) throw { route: 'bankCard', key: 'msgBankCard' }; // 4.檢查銀行卡 this.checkLoading = false; } catch (e) { e.isError ? this.$router.go(-1) : this.routerPushWarning(e); } await this.GET_VIRTUAL_USDT(); await this.GET_WITHDRAWAL_CURRENCY_LIST(); // this.usdtHandler(); }, mounted() { this.SET_FULL_WIDTH(1); }, methods: { ...mapActions([ 'GET_USER_PROFILE', 'GET_USER_BANK_LIST', 'POST_WITHDRAWALS', 'PUT_SET_W_PASSWORD', 'GET_VIRTUAL_USDT', 'GET_WITHDRAWAL_CURRENCY_LIST', 'PATCH_VIRTUAL_USDT', 'SHOW_LIVE_CHAT', ]), ...mapMutations([ 'SET_CURRENT_MENU_TITLE', 'SET_MESSAGE', 'POST_WITHDRAWALS_STATUS', 'PUT_PASSWORD_STATUS', 'SET_FULL_WIDTH', 'ADD_WALLET_QRCODE', ]), routerPushWarning(error) { const msg = error.key; this.SET_MESSAGE({ message: this.textFilter('msg', { msg: this.textFilter(msg) }), type: 'warning' }); this.timerSaver = setTimeout(() => { this.$router.push(error.route); }, 1500); }, routerPush(path) { this.$router.push({ path }); }, changeStar(item) { return cardStarText(item.Card); }, async postWithdrawal() { if (this.withdraw < 100) { this.SET_MESSAGE({ message: this.textFilter('errorWithdrawLimit') }); return false; } if (!this.withdrawPass) { this.SET_MESSAGE({ message: this.textFilter('errorWithdrawPassNull') }); return false; } if (Number(this.withdraw) > this.balanceSum) { this.SET_MESSAGE({ message: this.textFilter('errorBalanceLimit') }); return false; } if (this.payId != 0) { this.select = this.bankCards[0]; } if (!this.select.Bank) { this.SET_MESSAGE({ message: this.textFilter('errorBankNull') }); return false; } const data = { Amount: parseFloat(this.withdraw), Bank: this.select.Bank, Branch: this.select.Branch, Card: this.select.Card.replace(/\s/gi, ''), Name: this.userProfileData.username, Password: this.withdrawPass, usdtAccount: this.usdtAccount, }; if (this.payId) { data.payName = this.pay.PayName; data.currency = this.pay.CurrencyCode; data.rate = this.pay.Drate; } try { await this.POST_WITHDRAWALS(data); } catch (err) { this.withdrawalError.text = err; this.withdrawalError.show = true; } }, // USDT 資訊處理 // usdtHandler() { // this.showUSDT = Boolean(this.virtualUsdtInfo.account); // if (this.showUSDT) this.usdtAccount = this.originalUsdtAccount = this.virtualUsdtInfo.account; // }, // // 更新 USDT 錢包地址 // updateUsdtAcc() { // if (this.showUSDT && !this.usdtAccount) { // this.SET_MESSAGE({ message: this.textFilter('errorUsdtAccountNull') }); // return false; // } // this.editUsdtAcc = false; // this.PATCH_VIRTUAL_USDT({ account: this.usdtAccount }); // }, // // 復原 USDT 錢包地址為初始值 // resetUsdtAcc() { // this.usdtAccount = this.virtualUsdtInfo.account; // }, textFilter(text, slot) { return slot ? textFilter(text, 'layout_userCentre_default_withdrawals_', slot) : textFilter(text, 'layout_userCentre_default_withdrawals_'); }, highlight(text) { return `<i class="green--text lighten-1 title">${text}</i>`; }, cardStarText, onDecode(content) { if (content) { this.ADD_WALLET_QRCODE(content); this.$refs.qrInput.$el.value = ''; } else { this.SET_MESSAGE({ message: this.textFilter('msg', { msg: this.textFilter('errorUsdtAccountNull') }), type: 'warning' }); } }, qrError(error) { // console.log(error); this.$store.commit('MsgError', '格式错误'); }, }, beforeDestroy() { clearTimeout(this.timerSaver); }, }; </script> <style lang="scss" scoped> .clip { color: transparent !important; border-radius: 0 !important; mask: url(./assets/icon/clip.png) no-repeat left center/auto 80%; width: 1.4em; } ::v-deep { .v-input input, .v-input textarea { color: inherit; align-self: stretch; max-height: 100%; } } </style>
<!doctype html> <html lang="en"> <head> <style> div{ } </style> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <nav class="navbar navbar-dark bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Navbar</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <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="#">Features</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Dropdown link </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <li><a class="dropdown-item" href="#">Action</a></li> <li><a class="dropdown-item" href="#">Another action</a></li> <li><a class="dropdown-item" href="#">Something else here</a></li> </ul> </li> </ul> </div> </div> </nav> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <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="https://cdn.pixabay.com/photo/2015/07/28/22/01/office-865091__340.jpg" style="width:200px;" height="600px;" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h3 style="color:black">Welcome To Bhise shop</h3> <h4 style="color:green">Here You get Top Products .</h4> </div> </div> <div class="carousel-item"> <img src="https://cdn.pixabay.com/photo/2014/09/24/14/29/macbook-459196__340.jpg" style="width:200px;" height="600px;" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h3 style="color:black">Shop Online Smartly</h5> <h4 style="color:green">We Suggests You Top Products From Amazon, Flipkart.</h4> </div> </div> <div class="carousel-item"> <img src="https://cdn.pixabay.com/photo/2016/04/04/14/12/monitor-1307227__340.jpg" style="width:200px;" height="600px;" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h3 style="color:white">Shop Online Best Products</h5> <h4 style="color:goldenrod">All Types of Products.</h4> </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="row mb-2"> <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-primary">World</strong> <h3 class="mb-0">Top 5 Smart watches</h3> <div class="mb-1 text-muted">Nov 12</div> <p class="card-text mb-auto">In This Post You Will Know about Top 5 Smart watches Which maybe In your Budget.</p> <a href="newpost.html" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img class="bd-placeholder-img" width="200" height="250" src="watch3.jpg" alt="ring imge"> </div> </div> </div> <div class="col-md-6"> <div class="row g-0 border rounded overflow-hidden flex-md-row mb-4 shadow-sm h-md-250 position-relative"> <div class="col p-4 d-flex flex-column position-static"> <strong class="d-inline-block mb-2 text-success">Design</strong> <h3 class="mb-0">Top 5 Rings For Girls</h3> <div class="mb-1 text-muted">Nov 11</div> <p class="mb-auto">In This post You Will see top 5 Rigns for girls which are in budget but amazing.</p> <a href="2nd.html" class="stretched-link">Continue reading</a> </div> <div class="col-auto d-none d-lg-block"> <img class="bd-placeholder-img" width="200" height="250" src="ring2.jpg" alt="ring imge"> </div> </div> </div> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: Bootstrap Bundle with Popper --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> <!-- Option 2: Separate Popper and Bootstrap JS --> <!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> --> </body> </html>
import React from 'react'; import {Link, useHistory} from 'react-router-dom'; import '../App.css'; import {connect} from 'react-redux'; const NavBar = (props) => { const history = useHistory(); const renderList = () => { if(props.user){ return [ <li key="feature"><Link to="/features">Features</Link></li>, <li key="logout" className="logoutbtn" onClick={()=>{ localStorage.clear(); props.clearUser(); history.push('/'); }}>Logout</li> ] }else{ return [ <li key="feature"><Link to="/features">Features</Link></li>, <li key="login"><Link to="/login">Login</Link></li>, <li key="signup"><Link to="/signup">Signup</Link></li> ] } } return( <div className="navbar"> <div className="container"> <nav> <h1 className="logo"><Link to="/">linkminify</Link></h1> <ul className="links"> {renderList()} </ul> </nav> </div> </div> ) } const mapStateToProps = (state) => { return { user: state.user } } const mapDispatchToProps = (dispatch) => { return { clearUser: () => { dispatch({type: "CLEAR_USER"}) } } } export default connect(mapStateToProps, mapDispatchToProps)(NavBar);
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import { Profile } from '@/entity/Profile'; import { ProfileSchema } from '../../model/types/editorProfileSchema'; import { fetchProfileData } from '../services/fetchProfileData/fetchProfileData'; import { updateProfileData } from '../services/updateProfileData/updateProfileData'; const initialState: ProfileSchema = { data: undefined, form: undefined, isLoading: true, readonly: true, error: undefined, }; export const editorProfileSlice = createSlice({ name: 'editorProfile', initialState, reducers: { setReadonly: (state, action: PayloadAction<boolean>) => { state.readonly = action.payload; }, setDataForm: (state, action: PayloadAction<Profile>) => { state.form = { ...state.form, ...action.payload, }; }, setCancelEdit: state => { state.readonly = true; state.validateForm = undefined; state.form = state.data; }, }, extraReducers: builder => { builder.addCase(fetchProfileData.pending, state => { state.error = undefined; state.isLoading = true; }); builder.addCase(fetchProfileData.rejected, (state, actions) => { state.isLoading = false; state.error = actions.payload; }); builder.addCase(fetchProfileData.fulfilled, (state, action) => { state.isLoading = false; state.data = action.payload; state.form = state.data; }); builder.addCase(updateProfileData.pending, state => { state.validateForm = undefined; state.error = undefined; state.isLoading = true; }); builder.addCase(updateProfileData.rejected, (state, actions) => { state.isLoading = false; state.validateForm = actions.payload; }); builder.addCase(updateProfileData.fulfilled, (state, action) => { state.isLoading = false; state.data = action.payload; state.readonly = true; }); }, }); export const { actions: editorProfileActions } = editorProfileSlice; export const { reducer: editorProfileReducer } = editorProfileSlice;
import React from "react"; import { connect } from "react-redux"; import { firestoreConnect } from "react-redux-firebase"; import { compose } from "redux"; import { Redirect } from "react-router-dom"; import Spinner from "../../UI/Spinner/Spinner"; import moment from "moment"; const ProjectDetails = props => { if (!props.auth.uid) { return <Redirect to="/signin" />; } console.log(props); if (props.project) { return ( <div className="container section project-details"> <div className="card z-depth-o" style={{ borderRadius: "15px" }}> <div className="card-content"> <span className="card-title">{props.project.title}</span> <p>{props.project.content}</p> </div> <div style={{ borderBottomRightRadius: "15px", borderBottomLeftRadius: "15px" }} className="card-action grey lighten-4 grey-text" > <div> Posted by {props.project.authorFirstName}{" "} {props.project.authorLastName} </div> <div>{moment(props.project.createdAt.toDate()).calendar()}</div> </div> </div> </div> ); } else { return ( <div className="container center"> <Spinner /> </div> ); } }; const mapStateToProps = (state, ownProps) => { const id = ownProps.match.params.id; const projects = state.firestore.ordered.projects; const project = projects ? projects.filter(el => id === el.id)[0] : null; return { project, auth: state.firebase.auth }; }; export default compose( firestoreConnect(["projects"]), connect(mapStateToProps) )(ProjectDetails);
import React, { forwardRef } from "react"; import projects from "/src/data/projects"; import ProjectsListItem from "/src/components/ProjectsListItem"; // Forward ref to be used in HomePage component const RecentProjects = forwardRef((props, ref) => { const { ...propsRest } = props; // Reverse array's order to list the last "projectsLimit" projects const projectsLimit = 3; const lastProjects = [...projects].slice(projectsLimit * -1).reverse(); return ( <section ref={ref} id="projects-section" className="bg-light-secondary" {...propsRest} > <div className="container section-stack-sm"> <h2>Mes projets récents</h2> {lastProjects.map((project, index) => ( <ProjectsListItem key={index} project={project} className={`project-${index % 2 == 0 ? "left" : "right"}`} /> ))} </div> </section> ); }); export default RecentProjects;
package com.example.fittracker.service; import com.example.fittracker.exception.ResourceNotFoundException; import com.example.fittracker.model.User; import com.example.fittracker.repository.UserFriendsRepository; import com.example.fittracker.repository.UserRepository; import org.hibernate.annotations.Cache; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; @Autowired private UserFriendsRepository userFriendsRepository; public List<User> getAllUsers() { return userRepository.findAll(); } public User saveUser(User user) { return userRepository.save(user); } public User getUserById(Long id) { return userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User", "id", id)); } public User updateUser(Long id, User userDetails) { User user = getUserById(id); user.setFirstName(userDetails.getFirstName()); user.setLastName(userDetails.getLastName()); user.setUsername(userDetails.getUsername()); user.setPassword(userDetails.getPassword()); user.setEmail(userDetails.getEmail()); user.setGender(userDetails.getGender()); user.setBirthday(userDetails.getBirthday()); user.setCity(userDetails.getCity()); user.setCountry(userDetails.getCountry()); user.setWeight(userDetails.getWeight()); user.setHeight(userDetails.getHeight()); user.setImage(userDetails.getImage()); return userRepository.save(user); } public void deleteUser(Long id) { User user = userRepository.findById(id) .orElseThrow(() -> new ResourceNotFoundException("User", "id", id)); userRepository.delete(user); } public List<User> searchFriends(String query) { return userRepository.findByUsernameContainingIgnoreCaseOrLastNameContainingIgnoreCaseOrFirstNameContainingIgnoreCase(query, query, query); } @Transactional @Cacheable("sendFriendRequest") public boolean sendFriendRequest(Long userId, Long friendId) { Optional<User> userOptional = userRepository.findById(userId); Optional<User> friendOptional = userRepository.findById(friendId); if (userOptional.isPresent() && friendOptional.isPresent()) { User user = userOptional.get(); User friend = friendOptional.get(); user.getFriends().add(friend); userRepository.save(user); return true; } else { return false; } } // @Transactional // public void confirmFriendRequest(Long userId, Long friendId) { // User user = userRepository.findById(userId) // .orElseThrow(() -> new IllegalArgumentException("Invalid user ID")); // User friend = userRepository.findById(friendId) // .orElseThrow(() -> new IllegalArgumentException("Invalid friend ID")); // // if (user.getFriends().contains(friend) && friend.getFriends().contains(user)) { // user.getFriends().remove(friend); // // Additional logic or actions for confirming friend request // } else { // throw new IllegalArgumentException("Friend request does not exist"); // } // } }
import { extendType, inputObjectType, intArg } from 'nexus' import { Context } from '../../../context' import { findManyFinanceDebt, debtCount } from '../finance' import { FindManyAccountDebtResponse } from '../nexus-type' export const FinanceWhereInput = inputObjectType({ name: 'FinanceWhereInput', definition(t) { t.string('searchTerm') t.field('startDate', { type: 'DateTime' }) t.field('endDate', { type: 'DateTime' }) t.int('locationId') t.int('issuingCompanyId') }, }) export const AccountDebtQuery = extendType({ type: 'Query', definition(t) { t.list.field('findManyAccountDebt', { type: FindManyAccountDebtResponse, description: 'Retrieve list of account debt based on company and location', args: { where: 'FinanceWhereInput', skip: intArg(), take: intArg(), }, async resolve(_root, input, ctx: Context) { try { return findManyFinanceDebt(ctx, input.where, input.skip, input.take) } catch (error) { return error } }, }) t.field('accountDebtCount', { type: 'Int', args: { where: 'FinanceWhereInput', }, description: 'Retrieve total count of account debt based on company and location', async resolve(_root, input, ctx: Context) { try { const data = await debtCount(ctx, input.where) return data.length } catch (error) { return error } }, }) }, })
@regression @employeeProposal Feature: Testing Proposals Functionality Background: Given Navigate to CRM url When User enters correct employee email and password And Click "Sales" Module from left side navigation menu And User clicks "Proposals" module @newProposal Scenario: Create New Proposal for a customer When Click New Proposal button from top And User fills new proposal info with: | subject | related | customer | customerName | project | projectName | | Alex_Proposal_Test_TC5 | Customer | Apple | Apple LLC | Apple | #1 - Apple Project - Apple LLC | And User clicks Add Item button and selects items from drop down list and clicks blue check button: | item1 | item2 | quantity | | (253.00) Asus Monitor | (10.00) Ethernet Cable | 2 | Then User verifies that Total is "$300.30" and clicks Save & Send button And User finds created Proposal by clicking "Sales", "Proposals" and verify that its status is "Sent" Scenario: Clear New Proposal Data Then User deletes the created proposal "Alex_Proposal_Test_TC5"
import {Component, OnInit} from '@angular/core'; import {NgClass} from "@angular/common"; @Component({ selector: 'app-ex03', standalone: true, imports: [ NgClass ], template: ` <h1>Exercice 3</h1> <p [ngClass]="getClass()">Random between 1 and 10: {{ n }}</p> `, styles: ` .fail {color: red;} .pass {color: green;} .perfect {color: blue;} ` }) export class Ex03Component implements OnInit { n: number = 0; constructor() { } ngOnInit(): void { this.n = Math.floor(Math.random() * 10 + 1); } getClass() { if (this.n < 5) { return 'fail'; } else if (this.n === 10) { return 'perfect'; } else { return 'pass'; } } }
#include <WiFi.h> #include <BlynkSimpleEsp32.h> #include <DHT.h> #include "MQ7.h" #include "SDS011.h" #define BLYNK_TEMPLATE_ID "TMPLTtUw3aPb" #define BLYNK_TEMPLATE_NAME "Living Sane" #define BLYNK_AUTH_TOKEN "Le1pNdDBrs0jBm2qL3VKWulK3QBCF7ix" #define DHTPIN 15 // Digital pin connected to the DHT sensor #define DHTTYPE DHT22 // DHT22 #define A_PIN 12 #define VOLTAGE 5 DHT dht(DHTPIN, DHTTYPE); MQ7 mq7(A_PIN, VOLTAGE); SDS011 my_sds; #ifdef ESP32 HardwareSerial port(2); #endif // #define BLYNK_TEMPLATE_ID "TMPLgMPdeKM9" // #define BLYNK_TEMPLATE_NAME "Living sane" #define BLYNK_AUTH_TOKEN "38YW7uNne98RK9y42zLXh9Vf8CpmMegp" // char auth[] = "Le1pNdDBrs0jBm2qL3VKWulK3QBCF7ix"; // Your Blynk project authentication token char auth[] = "38YW7uNne98RK9y42zLXh9Vf8CpmMegp"; // Your Blynk project authentication token char ssid[] = "Rishabh C9pro"; // Your WiFi SSID char pass[] = "testing@123"; // Your WiFi password float p10, p25; int err; void setup() { Blynk.begin(auth, ssid, pass); my_sds.begin(&port); Serial.begin(115200); dht.begin(); mq7.calibrate(); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("Searching for wifi..."); } Serial.print("Connected to "); Serial.println(ssid); } void loop() { float h = dht.readHumidity(); float t = dht.readTemperature(); if (isnan(h) || isnan(t)) { Serial.println("Failed to read from DHT sensor!"); return; } Serial.print("Humidity: "); Serial.print(h); Serial.print("% Temperature: "); Serial.print(t); Serial.println("°C"); //PM sensor, SDS011 err = my_sds.read(&p25, &p10); Serial.println("P2.5: " + String(p25)); Serial.println("P10: " + String(p10)); //CO sensor Serial.print("CO PPM = "); Serial.println(mq7.readPpm()); Serial.println(""); // blank new line Blynk.virtualWrite(0, h); // Send humidity data to Virtual Pin 5 Blynk.virtualWrite(1, t); // Send temperature data to Virtual Pin 6 Blynk.virtualWrite(2, p25); // Send PM2.5 data to Virtual Pin 5 Blynk.virtualWrite(3, p10); // Send PM10 data to Virtual Pin 6 delay(1000); }
'use strict'; //引入 vue import Vue from 'vue' //引入App.vue import App from './app.vue'; import Accessible from './components/ol/Accessible.vue'; import Animation from './components/ol/Animation.vue'; import XYZ from './components/ol/XYZ.vue'; import ArcgisImage from './components/ol/ArcgisImage.vue'; import geoJson from './components/ol/LoadGeoJson.vue'; import ArcgisTiled from './components/ol/ArcgisTiled.vue'; import VectorDemo from './components/ol/VectorDemo.vue'; import DrawFeatures from './components/ol/DrawFeatures.vue'; import WebGLDemo from './components/ol/WebGLDemo.vue'; import LayerSort from './components/ol/LayerSort.vue'; import LOD from './components/ol/LOD.vue'; //路由 import VueRouter from 'vue-router'; //安装插件 Vue.use(VueRouter); import ElementUI from 'element-ui'; import 'element-ui/lib/theme-chalk/index.css'; Vue.use(ElementUI); //自己公共样式 import './static/css/global.css'; //axios import Axios from 'axios'; //默认请求配置 //Axios.default.baseURL=""; //挂载原型 Vue.prototype.$ajax = Axios; //路由规则 let router = new VueRouter({ routes: [ {name:'openLayers',CNName:'openLayers 地图',path: '/',elIndx:'1', children:[ { name: 'accessible', CNName: 'Accessible', path: 'accessible', component: Accessible }, { name: 'Animation', CNName: '移动地图', path: '/animation', component: Animation }, { name: 'ArcgisImage', CNName: 'ArcgisImage', path: '/arcgis-image', component: ArcgisImage }, { name: 'ArcgisTiled', CNName: 'ArcgisTiled', path: '/arcgis-tiled', component: ArcgisTiled }, { name: 'XYZ', CNName: '万能图', path: '/xyz', component: XYZ }, { name: 'geoJson', CNName: '加载geoJson', path: '/geoJson', component: geoJson }, { name: 'VectorDemo', CNName: '矢量地图', path: '/vectorDemo', component: VectorDemo }, { name: 'DrawFeatures', CNName: '绘制地图', path: '/drawFeatures', component: DrawFeatures }, { name: 'WebGLDemo', CNName: 'WebGLDemo', path: '/webGLDemo', component: WebGLDemo }, { name: 'LayerSort', CNName: '图层叠加及管理', path: '/layerSort', component: LayerSort }, { name: 'LOD', CNName: 'LOD与分辨率', path: '/LOD', component: LOD } ] } ] }) //创建vue实例 //构建示例 new Vue({ el: '#app', router, render: c => c(App) })
<html> <head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type" /> </head> <body> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4bw+/aepP/YC94hEpVNVgiZdgIC5+VKNBQNGCHeKRQN+PtmoHDEXuppvnDJzQIu9" crossorigin="anonymous" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-HwwvtgBNo3bZJJLYd8oVXjrBZt8cqVSpeBNS5n7C8IVInixGAoxmnlMuBnhbgrkm" crossorigin="anonymous" ></script> <script type="module"> import { collectEvidence, canIUseWebAuthn } from "./canIUse.js"; const evidence = await collectEvidence(); const platform = evidence.userAgent.platform; const browser = evidence.userAgent.browser; const response = await canIUseWebAuthn(platform, browser); let responseText; let tryItOutText; if (response) { responseText = "Yes! You can use WebAuthn."; tryItOutText = "Try it out"; } else { responseText = "No! You have to use SubtleCrypto."; tryItOutText = "Try it out anyways"; } document.getElementById("response").innerText = responseText; document.getElementById("tryItOut").innerText = tryItOutText; document.getElementById("evidence").innerText = JSON.stringify( evidence, null, 2 ); </script> <script type="application/javascript"> function webauthnTest() { const challenge = new Uint32Array(10); const id = new Uint32Array(10); self.crypto.getRandomValues(challenge); const publicKeyCredentialCreationOptions = { challenge: challenge, rp: { name: "Beyond Identity, Inc.", }, user: { id: id, name: "bob@beyondidentity.com", displayName: "Bob", }, pubKeyCredParams: [{ alg: -7, type: "public-key" }], authenticatorSelection: { authenticatorAttachment: "platform", }, timeout: 60000, attestation: "direct", }; console.log("Registering with ", publicKeyCredentialCreationOptions); navigator.credentials .create({ publicKey: publicKeyCredentialCreationOptions, }) .then((cred) => { alert("It works!"); }) .catch((err) => { alert(`It doesn't work.\n${err.message}`); }); } </script> <div class="container col-xl-10 col-xxl-8 px-4 py-5"> <div class="row align-items-center g-lg-5 py-5"> <div class="col-lg-7 text-center text-lg-start"> <h1 class="display-4 fw-bold lh-1 text-body-emphasis mb-3"> Can I Use WebAuthn? </h1> <div class="col-md-10 mx-auto col-lg-5 border rounded-3 bg-body-tertiary" > <h1 class="py-2" id="response"></h1> <div class="text-center"> <button type="button" class="btn btn-primary" id="tryItOut" onclick="webauthnTest()" > Try it out </button> </div> <div class="text-start"> <h3 class="mx-2">Supporting evidence</h3> <pre class="border rounded-2 bg-dark-subtle mx-3 my-2" id="evidence" ></pre> </div> </div> </div> <!-- <div class="col-md-10 mx-auto col-lg-5"> <form class="p-4 p-md-5 border rounded-3 bg-body-tertiary"> <p class="text-center">No!</p> <div class="form-floating mb-3"> <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com" /> <label for="floatingInput">Email address</label> </div> <div class="form-floating mb-3"> <input type="password" class="form-control" id="floatingPassword" placeholder="Password" /> <label for="floatingPassword">Password</label> </div> <button class="w-100 btn btn-lg btn-primary" type="submit"> Submit Results </button> <hr class="my-4" /> </form> </div> --> </div> </div> </body> </html>
<!doctype html> <html class="no-js" lang="{{ request.locale.iso_code }}"> <head> <link rel="preload" href="https://cdn.shopify.com/s/files/1/0729/7938/2564/files/white-bg_460x.png?v=1689839554" as="image"> {% if template == 'index' %} <link rel="preload" href="https://zildjian.com/cdn/shop/files/Zildjian_Website_Horizontal_1.jpg?v=1691155350&width=1500" as="image"> {% elsif template contains 'collection' %} {% assign image = collection.metafields.global.header_banner_image | default: collection.image %} <link rel="preload" href="{{image | image_url: width: 2048}}" as="image"> {% elsif template contains 'product' %} {% assign image = product.selected_variant.featured_image | default: product.featured_image %} <link rel="preload" href="{{image | image_url: width: 823}}" as="image"> {% endif %} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta name="theme-color" content=""> <link rel="canonical" href="{{ canonical_url }}"> <link rel="preconnect" href="https://cdn.shopify.com" crossorigin> <link rel="preload" href="https://ui.powerreviews.com/stable/4.1/ui.js" as="script"> {%- if settings.favicon != blank -%} <link rel="icon" type="image/png" href="{{ settings.favicon | image_url: width: 32, height: 32 }}"> {%- endif -%} {%- unless settings.type_header_font.system? and settings.type_body_font.system? -%} <link rel="preconnect" href="https://fonts.shopifycdn.com" crossorigin> {%- endunless -%} <title> {{ page_title }} {%- if current_tags %} &ndash; tagged "{{ current_tags | join: ', ' }}"{% endif -%} {%- if current_page != 1 %} &ndash; Page {{ current_page }}{% endif -%} {%- unless page_title contains shop.name %} &ndash; {{ shop.name }}{% endunless -%} </title> {% if page_description %} <meta name="description" content="{{ page_description | escape }}"> {% endif %} {% render 'meta-tags' %} <script async="" src="https://www.googletagmanager.com/gtm.js?id=GTM-KZCNM2V"></script> <!-- Google tag (gtag.js) --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-152752418-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-152752418-1'); </script> <!-- Facebook tracking code. --> <script> !function(f,b,e,v,n,t,s) {if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)}; if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0'; n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t,s)}(window,document,'script', 'https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '1789827234600651'); fbq('track', 'PageView'); </script> <script defer src="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js"></script> <link rel="preload" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css" as="style" onload="this.onload=null;this.rel='stylesheet'"> <noscript> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css"> </noscript> <link rel="preload" href="{{'tagalys-customisations.css' | asset_url}}" as="style" onload="this.onload=null;this.rel='stylesheet'"> <noscript> <link rel="stylesheet" href="{{'tagalys-customisations.css' | asset_url}}"> </noscript> <script src="{{ 'constants.js' | asset_url }}" defer="defer"></script> <script src="{{ 'pubsub.js' | asset_url }}" defer="defer"></script> <script src="{{ 'global.min.js' | asset_url }}" defer="defer"></script> <script src="{{ 'custom.js' | asset_url }}" defer="defer"></script> {% assign content_for_header = content_for_header | replace: "const previewBarInjector", "let ticking = false;addEventListener('scroll', (event) => {if (!ticking) {ticking = true;const previewBarInjector" | replace: 'previewBarInjector.init();', 'previewBarInjector.init();}});' %} {{ content_for_header }} {%- liquid assign body_font_bold = settings.type_body_font | font_modify: 'weight', '700' assign body_font_italic = settings.type_body_font | font_modify: 'style', 'italic' assign body_font_bold_italic = body_font_bold | font_modify: 'style', 'italic' %} {% include 'base_style' %} {%- unless settings.type_body_font.system? -%} <link rel="preload" as="font" href="{{ settings.type_body_font | font_url }}" type="font/woff2" crossorigin> {%- endunless -%} {%- unless settings.type_header_font.system? -%} <link rel="preload" as="font" href="{{ settings.type_header_font | font_url }}" type="font/woff2" crossorigin> {%- endunless -%} {%- if settings.predictive_search_enabled -%} <link rel="stylesheet" href="{{ 'component-predictive-search.css' | asset_url }}" media="print" onload="this.media='all'"> {%- endif -%} <script>document.documentElement.className = document.documentElement.className.replace('no-js', 'js'); if (Shopify.designMode) { document.documentElement.classList.add('shopify-design-mode'); } </script> {% if template contains 'collection' %} <!--begin-boost-pfs-filter-css--> {% render 'boost-pfs-style' %} <!--end-boost-pfs-filter-css--> {% endif %} {{'custom-search.scss.css' | asset_url | stylesheet_tag }} <img width="2048" height="1024" style="position: absolute;height:auto;width:100%;max-height:100vh;" src="https://cdn.shopify.com/s/files/1/0729/7938/2564/files/white-bg_460x.png?v=1689839554"> </head> <body class="gradient {{ page.handle }} {{ article.title }} {{ blog.handle }} hide-price "> {{ 'tagalys-customisations.min.js' | asset_url | script_tag }} <script src="https://storage.googleapis.com/tagalys-front-end-components/tagalys-ui-widgets-1.3.3.min.js"></script> <a class="skip-to-content-link button visually-hidden" href="#MainContent"> {{ "accessibility.skip_to_text" | t }} </a> {%- if settings.cart_type == 'drawer' -%} {%- render 'cart-drawer' -%} {%- endif -%} {% sections 'header-group' %} <main id="MainContent" class="content-for-layout focus-none {{template}} {{template.suffix}}" role="main" tabindex="-1"> {% if template == 'cart' %} <div class="page-width {% if cart == empty %}empty-cart{% endif %} "> {{ content_for_layout }} </div> {% else %} {{ content_for_layout }} {% endif %} </main> {% sections 'footer-group' %} <ul hidden> <li id="a11y-refresh-page-message">{{ 'accessibility.refresh_page' | t }}</li> <li id="a11y-new-window-message">{{ 'accessibility.link_messages.new_window' | t }}</li> </ul> <script> window.shopUrl = '{{ request.origin }}'; window.routes = { cart_add_url: '{{ routes.cart_add_url }}', cart_change_url: '{{ routes.cart_change_url }}', cart_update_url: '{{ routes.cart_update_url }}', cart_url: '{{ routes.cart_url }}', predictive_search_url: '{{ routes.predictive_search_url }}' }; window.cartStrings = { error: `{{ 'sections.cart.cart_error' | t }}`, quantityError: `{{ 'sections.cart.cart_quantity_error_html' | t: quantity: '[quantity]' }}` } window.variantStrings = { addToCart: `{{ 'products.product.add_to_cart' | t }}`, soldOut: `{{ 'products.product.sold_out' | t }}`, unavailable: `{{ 'products.product.unavailable' | t }}`, unavailable_with_option: `{{ 'products.product.value_unavailable' | t: option_value: '[value]' }}`, } window.accessibilityStrings = { imageAvailable: `{{ 'products.product.media.image_available' | t: index: '[index]' }}`, shareSuccess: `{{ 'general.share.success_message' | t }}`, pauseSlideshow: `{{ 'sections.slideshow.pause_slideshow' | t }}`, playSlideshow: `{{ 'sections.slideshow.play_slideshow' | t }}`, } </script> <script> addEventListener('scroll', (event) => { var s = document.createElement('script'); var h = document.querySelector('head') || document.body; s.src = 'https://acsbapp.com/apps/app/dist/js/app.js'; s.async = true; s.onload = function(){ acsbJS.init({ statementLink : '', footerHtml : '', hideMobile : false, hideTrigger : false, disableBgProcess : false, language : 'en', position : 'right', leadColor : '#146FF8', triggerColor : '#146FF8', triggerRadius : '50%', triggerPositionX : 'right', triggerPositionY : 'bottom', triggerIcon : 'people', triggerSize : 'bottom', triggerOffsetX : 30, triggerOffsetY : 140, mobile : { triggerSize : 'small', triggerPositionX : 'left', triggerPositionY : 'bottom', triggerOffsetX : 30, triggerOffsetY : 30, triggerRadius : '20' } }); }; h.appendChild(s); }) </script> {% if template contains 'collection' %} <!--begin-boost-pfs-js--> {% render 'boost-pfs' %} <!--end-boost-pfs-js--> {% endif %} <script src="https://ui.powerreviews.com/stable/4.1/ui.js" defer></script> </body> </html>
# CALCULO NUMERICO # RAIZES DE NúMEROS REAIS # - METODO DA BISSECAO # # Versão 1.00 (2019) - 16.08.2019 # Autor: Prof. Giovanni Leopoldo Rozza (2019) # Os algorítmos aqui implementados estão descritos no capítulo 2 do livro: # # RUGGIERO, Márcia A. Gomes; LOPES, Vera Lúcia da Rocha. # Cálculo numérico: aspectos teóricos e computacionais. Makron Books do Brasil, 1997. # # chama a bibliteca ggplot2 (gráfico) [tem que instalar o package antes] library(ggplot2) # diretorio de trabalho setwd("G:/AULAS_ATUAL/Bagozzi/R_SOURCE/CALCULO_NUMERICO/CAP2_ZEROS_NR_REAIS") # loga console em arquivo sink("logconsole.txt", type = "output", append = FALSE, split = TRUE) # define a funcao que se deseja obter o valor de f(x) funcao_de_X <- function(dValorX) { dValor_fx <- dValorX^3 - 9*dValorX + 3 return(dValor_fx) } # define a funcao que se deseja-se obter o valor da derivada de f(x) funcao_Derivada_de_X <- function(dValorX) { dValor_fx <- 3*dValorX^2 - 9 return(dValor_fx) } # FUNCAO funcao_ZeroBissecao # # Parametros de Entradas # dValorAk --> valor inicial de a # dValorAk --> valor inicial de b # dValorErro --> valor maximo de erro (para de iterar se sero < dValorErro & iIter=NULL) # iIter=NULL --> se não for null, ignora dValorErro e itera at? iIter # # # Parametros de Saída # dataframe com o tipo de algo, erro, e ?ltimo valor de xk # funcao_ZeroBissecao <- function(dValorAk,dValorBk,dValorErro,iIter=NULL) { iTotalIteracoes <- 999 if(!is.null(iIter)) { iTotalIteracoes <- iIter } iConta<-1 # dataframe com ak, bk, xk e f(xk) dfBissecao<- data.frame( iCount<- integer(), dAk <-double(), dBk <-double(), dXk <-double(), dfXk <-double() ) dfAk<- funcao_de_X(dValorAk) dfBk<- funcao_de_X(dValorBk) dXk <- 0.5*(dValorAk + dValorBk) dfXk<- funcao_de_X(dXk) # linha do dataframe a ser inserida dfB_temp<-data.frame( iConta,dValorAk,dValorBk,dXk,dfXk) # renomeia colunas do dataframe para o bind com dfBissecao names(dfB_temp) <- c("iCount","dAk","dBk", "dXk","dfXk") dfBissecao <- rbind( dfBissecao, dfB_temp) # salva 1a iteracao no dataframe #imprime tabela print("|------------------------------------------------------------------------------------------------------------------------------------------|") print("| ZERO DE FUNCAO REAL - MÉTODO DA BISSEÇAO |") print("|------------------------------------------------------------------------------------------------------------------------------------------|") linha<- sprintf("| Intervalo [a,b] = [ % 12.8e, % 12.8e ] Erro Máximo = [ % 12.8e ] |",dValorAk,dValorBk,dValorErro) print(linha) print("|------------------------------------------------------------------------------------------------------------------------------------------|") print("| ak | bk | << xk >> | f(ak) | f(bk) | f(xk) | Erro |") print("|------------------------------------------------------------------------------------------------------------------------------------------|") linha<- sprintf("| % 12.8e | % 12.8e | % 12.8e | % 12.8e | % 12.8e | % 12.8e | % 12.8e |",dValorAk,dValorBk,dXk,dfAk,dfBk,dfXk,abs(dValorBk-dValorAk)) print(linha) print("|-------------------|-------------------|-------------------|-------------------|------------------|-------------------|-------------------|") while ( is.null(iIter) & ((abs(dValorBk-dValorAk) > dValorErro )) | ( !is.null(iIter) & (iConta < iTotalIteracoes) ) ) { iConta <- iConta + 1 if((dfAk > 0 & dfXk > 0) | (dfAk < 0 & dfXk < 0) ) { dValorAk <- dXk dfAk<- funcao_de_X(dValorAk) } if((dfBk > 0 & dfXk > 0) | (dfBk < 0 & dfXk < 0) ) { dValorBk <- dXk dfBk<- funcao_de_X(dValorBk) } dXk <- 0.5*(dValorAk + dValorBk) dfXk<- funcao_de_X(dXk) # linha do dataframe a ser inserida dfB_temp<-data.frame( iConta,dValorAk,dValorBk,dXk,dfXk) # renomeia colunas do dataframe para o bind com dfBissecao names(dfB_temp) <- c("iCount","dAk","dBk", "dXk","dfXk") dfBissecao <- rbind( dfBissecao, dfB_temp) # salva 1a iteracao no dataframe linha<- sprintf("| % 12.8e | % 12.8e | % 12.8e | % 12.8e | % 12.8e | % 12.8e | % 12.8e |",dValorAk,dValorBk,dXk,dfAk,dfBk,dfXk,abs(dValorAk-dValorBk)) print(linha) print("|-------------------|-------------------|-------------------|-------------------|------------------|-------------------|-------------------|") } # dataframe com ak, bk, xk e f(xk) dfComparaAlgos<- data.frame(cType <- character(), Itera <- integer(), dXk <-double(), dErro <-double() ) for(ik in seq_len(nrow(dfBissecao))) { df_temp<-data.frame( "Bisseccao",dfBissecao$iCount[ik] ,dfBissecao$dXk[ik], abs(dfBissecao$dAk[ik] - dfBissecao$dBk[ik]) ) # renomeia colunas do dataframe para o bind com dfPlot (tem que ter os mesmos nomes) names(df_temp) <- c("cType", "Itera","dXk", "dErro") dfComparaAlgos <- rbind( dfComparaAlgos, df_temp ) } return(dfComparaAlgos) } # FUNCAO funcao_ZeroNewtonRaphson # # Parametros de Entradas # dValorX --> valor inicial de x # dValorErro --> valor maximo de erro (para de iterar se sero < dValorErro & iIter=NULL) # iIter=NULL --> se n?o for null, ignora dValorErro e itera at? iIter # # # Parametros de Sa?da # dataframe com o tipo de algo, erro, e ?ltimo valor de xk # funcao_ZeroNewtonRaphson <- function(dValorX,dValorErro,iIter=NULL) { iTotalIteracoes <- 999 if(!is.null(iIter)) { iTotalIteracoes <- iIter } iConta<-1 # dataframe com xk e xk_1 dfNR<- data.frame( iCount<- integer(), dXk <-double(), dXk_1 <-double() ) dfXk<- funcao_de_X(dValorX) dDer_Xk<- funcao_Derivada_de_X(dValorX) dValorXk_1 <- dValorX - (dfXk/dDer_Xk) # linha do dataframe a ser inserida dfNR_temp<-data.frame( iConta,dValorX,dValorXk_1 ) # renomeia colunas do dataframe para o bind com dfBissecao names(dfNR_temp) <- c("iCount","dXk","dXk_1") dfNR <- rbind( dfNR, dfNR_temp) # salva 1a iteracao no dataframe #imprime tabela print("|-----------------------------------------------------------|") print("| ZERO DE FUNCAO REAL - MÉTODO DE NEWTON RAPHSON |") print("|-----------------------------------------------------------|") linha<- sprintf("| Xk = [ % 12.8e ] Erro Máx. = [ % 12.8e ] |",dValorX, dValorErro) print(linha) print("|-----------------------------------------------------------|") print("| xk | <<xk_1>> | Erro | |") print("|-----------------------------------------------------------|") linha<- sprintf("| % 12.8e | % 12.8e | % 12.8e |",dValorX,dValorXk_1,abs(dValorX-dValorXk_1)) print(linha) print("|-------------------|-------------------|-------------------|") while ( is.null(iIter) & ((abs(dValorX-dValorXk_1) > dValorErro )) | ( !is.null(iIter) & (iConta < iTotalIteracoes) ) ) { iConta <- iConta + 1 dValorX <- dValorXk_1 dfXk<- funcao_de_X(dValorX) dDer_Xk<- funcao_Derivada_de_X(dValorX) dValorXk_1 <- dValorX - (dfXk/dDer_Xk) # linha do dataframe a ser inserida dfNR_temp<-data.frame( iConta,dValorX,dValorXk_1 ) # renomeia colunas do dataframe para o bind com dfBissecao names(dfNR_temp) <- c("iCount","dXk","dXk_1") dfNR <- rbind( dfNR, dfNR_temp) # salva 1a iteracao no dataframe linha<- sprintf("| % 12.8e | % 12.8e | % 12.8e |",dValorX,dValorXk_1,abs(dValorX-dValorXk_1)) print(linha) print("|-------------------|-------------------|-------------------|") } # dataframe com dados do algoritmo dfComparaAlgos<- data.frame(cType <- character(), Itera <- integer(), dXk <-double(), dErro <-double() ) for(ik in seq_len(nrow(dfNR))) { df_temp<-data.frame( "Newton Raphson",dfNR$iCount[ik],dfNR$dXk[ik], abs(dfNR$dXk[ik] - dfNR$dXk_1[ik]) ) # renomeia colunas do dataframe para o bind com dfPlot (tem que ter os mesmos nomes) names(df_temp) <- c("cType", "Itera","dXk", "dErro") dfComparaAlgos <- rbind( dfComparaAlgos, df_temp ) } return(dfComparaAlgos) } # FUNCAO funcao_ZeroSecante # # Parametros de Entradas # dValorXk_m1 --> valor inicial de x0 # dValorXk_0 --> valor inicial de x1 # dValorErro --> valor maximo de erro (para de iterar se sero < dValorErro & iIter=NULL) # iIter=NULL --> se não for null, ignora dValorErro e itera até iIter # # # Parametros de Saída # dataframe com o tipo de algo, erro, e último valor de xk # funcao_ZeroSecante <- function(dValorXk_m1,dValorXk_0,dValorErro,iIter=NULL) { iTotalIteracoes <- 999 if(!is.null(iIter)) { iTotalIteracoes <- iIter } iConta<-1 # dataframe com xk e xk_1 dfSecante<- data.frame( iCount<- integer(), dXk_m1 <-double(), dXk_0 <-double(), dXk_1 <-double() ) # calcula 1a iteracao dfXk_m1<- funcao_de_X(dValorXk_m1) dfXfk_0<- funcao_de_X(dValorXk_0) dValorXk_1 <- ( (dValorXk_m1)*dfXfk_0 - ( dValorXk_0*dfXk_m1 ) )/(dfXfk_0 - dfXk_m1 ) # linha do dataframe a ser inserida dfSec_temp<-data.frame( iConta,dValorXk_m1,dValorXk_0,dValorXk_1 ) # renomeia colunas do dataframe para o bind com dfBissecao names(dfSec_temp) <- c("iCount","dXk_m1","dXk_0","dXk_1") dfSecante <- rbind( dfSecante, dfSec_temp) # salva 1a iteracao no dataframe #imprime tabela print("|-------------------------------------------------------------------------------|") print("| ZERO DE FUNCAO REAL - MÉTODO DA SECANTE |") print("|-------------------------------------------------------------------------------|") linha<- sprintf("| [xo,x1] = [ % 12.8e, % 12.8e ] Erro Máx. = [ % 12.8e ]|",dValorXk_m1,dValorXk_0,dValorErro) print(linha) print("|-------------------------------------------------------------------------------|") print("| xk-1 | xk | <<xk+1>> | Erro |") print("|-------------------------------------------------------------------------------|") linha<- sprintf("| % 12.8e | % 12.8e | % 12.8e | % 12.8e |",dValorXk_m1,dValorXk_0,dValorXk_1,abs(dValorXk_0 - dValorXk_1)) print(linha) print("|-------------------|-------------------|-------------------|-------------------|") while ( is.null(iIter) & ((abs(dValorXk_0 - dValorXk_1) > dValorErro )) | ( !is.null(iIter) & (iConta < iTotalIteracoes) ) ) { iConta <- iConta + 1 # atualiza valores dValorXk_m1 <- dValorXk_0 dValorXk_0 <- dValorXk_1 dfXk_m1<- funcao_de_X(dValorXk_m1) dfXfk_0<- funcao_de_X(dValorXk_0) dValorXk_1 = ( (dValorXk_m1)*dfXfk_0 - ( dValorXk_0*dfXk_m1 ) )/(dfXfk_0 - dfXk_m1 ) # se diferen?a muito pequena, f(xk_0) - f(Xk_m1) -->0 e valor tende a Inf if(is.nan(dValorXk_1)) { dValorXk_1<-dValorXk_0 } # linha do dataframe a ser inserida dfSec_temp<-data.frame( iConta,dValorXk_m1,dValorXk_0,dValorXk_1 ) # renomeia colunas do dataframe para o bind com dfBissecao names(dfSec_temp) <- c("iCount","dXk_m1","dXk_0","dXk_1") dfSecante <- rbind( dfSecante, dfSec_temp) # salva 1a iteracao no dataframe linha<- sprintf("| % 12.8e | % 12.8e | % 12.8e | % 12.8e |",dValorXk_m1,dValorXk_0,dValorXk_1,abs(dValorXk_0 - dValorXk_1)) print(linha) print("|-------------------|-------------------|-------------------|-------------------|") } # dataframe com dados do algoritmo dfComparaAlgos<- data.frame(cType <- character(), Itera <- integer(), dXk <-double(), dErro <-double() ) for(ik in seq_len(nrow(dfSecante))) { df_temp<-data.frame( "Secante",dfSecante$iCount[ik],dfSecante$dXk_1[ik], abs(dfSecante$dXk_0[ik] - dfSecante$dXk_1[ik]) ) # renomeia colunas do dataframe para o bind com dfPlot (tem que ter os mesmos nomes) names(df_temp) <- c("cType", "Itera","dXk", "dErro") dfComparaAlgos <- rbind( dfComparaAlgos, df_temp ) } return(dfComparaAlgos) } ########### #TODOS ########### ITERACOES<-18 # define o nr de iteracoes desejadas ERRO<-0.01 # define erro max (SE ITERACOES DIFERENTE DE NULL, IGNORA ESSE PARAMETRO) ########### #BISSECCAO ########### VALOR_A <- 1 VALOR_B <- 2 ################ #NEWTON RAPHSON ################ NR_Xo<-1.5 ################ #SECANTE ################ Sec_Xo <- 3 Sec_X1 <- 4 # monta dataframe com resultados das execucoes dfResultados <- funcao_ZeroNewtonRaphson(NR_Xo,ERRO,ITERACOES) dfResultados <- rbind( dfResultados, funcao_ZeroSecante(Sec_Xo,Sec_X1,ERRO,ITERACOES) ) dfResultados <- rbind( dfResultados, funcao_ZeroBissecao(VALOR_A,VALOR_B,ERRO,ITERACOES)) #converte cType em factor (gr?fico multiplas linhas) dfResultados$cType<-factor(dfResultados$cType) #require(ggplot2) ja chamei a lib no comeco do codigo # imprime resultados no mesmo gr?fico ggplot(dfResultados,aes(y=dErro, x=Itera, colour=cType,group=cType)) +ggtitle("Comparação Algos - Zero Função Real") + geom_line() + geom_point()+ ylab("Erro") + xlab("Iteração") + labs(color = "Algoritmo") + scale_x_continuous(breaks = seq_len(ITERACOES)) # retorna console sink(NULL, type = "output")
Problem Statement Given a matrix of N*N dimensions (Mat). Print the matrix rotated by 90 degrees and 180 degrees. Input The first line contains N. N lines follow each containing N space-separated integers. Constraints 2 <= N <= 100 1 <= Mat[i][j] <= 10000 Output Output 2*N+1 lines. First N lines should contain the Matrix rotated by 90 degrees. Then print a blank line. Then N lines should contain the Matrix rotated by 180 degrees. Example Sample Input 1: 2 3 4 7 6 Sample Output 1: 7 3 6 4 6 7 4 3 Sample Input 2: 2 1 2 3 4 Sample Output 2: 3 1 4 2 4 3 2 1 import java.io.*; // for handling input/output import java.util.*; // contains Collections framework // don't change the name of this class // you can add inner classes if needed class Main { public static void main (String[] args) { // Your code here Scanner inputTaker = new Scanner(System.in); int n = inputTaker.nextInt(); int[][] arr = new int[n][n]; for(int i =0; i<n; i++){ for(int j =0; j<n; j++){ arr[i][j] = inputTaker.nextInt(); } } //90 degree rotate rotateMatrix(arr, n); printMatrix(arr, n); System.out.println(""); //again 90 degree rotate, hence 180 degree in total rotateMatrix(arr, n); printMatrix(arr, n); } public static void printMatrix(int[][] arr, int n){ for(int i =0; i<n; i++){ for(int j =0; j<n; j++){ System.out.print(arr[i][j] + " "); } System.out.println(""); } } public static void rotateMatrix(int[][] arr, int n){ for(int i = 0; i< n/2; i++){ // number of boundaries for(int j = i; j < n-1-i; j++ ){ int temp = arr[i][j]; arr[i][j] = arr[n-1-j][i]; arr[n-1-j][i] = arr[n-1-i][n-1-j]; arr[n-1-i][n-1-j] = arr[j][n-1-i]; arr[j][n-1-i] = temp; } } } }
<template> <view class="setting"> <view class="yun-avatar-wrap"> <yun-avatar @upload="uploadImage" ref="avatar" avatarStyle="height: 0" noTab="true" /> </view> <view class="list-wrap"> <view class="item uCenterY uBet" @click="handleAvatar"> <view>更换头像</view> <view class="uCenterY"> <image class="avatar right-distance" :src="userInfo.headimgurl" mode="aspectFit" /> <image class="arrow" src="https://api.yunshangnc.com/client-img/inc-miniapp/icon/right_arrow.png" /> </view> </view> <view class="item uCenterY uBet"> <view>用户姓名</view> <view class="info uCenterY"> {{ userInfo.nickname }} </view> </view> <view class="item uCenterY uBet" @click="handleGoAuthPage"> <view>实名认证</view> <view class="uCenterY"> <image class="rank-icon" src="https://api.yunshangnc.com/client-img/inc-miniapp/my/level-blue.png" /> <text class="right-distance uCenterY"> 等级L{{ userInfo.authLevel }} </text> <image class="arrow" src="https://api.yunshangnc.com/client-img/inc-miniapp/icon/right_arrow.png" /> </view> </view> <view class="item uCenterY uBet" @click="handleLogoutAccount"> <view>账号注销</view> <view class="uCenterY"> <view class="info right-distance">注销后无法恢复,请谨慎操作</view> <image class="arrow" src="https://api.yunshangnc.com/client-img/inc-miniapp/icon/right_arrow.png" /> </view> </view> <view class="item uCenterY uBet" @click="handleGoAboutPage"> <view>关于我们</view> <view class="uCenterY"> <image class="arrow" src="https://api.yunshangnc.com/client-img/inc-miniapp/icon/right_arrow.png" /> </view> </view> </view> <view class="logout" @click="handleGoExit"> 退出登录 </view> <view class="main-bottom uCenterXY"> <view class="policy" @click="openH5PageByType('privacyAgreement')"> 隐私权政策 </view> <view class="treaty" @click="openH5PageByType('userAgreement')"> 用户协议 </view> </view> </view> </template> <script> import { openPage, SUB_ABOUT, SUB_PASSWORD_MANAGE, SUB_PERSON_AUTH, SUB_LOG_OUT, } from "@utils/open-uniapp-page"; import { H5_URL_MAP } from "@constant/h5"; import { queryLogOut } from "@api/index"; import { mapState, mapMutations } from "vuex"; import { uploadFullUrl, fetchAvatar } from "@api/index"; export default { data() { return {}; }, computed: { ...mapState("user", ["userInfo"]), }, mounted() {}, methods: { ...mapMutations({ removeToken(commit) { commit("user/REMOVE_TOKEN"); }, updateUserInfo(commit, userInfo) { commit("user/UPDATE_USER_INFO", userInfo); }, }), handleGoAuthPage() { openPage(SUB_PERSON_AUTH); }, handleGoAboutPage() { openPage(SUB_ABOUT); }, handleLogoutAccount() { openPage(SUB_LOG_OUT); }, handleGoExit() { const _this = this; uni.showModal({ title: "提示", content: "你确定要退出登录", success: function (res) { if (res.confirm) { queryLogOut().then(() => { // 回退到上一页 uni.showToast({ title: "退出成功", icon: "none", }); _this.removeToken(); setTimeout(() => { openPage("", {}, "navigateBack"); }, 500); }); } }, }); }, handleAvatar() { this.$refs.avatar.fChooseImg(0, { selWidth: "300rpx", selHeight: "300rpx", expWidth: "150px", expHeight: "150px", canRotate: false, stretch: "short", }); }, uploadImage(rsp) { const _this = this; // TODO 这种上传 H5 不兼容 this.upload(rsp.path).then((res) => { const { url } = res; if (!url) { return uni.showToast({ title: "头像更新失败,请稍后重试", icon: "none", }); } fetchAvatar({ data: { headimgurl: url } }).then((avatarUrl) => { _this.updateUserInfo({ headimgurl: avatarUrl }); return uni.showToast({ title: "头像上传完成", icon: "none", }); }); }); }, upload(thumb) { const token = `${this.storage.get("token_type")} ${this.storage.get( "token" )}`; return new Promise((resolve, reject) => { uni.uploadFile({ url: uploadFullUrl, filePath: thumb, name: "file", fileType: "image", formData: { bucketType: "ncbd", }, header: { "Content-Type": "multipart/form-data", Authorization: token, }, success: (res) => { try { res = JSON.parse(res.data); } catch (e) { reject({ type: "minio:uploadFile", code: -99999, msg: "JSON解析错误", }); console.error({ type: "minio:uploadFile", code: -99999, msg: "JSON解析错误", }); } if (+res.code === 200) { return resolve(res.data); } else if (+res.code === 403) { reject({ type: "minio:uploadFile 403", code: res.code, msg: res.msg, }); return uni.showToast({ title: "身份失效,登录后再操作", icon: "none", }); } else { reject({ type: "minio:uploadFile", code: res.code, msg: res.msg, }); } uni.hideLoading(); }, fail: (res) => { uni.showToast({ title: "头像更新失败,请稍后重试", icon: "none", }); return reject({ type: "wx:uploadFile", code: -99999, msg: res.errMsg, }); }, }); }); }, openH5PageByType(type) { this.openWebView(H5_URL_MAP[type]); }, }, }; </script> <style scoped lang="less"> .setting { min-height: 100vh; box-sizing: border-box; padding: 40rpx; background-color: #f7f8ff; .yun-avatar-wrap { height: 0; overflow: hidden; } .list-wrap { padding: 0 32rpx; border-radius: 16rpx; background-color: #fff; .item { padding: 32rpx 0; border-bottom: 2rpx solid #eeeeee; color: #333; &:last-child { border-bottom: none; } .arrow { width: 12rpx; height: 24rpx; } .avatar { width: 50rpx; height: 50rpx; } .rank-icon { width: 38rpx; height: 47rpx; margin-right: 12rpx; } .info { color: #999; font-size: 24rpx; } text { color: #5da47a; } .right-distance { margin-right: 30rpx; } } } .logout { height: 100rpx; line-height: 100rpx; margin-top: 32rpx; border-radius: 16rpx; text-align: center; color: #e13725; background-color: #fff; } .main-bottom { margin-top: 36rpx; font-size: 20rpx; color: #999999; view { padding: 0 20rpx; } .treaty { border-left: 2rpx solid #999999; } } } </style>