text
stringlengths 184
4.48M
|
---|
import React from 'react';
import { CarparkType } from 'types/types';
interface CarparkListProps {
carparks: CarparkType[];
}
interface CarparkCardProps {
carpark: CarparkType;
}
const CarparkCard = ({ carpark }: CarparkCardProps) => {
const { weekdayRate, weekdayMin, ppName, ppCode, parkCapacity } = carpark;
return (
<div className="m-2 mb-4 rounded-md shadow-md">
<div className="p-1 bg-gray-700 text-white rounded-t-md flex flex-row justify-between text-sm ">
<h2 className="pl-2">{ppName}</h2>
<text className="pr-2 ml-2 text-end">{`${parkCapacity} lots`}</text>
</div>
<div className="p-2">
<text className="font-bold text-lg text-bg-gray-700">
{weekdayRate}
</text>
<text className="ml-2">{`per ${weekdayMin}`}</text>
</div>
</div>
);
};
const ParkingList = ({ carparks }: CarparkListProps) => {
return (
<div className="h-screen w-[25%] overflow-auto">
{carparks.map((carpark, i) => (
<CarparkCard key={i} carpark={carpark} />
))}
</div>
);
};
export default ParkingList; |
// MIT License
//
// Copyright(c) 2019-2022 Filippos Gleglakos
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <AEON/Graphics/GUI/IntSlider.h>
namespace ae
{
// Public constructor(s)
IntSlider::IntSlider()
: Widget()
, mText(nullptr)
, mValue({ 0, 0, 0 })
, mSize(0.f)
{
init();
}
IntSlider::IntSlider(int minValue, int maxValue, int value, float size, int increment)
: Widget()
, mText(nullptr)
, mValue({ minValue, maxValue, value, increment })
, mSize(size)
{
init();
setValue(value);
}
// Public method(s)
void IntSlider::setLimits(int minValue, int maxValue, float size, int increment)
{
mValue.min = minValue;
mValue.max = maxValue;
mValue.increment = increment;
mSize = size;
setValue(mValue.value);
}
void IntSlider::setValue(int value)
{
mValue.value = Math::clamp(value, mValue.min, mValue.max);
const int RANGE = mValue.max - mValue.min;
const float SLICED_SIZE = mSize / RANGE;
// Update position and value
mText->setText(std::to_string(mValue.value));
Transform2DComponent* const transform = getComponent<Transform2DComponent>();
transform->setPosition(SLICED_SIZE * (value - mValue.min), transform->getPosition().y);
}
// Private method(s)
void IntSlider::init()
{
// Attach a text
auto text = std::make_unique<Text>();
mText = text.get();
attachChild(std::move(text));
}
// Private virtual method(s)
void IntSlider::handleEventSelf(Event* const event)
{
// Check if the slider has been disabled
const State ACTIVE_STATE = getActiveState();
if (ACTIVE_STATE == State::Disabled) {
return;
}
// Check if the slider is being hovered over or moved
if (event->type == Event::Type::MouseMoved) {
auto mouseMoveEvent = event->as<MouseMoveEvent>();
if (ACTIVE_STATE == State::Idle || ACTIVE_STATE == State::Hover) {
const bool HOVERED_OVER = isHoveredOver(mouseMoveEvent->position);
if (!event->handled && HOVERED_OVER) {
if (ACTIVE_STATE == State::Idle) {
enableState(State::Hover);
}
event->handled = true;
}
else if (!HOVERED_OVER && ACTIVE_STATE == State::Hover) {
enableState(State::Idle);
}
}
else if (ACTIVE_STATE == State::Click) {
const int RANGE = mValue.max - mValue.min;
const float SLICED_SIZE = mSize / RANGE;
const float MOUSE_POS = mouseMoveEvent->position.x;
const float BACKGROUND_POS = getParent()->getComponent<ae::Collider2DComponent>()->getGlobalBounds().min.x;
// Find closest slice
float closestDistance = std::abs(BACKGROUND_POS - MOUSE_POS);
int closestSlice = 0;
for (int i = 1; i <= RANGE; i += mValue.increment) {
const float NEW_CLOSEST_SLICE = std::abs(BACKGROUND_POS + SLICED_SIZE * i - MOUSE_POS);
if (NEW_CLOSEST_SLICE < closestDistance) {
closestDistance = NEW_CLOSEST_SLICE;
closestSlice = i;
}
}
// Update position and value
setValue(mValue.min + closestSlice);
}
}
// Check if the slider is clicked
else if (event->type == Event::Type::MouseButtonPressed && !event->handled && ACTIVE_STATE == State::Hover) {
auto mouseButtonEvent = event->as<MouseButtonEvent>();
if (mouseButtonEvent->button == Mouse::Button::Left) {
enableState(State::Click);
event->handled = true;
}
}
// Check if the slider is released
else if (event->type == Event::Type::MouseButtonReleased && ACTIVE_STATE == State::Click) {
auto mouseButtonEvent = event->as<MouseButtonEvent>();
if (mouseButtonEvent->button == Mouse::Button::Left) {
enableState((isHoveredOver(Mouse::getPosition())) ? State::Hover : State::Idle);
}
}
}
} |
# [SpaText: Spatio-Textual Representation for Controllable Image Generation](https://arxiv.org/abs/2211.14305)
## What is the central research question or hypothesis that this paper addresses?
Based on my reading, the key research questions/hypotheses addressed in this paper are:
1. Can a spatio-textual representation be developed that allows specifying the content and layout of image regions using free-form text, enabling more control over text-to-image generation?
2. Can this spatio-textual representation be effectively incorporated into state-of-the-art diffusion models for text-to-image generation, including both pixel-based and latent-based models?
3. Can classifier-free guidance be extended to handle multiple conditional inputs like a global text prompt and spatio-textual representation?
4. Does incorporating the proposed spatio-textual representation and adapting the diffusion models lead to improved controllability and quality compared to baseline methods for text-to-image generation with spatial/layout control?
The key hypothesis seems to be that by proposing a novel spatio-textual representation and incorporating it into state-of-the-art diffusion models adapted via an extended classifier-free guidance, it will enable more fine-grained control over text-to-image generation while improving quality compared to existing methods. The experiments aim to validate whether this hypothesis holds true.
In summary, the core research questions focus on developing a more controllable text-to-image interface using a new spatio-textual representation approach and evaluating its effectiveness quantitatively and qualitatively compared to baseline methods.
## What is the main contribution of this paper?
This paper proposes a new method called SpaText for text-to-image generation that allows for more fine-grained control over the layout and content of generated images. The key contributions are:
1. They introduce a new problem setting of image generation using a global text prompt and a spatio-textual representation that specifies local text descriptions and positions/shapes for regions of interest. This allows for more detailed scene control compared to using just a global text prompt.
2. They propose a novel spatio-textual representation based on CLIP embeddings that enables open-vocabulary textual descriptions to be provided for local image regions. This avoids limitations of prior work relying on a fixed label set.
3. They show how to adapt state-of-the-art diffusion models (both pixel-based and latent-based) to handle this multi-conditional input using an extension of classifier-free guidance.
4. They provide several automatic evaluation metrics tailored to their setting as well as human evaluations, and demonstrate improved performance over adapted baseline methods.
5. Their overall framework and spatio-textual representation allows users to have more fine-grained control over text-to-image generation, while still leveraging the capabilities of existing pre-trained models. This could be useful for content creation tasks.
In summary, the main contribution is proposing a more controllable text-to-image generation method using a novel spatio-textual representation and adaptation of diffusion models to handle this type of multi-conditional input. The results demonstrate improved generation quality and user control.
## What is the TL;DR (Too Long, Didn't Read) version of the paper? If you had to summarize it in one sentence, what would that be?
Here is a one sentence summary of the key points from the paper:
The paper presents SpaText, a new method for text-to-image generation that allows users to specify both a global text prompt describing the overall scene as well as a sparse spatio-textual representation indicating the content and layout of select image regions using free-form text.
## How does this paper compare to other research in the same field?
Here is a brief analysis of how this paper compares to other research in text-to-image generation with controllable scene generation:
The key idea in this paper is using a spatio-textual representation to allow more fine-grained control over the layout and content of generated images. This is in contrast to most prior work like DALL-E 2 and Stable Diffusion which take only a text prompt as input.
The most related work is Make-A-Scene (MAS) which also tries to add spatial/layout control on top of a text prompt. However, MAS relies on a fixed vocabulary of labels for segmentation while this paper proposes using free-form text to describe each segment. This allows for more expressivity and control. The paper also proposes techniques like a multi-scale inference algorithm to balance global and local control.
Compared to iterative/optimization based approaches like No Token Left Behind, this method trains an end-to-end model that directly generates the output image in one pass. This is more efficient compared to iterative optimization at test time.
The spatial control afforded by the proposed spatio-textual representation also exceeds what is possible with very detailed text prompts as shown in the examples. This demonstrates that text alone has limitations in conveying detailed layout preferences.
Overall, the proposed approach advances the state-of-the-art in controllable text-to-image generation by improving the flexibility and expressivity of layout control while generating high quality images. The experiments and comparisons to strong baselines validate these benefits.
## What future research directions do the authors suggest?
Based on my reading, some of the main future research directions suggested by the authors include:
- Developing methods to handle more complex scenes with more objects/segments - The authors note that their method sometimes struggles when there are many objects or segments in a scene, with details leaking across segments. Improving performance in complex, multi-object scenes is noted as an important direction.
- Enhancing spatial reasoning and relational understanding - The authors mention enabling models to better reason about spatial relationships and layouts of objects as an area for advancement. Their method uses segmentation masks that define object shapes/positions, but does not explicitly model relations.
- Expanding to full 3D scene generation - The current method is limited to 2D image generation. Extending to full 3D scene synthesis with spatial scene control would be impactful future work.
- Exploring alternative interfaces for spatial control - The segmentation masks used currently may not be ideal for all users and use cases. Research into alternative interfaces like sketching or 3D modeling for spatial control could be valuable.
- Scaling up with more training data - The authors trained on a dataset of 35M image-text pairs. Working with larger and more diverse training sets could potentially improve results further.
- Addressing limitations around small objects - The method struggles with tiny objects currently. Developing techniques to properly handle small objects and details is noted as important future work.
- Combining retrieval with spatial control - Leveraging retrieved content in addition to generated imagery may be a promising direction to explore for this task.
Overall, advancing spatial reasoning, scaling robustness, exploring interfaces, leveraging more data, and combining retrieval seem to be highlighted by the authors as key areas for advancing text-to-image generation with spatial control in the future.
## Summarize the paper in one paragraph.
The paper presents a new method called SpaText for text-to-image generation that allows for more fine-grained control over the shapes and layout of objects/regions in the generated image. Current text-to-image models like DALL-E 2 struggle to achieve this level of control from just a text prompt. SpaText takes as input a global text prompt describing the full scene plus a segmentation map where each region of interest is annotated with a free-form text description. This allows controlling the content and position/shape of key regions while letting the model generate the rest.
Since large datasets with text descriptions of image regions don't exist, the authors create a novel CLIP-based spatio-textual representation to extract this information from existing datasets. At training time they use panoptic segmentation and CLIP's image encoder to embed image regions. At inference, they embed user text descriptions with CLIP's text encoder, convert embeddings to the image space with a prior model, and construct the spatio-textual representation to condition diffusion models. They also extend classifier-free guidance to support multi-conditional inputs like theirs.
The authors show their method's effectiveness by implementing it with pixel-based and latent diffusion models. They propose automatic metrics to evaluate against baselines adapted from prior work, and also conduct a user study. Their results demonstrate state-of-the-art image generation with free-form textual scene control.
## Summarize the paper in two paragraphs.
Here is a two paragraph summary of the paper:
The paper presents a new method called SpaText for text-to-image generation that provides more fine-grained control over the layout and content of generated images. Current text-to-image models like DALL-E 2 can generate high quality images from text prompts, but do not allow controlling the precise position and appearance of objects within the image.
SpaText addresses this by taking as input both a global text prompt describing the overall scene, as well as a spatial map where regions of interest are annotated with local text prompts. This allows specifying both the content and layout of the desired image. The authors propose a novel spatio-textual representation using CLIP embeddings to enable conditioning on both global and local text. They show this representation can be effectively incorporated into state-of-the-art diffusion models like DALL-E 2 and Stable Diffusion. Experiments demonstrate SpaText's ability to generate images conforming to the spatial layout and local text specifications. The method provides more fine-grained control over image generation compared to prior text-to-image approaches.
## Summarize the main method used in the paper in one paragraph.
The paper presents a new method for text-to-image generation that allows more fine-grained control over the layout and content of different regions in the generated image.
The key idea is to augment the standard text prompt with a sparse segmentation map, where each region of interest is annotated with a free-form natural language description. This allows specifying the content and position of select objects, while letting the model infer the rest of the layout.
Since large-scale datasets with region-level textual annotations do not exist, the authors propose representing each region using embeddings from a pre-trained CLIP model. During training, region embeddings are extracted from real image segments. At inference time, embeddings are derived from the user's text descriptions by utilizing CLIP's text encoder and a separate module that translates text to image embeddings.
The proposed spatio-textual representation is incorporated into two state-of-the-art diffusion models for image generation - one operating in pixel space, the other in latent space. The models are adapted via convolutional input concatenation and fine-tuning. To support the multiple input conditions, classifier-free guidance is extended to the multi-conditional setting.
Experiments demonstrate that the proposed approach, dubbed SpaText, outperforms baselines in generating images that better match the global and local text specifications. Both automatic metrics and human evaluations confirm the benefits of finer spatial control through sparse segmentation maps and free-form text.
## What problem or question is the paper addressing?
From my understanding, this paper is addressing the problem of providing more fine-grained control over image generation from text descriptions. The key issues seem to be:
- Current state-of-the-art text-to-image models like DALL-E 2 and Stable Diffusion, while able to generate impressive results, lack the ability to precisely control the spatial layout and shapes of objects/regions in the image. It is hard to convey this kind of detailed spatial information using just a text prompt.
- Previous attempts like Make-A-Scene to add spatial control relied on dense segmentation maps with fixed labels. This can be limiting in terms of quality for uncommon objects, cumbersome for users to provide dense maps, and lacks instance-specific control.
- The key questions seem to be: How can users provide spatial and shape control over image generation without relying on a fixed label set? How to enable this while only needing a sparse specification of the scene?
The paper proposes a new approach called SpaText to address these issues. The key ideas are:
- Allow users to provide sparse segmentation masks where regions of interest are described with free-form natural language.
- Develop a novel CLIP-based spatial-textual representation to incorporate these spatial free-form text prompts into existing diffusion models.
- Demonstrate this technique on both pixel-based (DALL-E 2 like) and latent-based (Stable Diffusion) models.
- Extend classifier-free guidance to handle multiple conditions like global and spatial-textual prompts.
So in summary, the paper aims to provide more open-vocabulary spatial control over text-to-image generation while requiring only a sparse specification of the scene. The proposed SpaText technique and adaptations to existing models seem intended to achieve this goal.
## What are the keywords or key terms associated with this paper?
Based on my reading of the paper, some of the key terms and keywords are:
- Text-to-image generation - The paper focuses on generating images from text prompts.
- Controllability - A key goal is improving controllability over the image generation process, beyond using just a global text prompt.
- Scene control - The paper proposes a method for controlling the layout and content of different regions in a generated image scene.
- Spatio-textual representation - A novel representation is proposed that allows specifying the description and location of regions of interest using free-form text.
- Diffusion models - The method is evaluated by incorporating the spatio-textual representation into state-of-the-art diffusion models for image generation.
- Pixel-based vs latent-based models - The approach is tested on both a pixel-based model (DALL-E 2) and a latent-based model (Stable Diffusion).
- Classifier-free guidance - The paper shows how to extend classifier-free guidance to multi-conditional inputs.
- Evaluation metrics - New automatic metrics are proposed for evaluating image generation with textual scene control.
- User study - A user study is conducted to evaluate the method based on human judgments.
In summary, the key terms cover text-to-image generation, controllability, scene control, the proposed spatio-textual representation, diffusion models, classifier-free guidance, and quantitative evaluation of the method.
## Based on the paper, what questions should we ask to create a comprehensive summary of it? Please list at least 10 questions.
Here are 10 potential questions to ask to create a comprehensive summary of the paper:
1. What is the main problem or research question being investigated in the paper?
2. What is the proposed solution or approach to addressing this problem?
3. What datasets were used in the experiments?
4. What were the main evaluation metrics used to analyze the results?
5. What were the key quantitative results reported in the paper?
6. How did the proposed approach compare to other existing methods on the key metrics?
7. What are the main limitations or shortcomings of the proposed approach?
8. What are the key qualitative observations or analyses based on the results?
9. What are the main takeaways, conclusions, or future directions suggested by the authors?
10. How does this work fit into or extend prior research in the field? What new contributions does it make?
Asking these types of questions while reading the paper carefully should help identify and extract the most important details and themes to summarize the key contributions, results, and implications of the work comprehensively. The goal is to distill the essence of the paper into a concise yet complete overview focusing on the core ideas and findings.
## Design 10 in-depth questions about method proposed in this paper and avoid simple question.
Here are 10 in-depth questions about the method proposed in this paper:
1. The paper proposes a novel spatio-textual representation that enables free-form text control over image generation. Can you elaborate on how this representation is constructed during training and inference? What role does the panoptic segmentation model and CLIP model play?
2. The method is demonstrated on two state-of-the-art diffusion models - a pixel-based model (DALL-E 2) and a latent-based model (Stable Diffusion). How does the proposed representation get incorporated into each of these models? What modifications were made to the model architectures?
3. The paper shows how to extend classifier-free guidance to support multiple conditions, allowing control over both the global text prompt and the spatio-textual representation. Can you explain the standard classifier-free guidance formulation, and how it was extended to the multi-conditional case in this work?
4. Both a multi-scale and a single-scale inference formulation are presented for incorporating classifier-free guidance with multiple conditions. What is the trade-off between these two formulations in terms of controllability versus inference speed?
5. For evaluation, the paper proposes several automatic metrics that aim to measure different aspects of the model - global text matching, local text matching, shape matching. Can you describe each of these metrics and what they aim to capture?
6. The results show the proposed latent-based model achieves better metrics scores compared to the pixel-based model. What factors may contribute to this performance difference? How might the pixel-based model be improved?
7. The paper demonstrates the model has some robustness to mask inaccuracies, allowing generation of reasonable images even if the mask does not perfectly match the object shape. What property of the model architecture enables this behavior?
8. The user study evaluates the models along 3 criteria - visual quality, global text matching, local text matching. What did the study reveal about how the proposed model compares to baselines in these aspects?
9. The paper identifies some limitations such as characteristic leakage between segments, and difficulty handling tiny masks. Can you elaborate on these limitations and discuss potential ways to address them in future work?
10. Overall, how does the proposed spatio-textual representation and method advance the state-of-the-art in controllable text-to-image generation? What new capabilities does it enable compared to prior works?
## Write a very high-quality paragraph summarizing the paper that effectively covers the paper.
Here is a high-quality paragraph summarizing the key points of the paper:
This paper proposes SpaText, a new method for controllable text-to-image generation using open-vocabulary scene descriptions. The key idea is to provide two inputs to the model: (1) a global text prompt describing the entire image, and (2) a sparse segmentation map where each segment of interest is annotated with a free-form text description. To address the lack of suitable training data, the authors propose a novel spatio-textual representation using CLIP embeddings to encode both the visual information from image segments and semantic information from text prompts. They demonstrate this representation's effectiveness by incorporating it into two state-of-the-art diffusion models - a pixel-based model similar to DALL-E 2 and a latent-based model similar to Stable Diffusion. The authors also extend classifier-free guidance to support multi-conditional inputs like theirs. Experiments show their method achieves higher quality and better controllability than baseline approaches adapted from prior work. Both automatic metrics and human evaluation demonstrate the advantages of SpaText for controllable text-to-image generation with open-vocabulary scene descriptions specified through sparse segmentation maps.
## Summarize the paper in one sentence.
This paper proposes a novel spatio-textual representation called SpaText that enables fine-grained control over image generation using a combination of global text prompts and local free-form text descriptions paired with segmentation masks.
## Summarize the paper in one paragraphs.
Here is a one paragraph summary of the key points in this paper:
This paper presents SpaText, a new method for controllable text-to-image generation that allows users to specify both a global text prompt describing the overall scene as well as a sparse segmentation map where each region of interest is annotated with free-form text describing its content. Since large-scale datasets with per-region textual annotations do not exist, SpaText uses a novel CLIP-based spatio-textual representation to extract embeddings for image regions and translate user-provided text into the same embedding space. SpaText incorporates this representation into pixel and latent-based diffusion models by concatenating it as additional channels. It also extends classifier-free guidance to support multi-conditional inputs like global + local text. Experiments using automatic metrics and human evaluation show SpaText generates high quality images reflecting both global and local text, outperforming baselines. Key benefits are finer-grained control than global text alone and open vocabulary compared to fixed segmentation labels.
## Design 10 in-depth questions about the method proposed in this paper and avoid simple questions.
Here are 10 in-depth questions about the method proposed in this paper:
1. The paper introduces a new problem setting of image generation with free-form textual scene control. What are the key differences between this setting and previous works on layout-to-image generation or scene-based text-to-image generation?
2. The paper proposes a novel spatio-textual representation to tackle the lack of datasets with local text descriptions. Explain in detail how this representation is constructed during training and inference time. What is the motivation behind using CLIP embeddings?
3. The spatio-textual representation enables converting the sparse segmentation map to a dense embedding map. Discuss the advantages and potential limitations of this approach compared to using the raw sparse map directly.
4. The paper shows how to adapt two state-of-the-art diffusion models (pixel-based and latent-based) by incorporating the proposed spatio-textual representation. Elaborate on the differences between these two adaptation methods and why adapting the latent space may have advantages.
5. Classifier-free guidance is extended to support multiple conditions in this work. Explain the training and inference formulation for this multi-conditional case. What is the difference between the multi-scale and single-scale variants?
6. Several automatic metrics are proposed in the paper for evaluating compliance with global text, local text, and mask shape. Discuss the motivation behind each metric and how they allow a more thorough evaluation. What are potential limitations?
7. Analyze the results of the ablation studies. How does using CLIP embeddings compare to a simple binary mask representation? What is the effect of the local prompt concatenation trick?
8. The paper demonstrates the model has some degree of insensitivity to mask details. Speculate on why this characteristic emerges and discuss its advantages and disadvantages.
9. Examine the qualitative results comparing different methods. In what ways does the proposed approach lead to better correspondence between generated images and input text conditions?
10. The paper focuses on natural images. Discuss how the proposed method could be adapted to other domains like synthetic scenes or abstract art. What challenges might arise? |
import React, { useEffect, useState } from "react";
import useEnroll from "../../hooks/useEnroll";
import Container from "../../components/Container/Container";
import { useForm } from "react-hook-form";
import useAuth from "../../hooks/useAuth";
import axios from "axios";
import toast, { Toaster } from "react-hot-toast";
import { FrownOutlined, MehOutlined, SmileOutlined } from "@ant-design/icons";
import { Rate } from "antd";
const MyCollage = () => {
const [enrolls, refetch] = useEnroll();
const { user } = useAuth();
const customIcons = {
1: <FrownOutlined />,
2: <FrownOutlined />,
3: <MehOutlined />,
4: <SmileOutlined />,
5: <SmileOutlined />,
};
const {
register,
handleSubmit,
formState: { errors },
reset,
} = useForm();
const onSubmit = (data) => {
const { userName, description, rating } = data;
const newItem = {
userName,
description,
image: user?.photoURL,
rating: parseFloat(rating),
};
axios
.post(`${import.meta.env.VITE_BASE_URL}/review`, newItem)
.then((data) => {
if (data.data.insertedId) {
refetch();
reset();
toast.success(`${user?.displayName} Thank's for Feedback`);
}
console.log(data);
})
.catch((error) => {
console.log(error.message);
});
};
return (
<Container>
<div className="my-14">
<Toaster />
<h4 className="text-3xl md:text-5xl mb-10 font-bold text-neutral-500 text-center">
{" "}
Enrolled Collage
</h4>
<div>
{enrolls.map((enroll) => (
<div
key={enroll._id}
className="grid grid-cols-1 md:grid-cols-2 gap-4"
>
<img
src={enroll?.isCollage?.image}
className=" object-cover rounded-md"
alt=""
/>
<div>
<h4 className="text-xl font-semibold">
{enroll?.isCollage?.name}
</h4>
<p className="text-sm">{enroll?.isCollage?.description}</p>
<div className="py-6">
<h4 className="text-xl font-semibold text-center mb-4">
Give a Feedback
</h4>
<form
onSubmit={handleSubmit(onSubmit)}
className="max-w-[300px] mx-auto"
>
<div className="mb-3">
<input
type="text"
required
readOnly
defaultValue={user?.displayName}
placeholder="Your Name"
className="border border-neutral-300 w-full px-2 h-10"
{...register("userName", { required: true })}
/>
</div>
<div className="flex space-x-2 mb-3">
<Rate character={({ index }) => customIcons[index + 1]} />
<input
type="number"
required
placeholder="Plaese a Rate !"
className="border border-neutral-300 w-full px-2 h-10"
{...register("rating", {
required: true,
maxLength: 3,
})}
/>
</div>
<div className="mb-3">
<textarea
placeholder="Write a comment..."
{...register("description", {
required: true,
maxLength: 1000,
})}
id="description"
className="border border-neutral-300 w-full px-2 "
/>
</div>
<div className="mb-3">
<input
type="submit"
value="Submit"
className="border border-neutral-300 w-full px-2 h-10 cursor-pointer bg-sky-100 hover:bg-sky-200 shadow-sm hover:shadow"
/>
</div>
</form>
</div>
</div>
</div>
))}
</div>
</div>
</Container>
);
};
export default MyCollage; |
package com.team2898.engine.utils
import kotlin.math.PI
import kotlin.math.absoluteValue
import kotlin.math.pow
import kotlin.math.round
// Don't show warnings if these functions are unused or could be private
@Suppress("unused", "MemberVisibilityCanBePrivate")
/**
* Sugar is an object where we are adding convenience functions
*/
object Sugar {
/**
* Converts the value from radians to degrees
*
* @return the value in radians as a double
*/
fun Double.radiansToDegrees(): Double {
return times(180 / PI)
}
fun Double.eqEpsilon(other: Double, maxDistance:Double = 0.01) = (this - other).absoluteValue < maxDistance
fun Double.eqEpsilon(other: Int,maxDistance:Double = 0.01) = (this - other).absoluteValue < maxDistance
/**
* Converts the value from degrees to radians
*
* @return the value in degrees as a double
*/
fun Double.degreesToRadians(): Double {
return times(PI / 180)
}
/**
* Converts the value from radians to degrees
*
* @return the value in radians as a double
*/
fun Int.radiansToDegrees(): Double {
return toDouble().radiansToDegrees()
}
/**
* Converts the value from degrees to radians
*
* @return the value in degrees as a double
*/
fun Int.degreesToRadians():Double{
return toDouble().degreesToRadians()
}
/**
* Clamps this double to be within the range [min]..[max], inclusive.
*/
fun Double.clamp(min: Double = 0.0, max: Double = 1.0) = this.coerceIn(min, max)
fun Double.clamp(min: Int = 0, max: Int = 1) = this.coerceIn(min*1.0, max*1.0)
/**
* Finds angle difference between two angles in radians
*/
fun angleDifference(angle1: Double, angle2: Double): Double {
val a = angle1 - angle2
return (a + PI).mod(2.0 * PI) - PI
}
fun Double.roundTo(decimalPlace: Int) : Double{
val multiplier = 10.0.pow(decimalPlace).toInt()
return round(this*multiplier)/multiplier
}
fun Double.circleNormalize(): Double {
if(this < 0) return (this % (2* PI)) + (2*PI)
return this % (2*PI)
}
} |
using Entities.Entities;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using PdfSharpCore.Drawing;
using QRCoder;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Web_ECommerce.Models
{
public class HelpQrCode : Controller
{
private async Task<byte[]> GeraQrCode(string dadosBanco)
{
QRCodeGenerator qrCodeGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrCodeGenerator.CreateQrCode(dadosBanco, QRCodeGenerator.ECCLevel.H);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(20);
var bitmapBytes = BitmapToBytes(qrCodeImage);
return bitmapBytes;
}
private static byte[] BitmapToBytes(Bitmap img)
{
using (MemoryStream stream = new MemoryStream())
{
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
return stream.ToArray();
}
}
public async Task<IActionResult> Download(CompraUsuario compraUsuario, IWebHostEnvironment _environment)
{
using (var doc = new PdfSharpCore.Pdf.PdfDocument())
{
#region Configuracoes da folha
var page = doc.AddPage();
page.Size = PdfSharpCore.PageSize.A4;
page.Orientation = PdfSharpCore.PageOrientation.Portrait;
var graphics = XGraphics.FromPdfPage(page);
var corFonte = XBrushes.Black;
#endregion
#region Numeração das Páginas
int qtdPaginas = doc.PageCount;
var numeracaoPagina = new PdfSharpCore.Drawing.Layout.XTextFormatter(graphics);
numeracaoPagina.DrawString(Convert.ToString(qtdPaginas), new PdfSharpCore.Drawing.XFont("Arial", 10), corFonte, new PdfSharpCore.Drawing.XRect(575, 825, page.Width, page.Height));
#endregion
#region Logo
var webRoot = _environment.WebRootPath;
var logoFatura = string.Concat(webRoot, "/img/", "loja-virtual-1.png");
XImage imagem = XImage.FromFile(logoFatura);
graphics.DrawImage(imagem, 20, 5, 300, 50);
#endregion
#region Informações 1
var relatorioCobranca = new PdfSharpCore.Drawing.Layout.XTextFormatter(graphics);
var titulo = new PdfSharpCore.Drawing.XFont("Arial", 14, PdfSharpCore.Drawing.XFontStyle.Bold);
relatorioCobranca.Alignment = PdfSharpCore.Drawing.Layout.XParagraphAlignment.Center;
relatorioCobranca.DrawString("BOLETO ONLINE", titulo, corFonte, new XRect(0, 65, page.Width, page.Height));
#endregion
#region Informações 2
var alturaTituloDetalhesY = 120;
var detalhes = new PdfSharpCore.Drawing.Layout.XTextFormatter(graphics);
var tituloInfo_1 = new PdfSharpCore.Drawing.XFont("Arial", 8, XFontStyle.Regular);
detalhes.DrawString("Dados do banco", tituloInfo_1, corFonte, new XRect(25, alturaTituloDetalhesY, page.Width, page.Height));
detalhes.DrawString("Banco Itau 004", tituloInfo_1, corFonte, new XRect(150, alturaTituloDetalhesY, page.Width, page.Height));
alturaTituloDetalhesY += 9;
detalhes.DrawString("Código Gerado", tituloInfo_1, corFonte, new XRect(25, alturaTituloDetalhesY, page.Width, page.Height));
detalhes.DrawString("000000 000000 000000 000000", tituloInfo_1, corFonte, new XRect(150, alturaTituloDetalhesY, page.Width, page.Height));
alturaTituloDetalhesY += 9;
detalhes.DrawString("Quantidade:", tituloInfo_1, corFonte, new XRect(25, alturaTituloDetalhesY, page.Width, page.Height));
detalhes.DrawString(compraUsuario.QuantidadeProdutos.ToString(), tituloInfo_1, corFonte, new XRect(150, alturaTituloDetalhesY, page.Width, page.Height));
alturaTituloDetalhesY += 9;
detalhes.DrawString("Valor Total:", tituloInfo_1, corFonte, new XRect(25, alturaTituloDetalhesY, page.Width, page.Height));
detalhes.DrawString(compraUsuario.ValorTotal.ToString(), tituloInfo_1, corFonte, new XRect(150, alturaTituloDetalhesY, page.Width, page.Height));
var tituloInfo_2 = new PdfSharpCore.Drawing.XFont("Arial", 8, XFontStyle.Bold);
try
{
var img = await GeraQrCode("Dados do banco aqui");
Stream streamImage = new MemoryStream(img);
XImage qrCode = XImage.FromStream(() => streamImage);
alturaTituloDetalhesY += 40;
graphics.DrawImage(qrCode, 140, alturaTituloDetalhesY, 310, 310);
}
catch (Exception erro)
{
}
alturaTituloDetalhesY += 620;
detalhes.DrawString("Canhoto com QrCode para pagamento online.", tituloInfo_2, corFonte, new XRect(20, alturaTituloDetalhesY, page.Width, page.Height));
#endregion
using (MemoryStream stream = new MemoryStream())
{
var contentType = "application/pdf";
doc.Save(stream, false);
return File(stream.ToArray(), contentType, "BoletoLojaOnline.pdf");
}
}
}
}
} |
;; We've added new operators to our lookup table. The system now knows
;; how to dispatch '(complex) data that requires the operation
;; 'magnitude. Essentially, we have added a route for operations on
;; the complex-package that require implementations in
;; rectangular/polar packages.
;;
;; z is represented as a box-and-pointer in Fig. 2.24. As a list
;; structure z can be written as
;;
;; z = ('(complex) '(rectangular) 3 . 4)
;;
;; Now we use the substitution model with applicative order to follow
;; along what the interpreter does.
(magnitude z) ; generic interface
(apply-generic 'magnitude ('(complex) ('(rectangular) 3 . 4)))
((get 'magnitude '(complex)) ('(rectangular) 3 . 4))
(magnitude ('(rectangular) 3 . 4)) ; complex arithmetic package
(apply-generic 'magnitude ('(rectangular) 3 . 4))
((get 'magnitude '(rectangular)) (3 . 4))
(magnitude (3 . 4)) ; rectangular package procedure
(sqrt (+ (square 3) (square 4)))
;; We see that apply-generic is invoked twice, once for each level of
;; types. |
import { createContext, useContext, useReducer } from "react";
import userReducer from "../reducers/userReducer";
import productsReducer from "../reducers/productsReducer";
// 1. Crear el contexto
const AppContext = createContext(null);
// 2. Proveer el contexto
export const AppContextProvider = ({ children }) => {
//4.2. Aquí vamos a declarar los estados con useReducer para poderlos compartir en el contexto
const initialUser = {
user: null,
isAuth: false,
};
const initialProducts = {
products: [],
categories: [],
isActiveFilter: false,
};
const [user, userDispatch] = useReducer(userReducer, initialUser);
const [products, productsDispatch] = useReducer(
productsReducer,
initialProducts
);
const globalState = {
user: { user, userDispatch },
products: { products, productsDispatch },
};
return (
<AppContext.Provider value={{ ...globalState }}>
{children}
</AppContext.Provider>
);
};
// 3. Crear el hook personalizado para poder consumir el contexto en cualquier componentente
export const useAppContext = () => useContext(AppContext); |
package com.example.labdiary.view.screens
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavHostController
import com.example.labdiary.R
import com.example.labdiary.theme.LabDiaryCustomTheme
import com.example.labdiary.view.TitleComponent
import com.example.labdiary.viewModel.MainViewModel
import com.example.labdiary.viewModel.SettingsViewModel
import org.koin.androidx.compose.koinViewModel
@Composable
fun SettingsScreen(
navController: NavHostController,
vm: SettingsViewModel = koinViewModel()
) {
val uiState by vm.uiState.collectAsState()
SettingsView(
semester = uiState.semester,
disQuantity = uiState.disQuantity,
onSemesterChange = vm::onSemesterChangeToNext,
toDisList = { /*TODO*/ })
}
@Composable
fun SettingsView(
semester: Int,
disQuantity: Int,
onSemesterChange: () -> Unit,
toDisList: () -> Unit
) {
Surface(color = MaterialTheme.colors.background) {
Column(
Modifier
.fillMaxSize()
.padding(horizontal = 16.dp)
) {
TitleComponent(stringResource(R.string.settings_page))
MySettingsOption(
text = stringResource(id = R.string.current_semester),
value = semester,
buttonText = stringResource(id = R.string.next_semester),
onButtonClick = onSemesterChange
)
MySettingsOption(
text = stringResource(id = R.string.dis_quantity),
value = disQuantity,
buttonText = stringResource(id = R.string.dis_list),
onButtonClick = toDisList
)
}
}
}
@Composable
fun MySettingsOption(text: String, value: Int, buttonText: String, onButtonClick: () -> Unit) {
Row(
Modifier
.fillMaxWidth()
.padding(bottom = 12.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(text = "$text $value", Modifier.fillMaxWidth(0.6f))
TextButton(
onClick = onButtonClick,
Modifier
.padding(start = 4.dp)
.fillMaxWidth(1f)
) {
Text(text = buttonText, fontSize = 17.sp, textAlign = TextAlign.Right)
}
}
}
@Preview(showBackground = true)
@Composable
fun SettingsPreview() {
LabDiaryCustomTheme {
SettingsView(semester = 6, disQuantity = 7, onSemesterChange = {}, toDisList = {})
}
} |
////
Copyright 2023 Matt Borland
Distributed under the Boost Software License, Version 1.0.
https://www.boost.org/LICENSE_1_0.txt
////
= Getting Started
:idprefix: build_
== B2
Run the following commands to clone the latest versions of Boost and Charconv, prepare the Boost.Build system for use, and build the libraries with C++11 as the default standard:
[source, bash]
----
git clone https://github.com/boostorg/boost
cd boost
git submodule update --init
cd ..
./bootstrap
./b2 cxxstd=11
----
To install the development environment, run:
[source, bash]
----
sudo ./b2 install cxxstd=11
----
The value of cxxstd must be at least 11. https://www.boost.org/doc/libs/1_84_0/tools/build/doc/html/index.html[See the b2 documentation] under `cxxstd` for all valid values.
== vcpkg
Run the following commands to clone the latest version of Charconv and install it using vcpkg:
[source, bash]
----
git clone https://github.com/boostorg/charconv
cd charconv
vcpkg install charconv --overlay-ports=ports/charconv
----
Any required Boost packages not currently installed in your development environment will be installed automatically.
== Conan
Run the following commands to clone the latest version of Charconv and build a boost_charconv package using your default profile:
[source, bash]
----
git clone https://github.com/boostorg/charconv
conan create charconv/conan --build missing
----
The package will be put in the local Conan cache along with all direct and transitive dependencies.
TIP: Since Charconv only depends on a few header-only Boost libraries, you can save time by requesting header-only Boost:
[source, bash]
----
conan create charconv/conan -o 'boost*:header_only=True' --build missing
----
After the package is built, you can use it in your own projects.
For example, using a `conanfile.txt`:
[source, bash]
----
[requires]
boost_charconv/1.0.0
----
== Dependencies
This library depends on: Boost.Assert, Boost.Config, Boost.Core, and https://gcc.gnu.org/onlinedocs/libquadmath/[libquadmath] on supported platforms (e.g. Linux with x86, x86_64, PPC64, and IA64). |
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router';
const TrackDetails = () => {
const navigate=useNavigate();
const [currentStep, setCurrentStep] = useState(0);
const [progress, setProgress] = useState([0, 0, 0, 0]);
const stepLabels = ['Order Placed', 'Order Packed', 'Order Shipped', 'Order Delivered'];
const [orderDetails, setOrderDetails] = useState({
orderDate: new Date().toLocaleString(),
deliveryDate: '', // Actual delivery date
expectedDeliveryDate: '', // Expected delivery date after 3 days
orderPackedDate: '', // Date order packed
orderShippedDate: '', // Date order shipped
orderDeliveredDate: '', // Date order delivered
});
const startProgress = () => {
// Update progress for the current step
const updatedProgress = [...progress];
updatedProgress[currentStep] = 100;
setProgress(updatedProgress);
// Move to the next step after a delay
setTimeout(() => {
if (currentStep < stepLabels.length - 1) {
setCurrentStep(currentStep + 1);
} else {
// Set delivery date when order delivered
const deliveryDate = new Date().toLocaleString();
setOrderDetails(prevState => ({
...prevState,
deliveryDate: deliveryDate,
}));
}
}, 600); // 1 minute delay
};
useEffect(() => {
// Start progress when component mounts
startProgress();
}, [currentStep]); // Re-run effect when currentStep changes
useEffect(() => {
// Calculate expected delivery date after 3 days
const orderDate = new Date(orderDetails.orderDate);
const expectedDeliveryDate = new Date(orderDate);
expectedDeliveryDate.setDate(orderDate.getDate() + 3); // Adding 3 days
// Update state with the expected delivery date
setOrderDetails(prevState => ({
...prevState,
expectedDeliveryDate: expectedDeliveryDate.toLocaleString(),
}));
}, [orderDetails.orderDate]); // Re-run effect when orderDate changes
// Function to update step dates
const updateStepDates = () => {
const orderDate = new Date(orderDetails.orderDate);
const orderPackedDate = new Date(orderDate);
const orderShippedDate = new Date(orderDate);
const orderDeliveredDate = new Date(orderDetails.deliveryDate);
orderPackedDate.setDate(orderPackedDate.getDate() + 1);
orderShippedDate.setDate(orderShippedDate.getDate() + 2);
orderDeliveredDate.setDate(orderDate.getDate() +3);
setOrderDetails(prevState => ({
...prevState,
orderPackedDate: orderPackedDate.toLocaleDateString(),
orderShippedDate: orderShippedDate.toLocaleDateString(),
orderDeliveredDate: orderDeliveredDate.toLocaleDateString(),
}));
};
const handleComplaintClick = () => {
// Redirect to the complaint page
navigate('/complaintform');
};
// Call updateStepDates when currentStep changes
useEffect(() => {
updateStepDates();
}, [currentStep, orderDetails.deliveryDate]);
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<h2>Order Details</h2>
<div>
<p>Order Date: {orderDetails.orderDate}</p>
{orderDetails.expectedDeliveryDate && <p> Expected Delivery Date: {orderDetails.expectedDeliveryDate}</p>}
</div>
<h2>Order Status</h2>
<div style={{ display: 'flex', alignItems: 'center' }}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
{stepLabels.map((label, index) => (
<div key={index} style={{ marginBottom: '20px', textAlign: 'left', display: 'flex', alignItems: 'center' }}>
<div style={{ width: '30px', height: '30px', borderRadius: '15px', backgroundColor: currentStep >= index ? 'green' : '#f2f2f2', display: 'flex', justifyContent: 'center', alignItems: 'center', color: '#fff' }}>{index + 1}</div>
<div style={{ marginTop: '10px', color: currentStep >= index ? 'green' : '#000', marginLeft: '10px' }}>{label}</div>
{currentStep >= index && (
<div style={{ marginLeft: '10px' }}>
{index === 0 && orderDetails.orderDate && (
<p style={{ fontSize: '12px' }}>Date: {orderDetails.orderDate}</p>
)}
{index === 1 && orderDetails.orderPackedDate && (
<p style={{ fontSize: '12px' }}>Date: {orderDetails.orderPackedDate}</p>
)}
{index === 2 && orderDetails.orderShippedDate && (
<p style={{ fontSize: '12px' }}>Date: {orderDetails.orderShippedDate}</p>
)}
{index === 3 && orderDetails.orderDeliveredDate && (
<p style={{ fontSize: '12px' }}>Date: {orderDetails.orderDeliveredDate}</p>
)}
</div>
)}
</div>
))}
</div>
<div style={{ width: '2px', height: 'calc(100% - 40px)', backgroundColor: 'gray', marginLeft: '15px', marginRight: '15px' }}></div> {/* Line joining all steps */}
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
{progress.map((percentage, index) => (
<div key={index} style={{ width: '6px', height: `${percentage}%`, backgroundColor: currentStep >= index ? 'green' : '#f2f2f2', marginRight: '10px' }}></div>
))}
</div>
</div>
<div>
<h2>Have any complaints?</h2>
<p>If you have any complaints or feedback, please feel free to post them here:</p>
<button onClick={handleComplaintClick}>Post Complaint</button>
</div>
</div>
);
};
export default TrackDetails |
IDOR Checker Tool
IODRHunter is an IDOR (Insecure Direct Object Reference) checker tool built with Python. The tool scrapes a given URL for links, extracts the parameters from those links, and checks for potential IDOR vulnerabilities using payloads from a specified wordlist.
Features
- Fetches the content of a webpage.
- Parses HTML to extract all links.
- Extracts URL parameters.
- Checks for potential IDOR vulnerabilities using a wordlist of payloads.
- Identifies and reports any sensitive data exposure.
Requirements
- Python 3.x
- `requests` library
- `beautifulsoup4` library
- `colorama` library
- `urllib3` library
## Installation
1. Clone the repository or download the script file.
2. Install the required Python packages using `pip`:
bash
pip install requests beautifulsoup4 colorama urllib3
Usage
To run the IDOR checker, use the following command:
bash
python3 idor_checker.py -u <URL> -p <payload_file>
Replace <URL> with the target URL you want to scan and <payload_file> with the path to your payload wordlist file.
Example Command
bash
python3 idor_checker.py -u https://example.com -p payloads.txt
Example Output
less
-----------------------------------------
___ ______ _______ ______ __ __ __ __ __ _ _______ _______ ______
| || | | || _ | | | | || | | || | | || || || _ |
| || _ || _ || | || | |_| || | | || |_| ||_ _|| ___|| | ||
| || | | || | | || |_||_ | || |_| || | | | | |___ | |_||_
| || |_| || |_| || __ || || || _ | | | | ___|| __ |
| || || || | | || _ || || | | | | | | |___ | | | |
|___||______| |_______||___| |_||__| |__||_______||_| |__| |___| |_______||___| |_|
[*] Checking for any IDOR vulnerability on https://example.com
[+] IDOR vulnerability found: https://example.com/path?param=payload (200)
[-] No sensitive data exposed: https://example.com/path?param=payload (404)
License
This project is licensed under the MIT License. See the LICENSE file for details.
Acknowledgments
This tool uses the requests and beautifulsoup4 libraries for web scraping.
Inspired by various web security and penetration testing scripts and tutorials. |
package datastructures.D_Recursion;
/**
* Allowed Movements are Bottom or Right side only
*/
public class NumberOfWaysInMatrix {
public static void main(String[] args) {
System.out.println("Ways in 1 x 1 matrix = " + getNumberOfWays(1, 1));
System.out.println("Ways in 1 x 2 matrix = " + getNumberOfWays(1, 2));
System.out.println("Ways in 2 x 1 matrix = " + getNumberOfWays(2, 1));
System.out.println("Ways in 2 x 2 matrix = " + getNumberOfWays(2, 2));
System.out.println("Ways in 2 x 3 matrix = " + getNumberOfWays(2, 3));
System.out.println("Ways in 3 x 2 matrix = " + getNumberOfWays(3, 2));
System.out.println("Ways in 3 x 3 matrix = " + getNumberOfWays(3, 3));
System.out.println("Ways in 3 x 4 matrix = " + getNumberOfWays(3, 4));
System.out.println("Ways in 4 x 3 matrix = " + getNumberOfWays(4, 3));
System.out.println("Ways in 4 x 4 matrix = " + getNumberOfWays(4, 4));
System.out.println("Ways in 4 x 5 matrix = " + getNumberOfWays(4, 5));
System.out.println("Ways in 5 x 4 matrix = " + getNumberOfWays(5, 4));
System.out.println("Ways in 5 x 5 matrix = " + getNumberOfWays(5, 5));
}
private static int getNumberOfWays(int n, int m) {
if (n == 1 || m == 1) // base case
return 1;
return getNumberOfWays(n, m - 1) + getNumberOfWays(n - 1, m);
}
} |
/**
* @file message_handler.c
* @brief Provides facilities for creating and posting HTTP messages
*/
#include "common.h"
#include "nxjson.h"
#include "wifi_interface.h"
#include "http_client.h"
#include "controller.h"
#include "message_handler.h"
// Controls debug output to the serial port:
// 0 - nothing output
// 1 - basic information and error
// 2 - verbose output
#define DEBUG_OUTPUT 1
#define DEBUG_VERBOSE(format, ...) if (DEBUG_OUTPUT > 1) { ESP_LOGI(MODULE_NAME, format, ##__VA_ARGS__); }
#define DEBUG_INFO(format, ...) if (DEBUG_OUTPUT > 0) { ESP_LOGI(MODULE_NAME, format, ##__VA_ARGS__); }
#define DEBUG_ERROR(format, ...) if (DEBUG_OUTPUT > 0) { ESP_LOGE(MODULE_NAME, format, ##__VA_ARGS__); }
#define DEBUG_DUMP(buffer, buff_len, level) if (DEBUG_OUTPUT > 1) { ESP_LOG_BUFFER_HEXDUMP(MODULE_NAME, buffer, buff_len, level); }
// Codes for commands that can be embedded in an HTTP response message
#define COMMAND_CODE_NONE 0
#define COMMAND_CODE_SEND_CONFIGURATION 1
#define COMMAND_CODE_RETRIEVE_PROGRAM 2
#define COMMAND_CODE_STORE_PROGRAM 3
#define COMMAND_CODE_STOP_PROGRAM 4
#define COMMAND_CODE_RETRIEVE_EVENT 5
#define COMMAND_CODE_CLEAR_EVENTS 6
static const char *MODULE_NAME = "Message handler";
static int32_t _message_id = 0;
static int32_t _command_code = COMMAND_CODE_NONE;
static char _command_error_message[100] = "";
static char _post_message_body[MAX_POST_MESSAGE_BODY_LENGTH + 1];
static char _response_message_body[MAX_RESPONSE_MESSAGE_BODY_LENGTH + 1];
static int32_t _next_post_delay = 0;
static _TProgram _read_program_buffer;
static _TProgram _write_program_buffer;
static _TEvent _read_event_buffer;
static bool _event_logging_enabled = true;
static bool prepare_post_message();
static void encode_json_mandatory_fields(char *message);
static void encode_json_status_node(char *message);
static void encode_json_configuration_command_ack(char *message);
static void encode_json_retrieve_program_command_ack(char *message);
static void encode_json_store_program_command_ack(char *message);
static void encode_json_stop_program_command_ack(char *message);
static void encode_json_retrieve_event_command_ack(char *message);
static void encode_json_clear_events_command_ack(char *message);
static void encode_json_command_nak(char *message, char *code, char *error_message);
static void process_response(char *response_message_body);
static bool decode_json(const nx_json *json);
static bool decode_json_mandatory_fields(const nx_json *node);
static bool decode_json_retrieve_program_command(const nx_json *command_node);
static bool decode_json_store_program_command(const nx_json *command_node);
static bool decode_json_stop_program_command(const nx_json *command_node);
static bool decode_json_retrieve_event_command(const nx_json *command_node);
static bool decode_json_clear_events_command(const nx_json *command_node);
static char *get_firing_state_name(int32_t firing_state);
static char *get_thermocouple_type_name(int32_t thermocouple_type);
static char *get_event_relay_function_name(int32_t event_relay_function);
static char *get_event_type_name(int32_t event_type);
/**
* @brief Creates a post message, sends it to the server and processes the response
*
* @param next_post_delay Suggested time until the next post as suggested by the server
*
* @returns True if successful
*/
bool post_message_to_server(int32_t *next_post_delay)
{
int32_t response_status_code;
DEBUG_INFO("Preparing post message");
// Prepares a post message, reading data from the controller where necessary
if (!prepare_post_message())
{
DEBUG_ERROR("Error creating post message");
return false;
}
DEBUG_VERBOSE("Sending post message: %s", _post_message_body);
// Connect to the server
if (!connect_to_server())
{
// Log the first server error after enabling logging
if (_event_logging_enabled)
{
log_event(EVENT_SERVER_ERROR, COMMS_ERROR_CANNOT_CONNECT);
_event_logging_enabled = false;
}
DEBUG_ERROR("Cannot connect to server");
return false;
}
// Turn on the radio LED
write_radio_led(true);
// Post the message to the server and wait for a response
if (!post_http_message(_post_message_body,
_response_message_body,
&response_status_code))
{
// Log the first server error after enabling logging
if (_event_logging_enabled)
{
log_event(EVENT_SERVER_ERROR, COMMS_ERROR_NO_RESPONSE);
_event_logging_enabled = false;
}
DEBUG_ERROR("No response from server");
disconnect_from_server();
write_radio_led(true);
return false;
}
// Turn off the radio LED
write_radio_led(false);
// Disconnect from the server
disconnect_from_server();
DEBUG_INFO("Processing response");
// Check for a valid response
if (response_status_code != HTTP_OK)
{
// Log the first server error after enabling logging
if (_event_logging_enabled)
{
log_event(EVENT_SERVER_ERROR, COMMS_ERROR_INVALID_RESPONSE);
_event_logging_enabled = false;
}
DEBUG_ERROR("Server responding with error code %ld", response_status_code);
return false;
}
// Process the response
process_response(_response_message_body);
*next_post_delay = _next_post_delay;
// Re-enable server error logging
_event_logging_enabled = true;
return true;
}
/**
* @brief Create a post message, reading the necessary information from the controller
*
* @returns True if successful
*/
static bool prepare_post_message()
{
char *message = _post_message_body;
bool command_success;
// Build the POST message, starting with the mandatory fields
strcpy(message, "{");
encode_json_mandatory_fields(message);
// Add a status section
encode_json_status_node(message);
// Add a command ack/nak if there was a command in the last response
if (_command_code != COMMAND_CODE_NONE)
{
// See if the command has been handled successfully so far by looking at the error message
command_success = (_command_error_message[0] == 0);
switch (_command_code)
{
case COMMAND_CODE_SEND_CONFIGURATION:
if (command_success)
{
if (_controller.configuration_available)
{
encode_json_configuration_command_ack(message);
}
else
{
strcpy(_command_error_message, "Controller configuration is not available");
encode_json_command_nak(message, "send_conf", _command_error_message);
}
}
else
{
encode_json_command_nak(message, "send_conf", _command_error_message);
}
break;
case COMMAND_CODE_RETRIEVE_PROGRAM:
if (command_success)
{
// Read the program from the controller
if (read_program(_read_program_buffer.program_number,
_controller.configuration.max_segments,
&_read_program_buffer))
{
encode_json_retrieve_program_command_ack(message);
}
else
{
strcpy(_command_error_message, "Cannot read program from controller");
encode_json_command_nak(message, "get_prog", _command_error_message);
}
}
else
{
encode_json_command_nak(message, "get_prog", _command_error_message);
}
break;
case COMMAND_CODE_STORE_PROGRAM:
if (command_success)
{
encode_json_store_program_command_ack(message);
}
else
{
encode_json_command_nak(message, "store_prog", _command_error_message);
}
break;
case COMMAND_CODE_STOP_PROGRAM:
if (command_success)
{
encode_json_stop_program_command_ack(message);
}
else
{
encode_json_command_nak(message, "stop", _command_error_message);
}
break;
case COMMAND_CODE_RETRIEVE_EVENT:
if (command_success)
{
// Read the event from the controller
if (read_event(_read_event_buffer.event_id, &_read_event_buffer))
{
encode_json_retrieve_event_command_ack(message);
}
else
{
strcpy(_command_error_message, "Cannot read event from controller");
encode_json_command_nak(message, "get_event", _command_error_message);
}
}
else
{
encode_json_command_nak(message, "get_event", _command_error_message);
}
break;
case COMMAND_CODE_CLEAR_EVENTS:
if (command_success)
{
encode_json_clear_events_command_ack(message);
}
else
{
encode_json_command_nak(message, "clear_events", _command_error_message);
}
break;
}
}
// Complete the message body
strcat(_post_message_body, "}");
// Clear the last command, just in case
_command_code = COMMAND_CODE_NONE;
strcpy(_command_error_message, "");
return true;
}
/**
* @brief Encodes mandatory fields in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
*/
static void encode_json_mandatory_fields(char *message)
{
char line[50];
sprintf(line, "\"proto_ver\": %d,", PROTOCOL_VERSION);
strcat(message, line);
sprintf(line, "\"msg_id\": %ld,", ++_message_id);
strcat(message, line);
sprintf(line, "\"mac_addr\": \"%s\",", _controller.mac_address);
strcat(message, line);
}
/**
* @brief Encodes status information in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
*/
static void encode_json_status_node(char *message)
{
char line[50];
_TControllerStatus *status = &(_controller.status);
int32_t program_index;
_TCrcInfo *crc_info;
int32_t wifi_rssi = -100;
strcat(message, "\"status\": {");
sprintf(line, "\"rtc\": \"20%02d-%02d-%02d %02d:%02d:%02d\",",
status->year, status->month, status->day,
status->hour, status->minute, status->second);
strcat(message, line);
sprintf(line, "\"state\": \"%s\",", get_firing_state_name(status->firing_state));
strcat(message, line);
sprintf(line, "\"err_code\": %d,", status->error_code);
strcat(message, line);
sprintf(line, "\"amb_temp\": %.1f,", status->ambient_temperature);
strcat(message, line);
sprintf(line, "\"temp_1\": %.1f,", status->temperature_1);
strcat(message, line);
sprintf(line, "\"temp_2\": %.1f,", status->temperature_2);
strcat(message, line);
sprintf(line, "\"temp_3\": %.1f,", status->temperature_3);
strcat(message, line);
sprintf(line, "\"temp_set_1\": %.1f,", status->temperature_set_point_1);
strcat(message, line);
sprintf(line, "\"temp_set_2\": %.1f,", status->temperature_set_point_2);
strcat(message, line);
sprintf(line, "\"temp_set_3\": %.1f,", status->temperature_set_point_3);
strcat(message, line);
sprintf(line, "\"energy_1\": %.1f,", status->energy_used_1);
strcat(message, line);
sprintf(line, "\"energy_2\": %.1f,", status->energy_used_2);
strcat(message, line);
sprintf(line, "\"energy_3\": %.1f,", status->energy_used_3);
strcat(message, line);
sprintf(line, "\"duty_1\": %.1f,", status->total_duty_1);
strcat(message, line);
sprintf(line, "\"duty_2\": %.1f,", status->total_duty_2);
strcat(message, line);
sprintf(line, "\"duty_3\": %.1f,", status->total_duty_3);
strcat(message, line);
sprintf(line, "\"soak_rem\": %d,", status->soak_remaining);
strcat(message, line);
sprintf(line, "\"event_relays\": %d,", status->event_relay_states);
strcat(message, line);
sprintf(line, "\"prog\": %d,", status->current_program);
strcat(message, line);
sprintf(line, "\"seg\": %d,", status->current_segment);
strcat(message, line);
sprintf(line, "\"delay\": %d,", status->start_delay);
strcat(message, line);
sprintf(line, "\"delay_rem\": %d,", status->start_delay_remaining);
strcat(message, line);
sprintf(line, "\"events\": %d,", status->num_events);
strcat(message, line);
sprintf(line, "\"last_event_id\": %ld,", status->last_event_id);
strcat(message, line);
sprintf(line, "\"prog_changed\": %s,", status->program_changed ? "true": "false");
strcat(message, line);
sprintf(line, "\"conf_changed\": %s,", status->configuration_changed ? "true": "false");
strcat(message, line);
strcat(message, "\"prog_crcs\": [");
for (program_index = 0; program_index < MAX_PROGRAMS; program_index++)
{
crc_info = &(status->program_crc_info[program_index]);
if (crc_info->crc_known)
{
sprintf(line, "\"%08lX\"", crc_info->crc);
}
else
{
sprintf(line, "\"\"");
}
strcat(message, line);
if (program_index != MAX_PROGRAMS - 1)
{
strcat(message, ",");
}
}
strcat(message, "],");
strcat(message, "\"conf_crc\": ");
if (status->configuration_crc_info.crc_known)
{
sprintf(line, "\"%08lX\",", status->configuration_crc_info.crc);
}
else
{
sprintf(line, "\"\",");
}
strcat(message, line);
get_rssi(&wifi_rssi);
sprintf(line, "\"wifi_rssi\": %ld", wifi_rssi);
strcat(message, line);
strcat(message, "}");
}
/**
* @brief Encodes a send configuration command acknowledgement in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
*/
static void encode_json_configuration_command_ack(char *message)
{
char line[50];
_TControllerConfiguration *configuration = &(_controller.configuration);
int32_t setting_index;
strcat(message, ",\"cmd_ack\": {");
strcat(message, "\"code\": \"send_config\"");
strcat(message, ",\"config\": {");
sprintf(line, "\"firm_ver\": \"%s\",", configuration->pic_firmware_version);
strcat(message, line);
sprintf(line, "\"name\": \"%s\",", configuration->controller_name);
strcat(message, line);
sprintf(line, "\"tc_type\": \"%s\",", get_thermocouple_type_name(configuration->thermocouple_type));
strcat(message, line);
sprintf(line, "\"units\": \"%s\",", (configuration->is_fahrenheit_units ? "F" : "C"));
strcat(message, line);
sprintf(line, "\"max_temp\": %d,", configuration->max_user_temperature);
strcat(message, line);
sprintf(line, "\"zones\": %d,", configuration->zones_in_use);
strcat(message, line);
sprintf(line, "\"progs\": %d,", configuration->max_programs);
strcat(message, line);
sprintf(line, "\"segs\": %d,", configuration->max_segments);
strcat(message, line);
sprintf(line, "\"event_1\": \"%s\",", get_event_relay_function_name(configuration->event_relay_function_1));
strcat(message, line);
sprintf(line, "\"event_2\": \"%s\",", get_event_relay_function_name(configuration->event_relay_function_2));
strcat(message, line);
strcat(message, "\"settings\": [");
for (setting_index = 0; setting_index < NUM_CONFIG_SETTINGS; setting_index++)
{
sprintf(line, "%d", configuration->configuration_settings[setting_index]);
strcat(message, line);
if (setting_index != NUM_CONFIG_SETTINGS - 1)
{
strcat(message, ",");
}
}
strcat(message, "]");
strcat(message, "}}");
}
/**
* @brief Encodes a retrieve program command acknowledgement in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
*/
static void encode_json_retrieve_program_command_ack(char *message)
{
char line[50];
int32_t segment_index;
_TProgramSegment *segment;
_TControllerConfiguration *configuration = &(_controller.configuration);
strcat(message, ",\"cmd_ack\": {");
strcat(message, "\"code\": \"get_prog\"");
sprintf(line, ",\"prog\": %d", _read_program_buffer.program_number);
strcat(message, line);
strcat(message, ",\"segs\": [");
for (segment_index = 0; segment_index < _read_program_buffer.segments_used; segment_index++)
{
segment = &(_read_program_buffer.segments[segment_index]);
if (configuration->ramp_rate_scaling == 10)
{
sprintf(line, "[%.1f,%d,%d,%d]", (float)segment->ramp_rate / configuration->ramp_rate_scaling, segment->target_temperature, segment->soak_time, segment->event_flags);
}
else
{
sprintf(line, "[%d,%d,%d,%d]", segment->ramp_rate, segment->target_temperature, segment->soak_time, segment->event_flags);
}
strcat(message, line);
if (segment_index != _read_program_buffer.segments_used - 1)
{
strcat(message, ",");
}
}
strcat(message, "]}");
}
/**
* @brief Encodes a retrieve program command acknowledgement in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
*/
static void encode_json_store_program_command_ack(char *message)
{
char line[50];
strcat(message, ",\"cmd_ack\": {");
strcat(message, "\"code\": \"store_prog\"");
sprintf(line, ",\"prog\": %d", _write_program_buffer.program_number);
strcat(message, line);
strcat(message, "}");
}
/**
* @brief Encodes a stop program command acknowledgement in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
*/
static void encode_json_stop_program_command_ack(char *message)
{
strcat(message, ",\"cmd_ack\": {");
strcat(message, "\"code\": \"stop_prog\"");
strcat(message, "}");
}
/**
* @brief Encodes a retrieve event command acknowledgement in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
*/
static void encode_json_retrieve_event_command_ack(char *message)
{
char line[50];
strcat(message, ",\"cmd_ack\": {");
strcat(message, "\"code\": \"get_event\"");
sprintf(line, ",\"id\": %ld,", _read_event_buffer.event_id);
strcat(message, line);
sprintf(line, "\"rtc\": \"20%02d-%02d-%02d %02d:%02d:%02d\",",
_read_event_buffer.year, _read_event_buffer.month, _read_event_buffer.day,
_read_event_buffer.hour, _read_event_buffer.minute, _read_event_buffer.second);
strcat(message, line);
sprintf(line, "\"type\": \"%s\",", get_event_type_name(_read_event_buffer.event_type));
strcat(message, line);
sprintf(line, "\"state\": \"%s\",", get_firing_state_name(_read_event_buffer.firing_state));
strcat(message, line);
sprintf(line, "\"err_code\": %d,", _read_event_buffer.error_code);
strcat(message, line);
sprintf(line, "\"amb_temp\": %.1f,", _read_event_buffer.ambient_temperature);
strcat(message, line);
sprintf(line, "\"temp_1\": %.1f,", _read_event_buffer.temperature_1);
strcat(message, line);
sprintf(line, "\"temp_2\": %.1f,", _read_event_buffer.temperature_2);
strcat(message, line);
sprintf(line, "\"temp_3\": %.1f,", _read_event_buffer.temperature_3);
strcat(message, line);
sprintf(line, "\"temp_set\": %.1f,", _read_event_buffer.temperature_set_point);
strcat(message, line);
sprintf(line, "\"prog\": %d,", _read_event_buffer.current_program);
strcat(message, line);
sprintf(line, "\"seg\": %d,", _read_event_buffer.current_segment);
strcat(message, line);
sprintf(line, "\"comms_err_code\": %d,", _read_event_buffer.comms_error_code);
strcat(message, line);
sprintf(line, "\"comms_command\": %d", _read_event_buffer.comms_command_id);
strcat(message, line);
strcat(message, "}");
}
/**
* @brief Encodes a clear events command acknowledgement in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
* @param program Program data
*/
static void encode_json_clear_events_command_ack(char *message)
{
strcat(message, ",\"cmd_ack\": {");
strcat(message, "\"code\": \"clear_events\"");
strcat(message, "}");
}
/**
* @brief Encodes a retrieve program command command acknowledgement in JSON format and adds to the supplied post message
*
* @param message Post message to which JSON data should be added
* @param code Command code string
* @param error_message Error message
*/
static void encode_json_command_nak(char *message, char *code, char *error_message)
{
char line[50];
strcat(message, ",\"cmd_nak\": {");
sprintf(line, "\"code\": \"%s\"", code);
strcat(message, line);
sprintf(line, ",\"error\": \"%s\"", error_message);
strcat(message, line);
strcat(message, "}");
}
/**
* @brief Processes a response from the server
*
* @param response_message_body The body of the response message to process
*/
static void process_response(char *response_message_body)
{
const nx_json *json;
DEBUG_VERBOSE("Received response message body length %d: %s", strlen(response_message_body), response_message_body);
// Clear existing command data
_command_code = COMMAND_CODE_NONE;
strcpy(_command_error_message, "");
// Parse the response string into a JSON structure
json = nx_json_parse(response_message_body, 0);
if (!json)
{
strcpy(_command_error_message, "Invalid JSON");
DEBUG_ERROR("Error parsing response message");
return;
}
// Decode the JSON data
if (!decode_json(json))
{
DEBUG_ERROR("Error processing message (%s)", _command_error_message);
}
// Free memory
nx_json_free(json);
}
/**
* @brief Decodes the JSON data in a response
*
* @param node Top-level node containing all JSON data
*/
static bool decode_json(const nx_json *node)
{
const nx_json *field;
const nx_json *command_node;
const char *command_code;
// Extract common fields
if (!decode_json_mandatory_fields(node)) return false;
// Check for a command node
command_node = nx_json_get(node, "cmd");
if (command_node->type == NX_JSON_OBJECT)
{
// Extract the command code
field = nx_json_get(command_node, "code");
if (field->type != NX_JSON_STRING)
{
strcpy(_command_error_message, "Missing or incorrectly formatted command code");
return false;
}
command_code = field->text_value;
DEBUG_VERBOSE("Command code: %s", command_code);
// Process according to code
if (strcmp(command_code, "send_config") == 0)
{
_command_code = COMMAND_CODE_SEND_CONFIGURATION;
return true;
}
else if (strcmp(command_code, "get_prog") == 0)
{
_command_code = COMMAND_CODE_RETRIEVE_PROGRAM;
if (!decode_json_retrieve_program_command(command_node)) return false;
}
else if (strcmp(command_code, "store_prog") == 0)
{
_command_code = COMMAND_CODE_STORE_PROGRAM;
if (!decode_json_store_program_command(command_node)) return false;
}
else if (strcmp(command_code, "stop_prog") == 0)
{
_command_code = COMMAND_CODE_STOP_PROGRAM;
if (!decode_json_stop_program_command(command_node)) return false;
}
else if (strcmp(command_code, "get_event") == 0)
{
_command_code = COMMAND_CODE_RETRIEVE_EVENT;
if (!decode_json_retrieve_event_command(command_node)) return false;
}
else if (strcmp(command_code, "clear_events") == 0)
{
_command_code = COMMAND_CODE_CLEAR_EVENTS;
if (!decode_json_clear_events_command(command_node)) return false;
}
else
{
_command_code = COMMAND_CODE_NONE;
}
}
return true;
}
/**
* @brief Decodes the mandatory field values supplied in a JSON node structure
*
* @param node Top-level JSON node
*
* @returns Returns true if successful
*/
static bool decode_json_mandatory_fields(const nx_json *node)
{
const nx_json *field;
int32_t protocol_version;
int32_t message_id;
const char *mac_address;
// Extract and check the protocol version
field = nx_json_get(node, "proto_ver");
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted protocol version");
return false;
}
protocol_version = field->int_value;
if (protocol_version != PROTOCOL_VERSION)
{
DEBUG_ERROR("Incorrect protocol version");
strcpy(_command_error_message, "Incorrect protocol version");
return false;
}
// Extract the message number
field = nx_json_get(node, "msg_id");
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted message ID");
return false;
}
message_id = field->int_value;
// Extract the MAC address and check the message is for us
field = nx_json_get(node, "mac_addr");
if (field->type != NX_JSON_STRING)
{
strcpy(_command_error_message, "Missing or incorrectly formatted MAC address");
return false;
}
mac_address = field->text_value;
if (strcmp(mac_address, _controller.mac_address) != 0)
{
DEBUG_ERROR("Incorrect MAC address");
strcpy(_command_error_message, "Incorrect MAC address");
return false;
}
// Extract the next POST delay suggestion
field = nx_json_get(node, "next_post");
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted next post delay");
return false;
}
_next_post_delay = field->int_value;
DEBUG_VERBOSE("Protocol version: %ld", protocol_version);
DEBUG_VERBOSE("Message ID: %ld", message_id);
DEBUG_VERBOSE("MAC address: %s", mac_address);
DEBUG_VERBOSE("Next post delay: %ld", _next_post_delay);
return true;
}
/**
* @brief Decodes the fields for a retrieve program command supplied in a JSON node
*
* @param command_node JSON node containing the command
*
* @returns Returns true if successful
*/
static bool decode_json_retrieve_program_command(const nx_json *command_node)
{
const nx_json *field;
// Extract and check the program number
field = nx_json_get(command_node, "prog");
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted program number");
return false;
}
_read_program_buffer.program_number = (uint8_t)field->int_value;
DEBUG_VERBOSE("Program number: %d", _read_program_buffer.program_number);
if (_read_program_buffer.program_number < 1 ||
_read_program_buffer.program_number > _controller.configuration.max_programs)
{
strcpy(_command_error_message, "Program number out of range");
return false;
}
return true;
}
/**
* @brief Decodes the fields for a store program command supplied in a JSON node structure
*
* @param command_node JSON node containing the command
*
* @returns Returns true if successful
*/
static bool decode_json_store_program_command(const nx_json *command_node)
{
const nx_json *field;
const nx_json *segments_node;
const nx_json *segment_node;
int32_t segment_index;
_TProgramSegment *segment;
_TControllerConfiguration *configuration = &(_controller.configuration);
// Extract and check the program number
field = nx_json_get(command_node, "prog");
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted program number");
return false;
}
_write_program_buffer.program_number = (uint8_t)field->int_value;
DEBUG_VERBOSE("Program number: %d", _write_program_buffer.program_number);
if (_write_program_buffer.program_number < 1 ||
_write_program_buffer.program_number > _controller.configuration.max_programs)
{
strcpy(_command_error_message, "Program number out of range");
return false;
}
// Extract segment information
segments_node = nx_json_get(command_node, "segs");
if (segments_node->type != NX_JSON_ARRAY)
{
strcpy(_command_error_message, "Missing or incorrectly formatted segment array");
return false;
}
for (segment_index = 0; segment_index < segments_node->length; segment_index++)
{
segment_node = nx_json_item(segments_node, segment_index);
segment = &(_write_program_buffer.segments[segment_index]);
if (segment_node->length != 4)
{
strcpy(_command_error_message, "Incorrect program segment definition");
return false;
}
field = nx_json_item(segment_node, 0);
if (field->type != NX_JSON_INTEGER && field->type != NX_JSON_DOUBLE)
{
strcpy(_command_error_message, "Missing or incorrectly formatted ramp rate");
return false;
}
if (field->type == NX_JSON_INTEGER)
{
segment->ramp_rate = configuration->ramp_rate_scaling * field->int_value;
}
else
{
segment->ramp_rate = (uint16_t)(configuration->ramp_rate_scaling * field->dbl_value);
}
field = nx_json_item(segment_node, 1);
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted target temperature");
return false;
}
segment->target_temperature = field->int_value;
field = nx_json_item(segment_node, 2);
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted soak time");
return false;
}
segment->soak_time = field->int_value;
field = nx_json_item(segment_node, 3);
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted event flags");
return false;
}
segment->event_flags = field->int_value;
DEBUG_VERBOSE("Segment number: %ld", segment_index + 1);
DEBUG_VERBOSE("Ramp rate: %d", segment->ramp_rate);
DEBUG_VERBOSE("Target temperature: %d", segment->target_temperature);
DEBUG_VERBOSE("Soak time: %d", segment->soak_time);
DEBUG_VERBOSE("Event flags: %d", segment->event_flags);
}
// Store the number of segments
_write_program_buffer.segments_used = (uint8_t)segments_node->length;
// Write the program to the controller
if (!write_program(_write_program_buffer.program_number,
_controller.configuration.max_segments,
&_write_program_buffer))
{
strcpy(_command_error_message, "Cannot write program to controller");
return false;
}
return true;
}
/**
* @brief Decodes the fields for a stop program command supplied in a JSON node structure
*
* @param command_node JSON node containing the command
*
* @returns Returns true if successful
*/
static bool decode_json_stop_program_command(const nx_json *command_node)
{
// Stop the program
if (!stop_program())
{
strcpy(_command_error_message, "Cannot stop program");
return false;
}
return true;
}
/**
* @brief Decodes the fields for a retrieve event command supplied in a JSON node structure
*
* @param command_node JSON node containing the command
*
* @returns Returns true if successful
*/
static bool decode_json_retrieve_event_command(const nx_json *command_node)
{
const nx_json *field;
// Extract and check the event number
field = nx_json_get(command_node, "id");
if (field->type != NX_JSON_INTEGER)
{
strcpy(_command_error_message, "Missing or incorrectly formatted event number");
return false;
}
_read_event_buffer.event_id = field->int_value;
DEBUG_VERBOSE("Event ID: %ld", _read_event_buffer.event_id);
if (_read_event_buffer.event_id < 1)
{
strcpy(_command_error_message, "Invalid event ID number");
return false;
}
return true;
}
/**
* @brief Decodes the fields for a clear events command supplied in a JSON node structure
*
* @param command_node JSON node containing the command
*
* @returns Returns true if successful
*/
static bool decode_json_clear_events_command(const nx_json *command_node)
{
// Clear events
if (!clear_events())
{
strcpy(_command_error_message, "Cannot clear events");
return false;
}
return true;
}
/**
* @brief Returns the name associated with a given firing state code
*
* @param firing_state firing state code
*
* @returns Returns the name of the firing state
*/
static char *get_firing_state_name(int32_t firing_state)
{
switch (firing_state)
{
case FIRING_STATE_INITIALISING: return "initialising";
case FIRING_STATE_IDLE: return "idle";
case FIRING_STATE_DELAY: return "delay";
case FIRING_STATE_RAMP_HEATING: return "ramp_heating";
case FIRING_STATE_RAMP_HEATING_PAUSED: return "ramp_heating_paused";
case FIRING_STATE_RAMP_COOLING: return "ramp_cooling";
case FIRING_STATE_RAMP_COOLING_PAUSED: return "ramp_cooling_paused";
case FIRING_STATE_SOAK: return "soak";
case FIRING_STATE_SOAK_PAUSED: return "soak_paused";
case FIRING_STATE_COOLING: return "cooling";
case FIRING_STATE_COOL: return "cool";
case FIRING_STATE_ERROR: return "error";
case FIRING_STATE_SETUP: return "setup";
case FIRING_STATE_POWER_FAIL: return "power_fail";
case FIRING_STATE_PAIRING: return "pairing";
case FIRING_STATE_AP: return "access_point";
default: return "";
}
}
/**
* @brief Returns the name associated with a given thermocouple type
*
* @param thermocouple_type thermocouple type code
*
* @returns Returns the name of the thermocouple
*/
static char *get_thermocouple_type_name(int32_t thermocouple_type)
{
switch (thermocouple_type)
{
case THERMOCOUPLE_K: return "K";
case THERMOCOUPLE_N: return "N";
case THERMOCOUPLE_R: return "R";
case THERMOCOUPLE_S: return "S";
default: return "";
}
}
/**
* @brief Returns the name associated with a given event relay function
*
* @param event_relay_function event relay function
*
* @returns Returns the name associated with the function
*/
static char *get_event_relay_function_name(int32_t event_relay_function)
{
switch (event_relay_function)
{
case EVENT_RELAY_OFF: return "off";
case EVENT_RELAY_EVENT: return "event";
case EVENT_RELAY_DAMPER: return "damper";
case EVENT_RELAY_FAN: return "fan";
default: return "";
}
}
/**
* @brief Returns the name associated with a given event log entry type
*
* @param event_type event type code
*
* @returns Returns the name of the event type
*/
static char *get_event_type_name(int32_t event_type)
{
switch (event_type)
{
case EVENT_NONE: return "none";
case EVENT_POWER_ON: return "power_on";
case EVENT_PROGRAM_STARTED: return "start_prog";
case EVENT_PROGRAM_STOPPED: return "stop_prog";
case EVENT_CONTROLLER_ERROR: return "controller_error";
case EVENT_PIC_LINK_ERROR: return "comms_1_error";
case EVENT_ESP32_LINK_ERROR: return "comms_2_error";
case EVENT_WIFI_CONNECTED: return "wifi_connected";
case EVENT_WIFI_DISCONNECTED: return "wifi_disconnected";
case EVENT_SERVER_ERROR: return "server_error";
default: return "";
}
} |
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
// Contains the value and text for the options
const languages = [
{ value: "", text: "Options" },
{ value: "en", text: "English" },
{ value: "hi", text: "Hindi" },
{ value: "bn", text: "Bengali" },
];
function Helper() {
// It is a hook imported from 'react-i18next'
const { t } = useTranslation();
const [lang, setLang] = useState("en");
// This function put query that helps to
// change the language
const handleChange = (e) => {
setLang(e.target.value);
let loc = "http://localhost:3000/";
window.location.replace(loc + "?lng=" + e.target.value);
};
return (
<div>
<h1>{t("welcome")}</h1>
<label>{t("choose")}</label>
<select value={lang} onChange={handleChange}>
{languages.map((item) => {
return (
<option key={item.value} value={item.value}>
{item.text}
</option>
);
})}
</select>
</div>
);
}
export default Helper; |
--Creating the Batch Table--
CREATE TABLE ContactBatch
(
BatchID int Primary key Identity(1,1),
DateCreated DateTime,
CreatedBy nvarchar(50),
DateModified DateTime,
[Status] nvarchar(20)
)
--Adding BatchID to Contact table--
ALTER TABLE Contacts
ADD BatchID int,
FOREIGN KEY (BatchID) REFERENCES ContactBatch(BatchID)
--Adding BatchName to ContactBatch table--
ALTER TABLE ContactBatch
ALTER COLUMN BatchName nvarchar(50)
--Alter a column in ContactBatch--
ALTER TABLE ContactBatch
ALTER COLUMN DateModified DATETIME2
--Selecting the Table BatchID--
Select * from ContactBatch
--Deleteing table data--
TRUNCATE Table ContactBatch
--Deleting Identity Column with references--
DELETE from ContactBatch
DBCC Checkident('Sample.dbo.ContactBatch', reseed, 0);
--Adding stored procedure for batchId that returns the identity column--
--stored procedure to return output parameter
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[AddBatchReturnIDWithOutput]
@DateCreated DateTime = NULL,
@CreatedBy varchar(50),
@DateModified DateTime = null,
@Status varchar(20) = null,
@BatchName nvarchar(50) = null,
@BatchID int output
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO ContactBatch (DateCreated, CreatedBy, DateModified, [Status], BatchName)
VALUES (@DateCreated, @CreatedBy, @DateModified, @Status, @BatchName)
SELECT @BatchID = SCOPE_IDENTITY()
END
--GET ALL stored procedure--
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE spGetAllBatches
AS
BEGIN
SET NOCOUNT ON;
SELECT * from ContactBatch
END
GO
--stored procedure to get contact by BatchId--
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create PROCEDURE spGetContactByBatchId
@BatchID int
AS
BEGIN
SET NOCOUNT ON;
SELECT * from Contacts
WHERE BatchID = @BatchID
END
GO
--Get all from ContactBatch Table--
Select * from ContactBatch
--Get All from Contact TAble--
Select * from Contacts
--Stored Procedure to Get COntact by BatchID--
CREATE PROCEDURE spGetContactByBatches
@BatchID int
AS
BEGIN
SET NOCOUNT ON;
SELECT * FROM Contacts WHERE BatchID = @BatchID
END
GO
--Delete contacts by BatchId--
Delete from Contacts Where BatchID = 2
--Delete row by batchId
Delete from ContactBatch where BatchID = 1
--Stored Procedure to delete from both Contacts & ContactsBatch by BatchId--
CREATE PROCEDURE spDeleteFileByBatchId
@BatchID int
AS
BEGIN
SET NOCOUNT ON;
DELETE FROM Contacts WHERE BatchID = @BatchID;
DELETE FROM ContactBatch Where BatchID = @BatchID;
END
GO |
// 入口文件
// ----------------------------实现了一个基本的 Hello World
// // 1. 加载 express 模块
// const express = require('express');
//
// // 2. 创建一个 app 对象(类似于创建一个 server 对象)
// const app = express();
//
// // 通过中间件监听指定路由的请求
// app.get('/index', function (req, res) {
// // body...
// // res.end('hello world!你好世界!');
// res.send('Hello World.你好世界!');
//
// // res.end() 和 res.send() 区别
// // 1. 参数类型区别:
// // - res.send() 参数可以是a Buffer object,a String,an object,an Array.
// // - res.end() 参数类型只能是 Buffer 对象或者是字符串
// // 2. res.send() 会自动发送更多的响应报文头,其中就包括 Content-Type: text/html; charset=utf-8,所有没有乱码
// });
//
// // 3,启动服务
// app.listen(9092, function () {
// console.log('http://localhost:9092');
// });
//------------------------express 中注册路由的方法
// 1. 加载 express 模块
const express = require('express');
// 2. 创建一个 app 对象(类似于创建一个 server 对象)
const app = express();
// ----------------------注册路由---------------
// // 通过中间件监听指定路由的请求
// // req.url 中的 pathname 部分必须和 /index 一致
// app.get('/index', function (req, res) {
// res.send('Hello World.你好世界!');
// });
// // 1.在进行路由匹配的时候不限定方法,什么请求方法都可以
// // 2.请求路径中的第一部分只要与/index 相等即可,并不要求请求路径(pathname)完全匹配
// app.use('/index', function (req, res) {
// res.send('hello world!你好世界!');
// });
// 通过正则表达式注册路由
// app.get(/^\/index(\/.+)*$/, function (req, res) {
// res.send('Hello World.你好世界!');
// });
// 通过req.params获取路由参数
app.get('/news/:years/:month/:day', function (req, res) {
// console.log(req.params);
res.send(req.params);
});
// app.get() 和 app.use() 注册路由的区别
// app.all()
// 通过 app.all() 注册路由:1,不限定请求方法;2,请求的路径的pathname必须完全限定
// app.all('/index', function (req, res) {
// res.send('hello world!你好世界!');
// });
// 注册一个请求 / 的路由
app.get('/', function (req, res) {
res.send("Index");
});
// 含义:
// 1. 请求方法必须是 get
// 2. 请求路径的 pathname 必须等于(===)/submit
app.get('/submit', function (req, res) {
res.send("submit");
});
app.get('/item', function (req, res) {
res.send("item");
});
app.get('/add', function (req, res) {
res.send('get 请求 /add');
});
app.post('/add', function (req, res) {
res.send('post 请求 /add');
});
// 3,启动服务
app.listen(9092, function () {
console.log('http://localhost:9092');
}); |
import React, { useEffect, useState } from 'react';
import Box from '@mui/material/Box';
import Toolbar from '@mui/material/Toolbar';
import IconButton from '@mui/material/IconButton';
import Typography from '@mui/material/Typography';
import Menu from '@mui/material/Menu';
import MenuIcon from '@mui/icons-material/Menu';
import Button from '@mui/material/Button';
import MenuItem from '@mui/material/MenuItem';
const pages = ['search', 'about', 'contact'];
const MenuPages: React.FC = () => {
const [anchorElNav, setAnchorElNav] = React.useState(null);
const handleOpenNavMenu = (event: any) => {
setAnchorElNav(event.currentTarget);
};
const handleCloseNavMenu = () => {
setAnchorElNav(null);
};
return (
<Toolbar disableGutters>
<Box sx={{ flexGrow: 1, display: { xs: 'none', md: 'flex' } }}>
{pages.map((page) => (
<Button
href={page}
key={page}
onClick={handleCloseNavMenu}
sx={{ my: 2, display: 'block' }}>
{page}
</Button>
))}
</Box>
<Box sx={{ flexGrow: 1, display: { xs: 'flex', md: 'none' } }}>
<IconButton
size="large"
aria-label="account of current user"
aria-controls="menu-appbar"
aria-haspopup="true"
onClick={handleOpenNavMenu}
color="inherit">
<MenuIcon />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorElNav}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'right',
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={Boolean(anchorElNav)}
onClose={handleCloseNavMenu}
sx={{
display: { xs: 'block', md: 'none' },
}}>
{pages.map((page) => (
<MenuItem key={page} onClick={handleCloseNavMenu}>
<Typography textAlign="center">{page}</Typography>
</MenuItem>
))}
</Menu>
</Box>
</Toolbar>
);
};
export default MenuPages; |
package ex04_OutputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
public class MainClass {
/*
출력 단위
1. int : 1개
2. byte[] : 2개 이상
*/
public static void ex01() {
File dir = new File("/Users/woomin/Documents/storage");
File file = new File(dir, "ex01.bin");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
int c = 'A';
String str = "pple";
byte[] b = str.getBytes();
fos.write(c);
fos.write(b);
} catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(fos != null) {
fos.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void ex02() {
File dir = new File("/Users/woomin/Documents/storage");
File file = new File(dir, "ex02.bin");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
String str = "안녕하세요";
// getBytes(CharSet charset) : 텍스트 인코딩 설정 방법1, jdk 1.7부터 사용 가능
byte[] b = str.getBytes(StandardCharsets.UTF_8);
// getBytes(String charsetName) : 텍스트 인코딩 설정 방법2, jdk 1.1부터 사용 가능
// byte[] b = str.getBytes("UTF-8");
fos.write(b);
}catch(IOException e) {
e.printStackTrace();
} finally {
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("ex02.bin 파일의 크기 : " + file.length());
}
public static void ex03() {
File dir = new File("/Users/woomin/Documents/storage");
File file = new File(dir, "ex03.bin");
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write("반갑습니다\n 또 만나여".getBytes("UTF-8"));
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
if(bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("ex03.bin 파일의 크기 : " + file.length());
}
public static void ex04() {
// 변수를 그대로 출력하는 DataOutputStream
File dir = new File("/Users/woomin/Documents/storage");
File file = new File(dir,"ex04.dat");
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream(file));
// 출력할 변수
String name = "조우민";
String called = "땅땅땅깡땅땅";
int age = 27;
double height = 178.9;
boolean isAlive = true;
// 출력(변수 타입에 따라서 메소드가 다름)
dos.writeUTF(name);
dos.writeUTF(called);
dos.writeInt(age);
dos.writeDouble(height);
dos.writeBoolean(isAlive);
}catch(IOException e) {
e.printStackTrace();
} finally {
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("ex04.dat 파일 크기 : " + file.length());
}
public static void ex05() {
// 객체를 그대로 출력하는 ObjectOutputStream
File dir = new File("/Users/woomin/Documents/storage");
File file = new File(dir,"ex05.dat");
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(file));
// 출력할 객체
List<Person> people = Arrays.asList(
new Person("조우민", 27, 178.9, true),
new Person("제시", 54, 200.9, false)
);
Person person = new Person();
person.setName("존슨");
person.setAge(30);
person.setHeight(230.5);
person.setAlive(true);
// 출력하는 코드
oos.writeObject(people);
oos.writeObject(person);
}catch (IOException e) {
e.printStackTrace();
} finally {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("ex05.dat 파일 크기 : " + file.length());
}
public static void main(String[] args) {
ex05();
}
} |
import React, { useState } from 'react'
import { CardComponent } from '../components/CardComponent'
import { LoadingComponent } from '../components/LoadingComponent';
import { NoResultsComponent } from '../components/NoResultsComponent';
import { SearcherBarComponent } from '../components/SearcherBarComponent'
import { useUsers } from '../hooks/useUsers';
export const UsersPage = () => {
const [ userIsLooking, setUserIsLooking ] = useState( false );
const { users, isLoading, loadUsers } = useUsers();
return (
<div className='main-container shadow bg-light animate__animated animate__fadeIn'>
<h1 className='text-primary'>Github Users</h1>
<div className='row'>
<div className='col-sm-5'>
<SearcherBarComponent loadResults={ loadUsers } setUserIsLooking={ setUserIsLooking }/>
</div>
</div>
<div className='row pt-4'>
<div className='col-sm-12'>
{
( isLoading )
? <LoadingComponent />
: (
users.length > 0
? users.map( ( user ) => <CardComponent key={ user.login + user.id } user={ user } /> )
: <NoResultsComponent />
)
}
</div>
</div>
</div>
)
} |
/* Angular/vendor imports. */
import { Injectable } from '@angular/core';
/* Package Imports. */
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import * as _ from 'lodash';
import { NgRedux, select } from '@angular-redux/store';
import { SagaHelper } from '@setl/utils/index';
import { MyMessagesService } from '@setl/core-req-services';
import { commonHelper } from '@setl/utils';
import { IssueAssetActionModel } from './messages/message-components/issue-asset-action/issue-asset-action.model';
import {
MessageActionsConfig,
MessageCancelOrderConfig,
MessageConnectionConfig,
MessageKycConfig,
} from '@setl/core-messages';
import { MessageWithLinksConfig } from "./messages/message-components/message-with-links/message-with-links.model";
/* Service Class. */
@Injectable()
export class MessagesService {
@select(['user', 'connected', 'connectedWallet']) getConnectedWallet: Observable<any>;
@select(['wallet', 'walletDirectory', 'walletList']) getWalletDirectory: Observable<any>;
language;
subscriptionsArray: Subscription[] = [];
connectedWallet;
walletDirectory;
replyData;
/* Constructor. */
constructor(private ngRedux: NgRedux<any>,
private myMessageService: MyMessagesService) {
this.subscriptionsArray.push(
this.getConnectedWallet.subscribe(
(function (newWalletId) {
this.connectedWallet = newWalletId;
}).bind(this)),
);
this.subscriptionsArray.push(
this.getWalletDirectory.subscribe(
(function (data) {
this.walletDirectory = data;
}).bind(this),
),
);
}
/**
* Sends Message
*
* @param recipientsArr - Array of WalletId'
* @param subjectStr
* @param bodyStr
* @param {string} action
* @returns {Promise<any>}
*/
public sendMessage(recipientsArr, subjectStr, bodyStr, action: MessageActionsConfig | MessageConnectionConfig | MessageKycConfig | IssueAssetActionModel | MessageCancelOrderConfig | MessageWithLinksConfig = null) {
const bodyObj = {
general: commonHelper.b64EncodeUnicode(bodyStr),
action: JSON.stringify(action),
};
const body = JSON.stringify(bodyObj);
const subject = commonHelper.b64EncodeUnicode(subjectStr);
const recipients = {};
let senderPub;
// get pub key for recipients
for (const i in recipientsArr) {
const walletId = recipientsArr[i];
const wallet = _.find(this.walletDirectory, (obj) => {
return obj.walletID === parseInt(walletId, 10);
});
recipients[walletId] = wallet.commuPub;
}
// get current wallet
const currentWallet = _.find(this.walletDirectory, (obj) => {
return obj.walletID === parseInt(this.connectedWallet, 10);
});
senderPub = currentWallet.commuPub;
return this.sendMessageRequest(subject, body, this.connectedWallet, senderPub, recipients);
}
/**
* Send Message Request
*
* @param subject
* @param body
* @param senderId
* @param senderPub
* @param recipients
*
* @returns {Promise<any>}
*/
public sendMessageRequest(subject, body, senderId, senderPub, recipients) {
return new Promise((resolve, reject) => {
const asyncTaskPipe = this.myMessageService.sendMessage(
subject,
body,
senderId,
senderPub,
recipients,
);
// Get response from set active wallet
this.ngRedux.dispatch(SagaHelper.runAsyncCallback(
asyncTaskPipe,
(data) => {
resolve(data);
},
(data) => {
reject(data);
}),
);
});
}
/**
* Marks Message as Acted
*
* @param walletId
* @param mailsToMark
* @returns {Promise<any>}
*/
public markMessageAsActed(walletId, mailsToMark, hash) {
return this.markMessageAsActedRequest(walletId, mailsToMark, hash);
}
/**
* Marks Message as Acted Request
*
* @param subject
* @param body
* @param senderId
* @param senderPub
* @param recipients
*
* @returns {Promise<any>}
*/
public markMessageAsActedRequest(walletId, mailsToMark, hash) {
return new Promise((resolve, reject) => {
const asyncTaskPipe = this.myMessageService.markAsActed(walletId, mailsToMark, hash);
// Get response from set active wallet
this.ngRedux.dispatch(SagaHelper.runAsyncCallback(
asyncTaskPipe,
(data) => {
resolve(data);
},
(data) => {
reject(data);
}),
);
});
}
/**
* Saves reply message
*
* @param messageData
*/
public saveReply(messageData) {
this.replyData = {
senderId: messageData['senderId'],
senderWalletName: messageData['senderWalletName'],
subject: messageData['subject'],
body: messageData['content'],
date: messageData['date'],
};
}
/**
* Loads reply message
*
* @returns {Promise<any>}
*/
public loadReply() {
return new Promise((resolve, reject) => {
resolve(this.replyData);
});
}
/**
* Clears reply message
*/
public clearReply() {
this.replyData = {};
}
} |
package org.example;
public class JvmComprehension {
public static void main(String[] args) {
// Создание в Stack Memory в пределах одного фрейма, связанного с методом main, примитивной переменной и присваивание ей 1
int i = 1;
// Создание объекта класса Object: в куче выделится место под данный класс, после вызовется конструктор (без параметров),
// который создаст в куче объект данного класса, далее после присвоения переменной "o" типа Object в фрейме, который связан с методом main,
// создастся ссылка, которая будет указывать где в куче находится данный объект
Object o = new Object();
// Создание в Stack Memory в пределах одного фрейма, связанного с методом main, примитивной переменной и присваивание ей 2
Integer ii = 2;
// Вызов метода printAll(): в Stack Memory создастся новый фрейм printAll и в этот новый фрейм мы передаем объект "о" и две переменные "i" и "ii".
// Для создания переменных и объекта в фрейме создастся переменная "о", которая будет указывать на объект Object (который уже создан),
// и примитивные переменные "i" и "ii", которым будут присвоены значения 1 и 2 соответственно
printAll(o, i, ii);
// Вызов системного метода println(), который выведет на консоль "finished"
System.out.println("finished"); // 7
}
private static void printAll(Object o, int i, Integer ii) {
// Создание в Stack Memory в пределах одного фрейма, связанного с методом printAll, примитивной переменной и присваивание ей 700
Integer uselessVar = 700;
// Вызов системного метода println(): создастся новый фрейм в Stack Memory, далее в новом фрейме создастся переменная "o", которая будет ссылаться
// на объект Object (который уже создан), и примитивные переменные "i" и "ii", которым будут присвоены значения 1 и 2 соответственно.
// Затем из объекта Object вызовется метод toString(), который вернет нам текстовое описание объекта, т.е. полное наименование класса объекта,
// у которого вызвали метод и его хешкод + к этому текстовому описанию припишутся 1 и 2
System.out.println(o.toString() + i + ii);
}
} |
package com.challenge.bricks.controller.response;
import com.challenge.bricks.persistence.model.Product;
import lombok.*;
import java.math.BigDecimal;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class ProductListResponse {
private Long productId;
private String name;
private Integer stock;
private BigDecimal price;
private Boolean active;
private CategoryDTO category;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public static class CategoryDTO{
private Long categoryId;
private String categoryName;
}
public static ProductListResponse convertTo(Product p) {
return ProductListResponse.builder()
.productId(p.getProductId())
.name(p.getName())
.price(p.getPrice())
.stock(p.getStock())
.category(CategoryDTO.builder()
.categoryId(p.getCategory().getId())
.categoryName(p.getCategory().getName())
.build())
.active(p.getActive())
.build();
}
} |
""" The following script creates two data visualisations based on the results within euros_results.py.
The visualisations are as follows: - Bar Chart of the top ten highest xG players at the euros
- Scatter plot of xG per 90 vs actual goals per 90"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from highlight_text import fig_text
from Source import euros_results, jmann_viz_setup as jvs
def data_prep_viz():
"""Prepares the variables needed to create the bar chart and scatter plot visualisation.
Parameters:
- player_mintues (pd.DataFrame): Dataframe containing the minutes played data for each player at Euro 2020
Returns:
- top_10_players (pd.DataFrame): Dataframe containing the top 10 players in a certain statistic.
In this specific case, top 10 players with the highest xG at Euro 2020.
- x (pd.Series): Series containing xG per 90 values for each player at Euro 2020 (min of 90 mins played to qualify)
- y (pd.Series): Series containing the number of actual goals scored per player at Euro 2020 (min of 90 mins played)
"""
top_players: pd.DataFrame = euros_results.shots.groupby(
["player_name"])["our_xg"].sum().sort_values(ascending=False)[:10].reset_index()
file_path = '../euro2020.csv'
m_played: pd.DataFrame = pd.read_csv(file_path)
m_played = m_played.rename(columns={"Player_name": 'player_name'})
players_g: pd.DataFrame = euros_results.shots[
euros_results.shots["outcome_name"] == "Goal"].groupby("player_name").size().reset_index(
name='total_goals')
# Merge datasets
players_total: pd.DataFrame = pd.merge(players_g, m_played, on='player_name', how='inner')
players_total = pd.merge(players_total, euros_results.players_xg, on='player_name', how='inner')
# Apply the condition and calculate per 90 stats
players_total.loc[players_total['Player_Minutes'] > 90, "Goals P90"] = (
(players_total["total_goals"] / players_total['Player_Minutes']) * 90)
players_total.loc[players_total['Player_Minutes'] > 90, "xG P90"] = (
(players_total["our_xg"] / players_total['Player_Minutes']) * 90)
players_total['Difference'] = (players_total["Goals P90"] - players_total["xG P90"])
# Create X and Y variable to equate to goals and xG
x: pd.Series = players_total['xG P90']
y: pd.Series = players_total['Goals P90']
diff: pd.Series = players_total['Difference']
# Get surnames only
players_total['surname'] = players_total['player_name'].apply(lambda x: x.split()[-1])
# Identify the top 10 players based on the "Difference" column
top_10_players: pd.DataFrame = players_total.nlargest(10, 'Difference')
return top_players, top_10_players, x, y, diff
top_players, top_10_players, x, y, diff = data_prep_viz()
# State font required for visualisations
dmfont: dict[str, str] = {'family': 'DM Sans'}
""" ***** Data visualisations *****"""
def top_10_barchart(top_10: pd.DataFrame, font: dict):
""" Creates a barchart visualisation of the top 10 players within a certain statistic. Specific to this project,
this function creates a barchart of the top 10 players with the highest xG at Euro 2020.
Parameters:
- top_10 (pd.DataFrame): Dataframe containing the top 10 players in a certain statistic.
In this specific case, top 10 players with the highest xG at Euro 2020.
- font (dict): Dictionary strings related to the font use for text within the barchart
"""
fig = plt.figure(figsize=(6, 2.5), dpi=200, facecolor="#bebfc4")
ax = plt.subplot(111, facecolor="#bebfc4")
width = 0.5
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.grid(True, color="lightgrey", ls=":")
# width = 0.5 #todo check if this is needed
height = top_10["our_xg"]
bars = ax.barh(
top_10["player_name"],
top_10["our_xg"],
ec="black",
lw=.75,
color='#138015',
zorder=3,
)
ax.bar_label(bars, **font, fmt='%.1fxG',
label_type='edge', padding=0.5,
fontsize=5, color='#138015', fontweight='bold')
ax.tick_params(labelsize=8)
fig_text(
x=0.23, y=0.95,
s="Top 10 player with the highest expected goals for Euro 2020 based on a neural network model",
**font,
color="black",
size=10
)
fig_text(
x=0.23, y=0.9,
s="Viz by Josh Mann",
**font,
color="#565756",
size=8
)
# Add logo
jvs.watermark(ax, 10, 6)
top_10_barchart(top_players, dmfont)
plt.show()
def player_scatter(x: pd.Series, y: pd.Series, diff: pd.Series, font: dict):
""" Creates a scatter plot of player statistics. Specific to this project, the scatter is based on
actual goals scored per 90 minutes played vs xG per 90 minutes. This is to identify players who overperform
their xG.
Parameters:
- x (pd.Series): Series containing xG per 90 values for each player at Euro 2020 (min of 90 mins played to qualify).
- y (pd.Series): Series containing the number of actual goals scored per player at Euro 2020 (min of 90 mins played)
- font (dict): Dictionary strings related to the font use for text within the barchart
"""
fig = plt.figure(figsize=(8, 6), facecolor='#bebfc4')
ax = plt.subplot(111, facecolor="#bebfc4")
scatter = ax.scatter(x, y, s=100, c=diff, cmap='YlGn',
edgecolors='black', linewidths=1, alpha=0.75)
# Customisation
plt.style.use('seaborn')
cbar = fig.colorbar(scatter, ax=ax, label='xG Overperformance')
cbar.set_ticks(np.arange(0, 0.78, 0.25))
ax.set_xticks(np.arange(0, 1, 0.2))
ax.set_yticks(np.arange(0, 1.6, 0.2))
ax.set_xlabel('Expected Goals (xG) p90')
ax.set_ylabel('Actual Goals Score p90')
ax.grid(True, linestyle='--', linewidth=0.5, color='gray', which='both', alpha=0.7)
# Add logo
jvs.watermark(ax, 8, 6)
# Annotate the top 10 players on the scatterplot
for i, player in top_10_players.iterrows():
plt.annotate(player['player_name'], (player['xG P90'], player['Goals P90']),
textcoords="offset points", xytext=(4, 4), ha='left')
fig_text(
x=0.15, y=0.95,
s="Euro 2020: xG p90 vs Actual Goals Scored p90",
**font,
color="black",
size=20
)
fig_text(
x=0.15, y=0.9,
s="Viz by Josh Mann",
**font,
color="#565756",
size=16
)
player_scatter(x, y, diff, dmfont)
plt.show() |
package br.senai.sp.jandira.triproom.dao
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import br.senai.sp.jandira.triproom.model.User
@Database(entities = [User::class], version = 3)
abstract class TripDb: RoomDatabase() {
abstract fun userDao(): UserDao
companion object{
private lateinit var instanceDb: TripDb
fun getDataBase(context: Context): TripDb{
if(!::instanceDb.isInitialized){
instanceDb = Room
.databaseBuilder(
context,
TripDb::class.java,
"trip_db"
).allowMainThreadQueries().fallbackToDestructiveMigration().build()
}
return instanceDb
}
}
} |
'use client';
import React, { useState, useCallback } from "react";
import { AiOutlineMinus, AiOutlinePlus } from "react-icons/ai";
interface CounterProps {
title: string;
subtitle: string;
value: number;
onChange: (value: number) => void;
allowZero?: boolean;
}
const Counter: React.FC<CounterProps> = ({
title,
subtitle,
value,
onChange,
allowZero = false, // Default to false if not provided
}) => {
const [inputValue, setInputValue] = useState<string>(value.toString());
const isNumeric = (value: string) => /^[0-9]+$/.test(value); // Regex to check for numeric values
const updateValue = useCallback((newValue: number) => {
setInputValue(newValue.toString());
onChange(newValue);
}, [onChange]);
const onAdd = useCallback(() => updateValue(value + 1), [updateValue, value]);
const onReduce = useCallback(() => {
if (value > 0) updateValue(value - 1);
}, [updateValue, value]);
const handleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
const newValue = event.target.value;
if (newValue === '' || isNumeric(newValue)) {
setInputValue(newValue); // Update local state
}
const numericValue = parseInt(newValue, 10);
if (!isNaN(numericValue) && (allowZero || numericValue > 0)) {
onChange(numericValue); // Update parent state if value is valid
}
}, [onChange, allowZero]);
const handleBlur = useCallback(() => {
const numericValue = parseInt(inputValue, 10);
if (inputValue === '' || isNaN(numericValue) || (!allowZero && numericValue <= 0)) {
const resetValue = allowZero ? 0 : 1;
setInputValue(resetValue.toString()); // Reset to 0 or 1 based on allowZero
onChange(resetValue); // Update parent state
}
}, [inputValue, onChange, allowZero]);
return (
<div className="flex flex-row items-center justify-between">
<div className="flex flex-col">
<div className="font-medium">{title}</div>
<div className="font-light text-gray-600">{subtitle}</div>
</div>
<div className="flex flex-row items-center gap-4">
<button onClick={onReduce} className="w-10 h-10 rounded-full border border-neutral-400 flex items-center justify-center text-neutral-600 cursor-pointer hover:opacity-80 transition">
<AiOutlineMinus />
</button>
<input type="text" value={inputValue} onChange={handleChange} onBlur={handleBlur} className="w-20 text-center font-light text-xl text-neutral-600" />
<button onClick={onAdd} className="w-10 h-10 rounded-full border border-neutral-400 flex items-center justify-center text-neutral-600 cursor-pointer hover:opacity-80 transition">
<AiOutlinePlus />
</button>
</div>
</div>
);
}
export default Counter; |
<?php
namespace AppBundle\Entity;
use AppBundle\Traits\BlameableEntityAssociation;
use AppBundle\Validator\Constraints as AppAssert;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Timestampable\Traits\TimestampableEntity;
use JMS\Serializer\Annotation as JMS;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;
/**
* RisksControls.
*
* @ORM\Table(name="risks_controls", uniqueConstraints={
* @ORM\UniqueConstraint(name="RISKS_CONTROLS_UNIQUE_KEY_MINE_TYPE_SPECIFIC", columns={"type", "mine_id", "_specific"})
* })
* @ORM\Entity(repositoryClass="AppBundle\Repository\RisksControlsRepository")
* @UniqueEntity(
* fields={"type", "mine", "specific"},
* errorPath="type",
* message="Ya existe este tipo para esta mina."
* )
* @AppAssert\ThresholdType()
*
* @author snake77se <[email protected]>
*/
class RisksControls
{
const GUSTS_OF_WIND_KM_HR = 'gusts_of_wind_km_hr';
const SNOW_FALL = 'snow_fall';
const LOW_HUMIDITY = 'low_humidity';
const LOW_TEMPERATURES = 'low_temperatures';
const HIGH_PROBABILITY_RAIN = 'high_probability_rain';
const HIGH_PROBABILITY_SNOW = 'high_probability_snow';
const HIGH_PROBABILITY_THUNDERSTORM = 'high_probability_thunderstorm';
const SOIL_FREEZING = 'soil_freezing';
const SOIL_FREEZING_YES_LABEL = 'SI';
const SOIL_FREEZING_NO_LABEL = 'NO';
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @JMS\SerializedName("id")
* @JMS\Groups({"risks_controls_list","risks_controls_detail"})
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="type", type="string", length=255)
* @JMS\SerializedName("type")
* @JMS\Groups({"risks_controls_list","risks_controls_detail"})
* @Assert\NotNull()
*/
private $type;
/**
* @var bool
*
* @ORM\Column(name="_specific", type="boolean", options={"default": 0})
* @JMS\SerializedName("specific")
* @JMS\Groups({"risks_controls_list","risks_controls_detail"})
* @Assert\NotNull()
*/
private $specific = false;
/**
* @var string
*
* @ORM\Column(name="threshold", type="string")
* @JMS\SerializedName("threshold")
* @JMS\Groups({"risks_controls_detail"})
* @Assert\NotBlank()
*/
private $threshold;
/**
* @var array|null
*
* @ORM\Column(name="risks", type="json_array", nullable=true)
* @JMS\SerializedName("risks")
* @JMS\Groups({"risks_controls_detail"})
*/
private $risks;
/**
* @var array|null
*
* @ORM\Column(name="controls", type="json_array", nullable=true)
* @JMS\SerializedName("controls")
* @JMS\Groups({"risks_controls_detail"})
*/
private $controls;
/**
* @ORM\ManyToOne(targetEntity="Mine")
* @ORM\JoinColumn(nullable=true)
* @JMS\SerializedName("mine")
* @JMS\Groups({"r_risks_controls_mine"})
*
* @var Mine
*/
private $mine;
/*
* Hook timestampable behavior
* updates createdAt, updatedAt fields
*/
use TimestampableEntity;
/*
* Hook blameable behavior
* updates createdBy, updatedBy fields
*/
use BlameableEntityAssociation;
/**
* constructor.
*/
public function __construct(Mine $mine = null, bool $specific = false)
{
$this->mine = $mine;
$this->specific = $specific;
}
public function __toString()
{
return "{$this->mine->getName()} {$this->getTypeLabel()}";
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set type.
*
* @param string $type
*
* @return self
*/
public function setType($type)
{
$this->type = $type;
return $this;
}
/**
* Get type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Set threshold.
*
* @param string $threshold
*
* @return self
*/
public function setThreshold($threshold)
{
$this->threshold = $threshold;
return $this;
}
/**
* Get threshold.
*
* @return string
*/
public function getThreshold()
{
return $this->threshold;
}
/**
* Set risks.
*
* @param array|null $risks
*
* @return self
*/
public function setRisks($risks = null)
{
$this->risks = array_values($risks);
return $this;
}
/**
* Get risks.
*
* @return array|null
*/
public function getRisks()
{
return $this->risks;
}
/**
* Set controls.
*
* @param array|null $controls
*
* @return self
*/
public function setControls($controls = null)
{
$this->controls = array_values($controls);
return $this;
}
/**
* Get controls.
*
* @return array|null
*/
public function getControls()
{
return $this->controls;
}
/**
* Get the value of mine.
*
* @return Mine
*/
public function getMine()
{
return $this->mine;
}
/**
* Set the value of mine.
*
* @return self
*/
public function setMine(Mine $mine)
{
$this->mine = $mine;
return $this;
}
/**
* @return array
*/
public static function getTypes()
{
return [
self::GUSTS_OF_WIND_KM_HR => 'Racha de viento (Km/h)',
self::LOW_HUMIDITY => 'Baja humedad',
self::LOW_TEMPERATURES => 'Baja temperaturas',
self::SNOW_FALL => 'Caida de nieve',
self::HIGH_PROBABILITY_RAIN => 'Alta probabilidad de lluvia',
self::HIGH_PROBABILITY_SNOW => 'Alta probabilidad de nieve',
self::HIGH_PROBABILITY_THUNDERSTORM => 'Alta probabilidad de tormenta eléctrica',
self::SOIL_FREEZING => 'Suelos congelados',
];
}
/**
* get type label.
*
* @JMS\VirtualProperty()
* @JMS\SerializedName("type_label")
* @JMS\Groups({"risks_controls_detail"})
*
* @return string
*/
public function getTypeLabel()
{
$temp = $this->getTypes();
return $temp[$this->type];
}
/**
* get mine slug.
*
* @JMS\VirtualProperty()
* @JMS\SerializedName("mine_slug")
* @JMS\Groups({"risks_controls_detail"})
*
* @return string
*/
public function getMineSlug()
{
return $this->mine->getSlug();
}
/**
* Get the value of specific.
*
* @return bool
*/
public function getSpecific()
{
return $this->specific;
}
/**
* Set the value of specific.
*
* @return self
*/
public function setSpecific(bool $specific)
{
$this->specific = $specific;
return $this;
}
} |
package alyonachern;
import alyonachern.model.JsonModel;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import java.io.File;
import static org.junit.jupiter.api.Assertions.*;
public class JsonParsingTest {
ObjectMapper objectMapper = new ObjectMapper();
@Test
public void jsonReadTest() throws Exception {
File file = new File("src/test/resources/info.json");
JsonModel json = objectMapper.readValue(file, JsonModel.class);
assertAll(
() -> assertNotNull(json.getId(),
"ID is null"),
() -> assertEquals("Fill Coulson", json.getName(),
"Name is different"),
() -> assertTrue(json.isActive(),
"User is not active"),
() -> assertNotNull(json.getAccounts().get(0).getNumber(),
"Number of account is null"),
() -> assertEquals("BYN", json.getAccounts().get(1).getCurrency(),
"Currency is absent"),
() -> assertEquals("Otkrytie", json.getAccounts().get(0).getBank())
);
}
} |
import { useEffect } from "react";
type UseAddDocumentKeydownProps = {
condition: (e: KeyboardEvent) => boolean;
callback: (e: KeyboardEvent) => void;
};
export function useAddDocumentKeydown({
condition,
callback,
}: UseAddDocumentKeydownProps) {
useEffect(() => {
document.addEventListener("keydown", (e) => {
if (condition(e)) {
callback(e);
}
});
return () => {
document.removeEventListener("keydown", () => {});
};
}, [callback, condition]);
} |
import time as t
## Animal is-a object (yes, sort of confusing) look at the extra credit
class Animal(object):
def __init__ (self):
print "I'm an animal"
t.sleep(1)
## Dog is-a Animal
class Dog(Animal):
def __init__(self, name):
## Dog has-a name
self.name = name
print "Bark bark i'm a dog"
t.sleep(1)
print "bark, my name is: ", self.name
t.sleep(1)
def bark(self):
print "Bark!"
## Cat is-a Animal
class Cat(Animal):
def __init__(self, name):
## Cat has-a name
self.name = name
print "meow mewo, i'm a cat"
t.sleep(1)
print "meow, my name is: ", self.name
t.sleep(1)
def meow(self):
print "Meow!"
## Person is-a object
class Person(object):
def __init__(self, name):
## Person has-a name
self.name = name
## Person has-a pet of some kind
self.pet = None
print "I'm human..and my name is: ",self.name
t.sleep(1)
## Employee is-a Person
class Employee(Person):
def __init__(self, name, salary):
## Employee has-a super class with a name hmm what is this strange magic?
super(Employee, self).__init__(name)
## Employee has-a salary
self.salary = salary
print "I've gotta job making: ", self.salary
t.sleep(1)
## Fish is-a object
class Fish(object):
"""docstring for Fish"""
pass
def swim(self):
print "I'm swimming.."
## Salmon is-a Fish
class Salmon(Fish):
pass
## Halibut is-a Fish
class Halibut(Fish):
"""docstring for Halibut"""
pass
## rpver is-a Dog
rover = Dog("Rover")
## satan is-a Cat
satan = Cat("Satan")
## mary is-a Person
mary = Person("Mary")
## mary has-a pet cat named Satan
mary.pet = satan
## frank is-a Employee that has-a salary of 120000
frank = Employee("Frank",120000)
## frank has-a pet dog named rover
frank.pet = rover
## flipper is-a fish
flipper = Fish()
## crouse is-a Salmon
crouse = Salmon()
##harry is-a Halibut
harry = Halibut()
print type(harry)
print harry.__class__, frank.name |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hot Gadget</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<header class="topside">
<div class="row">
<div class="col-12 col-md-3 col-sm-3 logo">
<img src="images/logo.png" alt="logo">
</div>
<div class="navigation col-12 col-md-9 col-sm-9">
<nav class="navbar navbar-expand-lg navbar-light">
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Products</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About us</a>
</li>
<li class="nav-item">
<a class="nav-link Contact us" href="#" tabindex="-1">Contact us</a>
</li>
</ul>
</div>
</nav>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<div class="row d-flex align-items-center">
<div class="col-md-7">
<h1>MackBook Pro</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae repudiandae a tempore tenetur quis at animi quasi veritatis velit laudantium.</p>
<button class="BuyNowButton">BUY NOW →</button>
</div>
<div class="col-md-5">
<img src="images/banner-products/product-1.png" class="d-block w-100" alt="...">
</div>
</div>
</div>
<div class="carousel-item">
<div class="row d-flex align-items-center">
<div class="col-md-7">
<h1>MackBook Pro</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae repudiandae a tempore tenetur quis at animi quasi veritatis velit laudantium.</p>
<button class="BuyNowButton">BUY NOW →</button>
</div>
<div class="col-md-5">
<img src="images/banner-products/slider-1.png" class="d-block w-100" alt="...">
</div>
</div>
</div>
<div class="carousel-item">
<div class="row d-flex align-items-center">
<div class="col-md-7">
<h1>MackBook Pro</h1>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Vitae repudiandae a tempore tenetur quis at animi quasi veritatis velit laudantium.</p>
<button class="BuyNowButton">BUY NOW →</button>
</div>
<div class="col-md-5">
<img src="images/banner-products/slider-3.png" class="d-block w-100" alt="...">
</div>
</div>
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
</div>
<div class="top_product">
<div class="row">
<div class="container title">
<div class="row d-flex justify-content-between align-items-center">
<div class="smartphone">
<h1>Smart Phone</h1>
</div>
<div>
<a href="#" class="text-decoration-none text-warning">See All</a>
</div>
</div>
</div>
<div class="card-deck">
<div class="card">
<img src="images/phone/phone-1.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">iPhone 11 Pro</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui, at.</p>
<h5>$660</h5>
</div>
<div class="card-footer">
<button class="BuyNowButton">BUY NOW →</button>
</div>
</div>
<div class="card">
<img src="images/phone/phone-2.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Samsung Galexy Note 10+</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui, at.</p>
<h5>$660</h5>
</div>
<div class="card-footer">
<button class="BuyNowButton">BUY NOW →</button>
</div>
</div>
<div class="card">
<img src="images/phone/phone-3.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Walton S3</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui, at.</p>
<h5>$660</h5>
</div>
<div class="card-footer">
<button class="BuyNowButton">BUY NOW →</button>
</div>
</div>
</div>
</div>
</div>
<div class="top_product">
<div class="row">
<div class="container title">
<div class="row d-flex justify-content-between align-items-center">
<div class="smartphone">
<h1>laptop</h1>
</div>
<div>
<a href="#" class="text-decoration-none text-warning">See All</a>
</div>
</div>
</div>
<div class="card-deck">
<div class="card">
<img src="images/laptop/product-1.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Asus VivoBook</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui, at.</p>
<h5>$999</h5>
</div>
<div class="card-footer">
<button class="BuyNowButton">BUY NOW →</button>
</div>
</div>
<div class="card">
<img src="images/laptop/product-2.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Razer Balde 15</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui, at.</p>
<h5>$2799</h5>
</div>
<div class="card-footer">
<button class="BuyNowButton">BUY NOW →</button>
</div>
</div>
<div class="card">
<img src="images/laptop/product-3.png" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Walton NetBook Pro</h5>
<p class="card-text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Qui, at.</p>
<h5>$999</h5>
</div>
<div class="card-footer">
<button class="BuyNowButton">BUY NOW →</button>
</div>
</div>
</div>
</div>
<div class="categories">
<h1 class="text-center">Categories</h1>
<hr class="line">
<div class="row">
<div class="col-md-3 d-flex align-items-center justify-content-center">
<img class="bag" src="images/Categories/bag.png" alt="bag">
</div>
<div class="col-md-3 d-flex justify-content-center align-content-between flex-wrap">
<img class="perfume" src="images/Categories/perfume.png" alt="perfume" >
<img class="shoe" src="images/Categories/shoe.png" alt="shoe" >
</div>
<div class="col-md-6 place-order d-flex align-items-center justify-content-center">
<img src="images/Categories/pale-order.png" alt="pale-order">
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html> |
import Image from "next/image"
import React, { ReactNode, useContext, useState } from "react"
import LoadingSpinner from "../components/LoadingSpinner"
const ImageFullViewContext = React.createContext<any>(null)
export const ImageFullViewProvider = ({ children }: { children: ReactNode }) => {
const [imageFullViewToggle, setImageFullViewToggle] = useState<boolean>(false)
const [imageFullViewImage, setImageFullViewImage] = useState<{ src: string }>()
return (
<ImageFullViewContext.Provider
value={{
imageFullViewToggle,
setImageFullViewToggle,
imageFullViewImage,
setImageFullViewImage,
}}
>
<ImageFullViewModal />
{children}
</ImageFullViewContext.Provider>
)
}
const ImageFullViewModal = () => {
const {
imageFullViewToggle,
setImageFullViewToggle,
imageFullViewImage,
}: {
imageFullViewToggle: boolean
setImageFullViewToggle: React.Dispatch<React.SetStateAction<boolean>>
imageFullViewImage: { src: string }
} = useContext(ImageFullViewContext)
return (
<div
className="fixed flex h-screen w-screen cursor-pointer flex-row items-center justify-center bg-foreground bg-opacity-50"
style={{ visibility: imageFullViewToggle ? "visible" : "hidden", zIndex: 200 }}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
e.nativeEvent.stopImmediatePropagation()
setImageFullViewToggle(false)
}}
>
{imageFullViewImage ? (
<div className="relative" style={{ height: "80%", width: "80%" }}>
<Image
src={imageFullViewImage.src}
fill={true}
alt={""}
className="cursor-default"
style={{ objectFit: "contain" }}
onClick={(e) => {
e.preventDefault()
e.stopPropagation()
e.nativeEvent.stopImmediatePropagation()
setImageFullViewToggle(false)
}}
/>
{/* <div className="absolute top-0 left-0 h-full w-full bg-black opacity-50" /> */}
</div>
) : (
<LoadingSpinner />
)}
<div
className="absolute flex h-9 w-9 cursor-pointer items-center justify-center rounded-full bg-[rgba(255,255,255,0)] transition-colors duration-200"
style={{ top: "36px", right: "36px", height: "36px", width: "36px" }}
onMouseEnter={(e) => {
e.currentTarget.style.backgroundColor = "rgb(255,255,255,0.05)"
}}
onMouseLeave={(e) => {
e.currentTarget.style.backgroundColor = "rgb(255,255,255,0)"
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
className="h-6 fill-background drop-shadow-lg"
viewBox="0 0 384 512"
>
<path d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z" />
</svg>
</div>
</div>
)
}
export const useImageFullViewer = () => {
const {
setImageFullViewImage,
setImageFullViewToggle,
}: {
setImageFullViewImage: React.Dispatch<
React.SetStateAction<
| {
src: string
}
| undefined
>
>
setImageFullViewToggle: React.Dispatch<React.SetStateAction<boolean>>
} = useContext(ImageFullViewContext)
return {
onImageFullView: (src: string) => {
setImageFullViewImage({ src })
setImageFullViewToggle(true)
},
}
} |
import React from 'react';
import { useState } from 'react';
import Button from 'react-bootstrap/Button';
import Col from 'react-bootstrap/Col';
import Form from 'react-bootstrap/Form';
import InputGroup from 'react-bootstrap/InputGroup';
import Row from 'react-bootstrap/Row';
import './Driver.css'
import axios from 'axios';
import { baseUrl, postData } from '../../helpers/api';
const Driver = () => {
const [validated, setValidated] = useState(false);
const [FIO, setFIO] = useState({});
const [carNumber, setCarNumber] = useState({})
const handleSubmit = async (event) => {
event.preventDefault();
const form = event.currentTarget;
if (form.checkValidity() === false) {
event.stopPropagation();
}
setValidated(true);
const fio = Object.values(FIO).join(' ');
const car_number = carNumber.region + 'KG' + carNumber.number + carNumber.series
const data = {
fio,
car_number
}
const response = await postData('/main_app/driver/', data)
console.log(response)
};
const handleFIO = (e) => {
const value = e.target.value;
const name = e.target.name
console.log(e)
setFIO(prev => ({
...prev,
[name]:value.trim()
}))
}
const handleCarNumber = (e) => {
const value = e.target.value;
const name = e.target.name
console.log(e)
setCarNumber(prev => ({
...prev,
[name]:value.trim()
}))
}
return (
<div className='driver-container'>
<Form noValidate validated={validated} onSubmit={handleSubmit}>
<Row className="mb-3">
<h2>Водитель</h2>
<Form.Group as={Col} md="4" controlId="validationCustom01">
<Form.Label>Фамилия</Form.Label>
<Form.Control
required
name='lastName'
type="text"
onChange={handleFIO}
/>
<Form.Control.Feedback type="invalid">
Введите фамилию
</Form.Control.Feedback>
</Form.Group>
<Form.Group as={Col} md="4" controlId="validationCustom02">
<Form.Label>Имя</Form.Label>
<Form.Control
required
name='firstName'
type="text"
onChange={handleFIO}
/>
<Form.Control.Feedback type="invalid">
Введите имя
</Form.Control.Feedback>
</Form.Group>
<Form.Group as={Col} md="4" controlId="validationCustomUsername">
<Form.Label>Отчество</Form.Label>
<InputGroup>
<Form.Control
type="text"
name='middleName'
onChange={handleFIO}
/>
</InputGroup>
</Form.Group>
</Row>
<Row className="mb-3">
<h2>Номер авто</h2>
<Form.Group as={Col} md="4" controlId="validationCustomUsername">
<Form.Label>Регион</Form.Label>
<InputGroup hasValidation>
<Form.Control
type="text"
placeholder="08"
name='region'
required
onChange={handleCarNumber}
/>
<InputGroup.Text id="inputGroupPrepend">KG</InputGroup.Text>
<Form.Control.Feedback type="invalid">
Введите регион
</Form.Control.Feedback>
</InputGroup>
</Form.Group>
<Form.Group as={Col} md="3" controlId="validationCustom04">
<Form.Label>Номер</Form.Label>
<Form.Control type="text" placeholder="123" required
name='number'
onChange={handleCarNumber} />
<Form.Control.Feedback type="invalid">
Введите номер
</Form.Control.Feedback>
</Form.Group>
<Form.Group as={Col} md="3" controlId="validationCustom05">
<Form.Label>Серия</Form.Label>
<Form.Control type="text" placeholder="AAA" required
name='series'
onChange={handleCarNumber} />
<Form.Control.Feedback type="invalid">
Введите серию
</Form.Control.Feedback>
</Form.Group>
</Row>
<Button type="submit">Создать водителя</Button>
</Form>
</div>
);
};
export default Driver; |
<template>
<div>
<div class="navbar is-dark" role="navigation" aria-label="main navigation">
<div class="navbar-brand">
<a class="navbar-item" href="/">
Warket
</a>
<a class="navbar-burger" aria-label="menu" aria-expanded="false" data-target="navbar-menu" @click="showMobileMenu = !showMobileMenu">
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
<span aria-hidden="true"></span>
</a>
</div>
<div id="navbarBasicExample" class="navbar-menu" v-bind:class="{'is-active': showMobileMenu}">
<div class="navbar-start">
<div class="navbar-item">
<form method='get' action="/search">
<div class="field has-addons">
<input type="text" class="input" placeholder="What are you looking for?" name="query"/>
<div class="control">
<button class="button is-success">
<span class="icon">
<i class="fas fa-search"></i>
</span>
</button>
</div>
</div>
</form>
</div>
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link">
Categories
</a>
<div class="navbar-dropdown">
<a class="navbar-item" href="/computers">
Computers
</a>
<a class="navbar-item" href="/laptops">
Laptops
</a>
</div>
</div>
</div>
<div class="navbar-end">
<div class="navbar-item">
<div class="buttons">
<template v-if="$store.state.isAuthenticated">
<router-link to="/my-account" class="button is-light">My account</router-link>
</template>
<template v-else>
<router-link to="/log-in" class="button is-light">Log in</router-link>
</template>
<router-link to="/cart" class="button is-success">
<span class="icon"><i class="fas fa-shopping-cart"></i></span>
<span>Cart ({{ cartTotalLength }})</span>
</router-link>
</div>
</div>
</div>
</div>
</div>
<div id="content">
<router-view/>
</div>
</div>
</template>
<script>
import axios from 'axios'
import Modal from './components/Modal.vue'
export default {
data(){
return{
showMobileMenu: false,
cart: {
items: []
}
}
},
beforeCreate(){
this.$store.commit('initializeStore')
const token = this.$store.state.token
if(token){
axios.defaults.headers.common['Authorization'] = "Token " + token
} else {
axios.defaults.headers.common['Authorization'] = ""
}
},
mounted(){
this.cart = this.$store.state.cart
},
computed: {
cartTotalLength(){
let totalLength = 0
for (let i = 0; i < this.cart.items.length; i++) {
totalLength += this.cart.items[i].quantity
}
return totalLength
}
}
}
</script>
<style lang="scss">
@import '../node_modules/bulma';
#content{
margin: 20px;
}
</style> |
import React, { useState, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { utils, writeFileXLSX, read } from 'xlsx'
import { Button, Card, Col, message, Modal, Row, Space, Typography, Upload } from 'antd'
import groupApi from '~/api/groupApi'
import { CrownTwoTone, ExclamationCircleOutlined, UploadOutlined, UsergroupAddOutlined } from '@ant-design/icons'
import _ from 'lodash'
const UploadFile = () => {
const { id } = useParams()
const [groupDetail, setGroupDetail] = useState({})
const [fileList, setFileList] = useState([])
const [result, setResult] = useState([])
const [display, setDisplay] = useState([])
const [isClickedNextStep, setIsClickedNextStep] = useState(false)
useEffect(() => {
loadData()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const loadData = async () => {
await groupApi
.getReuseGroup(id)
.then((response) => {
setGroupDetail(response)
})
.catch((error) => {
console.log(error)
})
}
const toastMessage = (type, mes) => {
message[type]({
content: mes,
style: {
transform: `translate(0, 8vh)`,
},
})
}
const modalConfirm = () => {
Modal.confirm({
title: 'Are you sure to confirm this configure group this milestone?',
icon: <ExclamationCircleOutlined />,
okText: 'Confirm',
cancelText: 'Cancel',
okType: 'danger',
async onOk() {
await handleFinish()
},
onCancel() {},
})
}
const handleDownloadFileStudent = () => {
const listExport = [
...groupDetail.traineeList.map((student) => ({
'Group Name': '',
Email: student.email,
Fullname: student.fullName,
Username: student.username,
'Is Leader': '',
})),
]
const ws = utils.json_to_sheet(listExport)
const wb = utils.book_new()
utils.sheet_add_aoa(ws, [['Group Name', 'Email', 'Fullname', 'Username', 'Is Leader']], { origin: 'A1' })
var wscols = [{ wch: 20 }, { wch: 30 }, { wch: 20 }, { wch: 20 }, { wch: 20 }]
ws['!cols'] = wscols
utils.book_append_sheet(wb, ws, 'List Student')
writeFileXLSX(wb, 'FileOfStudentList.xlsx')
}
const props = {
name: 'file',
accept: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
multiple: false,
maxCount: 1,
beforeUpload: () => {
return false
},
onChange(info) {
if (info.file.status !== 'uploading') {
//Handle read file and verify here
const extensionFile = info.file.name.split('.').pop()
const extensionsValid = ['xlsx', 'xls', 'csv']
if (info.file.status === 'removed') return
if (!extensionsValid.includes(extensionFile)) {
toastMessage('error', 'File type is invalid (support .xlsx, .xls and .csv only)')
return
}
const readFile = new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.readAsArrayBuffer(info.file)
fileReader.onload = (e) => {
const bufferArray = e.target.result
const wb = read(bufferArray, { type: 'buffer' })
const ws_name = wb.SheetNames[0]
const ws = wb.Sheets[ws_name]
const data = utils.sheet_to_json(ws)
resolve(data)
}
fileReader.onerror = (error) => {
reject(error)
}
})
readFile.then((data) => {
setFileList(data)
})
}
},
}
const handleNextStep = () => {
for (let i = 0; i < fileList.length; i++) {
fileList[i]['Group Name'] = fileList[i]['Group Name']?.trim()
}
if (groupDetail.traineeList.length !== fileList.length) {
toastMessage('error', 'Data is invalid, follow the File of Student List please')
return
}
for (let i = 0; i < fileList.length; i++) {
if (Object.keys(fileList[i]).length !== 5) {
toastMessage('error', 'Data is invalid, follow the File of Student List please')
return
}
if (groupDetail.traineeList[i].username?.trim() !== fileList[i].Username?.trim()) {
toastMessage('error', 'Data is invalid, follow the File of Student List please')
return
}
if (groupDetail.traineeList[i].fullName?.trim() !== fileList[i].Fullname?.trim()) {
toastMessage('error', 'Data is invalid, follow the File of Student List please')
return
}
if (groupDetail.traineeList[i].email?.trim() !== fileList[i].Email?.trim()) {
toastMessage('error', 'Data is invalid, follow the File of Student List please')
return
}
}
const grouped = _.groupBy(fileList, (item) => item['Group Name'])
const result = []
for (const [key, value] of Object.entries(grouped)) {
if (key === 'undefined') {
result.unshift({
groupCode: 'Waiting List',
topicName: `Topic Waiting List`,
description: `Description Waiting List`,
fullData: value,
members: value.map((item) => ({
memberName: item.Username,
isLeader: false,
})),
})
} else {
result.push({
groupCode: key,
topicName: `Topic ${key}`,
description: `Description ${key}`,
fullData: value,
members: value.map((item) => ({
memberName: item.Username,
isLeader: item['Is Leader'] === 'TRUE' ? true : false,
})),
})
}
}
setDisplay(result)
setResult(result)
setIsClickedNextStep(true)
}
const handleFinish = async () => {
let paramsGroup = [...result]
paramsGroup = paramsGroup.map((item) => ({
...item,
members: item.fullData.map((item2) => ({
memberName: item2.Username,
isLeader: item2['Is Leader'] === true ? true : false,
})),
}))
if (paramsGroup[0].groupCode === 'Waiting List') {
paramsGroup.shift()
}
const params = {
listGroup: paramsGroup,
}
console.log(params)
await groupApi
.overrideGroup(id, params)
.then((response) => {
console.log(response)
toastMessage('success', 'Create Group Successfully!')
})
.catch((error) => {
console.log(error)
toastMessage('error', 'Something went wrong, please try again')
})
}
const handleCancel = () => {
loadData()
setIsClickedNextStep(false)
}
return (
<div className="widget-inner">
{!isClickedNextStep ? (
<div className="row">
<Space
align="center"
style={{
width: '100%',
height: '50px',
justifyContent: 'center',
flexDirection: 'column',
borderTop: '1px grey dashed',
borderLeft: '1px grey dashed',
borderRight: '1px grey dashed',
}}
>
<Typography.Text className="d-flex justify-content-center" strong>
You need to download the{' '}
<Button
className="p-0 m-0"
type="link"
onClick={async () => {
handleDownloadFileStudent()
}}
>
File of Student List
</Button>{' '}
to create groups
</Typography.Text>
</Space>
<Space
align="center"
style={{
width: '100%',
height: '200px',
justifyContent: 'center',
flexDirection: 'column',
border: '1px grey dashed',
}}
>
<Space
style={{
width: '100%',
height: '100%',
flexDirection: 'column',
paddingLeft: '35%',
paddingRight: '35%',
alignContent: 'center',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
}}
>
<Typography.Text className="text-center" strong>
Please click "Upload" to import the file
</Typography.Text>
<Upload {...props} className="d-flex flex-column mx-auto justify-content-center align-item-center w-75">
<Button
className="d-flex flex-row mx-auto justify-content-center align-item-center w-100"
icon={<UploadOutlined />}
>
Click to Upload
</Button>
</Upload>
</Space>
</Space>
<Space className="mt-4">
<Typography.Title level={5} strong>
Upload File
</Typography.Title>
</Space>
<Space className="mt-1">
<Typography.Text>
<Typography.Text strong>Step 1: </Typography.Text>
<Typography.Text>
To create groups, you need to download the student list by clicking link "File of Student List".
</Typography.Text>
</Typography.Text>
</Space>
<Space className="mt-3">
<Typography.Text>
<Typography.Text strong>Step 2: </Typography.Text>
<Typography.Text>
Add group names to the column "Group Name". The first member of each group is defaulted as the group
leader.
</Typography.Text>
</Typography.Text>
</Space>
<Space className="mt-3">
<Typography.Text>
<Typography.Text strong>Step 3: </Typography.Text>
<Typography.Text>Click button "Upload" to upload the file of group list.</Typography.Text>
</Typography.Text>
</Space>
<Space className="mt-3">
<Typography.Text>
<Typography.Text strong>Step 4: </Typography.Text>
<Typography.Text>
Click Next Step to preview groups. The groups are displaed on the screen.
</Typography.Text>
</Typography.Text>
</Space>
<Space className="mt-3">
<Typography.Text>
<Typography.Text strong>Step 5: </Typography.Text>
<Typography.Text>
Click "Finish" to complete create groups. Then you can start the constructive questions.
</Typography.Text>
</Typography.Text>
</Space>
</div>
) : (
<>
<Space className="d-inline-flex">
<Typography.Text className="d-flex flex-column" strong>
<Typography.Text>Class size:</Typography.Text>
<Typography.Text type="warning" strong>
{` ${groupDetail.traineeList.length} `}
</Typography.Text>
<Typography.Text>Students</Typography.Text>
</Typography.Text>
</Space>
<Space className="d-inline-flex ml-2">
<Typography.Text className="d-flex flex-column" strong>
<Typography.Text> - Group:</Typography.Text>
<Typography.Text type="warning" strong>
{` ${display?.length} `}
</Typography.Text>
</Typography.Text>
</Space>
<Row gutter={24} className="mt-3">
{display.map((group) => {
return (
<Col span={8} className="pb-3">
<Card
title={group.groupCode === '' ? 'Waiting List' : group.groupCode}
bordered
style={{ backgroundColor: '#ededed', minHeight: '200px', maxHeight: '200px', overflow: 'auto' }}
bodyStyle={{ paddingTop: 0 }}
extra={
<Space>
<UsergroupAddOutlined style={{ fontSize: '20px' }} />
<Typography>{group.members.length}</Typography>
</Space>
}
>
{group.fullData.map((student) => (
<Typography className="p-0 m-0 d-flex flex-row">
{student.Fullname} - {student.Username}{' '}
{student['Is Leader'] === true && <CrownTwoTone className="ml-2 d-flex align-items-center" />}
</Typography>
))}
</Card>
</Col>
)
})}
</Row>
</>
)}
<div className="d-flex justify-content-end ">
{!isClickedNextStep ? (
<Button type="primary" onClick={handleNextStep}>
Next Step
</Button>
) : (
<>
<Button type="text" className="ml-3" onClick={handleCancel}>
Cancel
</Button>
<Button type="danger" className="ml-3" onClick={modalConfirm}>
Finish
</Button>
</>
)}
</div>
</div>
)
}
export default UploadFile |
import { Meta, StoryObj } from '@storybook/react';
import { Heading, HeadingProps } from "./Heading";
export default {
title: 'Components/Heading',
component: Heading,
args:{
children: 'Lorem ipsum',
size: 'md',
},
argTypes:{
size: {
options: ['sm', 'md', 'lg'],
control:{
type: 'inline-radio'
}
}
}
} as Meta<HeadingProps>
export const Default : StoryObj<HeadingProps> = {}
export const Small : StoryObj<HeadingProps> = {
args:{
size: 'sm'
}
}
export const Large : StoryObj<HeadingProps> = {
args:{
size: 'lg'
}
}
export const CustomComponent : StoryObj<HeadingProps> = {
args:{
asChild: true,
children:(
<h1>Heading | H1</h1>
)
},
argTypes:{
children:{
table:{
disable:true
}
},
asChild:{
table:{
disable: true
}
}
}
} |
package com.example.quizbox;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.Collections;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{
private List<String> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
// data is passed into the constructor
Adapter(Context context, List<String> data) {
this.mInflater = LayoutInflater.from(context);
Collections.reverse(data);
mData = data;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView name,rank;
ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
rank = itemView.findViewById(R.id.rank);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
}
}
// inflates the row layout from xml when needed
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.list_add, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
String name = mData.get(position);
holder.rank.setText((position+1)+"");
holder.name.setText(name);
}
// total number of rows
@Override
public int getItemCount() {
return mData.size();
}
// stores and recycles views as they are scrolled off screen
// convenience method for getting data at click position
String getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
} |
<template>
<q-page padding>
<GenericTable
v-if="getterData.length > 0"
ref="child"
:table-title="'Usuarios'"
:form-config="formConfig"
:title-export="'users'"
:getter-data="getterData"
:delete-keys="deleteKeys"
:api-route="'users/'"
:front-route="'/config/users'"
v-on:sync:data="getData($event)"
v-on:send:put="putRecord($event)"
v-on:send:post="postRecord($event)"
v-on:send:del="deleteRecord($event)"
/>
</q-page>
</template>
<script>
import { useQuasar } from "quasar";
import { defineComponent } from "vue";
import GenericTable from "src/components/custom/GenericTable.vue";
import { useUserStore } from "src/stores/user/userStore";
export default defineComponent({
name: "UsuariosPage",
components: {
GenericTable,
},
setup() {
const userStore = useUserStore();
const quasar = useQuasar();
return {
userStore,
quasar,
};
},
data: function () {
return {
data: [],
getterData: [],
deleteKeys: ["password"],
formConfig: [
{
element: "name",
type: "text",
required: true,
label: "Nombre",
},
{
element: "last_name",
type: "text",
required: false,
},
{
element: "username",
type: "text",
required: true,
},
{
element: "password",
label: "Password",
type: "text",
required: false,
skipList: true,
},
{
element: "email",
type: "text",
required: false,
},
],
};
},
mounted() {
this.getData();
},
methods: {
async getData() {
try {
await this.userStore.fetchUsers();
this.getterData = this.userStore.getUsers;
} catch (err) {
if (err.response.data.error) {
this.quasar.notify({
type: "negative",
message: err.response.data.error,
});
}
if (err.response.data.detail) {
this.quasar.notify({
type: "warning",
message: err.response.data.detail,
});
}
}
},
async putRecord(ev) {
console.log(ev);
try {
await this.userStore.putUser(ev.rows.id, ev.formData);
await this.getData();
} catch (error) {
console.error(error);
if (error.response.data.error) {
this.quasar.notify({
type: "negative",
message: error.response.data.error,
});
}
}
},
async postRecord(ev) {
try {
await this.userStore.postUser(ev);
this.$refs.child.cancel();
await this.getData();
} catch (error) {
if (error.response.data.errors) {
let msg = error.response.data.errors;
let keys = Object.keys(msg);
for (let index = 0; index < keys.length; index++) {
this.quasar.notify({
type: "negative",
position: "bottom",
message: `${keys[index].toUpperCase()}: ${msg[keys[index]]}`,
});
}
}
}
},
async deleteRecord(ev) {
try {
await this.userStore.deleteUser(ev);
this.$refs.child.cancel();
this.getData();
} catch (error) {
console.error(error);
}
},
},
});
</script> |
% addarrows Add arrows along a contour handle
%
% [AR TX TY] = addarrows(H,[OPTIONS_PAIRS])
%
% Add arrows along a contour handle H.
%
% Options:
% arrowgap = 10; % Nb of points between arrows
% arrowangle = 10; % Arrow angle
% arrowlength = 1; % Arrow length
% arrowsharpness = 1; % How sharp is the arrow ? (1 for a triangle)
%
% Outputs:
% AR: Patch handle for each arrows
%
% See also:
% patcharrow
%
% Created: 2010-08-25.
% Copyright (c) 2010, Guillaume Maze (Laboratoire de Physique des Oceans).
% All rights reserved.
% http://codes.guillaumemaze.org
%
% Redistribution and use in source and binary forms, with or without
% modification, are permitted provided that the following conditions are met:
% * Redistributions of source code must retain the above copyright notice, this list of
% conditions and the following disclaimer.
% * 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.
% * Neither the name of the Laboratoire de Physique des Oceans nor the names of its contributors may be used
% to endorse or promote products derived from this software without specific prior
% written permission.
%
% THIS SOFTWARE IS PROVIDED BY Guillaume Maze ''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 Guillaume Maze 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.
%
function [AR TX TY] = addarrows(varargin)
%- Default parameters:
arrowgap = 10; % Nb of points between arrows
arrowangle = 10; % Arrow angle
arrowlength = 1; % Arrow length
arrowsharpness = 1; % How sharp is the arrow ? (1 for a triangle)
%- Load arguments:
switch nargin
case 0 %-- Load demo fields
iY = [90 160]; iX = [270 360]; % Classic North Atlantic
load('LSmask_MOA','LSmask','LONmask','LATmask');
LSmask = LSmask(iY(1):iY(2),iX(1):iX(2));
lon = LONmask(iX(1):iX(2)); clear LONmask
lat = LATmask(iY(1):iY(2)); clear LATmask
SSH = load_climOCCA('SSH');
SSH = SSH(iY(1):iY(2),iX(1):iX(2));
clear iX iY
figure;hold on
contourf(lon,lat,SSH,[-2:.1:2]);
[cs,h] = contour(lon,lat,SSH,[1 1]*-0.2);
otherwise
h = varargin{1};
for in = 2 : 2 : nargin
par = varargin{in};
val = varargin{in+1};
eval(sprintf('%s = val;',par));
end%for in
end%if
%- Load marker polygon in the initial position:
%[px py] = getatriangle(gam,d); % A simple triangle
%[px py] = getatrianglefliplr(gam,d); % A simple triangle
[px py] = getanarrow(arrowangle,arrowlength,arrowsharpness); %
%- Loop over contours:
try
contourtype = get(h(1),'type');
catch
contourtype = 'double';
end
switch contourtype
case 'patch'
for icont = 1 : length(h)
lx = get(h(icont),'xdata');
ly = get(h(icont),'ydata');
[tx ty] = addarrowsto1contour(lx,ly,px,py,arrowgap);
if exist('TX','var')
TX = [TX tx];
TY = [TY ty];
UD = [UD ones(1,size(tx,2))*get(h(icont),'userdata')];
else
TX = tx;
TY = ty;
UD = ones(1,size(tx,2))*get(h(icont),'userdata');
end
end%for icont
case 'hggroup'
ch = get(h,'children');
for icont = 1 : length(ch)
lx = get(ch(icont),'xdata');
ly = get(ch(icont),'ydata');
[tx ty] = addarrowsto1contour(lx,ly,px,py,arrowgap);
if exist('TX','var')
TX = [TX tx];
TY = [TY ty];
UD = [UD ones(1,size(tx,2))*get(ch(icont),'userdata')];
else
TX = tx;
TY = ty;
UD = ones(1,size(tx,2))*get(ch(icont),'userdata');
end
end%for icont
case 'double'
lx = h(1,:);
ly = h(2,:);
[TX TY] = addarrowsto1contour(lx,ly,px,py,arrowgap);
UD = ones(1,size(TX,2));
end%switch
%- Plot arrows as patchs:
AR = patch(TX,TY,'b');
%-- Color arrows like contours:
set(AR,'cdata',UD,'facecolor','flat','edgecolor','none');
end%function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [tx ty] = addarrowsto1contour(lx,ly,px,py,dpt);
ii = 0;
len = length(px); % Nb of points in the marker (arrow)
L = length(lx);
if L < 3
tx(1:len,1) = NaN;
ty(1:len,1) = NaN;
return;
end
for ipt = 2 : dpt : length(lx)-1
try
% Slope between points:
if (lx(ipt+1) - lx(ipt-1)) ~= 0
slope = (ly(ipt+1) - ly(ipt-1)) / (lx(ipt+1) - lx(ipt-1));
else
slope = 1e10;
end
if lx(ipt+1) >= lx(ipt-1)
[PX PY] = rotatepolygon(px,py,atand(-slope));
else
[PX PY] = rotatepolygon(px,py,180+atand(-slope));
end
ii = ii + 1;
if exist('tx','var')
% a=NaN;%a = patch(PX+lx(ipt),PY+ly(ipt),'b');
% AR = [AR a];
tx(:,ii) = PX+lx(ipt);
ty(:,ii) = PY+ly(ipt);
else
% AR = NaN;%patch(PX+lx(ipt),PY+ly(ipt),'b');
tx(:,ii) = PX+lx(ipt);
ty(:,ii) = PY+ly(ipt);
end
%set(AR(ii),'edgecolor','none','facecolor','k');
catch
if exist('tx','var')
ii = ii + 1;
% AR = [AR NaN];
tx(1:4,1) = NaN;
ty(1:4,1) = NaN;
end
end
end%for ipt
if ~exist('tx','var')
% AR = NaN;
tx(1:4,1) = NaN;
ty(1:4,1) = NaN;
end
end%function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [px py] = getatriangle(gam,d);
gam = gam*pi/180;
ii = 0;
% Start from the origin:
ii = ii + 1;
px(ii) = 0;
py(ii) = 0;
% Upper left point:
ii = ii + 1;
px(ii) = -d;
py(ii) = d*tan(gam);
% Lower left point:
ii = ii + 1;
px(ii) = -d;
py(ii) = -d*tan(gam);
% Back to origin:
ii = ii + 1;
px(ii) = px(1);
py(ii) = py(1);
% Center the triangle:
px = px + d/2;
end%function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [px py] = getatrianglefliplr(gam,d);
gam = gam*pi/180;
ii = 0;
% Start from the origin:
ii = ii + 1;
px(ii) = 0;
py(ii) = 0;
% Upper right point:
ii = ii + 1;
px(ii) = d;
py(ii) = d*tan(gam);
% Lower right point:
ii = ii + 1;
px(ii) = d;
py(ii) = -d*tan(gam);
% Back to origin:
ii = ii + 1;
px(ii) = px(1);
py(ii) = py(1);
% Center the triangle:
px = px - d/2;
end%function
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [px py] = getanarrow(gam,d,n);
gam = gam*pi/180;
ii = 0;
N = 20;
% Start from the origin:
ii = ii + 1;
px(ii) = 0;
py(ii) = 0;
% Upper Branch of the arrow:
X = linspace(px(1),-d,N);
Y = linspace(py(1),d*tan(gam),N);
px = [px X];
py = [py Y.^n./xtrm(Y.^n)*d*tan(gam)];
% Lower Branch
px = [px fliplr(X)];
py = [py fliplr(-Y.^n./xtrm(Y.^n)*d*tan(gam))];
% Center the arrow:
px = px + d/2;
end%function |
import React, { Component } from 'react'
import { Col, Grid, Row } from 'react-bootstrap'
import ChannelActions from '../actions/ChannelActions'
import ChannelsStore from '../stores/ChannelsStore'
import connectToStores from 'alt/utils/connectToStores'
class Channel extends Component {
renderMessage(message) {
return (
<Row>
<Col sm={1}>
<img src={message.avatar} width={50} />
</Col>
<Col sm={10}>
<strong>{message.user}</strong>
<p>{message.text}</p>
</Col>
</Row>
)
}
handleKeyPress = (ev) => {
const keyCode = ev.charCode
if (keyCode === 13) {
ChannelActions.messageAdded(
this.props.params.channel,
ev.target.value
)
ev.target.value = ''
console.log(ChannelsStore.getState())
}
}
render() {
const { channels } = this.props
const { params } = this.props
const currentChannel = channels[params.channel]
const messages = currentChannel.messages || []
return (
<div>
{messages.map(this.renderMessage)}
<input type="text" onKeyPress={this.handleKeyPress} />
</div>
)
}
}
export default connectToStores({
getStores() {
return [ChannelsStore]
},
getPropsFromStores() {
return ChannelsStore.getState()
},
}, Channel) |
# Import libraries
import geopandas
import plotly.express as px
import streamlit as st
import pandas as pd
import numpy as np
import os
from PIL import Image
# Functions
@st.cache_data
def create_features(df_raw):
df_raw['basement'] = df_raw.sqft_basement.apply(lambda x: 'No' if x==0 else 'Yes')
df_raw['standard'] = df_raw.apply(lambda row: 'low_standard' if (row.price<df_raw.price.quantile(0.75))&(row.condition!=5)&(row.grade<=10 ) else 'high_standard',
axis=1)
df_raw['house_age'] = df_raw.yr_built.apply(lambda x: 'new_house' if x > 2014 else 'old_house')
df_raw['renovated'] = df_raw.yr_renovated.apply(lambda x: 'No' if x==0 else 'Yes')
dormitory_types = ['no_bedrooms', 'studio', 'apartament', 'house']
df_raw['dormitory_type'] = [dormitory_types[min(x, 3)] for x in df_raw.bedrooms]
df_raw['waterfront'] = df_raw.waterfront.apply(lambda x: 'No' if x==0 else 'Yes')
df_raw['price_per_sqft'] = df_raw.price / df_raw.sqft_living
return df_raw
@st.cache_data
def categorize_features(df_raw):
cols_to_categorize = ['id', 'waterfront', 'view', 'zipcode', 'season', 'basement', 'standard', 'house_age', 'renovated', 'dormitory_type']
df_raw[cols_to_categorize] = df_raw[cols_to_categorize].apply(pd.Categorical)
return df_raw
@st.cache_data
def insert_city_names(df_raw, _king_county):
# create a GeoDataFrame with 'id' and the coordinates ('long', 'lat')
geometry = geopandas.points_from_xy(df_raw.long, df_raw.lat)
geo_df_raw = geopandas.GeoDataFrame(df_raw['id'], geometry=geometry)
# checking if a point in 'geo_df_raw' is inside a polygon in 'king_county'
pointInPolys = geopandas.tools.sjoin(geo_df_raw,
king_county,
op="within",
how='left')
# merging 'pointInPolys' with the original 'df_raw'
df_raw = pd.merge(df_raw, pointInPolys[['id', 'NAME']], how='left', on=['id', 'id'])
df_raw.rename(columns={'NAME':'city'}, inplace=True)
allowed_vals = ['Seattle', 'Northshore', 'Lake Washington', 'Federal Way', 'Highline', 'Tahoma', 'Bellevue','Riverview', 'Auburn', 'Mercer Island', 'Kent', 'Issaquah', 'Renton', 'Vashon Island', 'Snoqualmie Valley','Shoreline', 'Enumclaw', 'Tukwila', 'Fife', 'Skykomish']
df_raw.loc[~df_raw["city"].isin(allowed_vals), "city"] = "undefined"
df_raw['city'] = pd.Categorical(df_raw.city)
return df_raw
@st.cache_data
def extract_features(df_raw):
df_raw = create_features(df_raw)
df_raw = categorize_features(df_raw)
df_raw = insert_city_names(df_raw, king_county)
# Reordering cols
cols_order = ['id', 'date', 'season', 'year_sold', 'year_month', 'year_week', 'yr_built', 'house_age', 'yr_renovated', 'renovated',
'price', 'price_per_sqft', 'sqft_living', 'sqft_above', 'sqft_basement', 'basement', 'sqft_lot', 'sqft_living15', 'sqft_lot15',
'bedrooms', 'dormitory_type', 'bathrooms', 'floors', 'waterfront', 'view', 'condition', 'grade', 'standard',
'zipcode', 'lat', 'long', 'city']
# Drop duplicates and sort by date
df = (df_raw[cols_order]
.drop_duplicates()
.sort_values(by='date')
.drop_duplicates(subset=['id'], keep='last'))
return df
@st.cache_data
def feature_engineering(df_raw):
# Some data transformation and feature engineering
df_raw['date'] = df_raw['date'].str.replace('T000000', '')
df_raw.date = pd.to_datetime(df_raw.date)
df_raw['year_sold'] = df_raw.date.dt.year
df_raw['year_month'] = df_raw.date.dt.strftime('%Y-%m')
df_raw['year_week'] = df_raw.date.dt.strftime('%Y-%U')
df_raw['date'] = df_raw['date'].dt.strftime('%Y-%m-%d')
df_raw['season'] = ['Spring' if (x <= '2014-06-20') or (x >= '2015-03-20') else
('Summer' if (x >= '2014-06-21') and (x <= '2014-09-21') else
('Fall' if (x >= '2014-09-22') and (x <= '2014-12-20') else
'Winter')) for x in df_raw.date]
# correcting some errors
# https://blue.kingcounty.com/Assessor/eRealProperty/default.aspx
# to make some corrections each property with inconsistent data was searched on the site above to see what changes needed to be made
replacements = {
2569500210: {'bedrooms': 3},
6306400140: {'bedrooms': 5, 'bathrooms': 4.5},
3918400017: {'bedrooms': 3, 'bathrooms': 2.25},
2954400190: {'bedrooms': 4, 'bathrooms': 4},
2310060040: {'bedrooms': 4, 'bathrooms': 2.5},
7849202190: {'bedrooms': 3, 'bathrooms': 1.5},
9543000205: {'bedrooms': 2, 'bathrooms': 1},
1222029077: {'bedrooms': 1, 'bathrooms': 1.5}
}
df_raw = df_raw.replace({'id': replacements})
# what could not be changed was removed
index_to_drop = [index for index in df_raw.index if df_raw.loc[index, 'bedrooms'] == 33 or
df_raw.loc[index, 'bathrooms'] == 0 or
df_raw.loc[index, 'bedrooms'] == 0]
df_raw.drop(index_to_drop, inplace=True)
return extract_features(df_raw)
def map_cities(data):
fig = px.scatter_mapbox(data,
title="<b>Cities Distribution</b>",
lat='lat',
lon='long',
size='price',
color='city',
hover_data=["zipcode"],
color_discrete_sequence=['#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f','#ff7f00','#cab2d6','#6a3d9a'],
size_max=15,
zoom=8.5)
fig.update_layout(mapbox_style='carto-positron',
height=600,
margin={'r': 0, 't': 0, 'l': 0, 'b': 0},
title_x=0.05,
title_y=0.9,
title_font_size=50,
title_font_color='black',
title_font_family='Arial'
)
st.plotly_chart(fig, use_container_width=True)
# ----------------------------- Start of the logical code structure -----------------------------
st.set_page_config(page_title='Overview',
page_icon='🔎',
layout='wide'
)
# -------------------
# Import Datasets
# -------------------
kc_house_data = pd.read_csv("dataset/kc_house_data.csv")
king_county = geopandas.read_file('dataset/King_County_Shape_File/School_Districts_in_King_County___schdst_area.shp')
# -------------------
# Feature engineering
# -------------------
data = feature_engineering(kc_house_data)
# Sidebar
image = Image.open('images/logo.png')
st.sidebar.image(image, width=250)
st.sidebar.markdown('# Project overview')
f_attributes = st.sidebar.multiselect('Enter columns', data.columns)
f_zipcode = st.sidebar.multiselect('Enter zipcodes', data.zipcode.unique())
f_city = st.sidebar.multiselect('Enter cities', data.city.unique())
data_overview = data.copy()
if f_zipcode:
data_overview = data_overview.loc[data_overview.zipcode.isin(f_zipcode)]
if f_attributes:
data_overview = data_overview[f_attributes]
if f_city:
data_overview = data_overview.loc[data_overview.city.isin(f_city)]
st.sidebar.markdown('''___''')
st.sidebar.markdown('##### Powered by Comunidade DS')
st.sidebar.markdown('##### Data Analyst: Daniel Gomes')
# Layout in Streamlit
st.title('Data overview')
st.markdown(
'''
## Business Question
House Rocket is a (fictitious) digital platform whose business model is to buy and sell real estate using technology.
The company wants to find the best business opportunities in the real estate market. The CEO of House Rocket would like to maximize the company's revenue by finding good business opportunities.
The main strategy is to __buy GOOD HOUSES__ in great locations at __LOW PRICES__ and then __resell them at HIGHER PRICES__. The greater the difference between buying and selling, the greater the company's profit and therefore its revenue.
However, houses have many attributes that make them more or less attractive to buyers and sellers. Location and the time of year the property is traded can also influence prices.
## Business Understanding
1. Which houses should the CEO of House Rocket buy and for what purchase price?
2. Once the houses are in the company's possession, when would be the best time to sell them and what would be the sale price?
3. Should House Rocket renovate to increase the sale price? What would be the suggested changes? What is the increase in price for each renovation option?
## Set of hypotheses
* Are houses with garages more expensive? Why is that?
* Are houses with many bedrooms more expensive? Why is that? From how many rooms does the price increase? What is the price increase for each room added?
* Are the most expensive houses in the center? Which region? Is there anything in the area that correlates with the house's sale price? Shopping centers? Mountains? Famous people?
''')
st.markdown(
'''
## Dataset overview
The dataset that represents the context of the problem addressed is available on the Kaggle platform.
This is the link: https://www.kaggle.com/harlfoxem/housesalesprediction
This dataset contains houses sold between May 2014 and May 2015.
''')
st.dataframe(data_overview)
st.markdown(
'''
| Original variables dictionary | |
|:------------------------:|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| id | Unique ID for each home sold |
| date | Date of the home sale |
| price | Price of each home sold |
| bedrooms | Number of bedroom |
| bathrooms | Number of bathrooms, where .5 accounts for a room with a toilet but no shower |
| sqft_living | Square footage of the apartments interior living space (sqft_living = sqft_above + sqft_basement) |
| sqft_lot | Square footage of the land space |
| floors | Number of floors |
| waterfront | A dummy variable for whether the apartment was overlooking the waterfront or not |
| view | An index from 0 to 4 of how good the view of the property was |
| condition | An index from 1 to 5 on the condition of the apartment, |
| grade | An index from 1 to 13, where 1-3 falls short of building construction and design, 7 has an average level of construction and design, and 11-13 have a high quality level of construction and design. |
| sqft_above | The square footage of the interior housing space that is above ground level |
| sqft_basement | The square footage of the interior housing space that is below ground level |
| yr_built | The year the house was initially built |
| yr_renovated | The year of the house’s last renovation |
| zipcode | What zipcode area the house is in |
| lat | Lattitude |
| long | Longitude |
| sqft_living15 | The square footage of interior housing living space for the nearest 15 neighbors |
| sqft_lot15 | The square footage of the land lots of the nearest 15 neighbors |
> Source: <https://www.kaggle.com/harlfoxem/housesaleprediction/discussion/207885>
''')
st.markdown("## Map overview")
map_cities(data[['lat', 'long', 'price', 'city', "zipcode"]])
st.markdown(
'''
### Ask for help
- Data Science Team on Discord
- @daniel_asg
- For more information, please visit the [project page on GitHub](https://github.com/Daniel-ASG/dishy_company/tree/main). Thanks for your visit.
''') |
---
title: "In 2024, Master the Art of Livestream Recession with These 24 Dynamic Tips"
date: 2024-06-12T01:15:17.372Z
updated: 2024-06-13T01:15:17.372Z
tags:
- screen-recording
- ai video
- ai audio
- ai auto
categories:
- ai
- screen
description: "This Article Describes In 2024, Master the Art of Livestream Recession with These 24 Dynamic Tips"
excerpt: "This Article Describes In 2024, Master the Art of Livestream Recession with These 24 Dynamic Tips"
keywords: "\"Live Streaming Skills,Recession-Proof Streams,Dynamic Streaming Tips,Masterful Livestreaming,Recession Livestreaming Strategies,Engaging Live Viewers,Effective Streaming Practices\""
thumbnail: https://thmb.techidaily.com/781e8428af43f7240e5d953add419c8aa194f2d4e4f1f7a9a67dc80aa935e243.jpg
---
## Master the Art of Livestream Recession with These 24 Dynamic Tips
Twitch is a popular streaming platform that game lovers use to watch, play, and record gameplay. Along with that, you can also watch cooking shows, tutorials, and various sports events on Twitch efficiently. Moreover, you can also use this platform to endorse your product or brand by reaching the audience through live streams. However, it may be possible that you miss live streams on Twitch due to being stuck in another work.
If you have missed any important part from live streams on Twitch, this article is for you. By reading this article, you can learn **how to rewind a Twitch stream** using 5 different methods.
## Method 1: With Easy Extension – Twitch DVR Player
[Twitch DVR player](https://chrome.google.com/webstore/detail/twitch-dvr-player/iaeibhcmabccclfnafahihdndonfgebo) is an excellent Chrome extension through which you can perform multiple functions. Through this extension, you can rewind a Twitch stream easily. By downloading this extension, you can easily shift between a regular Twitch player and a DVR player anytime. Thus, you can easily use this special extension to move back and forth during a live stream. To use this Chrome extension, follow the below steps:
Step1 To begin, you can go to the Chrome store and download the Twitch DVR Extension. From there, click on the “Add to Chrome” button to use this extension. You can also use this [link](https://chrome.google.com/webstore/detail/twitch-dvr-player/iaeibhcmabccclfnafahihdndonfgebo) to initiate the installation.

Step2 Once you have added this Chrome extension to your web browser, you can easily use it during a live stream on Twitch. Through this, you can easily move the playhead during a live stream on Twitch.

## Method 2: Watch the Playback in VODs
Many people can miss live streams on Twitch due to multiple reasons. However, you can use the VOD storage option to save your previous live broadcasts on your channel. This will help grow your audience, as anyone can visit and play your live broadcasts efficiently. Moreover, it instantly saves the previous broadcasts on your channel for 7 days. To watch a previous live stream on any streamer’s channel, check the below steps:
Step1 Open your Twitch account and navigate to your favorite streamer’s channel. Once done, click on the username to open their channel.

Step2 Now go to the “Videos” tab on their channel to check all the available past live broadcasts. Click on your preferred video and move its playhead easily. By doing so, you can watch any specific part of the stream efficiently.

## Method 3: Click the “Clip” button on Twitch
Twitch has a Clip button through which you can watch the previous 90 seconds of a live broadcast. Through this, you can quickly move back to the previous 90 seconds to listen to a particular part again. To **rewind live stream Twitch** using this function, here are simple instructions that you can follow:
Step1 While watching a live stream, go to the bottom right corner and click on the “Clip” icon. You can also press the shortcut keys “Alt + X” alternatively.

Step2 Once you have clicked on the “Clip” icon, you will redirected to a new window. By navigating through the playhead, you can watch the past 90 seconds of a live stream.

## Method 4: Use the “Rewind the Stream” Button (Test)
Twitch aims to test with three buttons so that some users can enhance features to watch live streams. The expected new buttons on Twitch are Rewind the Stream, Remind Me, and Watch Trailer. Through Rewind the Stream button, a picture-in-picture window will open through which you can rewind two minutes of a stream. This feature can only be functional if the streamer has enabled the VODs.
Moreover, using the Remind Me button, you can receive a reminder for any upcoming scheduled stream. On the other hand, using the Watch Trailer option, you can play a trailer of a particular channel instantly. To use the Rewind the Stream button for **Twitch rewind stream**, check the below steps:
Step1 Open your Twitch app and go to any streamer’s channel that is holding a live stream. You can click on the “Rewind the Stream” button given on the bottom right side.

Step2 Now you can see the past 2 minutes of the stream on your screen easily. To leave the rewind screen, click on the “Go back to Live” option. This will redirect you to the live stream instantly.
## Method 5: Save the Stream with Filmora Screen Recorder
Do you want to **rewind live stream Twitch** effortlessly? By using the [Filmora Screen Recorder](https://tools.techidaily.com/wondershare/filmora/download/), you can easily capture any live stream on Twitch. After that, you can rewind any part of the live stream without any restrictions. This screen recorder for Twitch has an excellent capability to capture live streams with high audio and video quality.
You can also set custom settings to screen record the live stream according to your desire. Furthermore, if you want to trim or split any part of your recorded live stream on Twitch, use the Filmora editor. Through this editor, you can add smooth transitions and stunning effects with a few clicks. Also, you can modify the speed of your recorded videos through this platform efficiently.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For Win 7 or later(64-bit)
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later
Thus, Wondershare Filmora is a complete tool consisting of all necessary functions and advanced features. To screen record a live stream on Twitch using Filmora, read the below steps:
##### Step1 Choose Recording Mode
Launch Filmora on your PC and click on “Screen Recorder” from its interface. It will open a screen recorder window on your screen. On this window, you can choose your preferred recording modes, such as a full screen or a target window.

##### Step2 Select Frame Rate and Quality
You can also change the frame rate and quality of your recording from Settings. Once you have modified the settings according to your preference, hit the “REC” button.

##### Step3 Begin and Stop the Recording
A countdown will appear on your screen. After that, the toll will begin the screen recording efficiently. To stop the recording anytime, press the F9 key. The screen recording will be automatically saved in the media library of Filmora.

## Conclusion
Are you missing live streams on Twitch frequently? No need to worry as this article has provided different ways through which you can **rewind live stream Twitch** flawlessly. For greater ease, you can also use the screen recorder of Filmora to capture live streams on Twitch efficiently. By doing so, you can easily rewind a live stream without any complications. Filmora also offers a video editor that can also help you in modifying your recorded live streams professionally.
[Free Download](https://tools.techidaily.com/wondershare/filmora/download/) For macOS 10.14 or later
Thus, Wondershare Filmora is a complete tool consisting of all necessary functions and advanced features. To screen record a live stream on Twitch using Filmora, read the below steps:
##### Step1 Choose Recording Mode
Launch Filmora on your PC and click on “Screen Recorder” from its interface. It will open a screen recorder window on your screen. On this window, you can choose your preferred recording modes, such as a full screen or a target window.

##### Step2 Select Frame Rate and Quality
You can also change the frame rate and quality of your recording from Settings. Once you have modified the settings according to your preference, hit the “REC” button.

##### Step3 Begin and Stop the Recording
A countdown will appear on your screen. After that, the toll will begin the screen recording efficiently. To stop the recording anytime, press the F9 key. The screen recording will be automatically saved in the media library of Filmora.

## Conclusion
Are you missing live streams on Twitch frequently? No need to worry as this article has provided different ways through which you can **rewind live stream Twitch** flawlessly. For greater ease, you can also use the screen recorder of Filmora to capture live streams on Twitch efficiently. By doing so, you can easily rewind a live stream without any complications. Filmora also offers a video editor that can also help you in modifying your recorded live streams professionally.
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-format="autorelaxed"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="1223367746"></ins>
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7571918770474297"
data-ad-slot="8358498916"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<span class="atpl-alsoreadstyle">Also read:</span>
<div><ul>
<li><a href="https://article-posts.techidaily.com/new-mastering-telegram-a-step-by-step-walkthrough/"><u>[New] Mastering Telegram A Step-By-Step Walkthrough</u></a></li>
<li><a href="https://article-posts.techidaily.com/updated-2024-approved-clearskiesedit-premium-software-to-remove-backgrounds/"><u>[Updated] 2024 Approved ClearSkiesEdit Premium Software to Remove Backgrounds</u></a></li>
<li><a href="https://article-posts.techidaily.com/updated-2024-approved-gradual-amplitude-reduction-guide/"><u>[Updated] 2024 Approved Gradual Amplitude Reduction Guide</u></a></li>
<li><a href="https://article-posts.techidaily.com/clarity-cutting-edge-expert-recommendations-for-8k-for-2024/"><u>Clarity Cutting-Edge Expert Recommendations for 8K for 2024</u></a></li>
<li><a href="https://article-posts.techidaily.com/updated-in-2024-momentum-meets-mass-audience/"><u>[Updated] In 2024, Momentum Meets Mass Audience</u></a></li>
<li><a href="https://article-posts.techidaily.com/in-2024-intensive-analysis-sonys-high-def-action-cam/"><u>In 2024, Intensive Analysis Sony's High-Def Action Cam</u></a></li>
<li><a href="https://article-posts.techidaily.com/new-the-key-to-accumulating-a-huge-collection-of-tiktok-videos-for-2024/"><u>[New] The Key to Accumulating a Huge Collection of TikTok Videos for 2024</u></a></li>
<li><a href="https://screen-mirror.techidaily.com/in-2024-the-top-10-apple-iphone-xs-max-emualtors-for-windows-mac-and-android-drfone-by-drfone-ios/"><u>In 2024, The Top 10 Apple iPhone XS Max Emualtors for Windows, Mac and Android | Dr.fone</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/2024-approved-how-to-download-and-use-kinemaster-on-your-mac/"><u>2024 Approved How to Download and Use KineMaster on Your Mac</u></a></li>
<li><a href="https://extra-lessons.techidaily.com/new-burst-life-into-slow-motion-with-top-android-apps/"><u>[New] Burst Life Into Slow Motion with Top Android Apps</u></a></li>
<li><a href="https://eaxpv-info.techidaily.com/new-in-2024-how-to-choose-the-best-free-introduction-maker/"><u>[New] In 2024, How to Choose the Best Free Introduction Maker</u></a></li>
<li><a href="https://phone-solutions.techidaily.com/in-2024-how-to-use-life360-on-windows-pc-for-vivo-y200-drfone-by-drfone-virtual-android/"><u>In 2024, How to Use Life360 on Windows PC For Vivo Y200? | Dr.fone</u></a></li>
<li><a href="https://some-approaches.techidaily.com/new-top-tips-for-pop-culture-meme-success/"><u>[New] Top Tips for Pop Culture Meme Success</u></a></li>
<li><a href="https://youtube-video-recordings.techidaily.com/sync-your-device-pace-youtube-audio-control-guide/"><u>Sync Your Device Pace YouTube Audio Control Guide</u></a></li>
<li><a href="https://ai-video-tools.techidaily.com/updated-sizing-up-your-images-how-to-calculate-aspect-ratios-like-a-pro-for-2024/"><u>Updated Sizing Up Your Images How to Calculate Aspect Ratios Like a Pro for 2024</u></a></li>
</ul></div> |
package command
import (
"context"
"sync"
)
type pwdCommand struct {
args []string
inputChannel <-chan string
outputChannel chan<- string
errorChannel chan<- error
}
func (p *pwdCommand) Execute(ctx context.Context, wg *sync.WaitGroup) {
defer wg.Done()
wd, err := getwd()
if err != nil {
p.errorChannel <- err
return
}
p.outputChannel <- wd
}
func (p *pwdCommand) SetArgs(args []string) error {
p.args = args
return nil
}
func NewPwdCommand(
inputChannel <-chan string,
outputChannel chan<- string,
errorChannel chan<- error,
) Command {
return &pwdCommand{
inputChannel: inputChannel,
outputChannel: outputChannel,
errorChannel: errorChannel,
}
} |
#pragma once
#include <functional>
#include "ChartPoint.h"
#include "ObserverValue.h"
#include "DBWrapper.h"
#include "Properties.h"
#include <iostream>
namespace angarawindows {
using namespace System;
using namespace System::Windows::Forms;
using namespace System::Data::OleDb;
delegate void CalculateDelegat(double, double, double, int);
delegate void DrawDelegat(double, double, double, double);
double getCPD(double H, double Q, double N);
double* getInterval(double x);
double round3(double x);
struct ChartData
{
double H0 = 0;
double S = 0;
double N0 = 0;
double C = 0;
};
struct ChartIntevals
{
double HInterval = 0;
double HMax = 0;
double NInterval = 0;
double NMax = 0;
double QInterval = 0;
double QMax = 0;
double MInterval = 0;
double MMax = 0;
};
ChartIntevals drawPumpCharts(ChartData& data,
DrawDelegat^ drawFunc,
bool isInterval,
double maxX,
System::Collections::Generic::List<ChartPoint^>^ points);
ChartIntevals drawPumpCharts(ChartData& data,
DrawDelegat^ drawFunc,
bool isInterval,
double maxX);
ChartData calculateChartData(double k, System::Collections::Generic::List<ChartPoint^>^ points, CalculateDelegat^ pointItCallback);
void sortPoint(System::Collections::Generic::List<ChartPoint^>^ points);
void checkPoint(System::Windows::Forms::DataVisualization::Charting::Chart^ chart,
System::Windows::Forms::DataVisualization::Charting::DataPoint^ point,
int i);
String^ toSaintific(double value);
int GetIntLength(int q);
template<typename T>
DBWrapper<T>^ getDBData(System::Data::OleDb::OleDbDataReader^ reader, System::String^ name, T def) {
DBWrapper<T>^ wrapper = gcnew DBWrapper<T>;
wrapper->value = def;
int id = reader->GetOrdinal(name);
if (reader->IsDBNull(id))
return wrapper;
if constexpr (std::is_same<T, long long>::value) {
wrapper->value = reader->GetInt64(id);
wrapper->empty = wrapper->value == 0;
}else if constexpr (std::is_same<T, int>::value) {
wrapper->value = reader->GetInt32(id);
wrapper->empty = wrapper->value == 0;
}else if constexpr (std::is_same<T, short>::value) {
wrapper->value = reader->GetInt16(id);
wrapper->empty = wrapper->value == 0;
}else if constexpr (std::is_same<T, double>::value) {
wrapper->value = reader->GetDouble(id);
wrapper->empty = wrapper->value == 0;
}else if constexpr (std::is_same<T, float>::value) {
wrapper->value = reader->GetFloat(id);
wrapper->empty = wrapper->value == 0;
}else if constexpr (std::is_same<T, String^>::value) {
wrapper->value = reader->GetString(id);
wrapper->empty = wrapper->value->Length == 0;
}
return wrapper;
}
template<typename T>
DBWrapper<T>^ getDBData(System::Data::OleDb::OleDbDataReader^ reader, System::String^ name) {
if constexpr (std::is_same<T, String^>::value) {
return getDBData<T>(reader, name, gcnew String(L""));
}else
return getDBData<T>(reader, name, 0);
}
void setupChart(System::Windows::Forms::DataVisualization::Charting::Chart^ chart, System::String^ titleY, System::Drawing::Color mainGraf, System::Drawing::Color nominalGraf, System::Drawing::Color points);
void normalyzeTitleChart(System::Windows::Forms::DataVisualization::Charting::Chart^ chart);
template<typename T>
void log(T value) {
std::cout << value << "\n";
}
public ref class QueryBuilder {
protected:
OleDbCommand^ command;
public:
delegate void Read(OleDbDataReader^);
QueryBuilder() {
}
QueryBuilder(String^ sql) {
setSql(sql);
}
QueryBuilder^ setSql(String^ sql) {
command = gcnew OleDbCommand(sql);
return this;
}
template<typename T>
QueryBuilder^ add(T value) {
throw std::runtime_error("a function not defined for" + typeid(T).name());
return this;
}
template<>
QueryBuilder^ add<long long>(long long value) {
OleDbParameter^ prms = gcnew OleDbParameter("?", OleDbType::BigInt);
prms->Value = value;
command->Parameters->Add(prms);
return this;
}
template<>
QueryBuilder^ add<int>(int value) {
OleDbParameter^ prms = gcnew OleDbParameter("?", OleDbType::Integer);
prms->Value = value;
command->Parameters->Add(prms);
return this;
}
template<>
QueryBuilder^ add<float>(float value) {
OleDbParameter^ prms = gcnew OleDbParameter("?", OleDbType::Single);
prms->Value = value;
command->Parameters->Add(prms);
return this;
}
template<>
QueryBuilder^ add<double>(double value) {
OleDbParameter^ prms = gcnew OleDbParameter("?", OleDbType::Double);
prms->Value = value;
command->Parameters->Add(prms);
return this;
}
template<>
QueryBuilder^ add<std::string>(std::string value) {
OleDbParameter^ prms = gcnew OleDbParameter("?", OleDbType::VarChar);
prms->Value = gcnew String(value.c_str());
command->Parameters->Add(prms);
return this;
}
template<>
QueryBuilder^ add<String^>(String^ value) {
OleDbParameter^ prms = gcnew OleDbParameter("?", OleDbType::VarChar);
prms->Value = value;
command->Parameters->Add(prms);
return this;
}
QueryBuilder^ addEmpty() {
command->Parameters->AddWithValue("?", DBNull::Value);
return this;
}
template<typename T>
QueryBuilder^ add(ObserverValue<T>^ value) {
if (value->isEmpty())
return addEmpty();
return add(value->getValue());
}
int executeUpdate() {
OleDbConnection^ connection = gcnew OleDbConnection(Properties::getUrlConnect());
connection->Open();
command->Connection = connection;
int ans = command->ExecuteNonQuery();
connection->Close();
return ans;
}
void executeQuery(Read^ func) {
OleDbConnection^ connection = gcnew OleDbConnection(Properties::getUrlConnect());
connection->Open();
command->Connection = connection;
OleDbDataReader^ reader = command->ExecuteReader();
func(reader);
reader->Close();
connection->Close();
}
};
} |
<script>
import Label from '@/components/Label'
import LabelWarning from '@/components/LabelWarning'
import { mapActions, mapGetters } from 'vuex'
export default {
components: {
Label,
LabelWarning
},
props: {
flow: {
type: Object,
default: () => {}
},
flowGroup: {
type: Object,
default: () => {}
},
flowRun: {
type: Object,
default: () => {}
},
type: {
type: String,
default: ''
}
},
data() {
return {
//labels
newLabel: '',
labelMenuOpen: false,
labelEditOpen: false,
labelSearchInput: '',
removingLabel: null,
newLabels: null,
disableRemove: false,
disableAdd: false,
valid: false,
errorMessage: '',
duplicateLabel: '',
rules: {
labelCheck: value => this.checkLabelInput(value) || this.errorMessage
}
}
},
computed: {
...mapGetters('tenant', ['role']),
...mapGetters('license', ['hasPermission']),
permissionsCheck() {
return !this.hasPermission('update', 'run')
},
labels() {
const labels =
this.newLabels ||
this.flowRun?.labels ||
this.flowGroup?.labels ||
this.flow?.run_config?.labels ||
this.flow?.environment?.labels ||
[]
return labels?.slice().sort()
},
flowOrFlowRun() {
return this.flowRun ? 'Flow Run' : 'Flow'
},
labelResetDisabled() {
const labels = this.newLabels || this.labels
const defaultLabels =
this.flow?.run_config?.labels || this.flow?.environment?.labels
return (
Array.isArray(labels) &&
Array.isArray(defaultLabels) &&
labels.length === defaultLabels.length &&
labels.every((val, index) => val === defaultLabels[index])
)
}
},
methods: {
...mapActions('alert', ['setAlert']),
checkLabelInput(val) {
const labels = this.newLabels || this.labels
if (labels.includes(val) && !this.disableAdd) {
this.errorMessage = 'Duplicate label'
this.duplicateLabel = val
this.valid = false
return false
}
this.duplicateLabel = ''
this.valid = true
return true
},
removeLabel(labelToRemove) {
this.removingLabel = labelToRemove
this.disableRemove = true
const labels = this.newLabels || this.labels
const updatedArray = labels.filter(label => {
return labelToRemove != label
})
this.editLabels(updatedArray)
},
addLabel() {
if (!this.valid) return
if (!this.newLabel) return
this.disableAdd = true
const labelArray = this.newLabels || this.labels.slice()
labelArray.push(this.newLabel)
this.editLabels(labelArray)
},
async editLabels(newLabels) {
try {
let result
if (this.type !== 'flowRun') {
result = await this.$apollo.mutate({
mutation: require('@/graphql/Mutations/set-labels.gql'),
variables: {
flowGroupId: this.flowGroup.id,
labelArray: newLabels
}
})
} else {
result = await this.$apollo.mutate({
mutation: require('@/graphql/Mutations/set-flow-run-labels.gql'),
variables: {
flowRunId: this.flowRun.id,
labelArray: newLabels
}
})
this.$emit('refetch')
}
if (result.data) {
this.newLabels =
newLabels ||
this.flowRun?.labels ||
this.flow?.run_config?.labels ||
this.flow?.environment?.labels ||
[]
this.resetLabelSettings()
} else {
this.labelsError()
this.resetLabelSettings()
}
} catch (e) {
this.labelsError(e)
this.resetLabelSettings()
}
},
labelReset() {
this.editLabels(null)
},
resetLabelSettings() {
this.removingLabel = false
this.disableAdd = false
this.newLabel = ''
this.disableRemove = false
},
labelsError(e) {
const message = e
? `There was a problem: ${e}`
: 'There was a problem updating your labels. Please try again.'
this.setAlert({
alertShow: true,
alertMessage: message,
alertType: 'error'
})
}
}
}
</script>
<template>
<v-list-item dense>
<v-list-item-content width="800px" style="overflow-x: auto;">
<v-list-item-subtitle class="text-caption">
Labels
<v-menu :close-on-content-click="false" offset-y open-on-hover>
<template #activator="{ on }">
<v-btn text icon x-small class="mr-2" v-on="on">
<v-icon>
info
</v-icon>
</v-btn>
</template>
<v-card tile class="pa-0" max-width="320">
<v-card-title class="subtitle pb-1"
>{{ flowOrFlowRun }} Labels
</v-card-title>
<v-card-text class="pt-0">
Flows, flow runs and agents have optional labels which allow you
to determine where your flow runs are executed. For more
information see
<a
href="https://docs.prefect.io/orchestration/execution/overview.html#labels"
target="_blank"
>the docs on labels</a
>.
</v-card-text>
</v-card>
</v-menu>
<LabelWarning
:flow="type === 'flowRun' ? flowRun.flow : flow"
:flow-group="flowGroup"
:flow-run="flowRun"
icon-size="x-large"
location="flowPageDetails"
/>
<span v-if="$vuetify.breakpoint.sm" class="ml-8">
<v-menu
v-model="labelEditOpen"
:close-on-content-click="false"
offset-y
>
<template #activator="{ on: menu, attrs }">
<v-tooltip bottom>
<template #activator="{ on: tooltip }">
<div v-on="tooltip">
<v-btn
small
icon
:disabled="permissionsCheck"
aria-label="Add label"
color="primary"
v-bind="attrs"
v-on="menu"
>
<i class="far fa-plus fa-2x" />
</v-btn>
</div>
</template>
<span v-if="permissionsCheck">
You don't have permission to edit labels</span
>
<span v-else>Add a label</span>
</v-tooltip>
</template>
<v-card width="800px" class="py-0">
<v-card-title class="subtitle pr-2 pt-2 pb-0"
>{{ flowOrFlowRun }} labels</v-card-title
>
<v-card-text class="py-0 width=1500px">
<div class="width=800px">
Flows, flow runs and agents have optional labels which allow
you to determine where your flow runs are executed. For more
information see
<a
href="https://docs.prefect.io/orchestration/execution/overview.html#labels"
target="_blank"
>the docs on labels</a
>.
</div>
<v-text-field
v-model="newLabel"
:rules="[rules.labelCheck]"
color="primary"
clearable
class="mr-2 width=2000px"
:disabled="disableAdd"
@keyup.enter="addLabel"
>
<template #prepend-inner>
<Label
v-for="(label, i) in newLabels || labels"
:key="i"
closable
:duplicate="duplicateLabel === label"
:loading="removingLabel === label"
:disabled="disableRemove"
class="mr-1 mb-1"
@remove="removeLabel"
>{{ label }}</Label
>
</template>
</v-text-field>
</v-card-text>
</v-card>
</v-menu>
<v-tooltip v-if="type !== 'flowRun'" top>
<template #activator="{ on }">
<v-btn
class="mt-0"
icon
:disabled="labelResetDisabled"
color="codePink"
small
@click="labelReset"
v-on="on"
>
<i class="far fa-undo-alt fa-2x" />
</v-btn>
</template>
<span>Reset to labels from flow registration</span>
</v-tooltip>
</span>
</v-list-item-subtitle>
<div
v-if="
(newLabels && newLabels.length > 0) || (labels && labels.length > 0)
"
>
<Label
v-for="(label, i) in newLabels || labels"
:key="i"
closable
:duplicate="duplicateLabel === label"
:loading="removingLabel === label"
:disabled="disableRemove"
class="mr-1 mb-1"
@remove="removeLabel"
>{{ label }}</Label
>
</div>
<div v-else class="text-subtitle-2">
None
</div>
</v-list-item-content>
<v-list-item-action v-if="!$vuetify.breakpoint.sm" class="ma-0">
<v-tooltip v-if="type !== 'flowRun'" top>
<template #activator="{ on }">
<v-btn
class="mt-0"
icon
:disabled="labelResetDisabled"
color="codePink"
small
@click="labelReset"
v-on="on"
>
<i class="far fa-undo-alt fa-2x" />
</v-btn>
</template>
<span>Reset to labels from flow registration</span>
</v-tooltip>
<v-menu v-model="labelEditOpen" :close-on-content-click="false" offset-y>
<template #activator="{ on: menu, attrs }">
<v-tooltip top>
<template #activator="{ on: tooltip }">
<div v-on="tooltip">
<v-btn
small
icon
:disabled="permissionsCheck"
aria-label="Add label"
color="primary"
v-bind="attrs"
v-on="menu"
>
<i class="far fa-plus fa-2x" />
</v-btn>
</div>
</template>
<span v-if="permissionsCheck">
You don't have permission to edit labels
</span>
<span v-else>Add a label</span>
</v-tooltip>
</template>
<v-card width="800px" class="py-0">
<v-card-title class="subtitle pr-2 pt-2 pb-0"
>{{ flowOrFlowRun }} labels</v-card-title
>
<v-card-text class="py-0 width=1500px">
<div class="width=800px">
Flows, flow runs and agents have optional labels which allow you
to determine where your flow runs are executed. For more
information see
<a
href="https://docs.prefect.io/orchestration/execution/overview.html#labels"
target="_blank"
>the docs on labels</a
>.
</div>
<v-text-field
v-model="newLabel"
:rules="[rules.labelCheck]"
color="primary"
clearable
class="mr-2 width=2000px"
:disabled="disableAdd"
@keyup.enter="addLabel"
>
<template #prepend-inner>
<Label
v-for="(label, i) in newLabels || labels"
:key="i"
closable
:duplicate="duplicateLabel === label"
:loading="removingLabel === label"
:disabled="disableRemove"
class="mr-1 mb-1"
@remove="removeLabel"
>{{ label }}</Label
>
</template>
</v-text-field>
</v-card-text>
</v-card>
</v-menu>
</v-list-item-action>
</v-list-item>
</template>
<style lang="scss" scoped>
/* stylelint-disable */
.v-list-item__action--stack {
align-items: flex-start;
flex-direction: row;
}
</style> |
----------------------------------------------------------------------
Freeciv Rulesets
----------------------------------------------------------------------
(Originally by David Pfitzner, [email protected])
Quickstart:
-----------
Rulesets allow modifiable sets of data for units, advances, terrain,
improvements, wonders, nations, cities, governments and miscellaneous
game rules, without requiring recompilation, in a way which is
consistent across a network and through savegames.
- To play Freeciv normally: don't do anything special; the new
features all have defaults which give the standard Freeciv
behaviour.
- To play a game with rules more like Civ1, start the server with:
./ser -r data/civ1.serv
(and any other command-line arguments you normally use; depending on
how you have Freeciv installed you may have to give the installed
data directory path instead of "data").
Start the client normally. The client must be network-compatible
(usually meaning the same or similar version) but otherwise nothing
special is needed. (However some third-party rulesets may
potentially require special graphics to work properly, in which case
the client should have those graphics available and be started with
an appropriate '--tiles' argument.)
As well as a Civ1 style as above, Freeciv now has a Civ2 style
similary, although currently it is almost identical to standard
Freeciv rules.
Note that the Freeciv AI might not play as well with rules other
than standard Freeciv. The AI is supposed to understand and
utilize all sane rules variations, so please report any AI
failures so that they can be fixed.
The rest of this file contains:
- More detailed information on creating and using custom/mixed
rulesets.
- Information on implementation, and notes for further development.
----------------------------------------------------------------------
Using and modifying rulesets:
-----------------------------
Rulesets are specified using the server command "rulesetdir". The
command above of "./ser -r data/civ1.serv" just reads a file which
uses this command (as well as a few of the standard server options).
The server command specifies in which directory the ruleset files
are to be found.
The ruleset files in the data directory are user-editable, so you can
modify them to create modified or custom rulesets (without having to
recompile Freeciv). It is suggested that you _don't_ edit the
existing files in the "default", "classic", "civ1" and "civ2"
directories, but rather copy them to another directory and edit the
copies. This is so that its clear when you are using modified rules
and not the standard ones.
The format used in the ruleset files should be fairly
self-explanatory. A few points:
- The files are not all independent, since eg, units depend on
advances specified in the techs file.
- Units have a field, "roles", which is like "flags", but
determines which units are used in various circumstances of the
game (rather than intrinsic properties of the unit).
See comments in common/unit.h
- The cities section of the nations ruleset files deserves some
explanation. At first glance, it simply contains a comma-
separated list of quoted city names. However, this list can
also be used to label cities by their preferred terrain type.
Cities can be labeled as matching or not matching a particular
type of terrain, which will make them more (or less) likely to
show up as the "default" name. The exact format of the list
entry is
"<cityname> (<label>, <label>, ...)"
where the cityname is just the name for the city (note that it
may not contain quotes or parenthesis), and each "label" matches
(case-insensitive) a terrain type for the city (or "river"), with a
preceeding ! to negate it. The terrain list is optional, of course,
so the entry can just contain the cityname if desired. A city name
labeled as matching a terrain type will match a particular map
location if that map location is on or adjacent to a tile of the named
terrain type; in the case of the "river" label (which is a special
case) only the map location itself is considered. A complex example:
"Wilmington (ocean, river, swamp, forest, !hills, !mountains, !desert)"
will cause the city of Wilmington to match ocean, river, swamp, and
forest tiles while rejecting hills, mountains, and deserts. Although
this degree of detail is probably unnecessary to achieve the desired
effect, the system is designed to degrade smoothly so it should work
just fine.
(A note on scale: it might be tempting to label London as !ocean, i.e.
not adjacent to an ocean. However, on a reasonably-sized FreeCiv world
map, London will be adjacent to the ocean; labeling it !ocean will tend
to give bad results. This is a limitation of the system, and should be
taken into account when labelling cities.)
Also note that a city earlier in the list has a higher chance of being
chosen than later cities.
Properties of units and advances are now fairly well generalised.
Properties of buildings are still rather inflexible.
----------------------------------------------------------------------
Restrictions and Limitations:
-----------------------------
units.ruleset:
Restrictions:
- At least one unit with role "FirstBuild" must be available
from the start (i.e., tech_req = "None").
- There must be units for these roles:
- "Explorer"
- "FerryBoat"
- "Hut"
- "Barbarian"
- "BarbarianLeader"
- "BarbarianBuild"
- "BarbarianBoat" (move_type must be "Sea")
- "BarbarianSea"
- There must be at least one unit with flag "Cities".
Limitations:
- These unit flag combinations won't work:
- "Diplomat" and "Caravan"
- These flags and roles work only for move_type "Land" units:
- "Diplomat"
- "Partisan"
- "Paratroopers"
- "Settler"
- "IgTer"
- "Marines"
- "Airbase"
- "Barbarian"
- "BarbarianTech"
- Flag "Cities" does not work for move_type "Air" or "Heli" units
nations.ruleset:
Unused entries:
- tech_goals
- wonder
- government
----------------------------------------------------------------------
Implementation details:
-----------------------
This section and following section will be mainly of interested to
developers who are familiar with the Freeciv source code.
Rulesets are mainly implemented in the server. The server reads the
files, and then sends information to the clients. Mostly rulesets
are used to fill in the basic data tables on units etc, but in some
cases some extra information is required.
For units and advances, all information regarding each unit or advance
is now captured in the data tables, and these are now "fully
customizable", with the old enumeration types completely removed. |
---
title: Administer teams
weight: 1
sidebarTitle: Teams
sidebarIgnore: true
description: Manage team access and permissions across all your projects and organizations.
---
Organizations on {{% vendor/name %}} are made up of both [projects](/projects/) and [users](/administration/users.md).
While organizations by themselves allow you to assign project and environment type permissions to individual users on certain projects,
having many users and projects calls for another method to group common access control settings.
**Teams** provide a grouping that connects a group of organization's users to a specified group of organization's projects.
That relationship enables organization owners to set default Project and environment type access settings for each user and project from one place.
There is no limit to the number of teams that can be defined within a single organization.
## Create a new team
As an organization owner or member with **Manage users** permissions,
you can create new teams.
Teams must belong to an organization, so [create one]() first.
You can create new organizations with different payment methods and billing addresses
and organize your projects as you want, but keep in mind that both users and teams are restricted to single organizations.
{{< codetabs >}}
+++
title=Using the Console
+++
1. Navigate to your existing organization.
1. Open the user menu (your name or profile picture).
1. Select **Teams** from the dropdown.
1. Click **+ Create team**.
1. Enter the information for your team. Only the team name is required at this point, but you can define environment type permissions now if you'd like.
1. Click **Create team**.
<--->
+++
title=Using the CLI
+++
Assuming you have already created the organization `deploy-friday-agency`, retrieve that {{% variable "ORGANIZATION_ID" %}} with the command:
```bash
{{% vendor/cli %}} organization:info -o deploy-friday-agency id
```
Then use that {{% variable "ORGANIZATION_ID" %}} to create a new team for your organization's "Frontend developers" by running:
```bash
{{% vendor/cli %}} api:curl -X POST /teams \
-d "{'organization_id':'{{% variable "ORGANIZATION_ID" %}}','label':'Frontend Developers'}"
```
That command will provide a {{% variable "TEAM_ID" %}}, which you can use to verify the team was created successfully:
```bash
{{% vendor/cli %}} api:curl -X GET /teams/{{% variable "TEAM_ID" %}}
```
{{< /codetabs >}}
## Delete an existing team
As an organization owner or member with **Manage users** permissions,
you can delete existing teams.
Note that deleting teams and deleting users are not equivalent.
Deleting a team will remove member access permissions to projects described by the team,
but it will _not_ [remove users from the organization](/administration/users.md#remove-a-user-from-an-organization) (or your billing).
{{< codetabs >}}
+++
title=Using the Console
+++
1. Navigate to your existing organization
1. Open the user menu (your name or profile picture).
1. Select **Teams** from the dropdown.
1. Find the team you want to delete under the **Manage teams** list,
then click **{{< icon more >}} More**.
1. Click **Delete team**.
1. Click **Yes** to confirm.
<--->
+++
title=Using the CLI
+++
To delete the team `Frontend developers` from the organization `deploy-friday-agency`, first retrieve the {{% variable "ORGANIZATION_ID" %}}:
```bash
{{% vendor/cli %}} organization:info -o deploy-friday-agency id
```
You can then use that {{% variable "ORGANIZATION_ID" %}} to list the teams associated with it:
```bash
{{% vendor/cli %}} api:curl -X GET '/teams?filter[organization_id]={{% variable "ORGANIZATION_ID" %}}'
```
The response will include a {{% variable "TEAM_ID" %}} for the team `Frontend developers`.
Use that ID to delete the team:
```bash
{{% vendor/cli %}} api:curl -X DELETE /teams/{{% variable "TEAM_ID" %}}
```
{{< /codetabs >}}
## Manage team settings
As an organization owner or member with **Manage users** permissions,
you can manage the settings of existing teams such as:
- [It's name](#team-name)
- [The environment type permissions granted to members on individual projects](#project--environment-type-permissions)
- [Team members](#team-members)
- [Project access](#team-access-to-projects)
### Team name
{{< codetabs >}}
+++
title=Using the Console
+++
1. Navigate to your existing organization.
1. Open the user menu (your name or profile picture).
1. Select **Teams** from the dropdown.
1. Find the team you want to delete under the **Manage teams** list,
then click **{{< icon more >}} More**.
1. Click **Edit team**.
1. In the sidebar click the **Edit** link, and edit the team name.
1. Click **Save**.
<--->
+++
title=Using the CLI
+++
To change the name of the team `Frontend developers` (organization `deploy-friday-agency`) to `JS developers`, first retrieve the {{% variable "ORGANIZATION_ID" %}}:
```bash
{{% vendor/cli %}} organization:info -o deploy-friday-agency id
```
You can then use that {{% variable "ORGANIZATION_ID" %}} to list the teams associated with it:
```bash
{{% vendor/cli %}} api:curl -X GET '/teams?filter[organization_id]={{% variable "ORGANIZATION_ID" %}}'
```
The response will include a {{% variable "TEAM_ID" %}} for the team `Frontend developers`.
Use that ID to update the team name:
```bash
{{% vendor/cli %}} api:curl -X PATCH /teams/{{% variable "TEAM_ID" %}} -d "{'label':'JS Developers'}"
```
{{< /codetabs >}}
### Project & environment type permissions
{{< codetabs >}}
+++
title=Using the Console
+++
1. Navigate to your existing organization
1. Open the user menu (your name or profile picture).
1. Select **Teams** from the dropdown.
1. Find the team you want to delete under the **Manage teams** list,
then click **{{< icon more >}} More**.
1. Click **Edit team**.
1. In the sidebar, you can:
* Assign **Project permissions** by selecting the check box to make team members *Project admins* of every project added to the team.
* Assign **Environment type permissions** by using the dropdowns to grant *No access*, *Viewer*, *Contributor*, or *Admin* rights to team members for *Production*, *Staging*, and *Development* project environment types.
1. Click **Save**.
<--->
+++
title=Using the CLI
+++
To change the name of the team `Frontend developers` (organization `deploy-friday-agency`) to `JS developers`, first retrieve the {{% variable "ORGANIZATION_ID" %}}:
```bash
{{% vendor/cli %}} organization:info -o deploy-friday-agency id
```
You can then use that {{% variable "ORGANIZATION_ID" %}} to list the teams associated with it:
```bash
{{% vendor/cli %}} api:curl -X GET '/teams?filter[organization_id]={{% variable "ORGANIZATION_ID" %}}'
```
The response will include a {{% variable "TEAM_ID" %}} for the team `Frontend developers`.
Use that ID to update the team's project and environment type permissions:
<!-- @todo: there is not a single PATCH to update default permissions, but rather applied to each user for each project behind the scenes. -->
```bash
TBD
```
{{< /codetabs >}}
### Team members
#### Add users to a team
To join a team, a user must already have been added [to the organization](/administration/users.md#manage-organization-access),
where their [organization permissions](/administration/users.md#organization-permissions) are defined.
{{< codetabs >}}
+++
title=Using the Console
+++
1. Navigate to your existing organization.
1. Open the user menu (your name or profile picture).
1. Select **Teams** from the dropdown.
1. Find the team you want to delete under the **Manage teams** list,
then click **{{< icon more >}} More**.
1. Click **Add user**.
1. Locate and select organization users from the dropdown.
1. In the sidebar click the **Edit** link, and edit the team name.
1. Click **Add users**.
<--->
+++
title=Using the CLI
+++
To add a user to the team `Frontend developers` (organization `deploy-friday-agency`), first retrieve the {{% variable "ORGANIZATION_ID" %}}:
```bash
{{% vendor/cli %}} organization:info -o deploy-friday-agency id
```
Also find a {{% variable "USER_ID" %}} for the user you want to add to the team from their email by running the command:
```bash
{{% vendor/cli %}} organization:user:get -o deploy-friday-agency {{% variable "USER_EMAIL" %}} -P id
```
You can use the {{% variable "ORGANIZATION_ID" %}} to list the teams associated with it:
```bash
{{% vendor/cli %}} api:curl -X GET '/teams?filter[organization_id]={{% variable "ORGANIZATION_ID" %}}'
```
The response will include a {{% variable "TEAM_ID" %}} for the team `Frontend developers`.
With all of this info, you can now add a user to the team `Frontend developers`:
```bash
{{% vendor/cli %}} api:curl -X POST /teams/{{% variable "TEAM_ID" %}}/members -d "{'user_id':'{{% variable "USER_ID" %}}'}"
```
{{< /codetabs >}}
#### Remove users from a team
Note that deleting users from teams and deleting users from organizations are not equivalent.
Deleting users from a team will remove member access permissions to projects described by the team,
but it will _not_ [remove users from the organization](/administration/users.md#remove-a-user-from-an-organization) (or your billing).
{{< codetabs >}}
+++
title=Using the Console
+++
1. Navigate to your existing organization.
1. Open the user menu (your name or profile picture).
1. Select **Teams** from the dropdown.
1. Find the team you want to delete under the **Manage teams** list,
then click **{{< icon more >}} More**.
1. Click **Edit team**.
1. Find the user you want to delete under the **USERS** tab view,
then click **{{< icon more >}} More**.
1. Click **Remove user**.
1. Click **Yes** to confirm.
<--->
+++
title=Using the CLI
+++
To remove a user from the team `Frontend developers` (organization `deploy-friday-agency`), first retrieve the {{% variable "ORGANIZATION_ID" %}}:
```bash
{{% vendor/cli %}} organization:info -o deploy-friday-agency id
```
You can use the {{% variable "ORGANIZATION_ID" %}} to list the teams associated with it:
```bash
{{% vendor/cli %}} api:curl -X GET '/teams?filter[organization_id]={{% variable "ORGANIZATION_ID" %}}'
```
The response will include a {{% variable "TEAM_ID" %}} for the team `Frontend developers`.
You can use that ID to list the members of that team:
```bash
{{% vendor/cli %}} api:curl -X GET '/teams/{{% variable "TEAM_ID" %}}/members'
```
That response will list all members, including the {{% variable "USER_ID" %}} for the user you want to remove.
To remove them, run:
```bash
{{% vendor/cli %}} api:curl -X DELETE /teams/{{% variable "TEAM_ID" %}}/members/{{% variable "USER_ID" %}}"
```
{{< /codetabs >}}
### Team access to projects
#### Add project to team's access
{{< codetabs >}}
+++
title=Using the Console
+++
**Option 1: Add projects to team with from Team settings**
1. Navigate to your existing organization.
1. Open the user menu (your name or profile picture).
1. Select **Teams** from the dropdown.
1. Find the team you want to delete under the **Manage teams** list,
then click **{{< icon more >}} More**.
1. Click **Edit team**.
1. Click **+ Add projects**.
1. Select **All projects**, or choose individual projects from the dropdown.
1. Click **Add to team**.
**Option 2: Add teams to project from project's Access settings**
1. Navigate to your existing organization.
1. Click on the project you want to add to the existing team.
1. Navigate to the projects settings by clicking the **{{< icon settings >}} Settings** icon.
1. Click on **Access** settings under **Project settings** in the sidebar.
1. Click on the **TEAMS** tab in the **Access** list view.
1. Click **+Add to projects**.
1. Select **All teams**, or choose individual teams from the dropdown.
1. Click **Add to team**.
<--->
+++
title=Using the CLI
+++
To add projects to the team `Frontend developers` (organization `deploy-friday-agency`), first retrieve the {{% variable "ORGANIZATION_ID" %}}:
```bash
{{% vendor/cli %}} organization:info -o deploy-friday-agency id
```
Locate the {{% variable "PROJECT_ID" %}} as well by running:
```bash
{{% vendor/cli %}} project:list -o deploy-friday-agency
```
You can use the {{% variable "ORGANIZATION_ID" %}} to list the teams associated with it:
```bash
{{% vendor/cli %}} api:curl -X GET '/teams?filter[organization_id]={{% variable "ORGANIZATION_ID" %}}'
```
The response will include a {{% variable "TEAM_ID" %}} for the team `Frontend developers`.
With all of this information in hand, add the project to the team by running:
<!-- @todo: there is not a single POST to add project to a team, but rather applied to each user for each project behind the scenes. -->
```bash
TBD
```
{{< /codetabs >}}
#### Remove project from team's access
{{< codetabs >}}
+++
title=Using the Console
+++
**Option 1: Remove projects from a team with from Team settings**
1. Navigate to your existing organization.
1. Open the user menu (your name or profile picture).
1. Select **Teams** from the dropdown.
1. Find the team you want to delete under the **Manage teams** list,
then click **{{< icon more >}} More**.
1. Click **Edit team**.
1. Find the project you want to modify under the **PROJECTS** tab view,
then click **{{< icon more >}} More**.
1. Click **Remove project**.
1. Select **All projects**, or choose individual projects from the dropdown.
1. Click **Yes** to confirm.
**Option 2: Remove teams from a project from project's Access settings**
1. Navigate to your existing organization.
1. Click on the project you want to add to the existing team.
1. Navigate to the projects settings by clicking the **{{< icon settings >}} Settings** icon.
1. Click on **Access** settings under **Project settings** in the sidebar.
1. Find the team under the **TEAMS** tab view,
then click **{{< icon more >}} More**.
1. Click **Remove team**.
1. Click **Yes** to confirm.
<--->
+++
title=Using the CLI
+++
To add projects to the team `Frontend developers` (organization `deploy-friday-agency`), first retrieve the {{% variable "ORGANIZATION_ID" %}}:
```bash
{{% vendor/cli %}} organization:info -o deploy-friday-agency id
```
Locate the {{% variable "PROJECT_ID" %}} as well by running:
```bash
{{% vendor/cli %}} project:list -o deploy-friday-agency
```
You can use the {{% variable "ORGANIZATION_ID" %}} to list the teams associated with it:
```bash
{{% vendor/cli %}} api:curl -X GET '/teams?filter[organization_id]={{% variable "ORGANIZATION_ID" %}}'
```
The response will include a {{% variable "TEAM_ID" %}} for the team `Frontend developers`.
With all of this information in hand, add the project to the team by running:
<!-- @todo: there is not a single DELETE to remove a project from a team, but rather applied to each user for each project behind the scenes. -->
```bash
TBD
```
{{< /codetabs >}} |
import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { User } from '../interfaces/user';
@Injectable({
providedIn: 'root',
})
export class DataService implements InMemoryDbService {
createDb() {
const userPreferences: User[] = [
{ id: 0, firstName: "Maria", lastName: "Paz", age: 5, colorName: "Pink" },
{ id: 0, firstName: "Gabriela", lastName: "Souza", age: 5, colorName: "Pink" },
{ id: 0, firstName: "Caroline", lastName: "Santos", age: 12, colorName: "Red" },
{ id: 0, firstName: "Gael", lastName: "Figueiredo", age: 15, colorName: "Green" },
{ id: 0, firstName: "Raquel", lastName: "Luz", age: 18, colorName: "Yellow" },
{ id: 0, firstName: "Severino", lastName: "Cardoso", age: 22, colorName: "Black" },
{ id: 0, firstName: "Murilo", lastName: "Porto", age: 37, colorName: "Gray" },
{ id: 0, firstName: "Ruan", lastName: "Monteiro", age: 42, colorName: "Purple" },
{ id: 0, firstName: "Elisa", lastName: "Bernardes", age: 65, colorName: "White" },
{ id: 0, firstName: "Agatha", lastName: "Peixoto", age: 82, colorName: "Orange" },
{ id: 0, firstName: "Ilda", lastName: "Peixoto", age: 81, colorName: "Orange" },
{ id: 0, firstName: "Cora", lastName: "Peixoto", age: 100, colorName: "Orange" }
];
let id = 0;
userPreferences.forEach(u => { u.id = ++id; });
return { userPreferences };
}
// Overrides the genId method
genId(userPreferences: User[]): number {
const maxId = userPreferences.length > 0 ? Math.max(...userPreferences.map(userPreference => userPreference.id)) : 0;
return maxId + 1;
}
} |
#include <stdio.h>
int isValidDate(int day, int month, int year) {
if (year < 0 || month < 1 || month > 12 || day < 1)
return 0;
int maxDays;
switch (month) {
case 2:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
maxDays = 29;
else
maxDays = 28;
break;
case 4:
case 6:
case 9:
case 11:
maxDays = 30;
break;
default:
maxDays = 31;
}
return day <= maxDays;
}
void printASCII(char start, char end) {
printf("Output:\n");
char c;
for (c = start; c >= end; c--) {
printf("%c: %d, %xh\n", c, c, c);
}
}
int main() {
int choice;
do {
printf("Menu:\n");
printf("1- Processing date data\n");
printf("2- Character data\n");
printf("3- Quit\n");
printf("Choose an operation: ");
scanf("%d", &choice);
switch (choice) {
case 1:
{
int day, month, year;
printf("Enter day, month, year: ");
scanf("%d%d%d", &day, &month, &year);
if (isValidDate(day, month, year))
printf("The date is valid.\n");
else
printf("The date is not valid.\n");
}
break;
case 2:
{
char start, end;
printf("Enter two characters: ");
scanf(" %c %c", &start, &end);
printASCII(start, end);
}
break;
case 3:
printf("Quitting the program. Goodbye!\n");
break;
default:
printf("Invalid choice. Please enter a number between 1 and 3.\n");
}
} while (choice != 3);
return 0;
} |
@extends('layouts.main')
@section('content')
@if(session()->has('success-msg'))
<div class="p-4 mb-4 fixed right-5 z-50 alert-msg w-80 mx-2 mt-4 flex justify-between items-center text-sm text-green-800 rounded-lg bg-green-200/50 dark:bg-gray-800 dark:text-green-400" role="alert" >
<span class="font-semibold">{{session('success-msg')}}<i class="fa-solid ms-1 fa-circle-check text-sm"></i></span>
<svg class="w-7 h-7 p-2 xmark cursor-pointer" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 14 14">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="m1 1 6 6m0 0 6 6M7 7l6-6M7 7l-6 6"/>
</svg>
</div>
@endif
<div class="main-container lg:pt-40 pt-52 bg-gray-100 md:px-[100px] px-[20px]">
<div class="reviews md:w-[1200px] max-w-full mx-auto">
<div class="container w-full max-w-full md:pb-20 pb-10">
<div class="title text-center my-8 border-b w-[700px] max-w-full mx-auto border-gray-400">
<h1 class="text-5xl text-main-back mb-5">آراء العملاء</h1>
<p class=" text-gray-600 pb-2 w-[600px] max-w-full mx-auto">
تصفح تجارب وآراء عملائنا وتفاصيل شهاداتهم الشخصية حول تجربتهم معنا. </p>
</div>
<div class="relative border-b-gray-400 border-b-2">
@if (count($reviews) != 0)
<div class="grid md:grid-cols-2 grid-cols-1 gap-8 pb-20 mb-20 mt-20">
@foreach ($reviews as $review)
<div class="user-review relative bg-gray-200 p-4 rounded shadow-md flex flex-col justify-between">
<div class="star_ratings inline-block mb-8">
@for ($i = 0; $i < 5; $i++)
@if ($i < $review->star_ratings)
<span><i class="fa-solid fa-star text-main-back"></i></span>
@php
continue
@endphp
@endif
<span><i class="fa-regular fa-star text-main-back"></i></span>
@endfor
</div>
<div class="content mb-5 leading-6 text-gray-600">{{$review->reviewer_content}}</div>
<div class="user-info flex">
<i class="fa-solid fa-user text-2xl me-2"></i>
<div class="">
<h3 class=" font-bold mr-2 relative top-1">{{$review->reviewer_name}}</h3>
<small class="text-gray-600 mr-2 relative top-1">{{$review->reviewer_city}}</small>
</div>
</div>
</div>
@endforeach
<div class="user-review relative bg-gray-200 p-4 rounded shadow-md">
<div class="star_ratings inline-block">
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span class="ms-2 text-main-text">(50+)</span>
</div>
<h3 class="my-4 text-main-text text-2xl font-bold">تقييمات العملاء على موقع حراج </h3>
<div class="content mb-5 leading-6 text-gray-600">
<a href="https://haraj.com.sa/users/%D8%A7%D8%A8%D9%88%20%D8%A8%D8%AF%D8%B1%20%D9%84%D9%84%D8%A7%D8%B3%D8%AA%D9%8A%D8%B1%D8%A7%D8%AF" target="_blank" title="آراء العملاء" class="text-main-text sm:text-xl text-lg block mb-5 underline hover:text-main-back font-normal transition-all ease-linear"><i class="fa-solid fa-up-right-from-square"></i> موقع حراج</a>
</div>
</div>
</div>
@else
<div class="max-w-full mx-auto w-[700px] mb-20 flex flex-col items-center py-10">
<i class="fa-solid fa-magnifying-glass max-w-full text-[100px] text-main-back mx-auto text-center mb-4"></i>
<h3 class="text-main-back text-center sm:text-2xl mt-2 max-w-full bg-green-100 py-2 px-4 w-[500px] mx-auto rounded-md shadow">ليس هنالك آراء بعد، <a href="#review-form " class="underline text-base">أضافة رأيي</a></h3>
</div>
<div class="user-review mb-4 w-1/2 relative bg-gray-200 p-4 rounded shadow-md">
<div class="star_ratings inline-block">
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span><i class="fa-solid fa-star text-yellow-400"></i></span>
<span class="ms-2 text-main-text">(50+)</span>
</div>
<h3 class="my-4 text-main-text text-2xl font-bold">تقييمات العملاء على موقع حراج </h3>
<div class="content mb-5 leading-6 text-gray-600">
<a href="https://haraj.com.sa/users/%D8%A7%D8%A8%D9%88%20%D8%A8%D8%AF%D8%B1%20%D9%84%D9%84%D8%A7%D8%B3%D8%AA%D9%8A%D8%B1%D8%A7%D8%AF" target="_blank" title="آراء العملاء" class="text-main-text sm:text-xl text-lg block mb-5 underline hover:text-main-back font-normal transition-all ease-linear"><i class="fa-solid fa-up-right-from-square"></i> موقع حراج</a>
</div>
</div>
@endif
</div>
<div class="add-review flex justify-center items-center flex-col ">
<div class="title my-10">
<h2 class="text-4xl text-gray-600 text-center mb-6" >رأيك يهمنا</h2>
<p>شكرًا لثقتكم وتعاونكم. نحن شركاء في النجاح.</p>
</div>
<form action="{{route('reviews.store')}}#review-form" method="POST" id="review-form" class="bg-white p-5 shadow-md w-[800px] max-w-full rounded review-form">
@csrf
<div class="flex md:flex-row flex-col md:gap-5">
<div class="relative md:w-1/2 w-full">
<label class=" my-2 inline-block">الإسم</label>
<input type="text" name="reviewer_name" placeholder="الإسم بالكامل" value="{{old('reviewer_name')}}" class="w-full rounded border-gray-400 focus:ring-2 focus:ring-main-back" required>
@error('reviewer_name')
<span class="text-red-500 block my-2 text-right" style="direction: ltr">{{$message}}</span>
@enderror
<p class="absolute left-2 top-[75%] -translate-y-1/2 text-red-500 text-xl">*</p>
</div>
<div class="relative md:w-1/2 w-full">
<label class="mb-2 inline-block mt-2">المدينة</label>
<input type="text" name="reviewer_city" placeholder="اكتب مدينتك: الرياض، أبها، جدة...." value="{{old('reviewer_city')}}" class="w-full rounded border-gray-400 focus:ring-2 focus:ring-main-back" required>
@error('reviewer_city')
<span class="text-red-500 block my-2 text-right" style="direction: ltr">{{$message}}</span>
@enderror
<p class="absolute left-2 top-[75%] -translate-y-1/2 text-red-500 text-xl">*</p>
</div>
</div>
<div class="my-4 relative">
<label class="mb-2 inline-block">رأي العميل</label>
<textarea name="reviewer_content" placeholder="أكتب رأيك..." minlength="2" maxlength="200" class=" w-full h-40 rounded border-gray-400 focus:ring-2 focus:ring-main-back" required>{{old('reviewer_content')}}</textarea>
@error('reviewer_content')
<span class="text-red-500 block my-2 text-right" style="direction: ltr">{{$message}}</span>
@enderror
<p class="absolute left-2 top-[30%] -translate-y-1/2 text-red-500 text-xl">*</p>
</div>
<div class="text-center py-8">
<label class="mb-2 inline-block text-xl"> (القيمة الأفتراضية هي 5 نجوم)</label>
<div class="star_ratings_add block mb-8">
<span><i class="fa-solid fa-star cursor-pointer select-none text-main-back text-3xl" data-rating="0"></i></span>
<span><i class="fa-solid fa-star cursor-pointer select-none text-main-back text-3xl" data-rating="1"></i></span>
<span><i class="fa-solid fa-star cursor-pointer select-none text-main-back text-3xl" data-rating="2"></i></span>
<span><i class="fa-solid fa-star cursor-pointer select-none text-main-back text-3xl" data-rating="3"></i></span>
<span><i class="fa-solid fa-star cursor-pointer select-none text-main-back text-3xl" data-rating="4"></i></span>
</div>
</div>
<input type="hidden" name="rating" id="ratingValue" value="">
<input type="submit" value="إرسال" class="bg-main-back rounded border-none text-white py-2 px-4 sm:w-1/3 w-full cursor-pointer hover:scale-[0.99] transition-all ease-linear ">
</form>
</div>
</div>
</div>
</div>
@endsection |
package cc.haoduoyu.demoapp.autoscrollviewpager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.util.LruCache;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import cc.haoduoyu.demoapp.R;
/**
* 自动循环ViewPager
* Created by XP on 2016/3/26.
*/
public class AutoScrollViewPagerActivity extends AppCompatActivity {
private List<Integer> imageList;
private TextView mTextView;
private LinearLayout ll;
private int preEnablePosition = 0;
private String[] imageText = {"Text1", "Text2", "Text3", "Text4", "Text5"};
int[] imageIds = {R.drawable.iv1, R.drawable.iv2, R.drawable.iv3, R.drawable.iv4, R.drawable.iv5};
private ViewPager mThreadViewPager;
private ViewPager mHandlerViewPager;
private boolean isRunning = true;
private boolean isStop = false;
private int messageTag = 0;
private static final int DEFAULT_TIME = 1200;
private boolean firstClick = true;
private PageChangeListener1 threadListener;
private PageChangeListener2 handlerListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auto_scroll_viewpager);
initViews();
}
//线程形式
Thread mThread = new Thread(new Runnable() {
@Override
public void run() {
while (!isStop) {
//每个两秒钟发一条消息到主线程,更新viewpager界面
SystemClock.sleep(DEFAULT_TIME);
runOnUiThread(new Runnable() {
public void run() {
int index = mThreadViewPager.getCurrentItem() + 1;
mThreadViewPager.setCurrentItem(index % imageList.size());
Log.d("线程形式index:", index + "");
}
});
}
}
});
//Handler形式
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (isRunning) {
int index = mHandlerViewPager.getCurrentItem() + 1;
mHandlerViewPager.setCurrentItem(index % imageList.size());
start(msg.arg1);
Log.d("Handler形式index:", index + "");
Log.d("123", mThread.isAlive() + "");
}
}
};
private void initViews() {
mThreadViewPager = (ViewPager) findViewById(R.id.viewpager);
mHandlerViewPager = (ViewPager) findViewById(R.id.loop_viewpager);
ll = (LinearLayout) findViewById(R.id.ll_point_group);
mTextView = (TextView) findViewById(R.id.tv_image_text);
threadListener = new PageChangeListener1();
handlerListener = new PageChangeListener2();
imageList = new ArrayList<>();
for (int id : imageIds) {
imageList.add(id);
// 每循环一次添加一个点到布局中
View view = new View(this);
view.setBackgroundResource(R.drawable.point_background);
LayoutParams params = new LayoutParams(5, 5);
params.leftMargin = 5;
view.setEnabled(false);
view.setLayoutParams(params);
ll.addView(view);
}
mThreadViewPager.setAdapter(new MyPageAdapter(this, imageList));
mHandlerViewPager.setAdapter(new MyPageAdapter(this, imageList));
mThreadViewPager.setOffscreenPageLimit(5);
mHandlerViewPager.setOffscreenPageLimit(5);
mThreadViewPager.addOnPageChangeListener(threadListener);
mHandlerViewPager.addOnPageChangeListener(handlerListener);
mTextView.setText(imageText[0]);
ll.getChildAt(0).setEnabled(true);
findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//线程形式
if (firstClick) {
mThread.start();
firstClick = false;
}
start();
}
});
findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stop();
}
});
}
//自动播放
public void start(int time) {
//Handler形式
isRunning = true;
//防止多次点击导致有多个消息
mHandler.removeMessages(messageTag);
Message message = Message.obtain();
message.arg1 = time;
//what作为Message的标记,用于移除未被接收到的Message
message.what = messageTag;
mHandler.sendMessageDelayed(message, time);
}
//自动播放,默认间隔
public void start() {
start(DEFAULT_TIME);
}
//停止自动播放
public void stop() {
isRunning = false;
//移除所有之前的Message
mHandler.removeMessages(messageTag);
}
@Override
protected void onDestroy() {
isRunning = false;
isStop = true;
if (mHandler != null)
mHandler.removeCallbacksAndMessages(null);
mThreadViewPager.removeOnPageChangeListener(threadListener);
mHandlerViewPager.removeOnPageChangeListener(handlerListener);
super.onDestroy();
}
private class PageChangeListener1 implements OnPageChangeListener {
private int mPosition;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// 取余后的索引
mPosition = position;
// 根据索引设置图片的描述
mTextView.setText(imageText[mPosition]);
// 把上一个点设置为未选中
ll.getChildAt(preEnablePosition).setEnabled(false);
// 根据索引设置一个点被选中
ll.getChildAt(mPosition).setEnabled(true);
preEnablePosition = mPosition;
}
@Override
public void onPageScrollStateChanged(int state) {
//未拖动页面时
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (mPosition == imageList.size() - 1) {
// mThreadViewPager.setCurrentItem(0, false);
// Log.d("", "mThreadViewPager.setCurrentItem(0, false);");
}
}
}
}
private class PageChangeListener2 implements OnPageChangeListener {
private int mPosition;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mPosition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
//未拖动页面时
if (state == ViewPager.SCROLL_STATE_IDLE) {
if (mPosition == imageList.size() - 1) {
// mHandlerViewPager.setCurrentItem(0, false);
// Log.d("", "mThreadViewPager.setCurrentItem(0, false);");
}
}
}
}
} |
@extends('layouts.backend.app')
@section('title')
<!-- start page title -->
<div class="row">
<div class="col-12">
<div class="page-title-box d-flex align-items-center justify-content-between">
<h4 class="page-title mb-0 font-size-18">{{__('Place Order')}}</h4>
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item"><a href="{{route('home')}}">{{__('Home')}}</a></li>
<li class="breadcrumb-item active">{{__('Place Order')}}</li>
</ol>
</div>
</div>
</div>
</div>
@stop
@section('content')
<!-- end page title -->
<form method="post" action="{{route('home.order.store')}}" enctype="multipart/form-data">
@csrf
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h2 class="card-title">{{__('General')}}</h2>
<div class="mt-4">
<div class="row">
<div class="col-xl-6">
<div class="mb-3">
<label for="job_title" class="form-label">{{__('Job Title')}}<span
class="text-danger">*</span></label>
<input
class="form-control @error('job_title') is-invalid @enderror"
name="job_title"
type="text"
placeholder="Job Title"
value="{{old('job_title')}}" required
/>
@error('job_title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="col-xl-6">
<div class="mb-3">
<label for="image_quantity" class="form-label">{{__('Image Quantity')}}<span
class="text-danger">*</span></label>
<input
class="form-control @error('image_quantity') is-invalid @enderror"
name="image_quantity"
type="number"
placeholder="Image Quantity"
value="{{old('image_quantity')}}" required
/>
@error('image_quantity')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="col-xl-12">
<label for="instruction" class="form-label">Instruction<span
class="text-danger">*</span></label>
<textarea class="mb-3" id="elm1" name="instruction"></textarea>
<div class="mt-2"><small>{{__('Please write instruction properly. Instruction will help designer to edit and retouch your image as per instuction')}}</small></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="card">
<div class="card-body">
<h2 class="card-title">Image Complexity</h2>
<div class="mt-4">
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="radio" name="image_complexity"
id="image_complexity" checked value="simple">
<label class="form-check-label" for="image_complexity">
{{__('Simple')}}
</label>
</div>
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="radio" name="image_complexity"
id="image_complexity" value="medium">
<label class="form-check-label" for="image_complexity">
{{__('Medium')}}
</label>
</div>
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="radio" name="image_complexity"
id="image_complexity" value="complex">
<label class="form-check-label" for="image_complexity">
{{__('Complex')}}
</label>
</div>
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="radio" name="image_complexity"
id="image_complexity" value="extreme">
<label class="form-check-label" for="image_complexity">
{{__('Extreme')}}
</label>
</div>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="card">
<div class="card-body">
<h2 class="card-title">Return File Extensions</h2>
<div class="mt-4">
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="checkbox" name="return_file_extension[]"
id="return_file_extension" checked value="jpg">
<label class="form-check-label" for="return_file_extension">
{{__('JPG')}}
</label>
</div>
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="checkbox" name="return_file_extension[]"
id="return_file_extension" value="png">
<label class="form-check-label" for="return_file_extension">
{{__('PNG')}}
</label>
</div>
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="checkbox" name="return_file_extension[]"
id="return_file_extension" value="pdf">
<label class="form-check-label" for="return_file_extension">
{{__('PDF')}}
</label>
</div>
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="checkbox" name="return_file_extension[]"
id="return_file_extension" value="psd">
<label class="form-check-label" for="return_file_extension">
{{__('PSD')}}
</label>
</div>
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="checkbox" name="return_file_extension[]"
id="return_file_extension" value="tif">
<label class="form-check-label" for="return_file_extension">
{{__('TIF')}}
</label>
</div>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="card">
<div class="card-body">
<h2 class="card-title">{{__('Required Services')}}</h2>
<div class="row">
@if(isset($pathServices) && !empty($pathServices))
@foreach($pathServices as $key=>$path)
<div class="col-4 py-3">
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="checkbox" name="service_id[]"
id="service_id" {{$key == 0?'checked':''}} value="{{$path->id}}">
<label class="form-check-label" for="service_id">
{{$path->service_name}}
<br/>
<small>{{__('Starting From $')}} {{$path->starting_price}}</small>
</label>
</div>
</div>
@endforeach
@endif
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="card">
<div class="card-body">
<h2 class="card-title">{{__('Turnaround')}}</h2>
<div class="row">
<div class="col-4">
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="radio" name="turnaround"
id="turnaround" value="48" checked>
<label class="form-check-label" for="turnaround">
{{__('48 Hours')}}
<br/>
<small>{{__('Regular Delivery. No extra charge')}}</small>
</label>
</div>
</div>
<div class="col-4">
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="radio" name="turnaround"
id="turnaround" value="72">
<label class="form-check-label" for="turnaround">
{{__('72 Hours')}}
<br/>
<small>{{__('Regular Delivery. No extra charge')}}</small>
</label>
</div>
</div>
<div class="col-4">
<div class="form-check mb-2 form-check-inline">
<input class="form-check-input" type="radio" name="turnaround"
id="turnaround" value="flexible">
<label class="form-check-label" for="turnaround">
{{__('Flexible')}}
<br/>
<small>{{__('Flexible Delivery. No extra charge')}}</small>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="card">
<div class="card-body">
<h2 class="card-title">Upload Type</h2>
<div class="row">
<div class="col-6">
<button type="button" class="w-full btn border bg-transparent p-5 image-link-btn">
{{__('Image Link')}}<br/>
<small>{{__('Links Like: Dropbox, Google Drive, One Drive etc.')}}</small>
</button>
<div class="image_link_wrap my-3 d-none">
<div class="image_link_inner">
<label for="job_title" class="form-label">{{__('Images Link')}}</label>
<div class="row link_wrap my-2">
<div class="col-10">
<input
class="form-control"
name="image_link[]"
type="url"
placeholder="Images Link"
value=""
/>
</div>
<div class="col-2">
<button type="button" class="btn btn-outline-danger image-link-delete-btn"><i class="fa fa-trash"></i></button>
</div>
</div>
</div>
<button type="button" class="btn btn-outline-info mt-3 add-more-btn"><i class="fa fa-plus"> {{__('Add Another Link')}}</i></button>
</div>
</div>
<div class="col-6">
<div class="input-group">
<input type="file" class="form-control" id="upload_file" name="upload_files[]" multiple>
<label class="input-group-text" for="upload_file">Upload</label>
</div>
<small>{{_('It will allow just for few small size sample images. If you have more images please provide image down link')}}</small>
</div>
<div class="col-12">
<button type="submit" class="btn btn-success waves-effect waves-light float-end mb-2">Place Order</button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- end row -->
@stop
@section('page-script')
<!--tinymce js-->
<script src="/assets/libs/tinymce/tinymce.min.js"></script>
<!-- init js -->
<script src="/assets/js/pages/form-editor.init.js"></script>
<script>
//on click image link button
$(document).on('click','.image-link-btn',function (){
// $('.image_link_inner').copy().append()
$('.image_link_wrap').removeClass('d-none').addClass('d-block')
})
//on click add another link input field
$(document).on('click','.add-more-btn',function (){
let inner = $('.link_wrap:last-child').clone();
$('.image_link_inner').append(inner)
})
//on click add another link input field
$(document).on('click','.image-link-delete-btn',function (){
$(this).closest('.row').remove()
})
</script>
@stop |
(ns tools.utils
(:require
[babashka.fs :as fs]
[clojure.edn :as edn]
[clojure.java.io :as io]
[clojure.string :as str]))
;;;; File io
(defn get-local-fname
"Get the full filename when in same dir as this file."
[fname]
(-> (fs/parent *file*)
(fs/path fname)
str))
(defn read-local-file
"Read an entire file file in the current directory"
[fname]
(let [path (get-local-fname fname)]
(slurp path)))
;; Duplicate of `read-local-file`
#_ (defn read-file
"Read an entire file in the current directory"
[fname]
(let [path (-> (fs/parent *file*)
(fs/path fname)
str)]
(slurp path)))
;; line-seq works on a reader object (not string)
;; str/split-lines works on a string (not reader)
(defn read-lines-io
"Read a file line-by-line"
[fname]
(with-open [reader (io/reader fname)]
(doall (line-seq reader))))
;; Not sure what the difference is here
(defn read-lines-io-local
"Same as `read-lines`, but uses io instead of slurp"
[fname]
(let [lfname (get-local-fname fname)]
(vec (line-seq (io/reader lfname)))))
;; Could also do this with `slurp`
(defn read-lines-local
"Read a file into a vec of lines.
Same result as `read-lines-io`"
[fname]
(let [lfname (get-local-fname fname)]
(str/split-lines (slurp lfname))))
;;;; Reading numbers
(defn extract-digits
"Extract the digits from a string (as strings)
(extract-digits '1a2b3cx')
=> ['1' '2' '3']
"
[x]
(vec (re-seq #"\d+" x)))
(defn extract-digits-as-nums
"Extract the digits from a string, and convert to vec of numbers.
(extract-digits-as-nums '1x2y3z')
=> [1 2 3]
"
[x]
(mapv parse-long (re-seq #"\d+" x)))
(defn extract-combine-numbers
"Extract all numbers from a string, concatenate them and read as a single number
(extract-combine-numbers '1a2b3cx')
=> 123
"
[s]
(->> s
(re-seq #"\d")
(apply str)
parse-long)) |
import React, { FC } from 'react';
import { useUser } from '../helpers/mock/mock-data';
import { DetailsItem } from './details-item';
export const PersonalInfoDetails: FC = (): JSX.Element => {
const { name, age, country } = useUser();
const personalInfo: Array<[string, string | number]> = [['Name', name], ['Age', age], ['Country', country]];
return (
<>
<h3>Your information</h3>
<ul>
{personalInfo.map(([listName, value]) => (
<DetailsItem key={`${listName}_${value}`} name={listName} value={value} />
))}
</ul>
</>
);
}; |
using System;
using System.Collections.Generic;
using System.Linq;
using Elders.Pandora;
using Multitenancy.Delivery.Serialization;
using PushNotifications.Aggregator.InMemory;
using PushNotifications.Contracts.PushNotifications.Delivery;
using PushNotifications.Contracts.Subscriptions;
using PushNotifications.Delivery.FireBase;
using PushNotifications.Delivery.Pushy;
namespace Multitenancy.Delivery
{
public class PandoraMultiTenantDeliveryProvisioner : IDeliveryProvisioner, ITopicSubscriptionProvisioner
{
readonly ISet<MultiTenantStoreItem> _store;
readonly ISet<MultiTenantStoreSubscriptionItem> _subscriptionStore;
readonly Pandora pandora;
public PandoraMultiTenantDeliveryProvisioner(Pandora pandora)
{
if (ReferenceEquals(null, pandora) == true) throw new ArgumentNullException(nameof(pandora));
_store = new HashSet<MultiTenantStoreItem>();
_subscriptionStore = new HashSet<MultiTenantStoreSubscriptionItem>();
this.pandora = pandora;
Initialize();
}
public IPushNotificationDelivery ResolveDelivery(SubscriptionType subscriptionType, NotificationForDelivery notification)
{
if (ReferenceEquals(null, subscriptionType) == true) throw new ArgumentNullException(nameof(subscriptionType));
if (ReferenceEquals(null, notification) == true) throw new ArgumentNullException(nameof(notification));
var tenant = notification.Id.Tenant;
var storeItem = _store.SingleOrDefault(x => x.Tenant == tenant && x.SubscriptionType == subscriptionType);
if (ReferenceEquals(null, storeItem) == true) throw new NotSupportedException($"There is no registered delivery for type '{subscriptionType}' and tenant '{tenant}'");
return storeItem.Delivery;
}
public ITopicSubscriptionManager ResolveTopicSubscriptionManager(SubscriptionType subscriptionType, string tenant)
{
if (ReferenceEquals(null, subscriptionType) == true) throw new ArgumentNullException(nameof(subscriptionType));
if (string.IsNullOrEmpty(tenant)) throw new ArgumentNullException(nameof(tenant));
MultiTenantStoreSubscriptionItem storeItem = _subscriptionStore.SingleOrDefault(x => x.Tenant == tenant && x.SubscriptionType == subscriptionType);
if (ReferenceEquals(null, storeItem) == true) throw new NotSupportedException($"There is no registered delivery for type '{subscriptionType}' and tenant '{tenant}'");
return storeItem.TopicSubscriptionManager;
}
public IEnumerable<IPushNotificationDelivery> GetDeliveryProviders(string tenant)
{
var registeredDeliveriesForTenant = new List<IPushNotificationDelivery>();
foreach (var multiTenantStoreItem in _store)
{
if (string.Equals(multiTenantStoreItem.Tenant, tenant, StringComparison.OrdinalIgnoreCase))
{
registeredDeliveriesForTenant.Add(multiTenantStoreItem.Delivery);
}
}
return registeredDeliveriesForTenant;
}
void Initialize()
{
var firebaseSettings = pandora.Get<List<FireBaseSettings>>("delivery_firebase_settings");
var firebaseUrl = pandora.Get("delivery_firebase_baseurl");
var firebaseSubscriptionsUrl = "https://iid.googleapis.com/"; //This is hardcoded because of reasons
var pushyUrl = pandora.Get("delivery_pushy_baseurl");
var pushySettings = pandora.Get<List<PushySettings>>("delivery_pushy_settings");
foreach (var fb in firebaseSettings)
{
RegisterFireBaseDelivery(firebaseUrl, fb);
RegisterFireBaseSubscriptionManager(firebaseSubscriptionsUrl, fb);
}
foreach (var pushy in pushySettings)
{
RegisterPushyDelivery(pushyUrl, pushy);
RegisterPushySubscriptionManager(pushyUrl, pushy);
}
}
private IPushNotificationDelivery GetFirebaseDelivery(string baseUrl, string serverKey)
{
var fireBaseRestClient = new RestSharp.RestClient(baseUrl);
var fireBaseDelivery = new FireBaseDelivery(fireBaseRestClient, NewtonsoftJsonSerializer.Default(), serverKey);
return fireBaseDelivery;
}
void RegisterFireBaseDelivery(string baseUrl, FireBaseSettings settings)
{
if (string.IsNullOrEmpty(baseUrl) == true) throw new ArgumentNullException(nameof(baseUrl));
if (settings.RecipientsCountBeforeFlush >= 1000) throw new ArgumentException($"FireBase limits the number of tokens to 1000. Use lower number for '{nameof(settings.RecipientsCountBeforeFlush)}'");
var fireBaseRestClient = new RestSharp.RestClient(baseUrl);
var fireBaseDelivery = new FireBaseDelivery(fireBaseRestClient, NewtonsoftJsonSerializer.Default(), settings.ServerKey);
var timeSpanBeforeFlush = TimeSpan.FromSeconds(settings.TimeSpanBeforeFlushInSeconds);
var recipientsCountBeforeFlush = settings.RecipientsCountBeforeFlush;
fireBaseDelivery.UseAggregator(new InMemoryPushNotificationAggregator(fireBaseDelivery.Send, timeSpanBeforeFlush, recipientsCountBeforeFlush));
_store.Add(new MultiTenantStoreItem(settings.Tenant, SubscriptionType.FireBase, fireBaseDelivery));
}
void RegisterFireBaseSubscriptionManager(string baseUrl, FireBaseSettings settings)
{
if (string.IsNullOrEmpty(baseUrl) == true) throw new ArgumentNullException(nameof(baseUrl));
var fireBaseRestClient = new RestSharp.RestClient(baseUrl);
var firebaseTopicSubscriptionManager = new FireBaseTopicSubscriptionManager(fireBaseRestClient, NewtonsoftJsonSerializer.Default(), settings.ServerKey);
_subscriptionStore.Add(new MultiTenantStoreSubscriptionItem(settings.Tenant, SubscriptionType.FireBase, firebaseTopicSubscriptionManager));
}
void RegisterPushySubscriptionManager(string baseUrl, PushySettings settings)
{
if (string.IsNullOrEmpty(baseUrl) == true) throw new ArgumentNullException(nameof(baseUrl));
var pushyRestClient = new RestSharp.RestClient(baseUrl);
var pushyTopicSubscriptionManager = new PushyTopicSubscriptionManager(pushyRestClient, NewtonsoftJsonSerializer.Default(), settings.ServerKey);
_subscriptionStore.Add(new MultiTenantStoreSubscriptionItem(settings.Tenant, SubscriptionType.Pushy, pushyTopicSubscriptionManager));
}
void RegisterPushyDelivery(string baseUrl, PushySettings settings)
{
if (string.IsNullOrEmpty(baseUrl) == true) throw new ArgumentNullException(nameof(baseUrl));
var timeSpanBeforeFlush = TimeSpan.FromSeconds(settings.TimeSpanBeforeFlushInSeconds);
var recipientsCountBeforeFlush = settings.RecipientsCountBeforeFlush;
var pushyRestClient = new RestSharp.RestClient(baseUrl);
var pushyDelivery = new PushyDelivery(pushyRestClient, NewtonsoftJsonSerializer.Default(), settings.ServerKey);
pushyDelivery.UseAggregator(new InMemoryPushNotificationAggregator(pushyDelivery.Send, timeSpanBeforeFlush, recipientsCountBeforeFlush));
_store.Add(new MultiTenantStoreItem(settings.Tenant, SubscriptionType.Pushy, pushyDelivery));
}
class PushySettings
{
public long TimeSpanBeforeFlushInSeconds { get; set; }
public int RecipientsCountBeforeFlush { get; set; }
public string ServerKey { get; set; }
public string Tenant { get; set; }
}
class FireBaseSettings
{
public long TimeSpanBeforeFlushInSeconds { get; set; }
public int RecipientsCountBeforeFlush { get; set; }
public string ServerKey { get; set; }
public string Tenant { get; set; }
}
}
} |
/*
* Copyright (C) Igor Sysoev
* Copyright (C) Nginx, Inc.
*/
#ifndef _NGX_LIST_H_INCLUDED_
#define _NGX_LIST_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
typedef struct ngx_list_part_s ngx_list_part_t;
/*
链表节点 节点大小 = size * nelts
节点元素用完后每次就会分配一个新的节点
*/
struct ngx_list_part_s {
void *elts; /*节点的内存起始位置*/
ngx_uint_t nelts;//已经使用的元素
ngx_list_part_t *next;//指向下一个链表节点
};
//链表结构ngx_list_t
typedef struct {
ngx_list_part_t *last; //指向最新的链表节点
ngx_list_part_t part; //第一个链表节点
size_t size; //这个链表默认的每个元素大小
ngx_uint_t nalloc;//每个节点part 可以支持多少个元素
ngx_pool_t *pool; //线程池
} ngx_list_t;
ngx_list_t *ngx_list_create(ngx_pool_t *pool, ngx_uint_t n, size_t size);
static ngx_inline ngx_int_t
ngx_list_init(ngx_list_t *list, ngx_pool_t *pool, ngx_uint_t n, size_t size)
{
//分配1个链表节点的内存块。内存块大小 n*size
list->part.elts = ngx_palloc(pool, n * size);
if (list->part.elts == NULL) {
return NGX_ERROR;
}
list->part.nelts = 0;//使用元素个数
list->part.next = NULL;//下一个节点
list->last = &list->part;//最后一个节点地址
list->size = size;//每个元素的大小
list->nalloc = n;//分配多少个
list->pool = pool;//线程池
return NGX_OK;
}
/*
*
* the iteration through the list:
*
* part = &list.part;
* data = part->elts;
*
* for (i = 0 ;; i++) {
*
* if (i >= part->nelts) {
* if (part->next == NULL) {
* break;
* }
*
* part = part->next;
* data = part->elts;
* i = 0;
* }
*
* ... data[i] ...
*
* }
*/
void *ngx_list_push(ngx_list_t *list);
#endif /* _NGX_LIST_H_INCLUDED_ */ |
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStudentActivitiesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('student_activities', function (Blueprint $table) {
$table->id();
$table->foreignId('admission_id')->constrained('studentadmissions')->onDelete('cascade');
$table->foreignId('class_id')->constrained('educlasses')->onDelete('cascade');
$table->string('activity_date');
$table->string('edurating');
$table->string('educomment')->nullable();
$table->string('biharating');
$table->string('bihacomment')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('student_activities');
}
} |
import { Link, useGlobal, getItemsSelector } from '@metafox/framework';
import React from 'react';
import { ItemText, ItemTitle, ItemView, LineIcon } from '@metafox/ui';
import { styled, Box, Button, MenuItem, Menu } from '@mui/material';
import LoadingSkeleton from './LoadingSkeleton';
import { slugify } from '@metafox/utils';
import { useSelector } from 'react-redux';
const name = 'ForumItemMainCard';
const SubInfoStyled = styled('div', { name, slot: 'subInfoStyled' })(
({ theme }) => ({
fontWeight: 'unset'
})
);
const ItemTextStyled = styled(ItemText, { name, slot: 'ItemTextStyled' })(
({ theme }) => ({
flexDirection: 'row',
justifyContent: 'space-between'
})
);
const TitleInfoStyled = styled('div', { name, slot: 'titleInfoStyled' })(
({ theme }) => ({
display: 'flex',
flexDirection: 'column',
alignSelf: 'center'
})
);
export default function ForumItemMainCard({
item,
identity,
itemProps,
user,
state,
handleAction,
wrapAs,
wrapProps
}) {
const { i18n } = useGlobal();
const to = `/forum/${item?.id}/${slugify(item?.title)}`;
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const open = Boolean(anchorEl);
const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
const { title, subs } = item;
const subsEntities = useSelector((state: GlobalState) =>
getItemsSelector(state, subs)
);
return (
<ItemView testid={item.resource_name} wrapAs={wrapAs} wrapProps={wrapProps}>
<ItemTextStyled>
<TitleInfoStyled>
<ItemTitle>
<Link to={to}>{title}</Link>
</ItemTitle>
{subs && subsEntities?.length ? (
<SubInfoStyled>
<Button
sx={{
color: 'text.secondary',
fontWeight: 'unset',
padding: 0,
background: 'transparent !important'
}}
onClick={handleClick}
id="menu-sub"
>
{i18n.formatMessage({ id: 'sub_forums' })}
<Box ml={1}>
<LineIcon
icon={open ? 'ico-caret-up' : 'ico-caret-down'}
sx={{ fontSize: 13 }}
/>
</Box>
</Button>
<Menu
id="menu-sub"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left'
}}
>
{subsEntities.map((sub, index) => (
<MenuItem onClick={handleClose} key={index}>
<Link to={`/forum/${sub?.id}/${slugify(sub?.title)}`}>
{sub?.title}
</Link>
</MenuItem>
))}
</Menu>
</SubInfoStyled>
) : null}
</TitleInfoStyled>
</ItemTextStyled>
</ItemView>
);
}
ForumItemMainCard.LoadingSkeleton = LoadingSkeleton;
ForumItemMainCard.displayName = 'ForumItem(MainCard)'; |
use std::collections::HashSet;
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::str::FromStr;
use anyhow::{Context, Result};
use utils::measure;
type Input = Vec<Card>;
#[derive(Debug)]
struct Card {
winning_numbers: HashSet<i32>,
numbers_you_have: HashSet<i32>,
}
fn both_parts(input: &Input) -> (i32, i32) {
let mut p1 = 0;
let mut copies = vec![1; input.len()];
for (idx, card) in input.iter().enumerate() {
let mut points = 0;
let mut matches = 0;
for n in &card.numbers_you_have {
if card.winning_numbers.contains(n) {
points = if points == 0 { 1 } else { points * 2 };
matches += 1;
}
}
p1 += points;
for nidx in ((idx + 1)..copies.len()).take(matches) {
copies[nidx] += copies[idx];
}
}
(p1, copies.into_iter().sum())
}
fn main() -> Result<()> {
measure(|| {
let input = input()?;
let (part1, part2) = both_parts(&input);
println!("Part1: {}", part1);
println!("Part2: {}", part2);
Ok(())
})
}
impl FromStr for Card {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut split = s.splitn(2, ':');
let mut numbers_part = split.nth(1).context("no reveal part")?.split('|');
let winning_numbers = numbers_part
.next()
.context("no winning numbers")?
.trim()
.split(' ')
.filter_map(|s| s.parse::<i32>().ok())
.collect();
let numbers_you_have = numbers_part
.next()
.context("no numbers you have")?
.trim()
.split(' ')
.filter_map(|s| s.parse::<i32>().ok())
.collect();
Ok(Card {
winning_numbers,
numbers_you_have,
})
}
}
fn read_input<R: Read>(reader: BufReader<R>) -> Result<Input> {
reader
.lines()
.map_while(Result::ok)
.map(|line| line.parse::<Card>().context("Unable to parse input line"))
.collect()
}
fn input() -> Result<Input> {
let path = env::args().nth(1).context("No input file given")?;
read_input(BufReader::new(File::open(path)?))
}
#[cfg(test)]
mod tests {
use super::*;
const INPUT: &str = "
Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53
Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19
Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1
Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83
Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36
Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11";
fn as_input(s: &str) -> Result<Input> {
read_input(BufReader::new(
s.split('\n')
.skip(1)
.map(|s| s.trim())
.collect::<Vec<_>>()
.join("\n")
.as_bytes(),
))
}
#[test]
fn test_part1() -> Result<()> {
assert_eq!(both_parts(&as_input(INPUT)?).0, 13);
Ok(())
}
#[test]
fn test_part2() -> Result<()> {
assert_eq!(both_parts(&as_input(INPUT)?).1, 30);
Ok(())
}
} |
// AdcDataPlotter.h
// David Adams
// July 2017
//
// Tool to make channel vs. tick displays of data from an ADC channel data map.
//
// Configuration:
// LogLevel - 0=silent, 1=init, 2=each event, >2=more
// DataType - Which data to plot: 0=prepared, 1=raw-pedestal, 2=signal, 3=not signal
// DataView - Which view to use: "" for top, xxx merges everything from xxx
// TickRange - Name of the tick range used in the display
// The name must be defined in the IndexRangeTool tickRanges
// If blank or not defined, the full range is used.
// TickRebin - If > 1, histo bins include this # ticks.
// ChannelRanges - Names of channel ranges to display.
// Ranges are obtained from the tool channelRanges.
// Special name "" or "data" plots all channels in data with label "All data".
// If the list is empty, data are plotted.
// ClockFactor - Clock to tick conversion factor (0.04 for protoDUNE).
// ClockOffset - Clock offset between trigger and nominal tick 0.
// FembTickOffsets - Tick offset for each FEMB. FEMB = (offline channel)/128
// Offset is zero for FEMBs beyond range.
// Values should be zero (empty array) for undistorted plots
// OnlineChannelMapTool - Name of tool mapping channel # to online channel #.
// MinSignal - Formula for min signal. If absent, -(max signal) is used.
// MaxSignal - Formula for max signal. Displayed signal range is (min signal, max signal)
// SkipBadChannels - If true, skip channels flagged as bad.
// EmptyColor - If >=0, empty bins are drawn in this color (See TAttColor).
// Otherwise empty bins are drawn with value zero.
// Bins may be empty if a channel is nor processed, if a tick out of range
// or a tick is not selected (outside ROI) for DataType 2.
// EmptyColor is not used when rebinning.
// ChannelLineModulus - Repeat spacing for horizontal lines
// ChannelLinePattern - Pattern for horizontal lines
// HistName - Histogram name (should be unique within Root file)
// HistTitle - Histogram title (appears above histogram)
// PlotTitle - Plot title (appears below histogram an only on plots)
// PlotSizeX, PlotSizeY: Size in pixels of the plot file.
// Root default (700x500?) is used if either is zero.
// PlotFileName - Name for output plot file.
// If blank, no file is written.
// Existing file with the same name is replaced.
// RootFileName - Name for the output root file.
// If blank, histograms are not written out.
// Existing file with the same is updated.
// For the title and file names, substitutions are made with adcStringBuilder, e.g.
// %RUN% --> run number
// %SUBRUN% --> subrun number
// %EVENT% --> event number
// %CHAN1% --> First channel number
// %CHAN2% --> Last channel number
// Drawings may include horizontal lines intended to show boundaries of APAs,
// FEMBs, wire planes, etc.
//
// Lines are draw at N*ChannelLineModulus + ChannelLinePattern[i] for any
// integer N and any value if i in range of the array which are within
// the drawn channel range.
// If ChannelLineModulus is zero, then lines are drawn for the channels in
// ChannelLinePattern.
//
// If FirstChannel < LastChannel, then only channels in that range are displayed
// and no histogram is produced if the passed data has no channels in the range.
//
// If ClockFactor > 0, then tick + ClockFactor*(channelClock - triggerClock + ClockOffset)
// is used in place of tick.
#ifndef AdcDataPlotter_H
#define AdcDataPlotter_H
#include "art/Utilities/ToolMacros.h"
#include "fhiclcpp/ParameterSet.h"
#include "dune/DuneInterface/Utility/ParFormula.h"
#include "dune/DuneInterface/Data/IndexRange.h"
#include "dune/DuneInterface/Tool/TpcDataTool.h"
#include <vector>
#include <memory>
class AdcChannelStringTool;
class IndexMapTool;
class IndexRangeTool;
namespace lariov {
class ChannelStatusProvider;
}
class RunDataTool;
class AdcDataPlotter : TpcDataTool {
public:
using Index = unsigned int;
using IndexVector = std::vector<Index>;
using IntVector = std::vector<int>;
using IndexRangeVector = std::vector<IndexRange>;
using Name = std::string;
using NameVector = std::vector<Name>;
AdcDataPlotter(fhicl::ParameterSet const& ps);
~AdcDataPlotter() override =default;
DataMap viewMap(const AdcChannelDataMap& acds) const override;
bool updateWithView() const override { return true; }
private:
// Configuration data.
int m_LogLevel;
int m_DataType;
Name m_DataView;
Name m_TickRange;
Index m_TickRebin;
NameVector m_ChannelRanges;
float m_ClockFactor;
float m_ClockOffset;
IntVector m_FembTickOffsets;
Name m_OnlineChannelMapTool;
ParFormula* m_MinSignal;
ParFormula* m_MaxSignal;
bool m_SkipBadChannels;
Index m_EmptyColor;
Index m_ChannelLineModulus;
IndexVector m_ChannelLinePattern;
int m_Palette;
Name m_HistName;
Name m_HistTitle;
Name m_PlotTitle;
Index m_PlotSizeX;
Index m_PlotSizeY;
Name m_PlotFileName;
Name m_RootFileName;
// Derived configuration data.
IndexRange m_tickRange;
bool m_needRunData;
// Channel ranges.
IndexRangeVector m_crs;
// Client tools and services.
const AdcChannelStringTool* m_adcStringBuilder;
const IndexMapTool* m_pOnlineChannelMapTool;
const lariov::ChannelStatusProvider* m_pChannelStatusProvider;
const RunDataTool* m_prdtool;
// Make replacements in a name.
Name nameReplace(Name name, const AdcChannelData& acd, const IndexRange& ran) const;
};
DEFINE_ART_CLASS_TOOL(AdcDataPlotter)
#endif |
import Container from 'react-bootstrap/Container';
import Navbar from 'react-bootstrap/Navbar';
import Sidebar from './Sidebar';
import { useAuthContext, useDarkMode } from '../hooks';
import { Link } from 'react-router-dom';
function Nav({ show, setShow }) {
const { user, logout } = useAuthContext();
const handleDarkMode = useDarkMode();
const scrollOption = {
iconClass: 'bi bi-arrow-right-square',
scroll: true,
backdrop: false,
show,
setShow,
};
function handleLogout(evt) {
evt.preventDefault();
logout();
}
return (
<Navbar className="bg-body-tertiary">
<Container>
{user && <Sidebar {...scrollOption} />}
<Navbar.Brand as={Link} to="/">
ReelSkill
</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse className="justify-content-end">
<Navbar.Text>
Signed in as: <Link to="/">{user ? user.username : 'Guest'}</Link>
</Navbar.Text>
<div className="d-flex align-items-center">
<div className="ms-3 me-3">
{user && (
<Link
to="/login"
className="btn btn-danger btn-sm"
onClick={handleLogout}
>
Log out
</Link>
)}
</div>
<div className="form-check form-switch">
<input
className="form-check-input"
type="checkbox"
role="switch"
id="switchDarkMode"
onChange={handleDarkMode}
/>
<label
className="form-check-label"
htmlFor="switchDarkMode"
></label>
</div>
</div>
</Navbar.Collapse>
</Container>
</Navbar>
);
}
export default Nav; |
package PiedraPapelYTijera;
import java.util.Random;
import java.util.Scanner;
public class PiedraPapelYTijera {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
Random random = new Random();
int jugador, computadora, resultadoJugador = 0, resultadoComputadora = 0;
System.out.println("Bienvenidos al Juego de Piedra, Papel y Tijera");
System.out.println(" ");
// Ciclo para 3 rondas
for (int ronda = 1; ronda <= 3; ronda++) {
System.out.println("\nRonda " + ronda);
System.out.println("Elije una opción:");
System.out.println(" ");
System.out.println("1. para Piedra");
System.out.println("2. para Papel");
System.out.println("3. para Tijera");
// Leer la elección del jugador
jugador = Integer.parseInt(entrada.nextLine());
System.out.println("");
// Mostrar la elección del jugador
if (jugador >= 1 && jugador <= 3) {
System.out.println("Elegiste " + jugador);
System.out.println("Jugador elige: " + getOpcion(jugador));
} else {
System.out.println("Opción no válida");
continue; // Volver al inicio del ciclo si la opción es inválida
}
// Generar la elección aleatoria de la computadora
computadora = random.nextInt(3) + 1;
System.out.println("Computadora elige: " + getOpcion(computadora));
// Determinar el resultado de la ronda y actualizar los puntos
int resultadoRonda = determinarResultado(jugador, computadora);
if (resultadoRonda == 1) {
resultadoJugador++;
} else if (resultadoRonda == -1) {
resultadoComputadora++;
}
// Mostrar el resultado de la ronda
if (resultadoRonda == 0) {
System.out.println("Empate en esta ronda.");
} else if (resultadoRonda == 1) {
System.out.println("Jugador gana esta ronda.");
} else if (resultadoRonda == -1) {
System.out.println("Computadora gana esta ronda.");
}
}
// Determinar al ganador general
System.out.println("\n--- Resultado Final ---");
System.out.println("Puntos del Jugador: " + resultadoJugador);
System.out.println("Puntos de la Computadora: " + resultadoComputadora);
if (resultadoJugador > resultadoComputadora) {
System.out.println("¡Jugador gana el juego!");
} else if (resultadoJugador < resultadoComputadora) {
System.out.println("¡Computadora gana el juego!");
} else {
System.out.println("El juego termina en empate.");
}
// Cerrar el escáner
entrada.close();
}
// Función para obtener la opción seleccionada como cadena
public static String getOpcion(int opcion) {
switch (opcion) {
case 1:
return "Piedra";
case 2:
return "Papel";
case 3:
return "Tijera";
default:
return "Opción no válida";
}
}
// Función para determinar el resultado de la ronda
public static int determinarResultado(int jugador, int computadora) {
if (jugador == computadora) {
return 0; // Empate
} else if ((jugador == 1 && computadora == 3) || (jugador == 2 && computadora == 1) || (jugador == 3 && computadora == 2)) {
return 1; // Jugador gana
} else {
return -1; // Computadora gana
}
}
} |
import React, { ButtonHTMLAttributes, DetailedHTMLProps, ReactNode } from 'react';
import styles from './button.module.css';
import cn from 'classnames';
interface ButtonProps extends DetailedHTMLProps<
ButtonHTMLAttributes<HTMLButtonElement>,
HTMLButtonElement
> {
children: ReactNode;
isLoading?: boolean;
}
export const Button: React.FC<ButtonProps> = ({ children, isLoading = false, className, ...props }) => {
return (
<button className={cn(styles.button, className)} {...props}>
{!isLoading && children}
{isLoading &&
<div className={styles.dotFlashing}/>
}
</button>
);
}; |
<div class="container">
<div class="row">
<div class="col-5 mx-auto">
<div class="card">
<div class="card-header text-center">
<h3 class="bg-primary text-white p-3">
{{getName()}}' TODO List
</h3>
</div>
<div class="card-body">
<div class="input-group input-group-sm mb-3">
<input type="text" class="form-control"
[(ngModel)] = "inputText"
(keyup.enter)="addItem();">
<button type="button"
[class] ="getButtonClasses()"
class="btn btn-sm"
(click)="addItem(); ">Add</button>
</div>
<div class="form-check mb-3">
<input class="form-check-input" [(ngModel)]="displayAll" type="checkbox" name="" id="dispalyAll">
<label for="dispalyAll" class="form-check-label">Hepsini Göster</label>
<div class="alert alert-success my-2 text-center" *ngIf="dispalyCount() > 0" role="alert">
{{ dispalyCount() }} görev tamamlandı.
</div>
<div class="alert alert-warning text-center" role="alert" *ngIf="getItems().length == 0 else itemsTable">
Listede Görev yok.
</div>
<ng-template #itemsTable>
<table class="table table-bordered text-center" *ngIf="getItems().length > 0">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Description</th>
<th scope="col">Action</th>
<th scope="col">completed</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let item of getItems(); let i = index;"
[class]="{'bg-secondary': item.action, 'bg-light': !item.action}">
<td>{{i+1}}</td>
<td>{{item.description}}</td>
<td *ngIf="item.action"><span class="badge rounded-pill bg-success">{{item.action}}</span></td>
<td *ngIf="!item.action"><span class="badge rounded-pill bg-danger">{{item.action}}</span></td>
<td >
<input type="checkbox" (change)="onActionChanged(item)" [(ngModel)]="item.action" name="" id="">
</td>
</tr>
</tbody>
</table>
</ng-template>
<button type="button"
class="btn btn-sm btn-danger"
(click)="clearList(); ">Clear</button>
</div>
</div>
<div class="card-footer text-muted text-center">
<a href="{{getSocialNetwork()}}" class="link-primary">instagram</a>
</div>
</div>
</div>
</div>
</div> |
import { pluralize } from 'lib/shared/utils/pluralize';
import { ExpandablePanel } from 'lib/ui/Panel/ExpandablePanel';
import { Spinner } from 'lib/ui/Spinner';
import { HStack, VStack } from 'lib/ui/Stack';
import { Text } from 'lib/ui/Text';
import { centerContentCSS } from 'lib/ui/utils/centerContentCSS';
import { roundedCSS } from 'lib/ui/utils/roundedCSS';
import styled from 'styled-components';
import { ReactNode, useMemo, useState } from 'react';
import { formatAmount } from 'lib/shared/utils/formatAmount';
import { SameWidthChildrenRow } from 'lib/ui/Layout/SameWidthChildrenRow';
import { Button } from 'lib/ui/buttons/Button';
const ContentFrame = styled.div`
display: grid;
grid-template-columns: 48px 1fr;
align-items: center;
gap: 24px;
width: 100%;
`;
const Identifier = styled.div`
aspect-ratio: 1/1;
${roundedCSS};
background: ${({ theme }) => theme.colors.mist.toCssValue()};
${centerContentCSS};
font-size: 20px;
color: ${({ theme }) => theme.colors.contrast.toCssValue()};
`;
interface TreasuryPanelProps<T> {
title: string;
icon: ReactNode;
itemName: string;
items: T[] | undefined;
isError?: boolean;
getTotalUsdValue: (items: T[]) => number;
depositAction?: ReactNode;
renderItems: (items: T[]) => ReactNode;
}
const Actions = styled(SameWidthChildrenRow)`
flex: 1;
justify-content: flex-end;
`;
export function TreasuryPanel<T>({
icon,
itemName,
items,
isError,
getTotalUsdValue,
depositAction,
renderItems,
title,
}: TreasuryPanelProps<T>) {
const isLoading = !items && !isError;
const [shouldShowAllItems, setShouldShowAllItems] = useState(false);
const itemsToDisplay = useMemo(() => {
if (!items) return [];
return shouldShowAllItems ? items : items.slice(0, 4);
}, [items, shouldShowAllItems]);
const renderFooterMsg = () => {
if (isError) {
return `Failed to load ${itemName}s`;
}
if (!items) {
return `Loading ${itemName}s`;
}
if (items.length === 0) {
return `No ${itemName}s`;
}
return `Displaying ${itemsToDisplay?.length} of ${pluralize(items.length, itemName)} total`;
};
return (
<ExpandablePanel
isExpandedInitially
header={
<ContentFrame>
<Identifier>{icon}</Identifier>
<HStack fullWidth alignItems="center" justifyContent="space-between">
<Text weight="semibold">{title}</Text>
{isLoading ? (
<Spinner />
) : items ? (
<Text weight="semibold">${formatAmount(getTotalUsdValue(items))}</Text>
) : (
<div />
)}
</HStack>
</ContentFrame>
}
renderContent={() => (
<ContentFrame>
<div />
<VStack gap={24}>
{itemsToDisplay && itemsToDisplay.length > 0 && renderItems(itemsToDisplay)}
<HStack wrap="wrap" alignItems="center" fullWidth justifyContent="space-between">
<Text color="supporting" size={16}>
{renderFooterMsg()}
</Text>
<Actions childrenWidth={186} gap={16}>
{items && items.length > 4 && (
<Button kind="secondary" onClick={() => setShouldShowAllItems(!shouldShowAllItems)}>
{itemsToDisplay.length < items.length ? 'Show more' : 'Show less'}
</Button>
)}
{depositAction}
</Actions>
</HStack>
</VStack>
</ContentFrame>
)}
/>
);
} |
from typing import List
import torch
import torch.nn as nn
from .ModelBase import ModelBase
# https://github.com/brysef/rfml/blob/master/rfml/nn/model/cnn.py
class LSTM2(ModelBase):
"""
References
S. Rajendran, W. Meert, D. Giustiniano, V. Lenders, and S. Pollin,
“Deep Learning Models for Wireless Signal Classification With Distributed Low-Cost Spectrum Sensors,”
IEEE Transactions on Cognitive Communications and Networking, vol. 4, no. 3, pp. 433-445, Sep. 2018,
doi: 10.1109/TCCN.2018.2835460.
"""
def __init__(
self,
input_samples: int,
input_channels: int,
classes: List[str],
learning_rate: float = 0.001,
**kwargs
):
super().__init__(classes=classes, **kwargs)
self.loss = nn.CrossEntropyLoss()
self.lr = learning_rate
self.example_input_array = torch.zeros((1,input_channels,input_samples), dtype=torch.cfloat)
# Batch x 1-channel x input_samples x IQ
#LSTM Unit
self.lstm = nn.LSTM(input_size=2*input_channels, hidden_size=128, num_layers=2, batch_first=True)
#DNN
self.lin = nn.Sequential(
nn.Flatten(),
# nn.LazyLinear(128),
# nn.ReLU(),
# nn.LazyLinear(128),
# nn.ReLU(),
nn.LazyLinear(len(classes))
)
def forward(self, x: torch.Tensor):
x1 = torch.view_as_real(x)
x1 = torch.transpose(x1, -2, -3)
x1 = torch.flatten(x1, -2, -1)
_, (h_t, _) = self.lstm(x1)
y = self.lin(h_t[-1])
return y
def configure_optimizers(self):
optimizer = torch.optim.Adam(self.parameters(), lr=self.lr, weight_decay=0.00001)
# optimizer = torch.optim.AdamW(self.parameters(), lr=self.lr)
schedulers = []
# schedulers.append({
# "scheduler": torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=[10], gamma=0.1),
# })
# schedulers.append({
# "scheduler": torch.optim.lr_scheduler.LinearLR(optimizer, start_factor=1.0/10, total_iters=1000),
# "interval": "step"
# })
# scheduler1 = {
# "scheduler": torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'max', patience=3, threshold=1e-3, min_lr=1e-6),
# "interval": "epoch",
# "frequency": 1,
# "monitor": "val/F1",
# "reduce_on_plateau": True,
# }
return [optimizer], schedulers |
# This the fourth R Code File for the Introduction to R Course available at
# https://github.com/brfitzpatrick/Intro_to_R
# Copyright (C) 2015 Ben R. Fitzpatrick.
#
# 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/>.
#
# The course author may be contacted by email at
# <[email protected]>
################################################################################
# #
# Code File to Accompany Course Module 4 #
# #
# Introduction to Programming in R #
# #
################################################################################
# Repetitions of a particular sequence of operations on successive selections of data possibly with a changes in the operations may be efficiently accomplished by utilising
# Control Flow
?Control
# and Logical statements
?Logic
# if(condition) action # read as: if condition is true then perform actions
# Sorts of Conditions that might be used in an if() statement:
x <- 3
#Equality
x == 3 # logical test of whether the statement x = 3 is true
x == 4 # logical test of the whether the statement x = 4 is true
!(x == 4) # think of this as the negation of the result of the test of whether x = 4 is true
x == 2 & 3 # logical test of whether x = both 2 and 3
x == 2 | 3 # | is an 'inclusive or' so the test here is whether x (2, 3 or 2 & 3) if x = any of these then the statement is true
# works with vectors by testing element by element equality
y <- c(1,2,3)
z <- seq(1:3)
z == y
y[1] | y[2] == z[1] | z[3] # logical test of whether the 1st element of y or the 2nd element of y equal the 1st element of z or the 3rd element of z
# works for character vectors too
a <- c('alpha')
b <- c('alpha','beta','gamma')
a == b
# Relative Size
x < 3
x <= 3
x > 1
# if(cond) expr
x
if(x==3) print('x = 3') # if x = 3 print 'x = 3'
if(x==3) print('x = 3') else print('x not equal to 3') # if x = 4 print 'x = 3', if x does not = 3 print 'x not equal to 4'
x <- 4
if(x==3) print('x = 3') else print('x not equal to 3')
# it's a bit hard to see the point of if() statements without a function
# so let's make a function that uses 'if else' statement to tell you whether a number is odd or even
# for the algorithm I have in mind we'll need the floor() command to round down (note: its opposite is ceiling() )
floor(35.5)
floor(1/3)
floor(4/3)
# and the paste command to create our output
paste(4,c('is even'))
x
paste(x)
paste(x,c('is even'))
if(x/2 == floor(x/2)) {paste(x,c('is even'))} else {paste(paste(x),c('is odd')) }
# try for a few x values
#e.g.
x <- 933
if(x/2 == floor(x/2)) {paste(x,c('is even'))} else {paste(x,c('is odd')) }
#
# the process of defining x then re-entering the test can be streamlined by defining a function
# defining a function is creating you own custom R command
even <- function(x){
if(x/2 == floor(x/2)) {paste(paste(x),c('is even'))} else {paste(paste(x),c('is odd')) }
}
even(x=121)
even(121) # assumes arguments are supplied in order
even(124)
# can you make a function to test if a number is odd?
even #recover the R code for a function by entering it without any brackets or arguments
#include R functions provided in R base
lm
# '!' negation symbol, read as 'not'
if(!x == 2) {paste(x,'is not 2')}
### for(variable in sequence) action
1:3 # quick way to define a sequece
for(i in 1:3) {print(paste(i))}
for(i in seq(3,27,3)) {print(paste(i))}
# we can store the results of for() loops in variables
x <- rep(0,6)
x
# refer to elements of a vector by number
x[2] # 2nd element of x
#define elements of a vector by number
x[2] <- 3
x
length(x) # length of vector x
# so we can use the sequence of a for() loop to perform actions on objects by element/row/column number e.g.
# storing the results of a for loop in a vector
for(i in 1:length(x)){
#we can let for() loops span several lines for readability much as we did for function definitions
x[i] <- i^2 # store i^2 in the i'th element of x
} # end of for loop
x
# we can excecute all sorts of commands across a for() loop
n <- 600
x <- seq(1:n)
y <- rnorm(n=n,mean=0,sd=1)
plot(x,y)
rainbow(5) # rainbow(n) 'Creates a vector of ‘n’ contiguous colors' in this case equally spaced across the rainbow see also heat.colors(),terrain.colors() ... etc.
?rainbow
for(i in 2:length(x)){
lines(x[(i-1):i],y[(i-1):i],col=rainbow(length(x))[i])
} # connects point (x[(i-1)],y[(i-1)]) to point (x[i],y[i]) by a line of colour given by element 'i' of rainbow(length(x)) (a list of colour codes with the same number of elements as there are in vector 'x' and the colours equally spaced across the full visual spectrum of the rainbow) and does this for all 'i' in order from 'i=2' to 'i=length(x)'
# it is necessary to start at 'i=2' since our first vector index 'x[(i-1)]' and we wish to start at the first element of 'x'
y.i.mean <- rep(0,length(y))
for(i in 1:length(y)){
y.i.mean[i] <- mean(y[1:i]) # calculate the mean of elements 1 to i of vector y and store this number in y.i.meam element i
}
plot(x,y.i.mean,type='l',xlab='sample size',ylab='mean')
abline(h=0)
plot(x[-seq(1:50)],y.i.mean[-seq(1:50)],type='l',xlab='sample size',ylab='mean') # plot vector x (after having droped the first 50 entries) against vector y.i.mean (again after having dropped the first 50 entries)
abline(h=0)
### while() loops
x <- 1
while(length(x)<10) x<-c(x,x[length(x)]+1) # while the length of vector x is less than 10 add another element onto the end of x of value eqaul to 1 + the last element of x
x
# so we could make our own sequence creation function:
my.seq <- function(from,to,by){
x <- from
length.max <- floor((to-from)/by)
while(length(x)<=length.max) x<-c(x,x[length(x)]+by)
return(x)
}
my.seq(1,10,1)
my.seq(3,27,3)
# but probably a more useful application is repeating some process until some level of precision is attained
# say increasing the sample size by 1 until the sample approximations to the population mean has remained within a particular precision around the population mean for 500 additions to the sample size
y <- rnorm(n=700,mean=0,sd=15) # start with a random sample of 700 observations from a normal distribution with a mean of 0 and a standard deviation of 15
#y
accr <- 5e-2 # this is the accuracy which we would like the estimate
# the first step is to have a function that for any particular vector v (of length > 500) will return the maximum absolute value of the means of elements 1 to the length of vector v, 1 to the 1 less than the length of vector v, 1 to the 2 less than the length of vector v,..., 1 to the 500 less than the length of vector v
# so that we may test if the maximum absolute value of these values is less the the accuracy (remember the the population mean is 0 here so sample mean - population mean = sample mean)
l500mm <- function(v){
l500m <- rep(0,500)
for(i in 1:500){
l500m[i] <- mean(v[1:(length(v)-i+1)])
}
mx.abs <- max(abs(l500m))
return(mx.abs)
}
#then we may use this function in a while() loop such that while the maximum of the means of 1 to each of the last 500 values of y is greater than the required accuracy (accr) additional samples of size one are drawn from the normal distribution and appended to the end of vector y
while(l500mm(y)>accr) y <- c(y,rnorm(n=1,mean=0,sd=15))
summary(y)
length(y)
cut <- 0.2*length(y) # the first 20% will probably be quite variable and we are interested in the covergence to 0 so I only plot the last 80% of the data
plot(0,0,ylim=c(-1.9*abs(mean(y[1:(cut+50)])),1.9*abs(mean(y[1:(cut+50)]))),xlim=c(cut,length(y)),type='n',xlab='sample size',ylab='sample mean') # setting up the plot box (just the x and y limits and the axis lables)
x <- 1:length(y) # the index to plot the sample means against
for(i in cut:length(y)){
lines(x[(i-1):i],c(mean(y[1:(i-1)]),mean(y[1:i])),col=rainbow(2*length(x))[i]) # joining the sample mean for y length (i-1) to the sample mean for y length i by lines (x coordinates are our count of sample size at y[i]) coloured in proportion to i
}
# and now the visual check that the sample mean has no strayed more than +/- accr from 0 for the last 500 additions to y
abline(h=accr,col='cyan')
abline(h=-accr,col='cyan')
abline(v=(length(y)-500),col='red')
mean(y)
################################
# #
# Programming Excercise 1 #
# #
# Create a solar system #
# emulation #
# #
################################
n.step <- 500 # number of animation frames to create
# Solution
start <- 0
end <- 2*pi
theta <- seq(from=start,to=end,length.out=n.step) #angle controlling rotation of Planet 1 by changing the angle gradually with a for() loop we can generate movement along a orbital path
Orbit1 <- data.frame(theta,x=rep(0,length(theta)),y=rep(0,length(theta))) # dataframe to store the x and y coordinates of the orbital path of Planet 1
#producing each new frame of video by ploting Planet 1 at the position in a row of this dataframe and advancing through these rows in order we can create the emulate the movement of planet 1 around the sun (note this is an emulation not a simulation there are no graviational law calculations in this code)
r <- 0.75 # radius of orbit of Planet 1
for(i in 1:nrow(Orbit1)){
Orbit1[i,2] <- r*cos(Orbit1[i,1]) # Planet 1 x-coordinate at angle theta[i] i.e. row i
Orbit1[i,3] <- r*sin(Orbit1[i,1]) # Planet 1 y-coordinate at angle theta[i] i.e. row i
}
# same proceedure as for Planet 1 just changing all the numbers a bit so Planet 2 follows a different path
Orbit2 <- data.frame(theta,x=rep(0,length(theta)),y=rep(0,length(theta)))
r <- 0.3 # radius
for(i in 1:nrow(Orbit2)){
Orbit2[i,2] <- r*cos(-(2*Orbit2[i,1]+pi/4))
Orbit2[i,3] <- r*sin(-(2*Orbit2[i,1]+pi/4))
}
# same proceedure as for Planet 1 just changing all the numbers a bit so Planet 2 follows a different path
Orbit3 <- data.frame(theta,x=rep(0,length(theta)),y=rep(0,length(theta)))
r <- 0.9 #radius
for(i in 1:nrow(Orbit3)){
Orbit3[i,2] <- r*cos((3.5*Orbit3[i,1]+pi/4))
Orbit3[i,3] <- r*sin((3.5*Orbit3[i,1]+pi/4))
}
# adding a moon orbiting around Planet 2
phi <- 6*(theta+pi/4)
O2.moon <- data.frame(phi,x=rep(0,length(theta)),y=rep(0,length(theta)))
r.O2m <- 0.15
for(i in 1:nrow(Orbit2)){
O2.moon[i,2] <- Orbit1[i,2] + r.O2m*cos(O2.moon[i,1]-pi/4)
O2.moon[i,3] <- Orbit1[i,3] + r.O2m*sin(O2.moon[i,1]-pi/4)
}
# adding a moon around Planet 3
eta <- 9*(theta+pi/4)
O3.moon <- data.frame(eta,x=rep(0,length(theta)),y=rep(0,length(theta)))
r.O3m <- 0.15
for(i in 1:nrow(O3.moon)){
O3.moon[i,2] <- Orbit3[i,2] + r.O3m*cos(O3.moon[i,1]+pi/4)
O3.moon[i,3] <- Orbit3[i,3] + r.O3m*sin(O3.moon[i,1]+pi/4)
}
# Warning for epileptics this plot flashes a lot as it progresses through the for() loop
setwd('/home/ben/animation') # change the file path to a file path on your computer where you would like the sequence frames (images) to be saved that we will stick together into an animation below
# to preview the animation in R use this code which has the image saving bits commented out
for(i in 1:nrow(Orbit1)){
jpeg(filename = paste('image',paste(i),'.jpg',sep=''),width = 800, height = 800)
plot(0,0,xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=5,col='yellow',pch=19,xlab='',ylab='')
par(new=T)
plot(Orbit1[i,2],Orbit1[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=3,col='blue',pch=19,xlab='',ylab='')
par(new=T)
plot(Orbit2[i,2],Orbit2[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=1,pch=19,col='red',xlab='',ylab='')
par(new=T)
plot(O2.moon[i,2],O2.moon[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=1,pch=19,col='grey',xlab='',ylab='')
par(new=T)
plot(O3.moon[i,2],O3.moon[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=0.5,pch=19,col='grey',xlab='',ylab='')
par(new=T)
plot(Orbit3[i,2],Orbit3[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=1.5,pch=19,col='green',xlab='',ylab='')
par(new=T)
plot(0,0,xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=5,col='yellow',pch=19,xlab='',ylab='') #par(new=T)
dev.off()
#dev.new()
}
# to write the image files that we will use to create the animation use this code:
for(i in 1:nrow(Orbit1)){
jpeg(filename = paste('image',paste(i),'.jpg',sep=''),width = 800, height = 800)
plot(0,0,xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=5,col='yellow',pch=19,xlab='',ylab='')
par(new=T)
plot(Orbit1[i,2],Orbit1[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=3,col='blue',pch=19,xlab='',ylab='')
par(new=T)
plot(Orbit2[i,2],Orbit2[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=1,pch=19,col='red',xlab='',ylab='')
par(new=T)
plot(O2.moon[i,2],O2.moon[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=1,pch=19,col='grey',xlab='',ylab='')
par(new=T)
plot(O3.moon[i,2],O3.moon[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=0.5,pch=19,col='grey',xlab='',ylab='')
par(new=T)
plot(Orbit3[i,2],Orbit3[i,3],xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=1.5,pch=19,col='green',xlab='',ylab='')
par(new=T)
plot(0,0,xlim=c(-1.5,1.5),ylim=c(-1.5,1.5),cex=5,col='yellow',pch=19,xlab='',ylab='') #par(new=T)
dev.off()
#dev.new()
}
graphics.off()
# the 3D version
rgl.open()
counter=1
for(i in 1:(0.5*nrow(Orbit1))){
#for(i in 1:250){
counter=counter+1
view3d(theta=0, phi=-30)
rgl.spheres(c(1.1),c(1.1),c(1.1),radius=0.05,xlab='',ylab='',interactive=F,alpha=0)
rgl.spheres(c(1.1),c(1.1),c(-1.1),radius=0.05,xlab='',ylab='',interactive=F,alpha=0)
rgl.spheres(c(1.1),c(-1.1),c(1.1),radius=0.05,xlab='',ylab='',interactive=F,alpha=0)
rgl.spheres(c(1.1),c(-1.1),c(-1.1),radius=0.05,xlab='',ylab='',interactive=F,alpha=0)
rgl.spheres(c(-1.1),c(1.1),c(-1.1),radius=0.05,xlab='',ylab='',interactive=F,alpha=0)
rgl.spheres(c(-1.1),c(1.1),c(1.1),radius=0.05,xlab='',ylab='',interactive=F,alpha=0)
rgl.spheres(c(-1.1),c(-1.1),c(-1.1),radius=0.05,xlab='',ylab='',interactive=F,alpha=0)
rgl.spheres(c(-1.1),c(-1.1),c(1.1),radius=0.05,xlab='',ylab='',interactive=F,alpha=0)
rgl.spheres(0,0,0,radius=0.25,col='yellow',xlab='',ylab='',interactive=F)
rgl.spheres(Orbit1[i,2],Orbit1[i,3],0,radius=0.05,col='blue',xlab='',ylab='',interactive=F)
rgl.spheres(Orbit2[i,2],Orbit2[i,3],0,radius=0.04,col='red',xlab='',ylab='',interactive=F)
rgl.spheres(O2.moon[i,2],O2.moon[i,3],0,radius=0.02,col='grey',xlab='',ylab='',interactive=F)
rgl.spheres(O3.moon[i,2],O3.moon[i,3],0,radius=0.02,col='grey',xlab='',ylab='',interactive=F)
rgl.spheres(Orbit3[i,2],Orbit3[i,3],0,radius=0.08,col='green',xlab='',ylab='',interactive=F)
rgl.snapshot(filename=paste('image',paste(counter),'.png',sep=''), fmt="png")
clear3d(type=c('shapes'))
}
#now the fun bit who can introduce a moon into this system
#how about a commet (commets have elliptical orbits)
# collision detection???? ;-)
#at the Linux Terminal
# ffmpeg -f image2 -r 1 -i image%d.jpg -r 1 -s 800x800 joo.avi
#ffmpeg -i joo.avi -f yuv4mpegpipe - | yuvfps -s 30:1 -r 30:1 | ffmpeg -f yuv4mpegpipe -i - -b 28800k aa30fps.avi
#########################################
# #
# Programming Excercise 2 #
# #
# Prime Numbers and Interger Divisors #
# #
##########################################
# The Excercise
# Can you make a function to test whether a number is prime then if it is not return it's interger divisors other than 1 and itself?
# Can you modify your function so that it can perform this sequence of actions for each element in a supplied vector of numbers to test?
# How long does your function take to run?
# Can you alter your code to make it run faster?
prime.test <- function(v){ # now just define prime.test2() once, deleted all the repeates of the same calculations
Out = data.frame(Number=v,Is.Prime=factor(rep(NA,length=length(v)),levels=c('Prime','Not.Prime')),N.Divs=numeric(length=length(v)))
n.divs = rep(0,(max(v)-2))
prime.test2 = function(x){
if(x<1) {return(paste('Not.Prime'))}
if(x==1 | x==2 | x==3) {return(list('Prime',0))}
pf = my.seq(from=2,to=(x-1),by=1) # potential factors
n.div.i = sum(as.numeric((x/pf-floor(x/pf))==0))
if(n.div.i==0) result = list('Prime',0) else result = list('Not.Prime',n.div.i)
return(result)
}
for(i in 1:length(v)){
op = prime.test2(x=v[i])
Out[i,2] = paste(op[1])
Out[i,3] = op[2]
}
max.divs = max(Out[,3]) # number of extra columns required (add them all here once outside any loop to avoid recreating the dataframe with each iteration of the loop
Out = data.frame(Out,matrix(0,nrow=nrow(Out),ncol=max.divs))
for(i in 1:length(v)){
x = v[i]
pf = my.seq(from=2,to=(x-1),by=1)
x.pf = as.numeric((x/pf-floor(x/pf))==0)
Divs = cbind(x.pf,pf) #making another matrix inside a loop further slowing things
counter = 0
for(j in 1:nrow(Divs)){ #nested loop, oh no!
if(Divs[j,1]==1) counter = counter + 1
if(Divs[j,1]==1) Out[i,3+counter] = Divs[j,2] # two separate if() statements using the same condition
}
}
Out=data.frame(Out)
return(Out)
}
system.time(sl <- ptv.slow(v=seq(1e4,1e4+1000,1)))[3]/1000 # 0.400605 sec per element in v
system.time(sl.sp3 <- ptv.sp3(v=seq(1e4,1e4+1000,1)))[3]/1000 # 0.405414 sec per element in v
system.time(sl2 <- ptv.slow(v=seq(1e5,1e5+100,1)))[3]/1000 # sec per element in v
system.time(sl2.sp3 <- ptv.sp3(v=seq(1e5,1e5+100,1)))[3]/1000 # sec per element in v
#################
############
################
# To Speed Up R Code:
# Replace loops with matrix operations
# Where loops are unavoidable:
# Define you data.storage object once outside the loop and fill it from within the loop (rather than adding new columns or rows with each iteration of the loop- R has to re-define the whole thing each time if you do this )
# try using lapply() instead of for()
# 'lapply() can be faster than a carefully crafted for() loop (since C-level code is more efficient in memory allocation)' - Brian D. Ripley, Professor of Applied Statistics, Oxford
# where job allows for parallel computing split it across multiple processor cores using package the `foreach' or 'parallel' pacakges
###############################
# #
# Extension Exercises: #
# #
###############################
# If you'd like more exercises to learn R programming by doing:
# Project Euler has a great series problems designed to be solved with mathematics and programming.
# 'The problems range in difficulty and for many the experience is inductive chain learning. That is, by solving one problem it will expose you to a new concept that allows you to undertake a previously inaccessible problem. So the determined participant will slowly but surely work his/her way through every problem.'
# <https://projecteuler.net/>
# R is a full programming language and so you should be able to solve any of the problems by programming in R
# Remember you've got Wikipedia and Wolfram MathWorld if you need to look up any maths concepts to do a problem
################################################################################
# #
# End of Code File 4 that Accompanies #
# #
# Course Module 4 #
# #
# Introduction to Programming in R #
# #
################################################################################ |
import React, {useEffect, useState} from 'react'
import {CSmartTable} from '../../custom/smart-table/CSmartTable'
import PropTypes from 'prop-types'
import {CBadge, CButton, CCol, CFormInput, CRow} from '@coreui/react'
import RangeDatePicker from '../../common/RangeDatePicker'
import moment from 'moment'
import {isPrice, maskString} from '../../../utils/utility'
import {getMallBadgeColor} from '../../../utils/badge/officalMall/Badge'
const ProductList = ({
items, // 리스트 아이템
onClick, // 리스트 클릭 이벤트 ex) Modal
columns, // 리스트의 헤더
className, // 리스트의 클레스 네임
datePickerHidden = true, // 기간선택 데이터 피커 출력 유무
setSelectedProduct, // radioButton 함수
onUpdateInvoice, // 송장번호 등록
}) => {
// Local state 선언
const [listItems, setListItems] = useState([])
const [filterItems, setFilterItems] = useState()
const [showModal, setShowModal] = useState(false)
const [startDate, setStartDate] = useState('')
const [endDate, setEndDate] = useState('')
const [selectedItem, setSelectedItem] = useState(false)
// 함수 선언
const modalOnClick = () => {
setShowModal(!showModal)
}
useEffect(() => {
setListItems(items)
}, [items])
useEffect(() => {
// data picker 에 선택된 값
if (endDate) {
if (listItems[0]?.orderDate) {
setFilterItems(
listItems.filter(
value =>
moment(value.orderDate, 'YYYYMMDDHHmmss').format('YYYY-MM-DD') >= startDate &&
moment(value.orderDate, 'YYYYMMDDHHmmss').format('YYYY-MM-DD') <= endDate,
),
)
} else {
// default 는 createdAt 그 외 하고 싶은 값은 위에 작성
setFilterItems(
listItems.filter(
value =>
moment(value.createdAt, 'YYYYMMDDHHmmss').format('YYYY-MM-DD') >= startDate &&
moment(value.createdAt, 'YYYYMMDDHHmmss').format('YYYY-MM-DD') <= endDate,
),
)
}
// 생성일로 필터
} else {
setFilterItems('')
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [endDate])
const onClickRadioButton = item => {
setSelectedItem(item)
setSelectedProduct(item)
}
const onClickStop = e => {
e.stopPropagation()
}
return (
<>
{datePickerHidden && (
<CRow className={'d-md-flex justify-content-md-end pt-2 pb-2'}>
<CButton className='me-md-2' color='success' size='sm'>
주문상태 변경
</CButton>
<CCol xs={4}>
<RangeDatePicker className='me-md-2' setStartDate={setStartDate} setEndDate={setEndDate} />
</CCol>
</CRow>
)}
<CSmartTable
items={filterItems || listItems}
columns={columns || null}
columnSorter
pagination
paginationProps={{
limit: 10,
}}
tableHeadProps={{
id: 'smTable',
}}
clickableRows
onRowClick={onClickRadioButton}
tableProps={{
hover: true,
responsive: true,
striped: true,
align: 'middle',
className: className,
}}
scopedColumns={{
radioButton: (item, index) => (
<td>
<input
id={`${index}`}
name='select-radio'
type='radio'
checked={item.orderItemId === selectedItem.orderItemId}
readOnly
/>
</td>
),
orderStatus: ({orderStatus}) => (
<td>
<CBadge size='sm' color={getMallBadgeColor(orderStatus)}>
{orderStatus}
</CBadge>
</td>
),
invoiceNumber: item => (
<td>
{/* <CFormInput id={`${index}`} className='me-md-2' size='sm' onClick={e => setSelectedProduct(e, item)} />
<CButton id={`${index}`} className='invoiceNumberBtn' color='warning' size='sm' onClick={onUpdateInvoice}>
등록
</CButton> */}
{item.invoiceNumber}
</td>
),
orderItemPrice: ({orderItemPrice}) => <td className='orderItemPrice'>{isPrice(orderItemPrice)}</td>,
totalPrice: ({totalPrice}) => <td className='totalPrice'>{isPrice(totalPrice)}</td>,
orderDate: ({orderDate}) => <td>{moment(orderDate, 'YYYYMMDDHHmmss').format('YYYY. MM. DD')}</td>,
payDate: ({payDate}) => <td>{moment(payDate, 'YYYYMMDDHHmmss').format('YYYY. MM. DD')}</td>,
}}
noItemsLabel={'데이터가 없습니다.'}
itemsPerPage={20}
/>
</>
)
}
ProductList.propTypes = {
items: PropTypes.array,
onClick: PropTypes.func,
columns: PropTypes.array,
className: PropTypes.string,
onDelete: PropTypes.func,
selectedOptions: PropTypes.object,
datePickerHidden: PropTypes.bool,
itemPerPageHidden: PropTypes.bool,
}
export default ProductList |
import {createBrowserRouter, RouterProvider} from 'react-router-dom';
import App from './App.jsx';
import Home from './pages/Home.jsx';
import ProductList from './pages/ProductList.jsx';
import Product from './pages/Product.jsx';
import ShoppingCart from './pages/ShoppingCart.jsx';
import Contact from './pages/Contact.jsx';
import ErrorPage from './pages/ErrorPage.jsx';
const Router = () => {
const router = createBrowserRouter([
{
path: '/',
element: <App />,
errorElement: <ErrorPage />,
children: [
{index: true, element: <Home />},
{
path: '/products',
element: <ProductList />,
},
{
path: '/products/:productId',
element: <Product />,
},
{
path: '/products/category/:category',
element: <ProductList />,
},
{
path: '/cart',
element: <ShoppingCart />
},
{
path: '/contact',
element: <Contact />
}
]
}
])
return <RouterProvider router={router} />
};
export default Router; |
# Declaring packages
using JuMP, HiGHS
# Preparing an optimization model
m = Model(HiGHS.Optimizer)
# Declaring variables
@variable(m, x[1:2])
@variable(m, z[1:3])
# Setting the objective
@objective(m, Max, 2x[1] + 3z[1])
# Adding constraints
@constraint(m, c1, z[1] <= x[2] - 10)
@constraint(m, c2, z[1] <= -x[2] + 10)
@constraint(m, c3, z[2] + z[3] <= 5)
@constraint(m, c4, z[2] <= x[1] + 2)
@constraint(m, c5, z[2] <= -x[1] - 2)
@constraint(m, c6, z[3] <= x[2])
@constraint(m, c7, z[3] <= -x[2])
# Printing the prepared optimization model
print(m)
# Solving the optimization problem
optimize!(m)
# Print the information about the optimum.
println("Objective value: ", objective_value(m))
println("Optimal solutions:")
println("x1 = ", value(x[1]))
println("x2 = ", value(x[2]))
println("z123 = ", value.(z)) |
// Path: quote/static/quote/main.js
/*
--> Ideas for JavaScript Enhancements
1. Dynamic Loading of Quotes: Instead of loading all quotes at once, use JavaScript to load them dynamically as the user scrolls down the page. This is often called "infinite scrolling" and can improve performance and user experience.
2. Form Validation: Use JavaScript to validate form inputs on the client side before they're submitted to the server. This can provide immediate feedback to the user and reduce server load.
3. Interactive Search: JavaScript can be used to implement a search feature that displays results as the user types, improving usability.
4. (DONE) Quote Rating or Liking System: If you plan to implement a system for users to rate or like quotes, JavaScript can be used to submit these ratings or likes without requiring a page reload.
5. User Profile Interactions: JavaScript can be used to enhance interactions on user profile pages. For example, you could use JavaScript to allow users to follow or unfollow other users without a page reload.
6. Animations and Transitions: JavaScript can be used to add animations and transitions to improve the visual appeal of your website.
7. (DONE) AJAX: AJAX stands for Asynchronous JavaScript and XML. It's a technique that allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it's possible to update parts of a web page, without reloading the whole page.
8. (DONE) Editing Quotes: You could use JavaScript to allow users to edit quotes without a page reload. This would involve using AJAX to submit the edited quote to the server and then updating the quote on the page with the new text.
*/
/*
--> Infinite Scrolling - Dynamic Loading of Quotes
1. Detect when the user has scrolled to the bottom of the page and load more quotes dynamically using jQuery and AJAX.
2. load_more_quotes() function in views.py takes a parameter indicating how many quotes have already been loaded. It returns a JSON response containing the next 20 quotes.
3. The JSON response is parsed in main.js and the quotes are added to the page.
*/
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
var start = $('#quotes').children().length;
$.get('/load_more_quotes/', {start: start}, function(data) {
var quotes = JSON.parse(data);
for (var i = 0; i < quotes.length; i++) {
var quote = quotes[i].fields;
// Append the new quote to the #quotes element
$('#quotes').append('<p>' + quote.quote + '</p>');
}
});
}
}); |
package fr.sqli.formation.gamelife.service;
import fr.sqli.formation.gamelife.entity.ProduitEntity;
import fr.sqli.formation.gamelife.ex.ProduitException;
import fr.sqli.formation.gamelife.repository.ProduitRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.swing.text.html.Option;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@SpringBootTest
public class ProduitServiceTest {
@Autowired
private ProduitService service;
@Test
void testGetAllProducts01() {
var games = this.service.getAllProduit();
Assertions.assertNotNull(games);
}
@Test
void testGetProductsByName01() throws Exception {
String game = "call";
var aGame = service.getProductsByName(game);
Assertions.assertNotNull(aGame);
Assertions.assertEquals(1, aGame.size());
for (ProduitEntity g : aGame) {
Assertions.assertTrue(g.getNom().contains(game));
}
}
@Test
void testGetProductsByName02() throws Exception {
String keyword = "Call";
var game = service.getProductsByName(keyword);
Assertions.assertNotNull(game);
Assertions.assertEquals(1, game.size());
for (ProduitEntity g : game) {
Assertions.assertTrue(g.getNom().toLowerCase().contains(keyword.toLowerCase()));
}
}
@Test
void testGetProductsByName03() {
String keyword = "";
Assertions.assertThrows(IllegalArgumentException.class, () -> service.getProductsByName(keyword));
}
@Test
void testGetProductsByName04() {
String keyword = "%ds";
var games = service.getProductsByName(keyword);
Assertions.assertNotNull(games);
Assertions.assertEquals(new ArrayList<>(), games);
}
@Test
void testGetProductsById01() {
String id = "1";
var game = this.service.getProductById(id);
Assertions.assertNotNull(game);
Assertions.assertEquals(1, game.getId());
}
@Test
void testGetProductsById02() {
String id = "";
Assertions.assertThrows(IllegalArgumentException.class, () -> this.service.getProductById(id));
}
@Test
void testGetProductsById03() {
String id = "1000000000";
var game = this.service.getProductById(id);
Assertions.assertTrue(game.getId() == 0);
}
} |
import { useLocation, useNavigate } from 'react-router-dom'
import { getAuth, signInWithPopup, GoogleAuthProvider } from 'firebase/auth'
import { doc, setDoc, getDoc, serverTimestamp } from 'firebase/firestore'
import { db } from '../firebase.config'
import { toast } from 'react-toastify'
import googleIcon from '../assets/svg/googleIcon.svg'
function OAuth() {
const navigate = useNavigate()
const location = useLocation()
const onGoogleClick = async () => {
try {
const auth = getAuth()
const provider = new GoogleAuthProvider()
const result = await signInWithPopup(auth, provider)
const user = result.user
// Vérification de l'utilisateur
const docRef = doc(db, 'users', user.uid)
const docSnap = await getDoc(docRef)
// Si l'utilisateur n'existe pas, on le crée
// La méthode doc prend 3 paramètres : La BDD, la collection et l'id de l'utilisateur
if (!docSnap.exists()) {
// La méthode setDoc prend elle, deux paramètres: le document actuel, et les données que l'on souhaite ajouter à la BDD
await setDoc(doc(db, 'users', user.uid), {
name: user.displayName,
email: user.email,
timestamp: serverTimestamp()
})
}
navigate('/')
} catch (error) {
toast.error('Connexion avec Google impossible')
}
}
return <div className='socialLogin'>
<p>S{location.pathname === '/sign-up' ? "'inscrire" : "e connecter"} avec </p>
<button className="socialIconDiv" onClick={onGoogleClick}>
<img className='socialIconImg' src={googleIcon} alt="Icône Google" />
</button>
</div>
}
export default OAuth |
import React, { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { Button, TextField, useTheme } from '@mui/material';
import Loading from './Loading';
import styles from '../styles/MainForm.module.css';
import { signIn } from 'next-auth/react';
import { Company } from '@prisma/client';
const CreateCompanyAcc = ({}) => {
const [error, setError] = useState<string>('');
const [formData, setFormData] = useState({
companyName: '',
nip: '',
companyEmail: '',
companyAddress: '',
phoneNumber: '',
secretPhrase: '',
});
const [loading, setLoading] = useState<boolean>(false);
const { palette } = useTheme();
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
setLoading(true);
await fetch('/api/company/createcompany', {
method: 'POST',
body: JSON.stringify(formData),
})
.then((data) => {
return data.json();
})
.then(async (company) => {
if (company?.meta) {
setError(`Error try different ${company.meta?.target}`);
return;
}
await fetch('/api/email/new-company', {
method: 'POST',
body: JSON.stringify({
to: company.companyEmail,
subject: 'Welcome ' + company.companyName,
id: company.id,
}),
});
await signIn('credentials', {
companyEmail: company.companyEmail,
id: company.id,
});
});
setLoading(false);
};
return (
<>
<h1 style={{ marginTop: 0 }}>Create Company Account</h1>
{loading ? (
<Loading />
) : (
<form
className={styles.form}
onSubmit={(event) => handleSubmit(event)}>
<div
className={styles.input}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<div
className={styles.label}
style={{ fontWeight: 'bold', textAlign: 'left' }}>
Company Name
</div>
<TextField
placeholder={'Name'}
fullWidth={true}
required={true}
type={'text'}
onChange={(event) =>
setFormData((pre) => {
return {
...pre,
companyName: event.target.value.trim(),
};
})
}
/>
</div>
<div
className={styles.input}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<div
className={styles.label}
style={{ fontWeight: 'bold', textAlign: 'left' }}>
NIP
</div>
<TextField
placeholder={'NIP'}
fullWidth={true}
required={true}
inputProps={{
minLength: 10,
maxLength: 10,
inputMode: 'numeric',
}}
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
type={'text'}
onChange={(event) =>
setFormData((pre) => {
return {
...pre,
nip: event.target.value,
};
})
}
/>
</div>
<div
className={styles.input}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<div
className={styles.label}
style={{ fontWeight: 'bold', textAlign: 'left' }}>
Company Email
</div>
<TextField
placeholder={'Email'}
fullWidth={true}
required={true}
type={'email'}
onChange={(event) =>
setFormData((pre) => {
return {
...pre,
companyEmail: event.target.value.trim(),
};
})
}
/>
</div>
<div
className={styles.input}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<div
className={styles.label}
style={{ fontWeight: 'bold', textAlign: 'left' }}>
Company Address
</div>
<TextField
placeholder={'Address'}
fullWidth={true}
required={true}
type={'text'}
onChange={(event) =>
setFormData((pre) => {
return {
...pre,
companyAddress:
event.target.value.trim(),
};
})
}
/>
</div>
<div
className={styles.input}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<div
className={styles.label}
style={{ fontWeight: 'bold', textAlign: 'left' }}>
Phone Number
</div>
<TextField
placeholder={'Phone Number'}
fullWidth={true}
required={true}
type={'text'}
onChange={(event) =>
setFormData((pre) => {
return {
...pre,
phoneNumber: event.target.value.trim(),
};
})
}
/>
</div>
<div
className={styles.input}
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
<div
className={styles.label}
style={{ fontWeight: 'bold', textAlign: 'left' }}>
Secret Phrase
</div>
<TextField
placeholder={'Secret Phrase'}
fullWidth={true}
required={true}
type={'password'}
onChange={(event) =>
setFormData((pre) => {
return {
...pre,
secretPhrase: event.target.value.trim(),
};
})
}
/>
</div>
<div
style={{
color: palette.warning.main,
fontWeight: '600',
}}>
{error}
</div>
<Button
style={{ order: 999999999, marginBottom: '10px' }}
type='submit'
variant='contained'>
Create Company Account
</Button>
</form>
)}
</>
);
};
export default CreateCompanyAcc; |
import { useState } from 'react';
import PropTypes from 'prop-types';
import { FaPlus } from 'react-icons/fa';
import { v4 as uuid } from 'uuid';
import ParticipantService from '../services/ParticipantService';
const Form = ({ add, loader }) => {
const [note, setNote] = useState('');
const handleSubmit = async event => {
try {
event.preventDefault();
loader(true);
if (note === '') {
window.alert('Please fill the form');
return;
}
const newNote = {
id: uuid(),
note,
};
await ParticipantService.add(newNote);
add(newNote);
} catch (error) {
window.alert(`Error Occurred: ${error.message}`);
} finally {
setNote('');
loader(false);
}
};
const handleNoteChange = event => {
setNote(event.target.value);
};
return (
<>
<form onSubmit={handleSubmit}>
<div className="input-group mb-4">
<input
type="text"
className="form-control"
placeholder="Write some notes..."
value={note}
onChange={handleNoteChange}
/>
<button className="btn btn-success" type="submit">
<FaPlus />
</button>
</div>
</form>
</>
);
};
export default Form;
Form.propTypes = {
add: PropTypes.func,
loader: PropTypes.func,
}; |
local options = {
backup = false, -- creates a backup file
cmdheight = 1, -- more space in the neovim command line for displaying messages
fileencoding = "utf-8", -- the encoding written to a file
hlsearch = false, -- highlight all matches on previous search pattern
incsearch = true,
ignorecase = true, -- ignore case in search patterns
mouse = "a", -- allow the mouse to be used in neovim
showtabline = 2, -- always show tabs
smartcase = true, -- smart case
smartindent = true, -- make indenting smarter again
splitbelow = true, -- force all horizontal splits to go below current window
splitright = true, -- force all vertical splits to go to the right of current window
swapfile = false, -- creates a swapfile
termguicolors = true, -- set term gui colors (most terminals support this)
timeout = true, -- enable timeout
timeoutlen = 1000, -- time to wait for a mapped sequence to complete (in milliseconds)
undodir = os.getenv("HOME") .. "/.vim/undodir", --allows for masive undos
undofile = true, -- enable persistent undo
updatetime = 100, -- faster completion (4000ms default)
writebackup = false, -- if a file is being edited by another program (or was written to file while editing with another program), it is not allowed to be edited
expandtab = true, -- convert tabs to spaces
shiftwidth = 2, -- the number of spaces inserted for each indentation
tabstop = 2, -- insert 2 spaces for a tab
cursorline = true, -- highlight the current line
number = true, -- set numbered lines
relativenumber = true, -- set relative numbered lines
numberwidth = 2, -- set number column width to 2 {default 4}
signcolumn = "yes", -- always show the sign column, otherwise it would shift the text each time
wrap = false, -- display lines as one long line
scrolloff = 8, -- minimal number of screen lines to keep above and below the cursor
sidescrolloff = 8, -- minimal number of screen columns either side of cursor if wrap is `false`
guifont = "Consolas", -- the font used in graphical neovim applications
whichwrap = "bs<>[]hl", -- which "horizontal" keys are allowed to travel to prev/next line
showmode = false,
fillchars = [[eob: ,fold: ,foldopen:,foldsep: ,foldclose:]],
foldcolumn = '1',
foldlevel = 99,
foldlevelstart = 99,
foldenable = true
}
for k, v in pairs(options) do
vim.opt[k] = v
end
vim.opt.list = true
vim.opt.listchars:append "eol:↴"
vim.opt.listchars:append "space:⋅"
vim.opt.iskeyword:append "-" -- hyphenated words recognized by searches
vim.opt.shortmess:append "c"
vim.g.loaded_netrw = 1
vim.g.loaded_netrwPlugin = 1
--vim.o.winbar = "%{%v:lua.require'nvim-navic'.get_location()%}"
--highlight on yank
local augroup = vim.api.nvim_create_augroup
local autocmd = vim.api.nvim_create_autocmd
local yank_group = augroup('HighlightYank', {})
autocmd('TextYankPost', {
group = yank_group,
pattern = '*',
callback = function()
vim.highlight.on_yank({
higroup = 'IncSearch',
timeout = 40,
})
end,
}) |
/**
* @jest-environment jsdom
*/
import { render, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import { Gravatar } from '../';
describe( 'Gravatar', () => {
/**
* Gravatar URLs use email hashes
* Here we're hashing [email protected]
* @see https://en.gravatar.com/site/implement/hash/
*/
const gravatarHash = 'f9879d71855b5ff21e4963273a886bfc';
const avatarUrl = `https://0.gravatar.com/avatar/${ gravatarHash }?s=96&d=mm`;
const genericUser = {
avatar_URL: avatarUrl,
display_name: 'Bob The Tester',
};
describe( 'rendering', () => {
test( 'should render an image given a user with valid avatar_URL, with default width and height 32', () => {
const { container } = render( <Gravatar user={ genericUser } /> );
const img = container.getElementsByTagName( 'img' )[ 0 ];
expect( img ).toBeDefined();
expect( img.getAttribute( 'src' ) ).toEqual( avatarUrl );
expect( img ).toHaveClass( 'gravatar' );
expect( img.getAttribute( 'width' ) ).toEqual( '32' );
expect( img.getAttribute( 'height' ) ).toEqual( '32' );
expect( img.getAttribute( 'alt' ) ).toEqual( 'Bob The Tester' );
} );
test( 'should update the width and height when given a size attribute', () => {
const { container } = render( <Gravatar user={ genericUser } size={ 100 } /> );
const img = container.getElementsByTagName( 'img' )[ 0 ];
expect( img ).toBeDefined();
expect( img.getAttribute( 'src' ) ).toEqual( avatarUrl );
expect( img ).toHaveClass( 'gravatar' );
expect( img.getAttribute( 'width' ) ).toEqual( '100' );
expect( img.getAttribute( 'height' ) ).toEqual( '100' );
expect( img.getAttribute( 'alt' ) ).toEqual( 'Bob The Tester' );
} );
test( 'should update source image when given imgSize attribute', () => {
const { container } = render( <Gravatar user={ genericUser } imgSize={ 200 } /> );
const img = container.getElementsByTagName( 'img' )[ 0 ];
expect( img ).toBeDefined();
expect( img.getAttribute( 'src' ) ).toEqual(
`https://0.gravatar.com/avatar/${ gravatarHash }?s=200&d=mm`
);
expect( img ).toHaveClass( 'gravatar' );
expect( img.getAttribute( 'width' ) ).toEqual( '32' );
expect( img.getAttribute( 'height' ) ).toEqual( '32' );
expect( img.getAttribute( 'alt' ) ).toEqual( 'Bob The Tester' );
} );
test( 'should serve a default image if no avatar_URL available', () => {
const noImageUser = { display_name: 'Bob The Tester' };
const { container } = render( <Gravatar user={ noImageUser } /> );
const img = container.getElementsByTagName( 'img' )[ 0 ];
expect( img ).toBeDefined();
expect( img.getAttribute( 'src' ) ).toEqual( 'https://www.gravatar.com/avatar/0?s=96&d=mm' );
expect( img ).toHaveClass( 'gravatar' );
expect( img.getAttribute( 'width' ) ).toEqual( '32' );
expect( img.getAttribute( 'height' ) ).toEqual( '32' );
expect( img.getAttribute( 'alt' ) ).toEqual( 'Bob The Tester' );
} );
test( 'should also pick up the default alt from the name prop', () => {
const userFromSiteApi = {
avatar_URL: avatarUrl,
name: 'Bob The Tester',
};
const { container } = render( <Gravatar user={ userFromSiteApi } /> );
const img = container.getElementsByTagName( 'img' )[ 0 ];
expect( img ).toBeDefined();
expect( img.getAttribute( 'src' ) ).toEqual( avatarUrl );
expect( img ).toHaveClass( 'gravatar' );
expect( img.getAttribute( 'width' ) ).toEqual( '32' );
expect( img.getAttribute( 'height' ) ).toEqual( '32' );
expect( img.getAttribute( 'alt' ) ).toEqual( 'Bob The Tester' );
} );
test( 'should prefer display_name for the alt', () => {
const userFromSiteApi = {
avatar_URL: avatarUrl,
name: 'Bob The Tester',
display_name: 'Bob',
};
const { container } = render( <Gravatar user={ userFromSiteApi } /> );
const img = container.getElementsByTagName( 'img' )[ 0 ];
expect( img ).toBeDefined();
expect( img.getAttribute( 'src' ) ).toEqual( avatarUrl );
expect( img ).toHaveClass( 'gravatar' );
expect( img.getAttribute( 'width' ) ).toEqual( '32' );
expect( img.getAttribute( 'height' ) ).toEqual( '32' );
expect( img.getAttribute( 'alt' ) ).toEqual( 'Bob' );
} );
test( 'should allow overriding the alt attribute', () => {
const { container } = render( <Gravatar user={ genericUser } alt="Another Alt" /> );
const img = container.getElementsByTagName( 'img' )[ 0 ];
expect( img ).toBeDefined();
expect( img.getAttribute( 'src' ) ).toEqual( avatarUrl );
expect( img ).toHaveClass( 'gravatar' );
expect( img.getAttribute( 'width' ) ).toEqual( '32' );
expect( img.getAttribute( 'height' ) ).toEqual( '32' );
expect( img.getAttribute( 'alt' ) ).toEqual( 'Another Alt' );
} );
// I believe jetpack sites could have custom avatars, so can't assume it's always a gravatar
test( 'should promote non-secure avatar urls to secure', () => {
const nonSecureUrlUser = { avatar_URL: 'http://www.example.com/avatar' };
const { container } = render( <Gravatar user={ nonSecureUrlUser } /> );
const img = container.getElementsByTagName( 'img' )[ 0 ];
expect( img ).toBeDefined();
expect( img.getAttribute( 'src' ) ).toEqual(
'https://i0.wp.com/www.example.com/avatar?resize=96%2C96'
);
expect( img ).toHaveClass( 'gravatar' );
expect( img.getAttribute( 'width' ) ).toEqual( '32' );
expect( img.getAttribute( 'height' ) ).toEqual( '32' );
} );
describe( 'when Gravatar fails to load', () => {
test( 'should render a span element', () => {
const { container } = render( <Gravatar user={ genericUser } /> );
// simulate the Gravatar not loading
const img = container.getElementsByTagName( 'img' )[ 0 ];
fireEvent.error( img );
const span = container.getElementsByTagName( 'span' )[ 0 ];
expect( img ).toBeDefined();
expect( span ).toBeDefined();
expect( span ).toHaveClass( 'is-missing' );
} );
test( 'should show temp image if it exists', () => {
const { container } = render( <Gravatar tempImage="tempImage" user={ genericUser } /> );
// simulate the Gravatar not loading
const img = container.getElementsByTagName( 'img' )[ 0 ];
fireEvent.error( img );
const span = container.getElementsByTagName( 'span' )[ 0 ];
expect( img ).toBeDefined();
expect( span ).toBeUndefined();
expect( img.getAttribute( 'src' ) ).toEqual( 'tempImage' );
expect( img ).toHaveClass( 'gravatar' );
} );
} );
} );
} ); |
# Dynamic Proxy
## Dynamic Proxy?
> Application이 실행되는 도중에(Runtime시) 특정 Interface들을 구현하는 클래스 또는 인스턴스를 만드는 기술
## Reflection Instance
> `Proxy`의 `newProxyInstance(ClassLoader, Class<?>[](구현해야 하는 인터페이스 타입), InvocationHandler)`를 필요로 하며 `InvocationHandler`에서 `Object`타입을 반환한다.
> 하지만 두번째 인자인 인터페이스 타입을 클래스로 제공하기 때문에 형변환이 가능하다.
> Proxy를 통해 동적으로 작업을 추가하고 싶은 일을 InvocationHandler에서 추가한다.
```java
BookService bookService = (BookService) Proxy.newProxyInstance(
BookService.class.getClassLoader(), //불러올
new Class[] {BookService.class},
new InvocationHandler() {
BookService bookService = new DefaultBookService();
@Override //해당 Proxy의 어떤 Method가 호출이 될 때 해당 Method를 어떻게 처리할 지
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().equals("rend")) {
System.out.println("aaaa");
Object invoke = method.invoke(bookService, args);
System.out.println("bbbb");
return invoke;
}
return method.invoke(bookService, args);
}
});
```
## 제약사항
> 자바의 **Dynamic Proxy Class**의 두번째 인자가 **Class**타입을 읽지를 못한다. **무조건 인터페이스 타입**이어야 한다.
>
> > 클래스로 밖에 존재하지 않으면 사용을 못한다. |
import { BiLogoCss3, BiLogoNodejs, BiLogoJavascript, BiLogoTypescript, BiLogoReact, BiLogoHtml5 } from 'react-icons/bi'
import { FaBootstrap } from 'react-icons/fa'
import { AiOutlineAntDesign } from 'react-icons/ai'
import { SiJest, SiExpo } from 'react-icons/si'
import { TbBrandReactNative } from 'react-icons/tb'
import { SiMongodb } from 'react-icons/si'
import { ProjectProps } from '@/typedefs/Projects_Types'
import { v4 as uuid } from 'uuid'
export const projectsdata: ProjectProps[] = [
{
name: 'BookNexus',
info: 'Web de libros con React/TS/Ant-Design (prueba tecnica de @midudev)',
cover: 'https://i.ibb.co/T1CX7Ln/Book-Nexus.webp',
thumbnail: 'https://i.ibb.co/J245vDK/Book-Nexus-tn.webp',
link: 'https://booknexus.netlify.app',
tecs: ['HTML5', 'CSS3', 'React', 'TypeScript', 'Ant-Design', 'Jest'],
repo: 'https://github.com/npminit-dev/npminit-dev.git'
},
{
name: 'ByteBlog',
info: 'Sencilla aplicación fullstack de administración de blogs',
cover: 'https://i.ibb.co/b1320qy/ByteBlog.webp',
thumbnail: 'https://i.ibb.co/wcBVs19/Byte-Blog-tn.webp',
link: 'https://byteblog.adaptable.app',
tecs: ['HTML5', 'CSS3', 'React', 'Typescript', 'NodeJS', 'MongoDB'],
repo: 'https://github.com/npminit-dev/ByteBlog.git'
},
{
name: 'Nasa APOD',
info: 'App de las fotos astronómicas de los ultimos 6 dias, usando la API NASA-APOD',
cover: 'https://i.ibb.co/2vgyjxY/Nasa-App.webp',
thumbnail: 'https://i.ibb.co/S6yYbWs/Nasa-App-tn.webp',
tecs: ['TypeScript', 'React Native', 'Jest'],
repo: 'https://github.com/npminit-dev/NASA-App.git'
},
{
name: 'DailyFuel',
info: 'App para controlar el consumo diario de calorías',
cover: 'https://i.ibb.co/8cXYDbL/Daily-Fuel.webp',
thumbnail: 'https://i.ibb.co/cvkzHCr/Daily-Fuel-tn.webp',
tecs: ['React Native', 'Expo Go'],
repo: 'https://github.com/npminit-dev/DailyFuel.git'
},
{
name: 'Landing Page',
info: 'Landing page con Bootstrap5',
cover: 'https://i.ibb.co/80kqmpC/Landing-Page-BS5.webp',
thumbnail: 'https://i.ibb.co/Z2r64Zw/Landing-Page-BS5-tn.webp',
link: 'https://capable-kringle-1fe2b3.netlify.app/',
tecs: ['HTML5', 'CSS3', 'JavaScript', 'Bootstrap5'],
repo: 'https://github.com/npminit-dev/BSLandingPage.git'
},
{
name: 'Football teams CRUD',
info: 'CRUD de equipos de fútbol con React y Bootstrap5',
cover: 'https://i.ibb.co/GJzRpjC/CRUDBS5.webp',
thumbnail: 'https://i.ibb.co/Jk753ZR/CRUDBS5-tn.webp',
link: 'https://melodious-licorice-c983f3.netlify.app/',
tecs: ['HTML5', 'CSS3', 'JavaScript', 'React', 'Bootstrap5'],
repo: 'https://github.com/npminit-dev/BS5-React-CRUD.git'
},
{
name: 'IndexedDB CRUD',
info: 'CRUD con VainillaJS y IndexedDB',
cover: 'https://i.ibb.co/ZGvBy74/Indexed-DBCRUD.webp',
thumbnail: 'https://i.ibb.co/S5XQpnZ/Indexed-DBCRUD-tn.webp',
link: 'https://fluffy-snickerdoodle-8f13a1.netlify.app/',
tecs: ['HTML5', 'CSS3', 'JavaScript'],
repo: 'https://github.com/npminit-dev/Vainilla-CRUD.git'
},
{
name: 'RealTime Chat',
info: 'Chat en tiempo real entre 2 pestañas con Vainilla y Service Workers',
cover: 'https://i.ibb.co/fGn6skd/Real-Time-Chat.webp',
thumbnail: 'https://i.ibb.co/rs0W6y1/Real-Time-Chat-tn.webp',
link: 'https://kaleidoscopic-muffin-fe5fc9.netlify.app/',
tecs: ['HTML5', 'CSS3', 'JavaScript'],
repo: 'https://github.com/npminit-dev/RealTimeChat.git'
}
]
export const tecs = [
{
name: 'HTML5',
icon: <BiLogoHtml5 color='#f64a1d' title='HTML5' className='h-6 w-6 mx-1' key={uuid()}/>
},
{
name: 'CSS3',
icon: <BiLogoCss3 color='#254bdc' title='CSS3' className='h-6 w-6 mx-1' key={uuid()} />
},
{
name: 'NodeJS',
icon: <BiLogoNodejs color='#87cf30' title='NodeJS' className='h-6 w-6 mx-1' key={uuid()} />
},
{
name: 'JavaScript',
icon: <BiLogoJavascript color='#e6a42d' title='JavaScript' className='h-6 w-6 mx-1' key={uuid()} />
},
{
name: 'TypeScript',
icon: <BiLogoTypescript color='#377cc8' title='TypeScript' className='h-6 w-6 mx-1' key={uuid()} />
},
{
name: 'React',
icon: <BiLogoReact color='#1ba1cc' title='React' className='h-6 w-6 mx-1 animate-[spin_4500ms_linear_infinite]' key={uuid()} />,
},
{
name: 'Bootstrap5',
icon: <FaBootstrap color='#7b18f7' title='Boostrap5' className='h-6 w-6 mx-1' key={uuid()} />
},
{
name: 'Ant-Design',
icon: <AiOutlineAntDesign color='#f6293b' title='Ant-Design' className='h-6 w-6 mx-1' key={uuid()} />
},
{
name: 'Jest',
icon: <SiJest color='#8f1844' title='Jest' className='h-6 w-6 mx-1' key={uuid()} />
},
{
name: 'Expo Go',
icon: <SiExpo color='#333' title='Expo' className='h-6 w-6 mx-1' key={uuid()} />
},
{
name: 'React Native',
icon: <TbBrandReactNative color='#1977f2' title='React-Native' className='h-6 w-6 mx-1 animate-[spin_4500ms_linear_infinite]' key={uuid()} />
},
{
name: 'MongoDB',
icon: <SiMongodb color='#116149' title='MongoDB' className='h-6 w-6 mx-1' key={uuid()} />
}
]
export const projectswithicons: ProjectProps[] = projectsdata.map(project => {
let projectWithIcon = { ...project }
projectWithIcon.tecs = projectWithIcon.tecs.map(tecname => tecs.find(tec => tec.name === tecname)?.icon)
return projectWithIcon
}) |
main <- function(Fichier_entree){
#import des fonctions de calc consult
source("R/I2M2_v1.0.6_calc_consultYM.r")
print(paste("fichier entree :",Fichier_entree))
#version/indic
indic <- "I2M2"
vIndic <- "v1.0.6"
## CHARGEMENT DES PACKAGES ----
dependencies <- c("dplyr", "sfsmisc", "tidyr")
loadDependencies <- function(dependencies) {
suppressAll <- function(expr) {
suppressPackageStartupMessages(suppressWarnings(expr))
}
lapply(dependencies,
function(x)
{
suppressAll(library(x, character.only = TRUE))
}
)
invisible()
}
loadDependencies(dependencies)
## IMPORT DES FICHIERS DE CONFIGURATION ----
Transcodage <- read.csv2("data/I2M2_params_transcodage.csv",
header = TRUE, stringsAsFactors = FALSE,
colClasses = c(CODE_TAXON = "character",
CODE_METHODE = "character"))
Base <- read.csv2("data/I2M2_params_base.csv",
colClasses = c(cd_taxon = "character"))
Typo <- read.csv2("data/I2M2_params_typo_I2M2.csv",
stringsAsFactors = FALSE)
Best <- read.csv2("data/I2M2_params_best.csv")
Worst <- read.csv2("data/I2M2_params_worst.csv")
De <- read.csv2("data/I2M2_params_de.csv",
stringsAsFactors = FALSE)
## INITIALISATION DU TRAITEMENT ----
# Ne pas afficher les messages d'avis ni d'erreur
options(warn = -1)
# Fichier_entree <- choose.files(caption = "Choisir le fichier", multi = FALSE,
# filters = cbind("Fichier texte (*.txt)", "*.txt"))
complementaire <- TRUE
# Initialisation de l'heure
heure_debut <- Sys.time()
## IMPORT DES FICHIERS ----
# Import du fichier d'entree
data_entree <- read.table(Fichier_entree, header = TRUE, sep = "\t",
stringsAsFactors = FALSE, quote = "\"",
colClasses = c(CODE_OPERATION = "character",
CODE_STATION = "character",
CODE_TAXON = "character")) %>%
filter(RESULTAT > 0)
## INITIALISATION DU FICHIER DE SORTIE ----
paramsOut <- data.frame(CODE_PAR = c(8058, 8057, 8056, 8055, 8054, 7613, 8050),
LIB_PAR = c("IndiceShannonI2M2",
"AverageScorePerTaxonI2M2",
"PolyvoltinismeI2M2",
"OvovivipariteI2M2",
"RichesseI2M2",
"Ind Invert Multimetrique",
"NbTaxonsI2M2Contributifs"),
stringsAsFactors = FALSE)
data_sortie <- funSortie(data_entree = data_entree,
paramsOut = paramsOut,
CODE_OPERATION, CODE_STATION, DATE) %>%
mutate(CODE_OPERATION = as.character(CODE_OPERATION),
CODE_STATION = as.character(CODE_STATION),
DATE = as.character(DATE))
## TAXONS CONTRIBUTIFS ----
TaxaContributifs <- funContributif(Table = data_entree,
Transcodage = Transcodage)
## CALCUL DE L'INDICE ----
metriques <- data_entree %>%
funHarmonisation(Table = ., Transcodage = Transcodage) %>%
funEffBocaux(Table = .) %>%
funMetriques(Table = ., Base = Base)
EQR <- metriques %>%
funTypo(Table = ., Typo = Typo) %>%
funEQR(Table = ., Worst = Worst, Best = Best)
I2M2 <- funI2M2(Table = EQR, De = De)
## RESULTATS COMPLEMENTAIRES ----
if (complementaire) {
data_complementaire <- mutate(metriques,
SHANNON = funArrondi(SHANNON, 4),
ASPT = funArrondi(ASPT, 4),
POLYVOLTIN = funArrondi(POLYVOLTIN, 4),
OVOVIVIPARE = funArrondi(OVOVIVIPARE, 4))
} else {
data_complementaire <- NULL
}
## SORTIE DES RESULTATS ----
resultats <- bind_rows(
funFormat(EQR),
funFormat(I2M2),
funFormat(TaxaContributifs)
)
data_sortie <- left_join(x = data_sortie,
y = resultats,
by = c("CODE_OPERATION", "CODE_PAR"))
Commentaires <- funCommentaires(Table = data_sortie,
TaxaContributifs = TaxaContributifs)
data_sortie <- left_join(x = data_sortie,
y = Commentaires,
by = c("CODE_OPERATION", "CODE_PAR")) %>%
mutate(RESULTAT = ifelse(CODE_PAR == 8050,
RESULTAT,
funArrondi(RESULTAT, 4)),
COMMENTAIRE = ifelse(is.na(COMMENTAIRE), "", COMMENTAIRE))
#le fichier de sortie a pour debut de nom le fichier d'netree, on enleve le .txt
#pour ne pas avoir de .txt au milieu
# de plus la liste des fichiers d'entree regarde tous les fichiers qui ont
#.txt dans leur nom
Ficentreemod <- str_remove(Fichier_entree,".txt")
#fichierResultat <- paste0("data/",indic, "_", vIndic, "_resultats.csv")
fichierResultat <- paste0(Ficentreemod, "-",vIndic, "_resultats.csv")
#fichierResultatComplementaire <- paste0("data",indic, "_", vIndic,"_resultats_complementaires.csv")
fichierResultatComplementaire <- paste0(Ficentreemod, "_", vIndic,"_resultats_complementaires.csv")
funResult(indic = indic,
vIndic = vIndic,
heure_debut = heure_debut,
data_sortie = data_sortie,
data_complementaire = data_complementaire,
complementaire = complementaire,
file = fichierResultat,
file_complementaire = fichierResultatComplementaire)
return(data_sortie)
print(paste("fin du traitement, résultats dans ",fichierResultat))
print("**********************************************************")
}
sortie <- main("data/I2M2_entree_op100.txt")
Liste_fichiers <- list.files("data/",pattern="*.txt",full.names=T)
test <- map_df(.x=Liste_fichiers,
.f=main)
#test2 <- test %>% reduce(rbind)
Extracti2m2<-filter(test,CODE_PAR=='7613') %>% distinct() #distinct pour enlever les doublons
colnames(Extracti2m2)[2] <- "cdstation"
stations <- "https://geobretagne.fr/geoserver/dreal_b/stations_qualite_eau_surf/wfs?SERVICE=WFS&REQUEST=GetCapabilities"
leaflet::leaflet() %>% setView(lng = -3, lat = 48, zoom = 8) %>%
leaflet::addWMSTiles(stations, layers = "stations_qualite_eau_surf")
st <- leaflet::leaflet() %>% setView(lng = -3, lat = 48, zoom = 8) %>%
addWMSTiles(stations, layers = "stations_qualite_eau_surf")
stations <- sf::st_read("couches/stations_qualite_eau_surf.shp",options = "ENCODING=WINDOWS-1252") %>% filter(y>687000)# il y a une station en
#afrique, on la vire
library(sf)
#mapview::mapview(stations)
indicesgeom <-left_join(Extracti2m2,stations,by="cdstation") %>% st_as_sf()
mapview::mapview(indicesgeom) |
package ru.ncideas.magazinof.gwt.client.registry;
import ru.ncideas.magazinof.gwt.client.event.BaseEvent;
import ru.ncideas.magazinof.gwt.client.event.EventType;
import ru.ncideas.magazinof.gwt.client.event.Listener;
import java.util.List;
public interface Observable {
/**
* Adds a listener bound by the given event type.
*
* @param eventType the eventType
* @param listener the listener to be added
*/
public void addListener(EventType eventType,
Listener<? extends BaseEvent> listener);
/**
* Fires an event.
*
* @param eventType eventType the event type
* @param be the base event
* @return <code>true</code> if any listeners cancel the event.
*/
public boolean fireEvent(EventType eventType, BaseEvent be);
/**
* Returns a list of listeners registered for the given event type. The
* returned list may be modified.
*
* @param eventType the event type
* @return the list of listeners
*/
public List<Listener<? extends BaseEvent>> getListeners(
EventType eventType);
/**
* Returns true if the observable has any listeners.
*
* @return true for any listeners
*/
public boolean hasListeners();
/**
* Returns true if the observable has listeners for the given event type.
*
* @param eventType the event type
* @return true for 1 or more listeners with the given event type
*/
public boolean hasListeners(EventType eventType);
/**
* Removes all listeners.
*/
public void removeAllListeners();
/**
* Removes a listener.
*
* @param eventType the event type
* @param listener the listener to be removed
*/
public void removeListener(EventType eventType,
Listener<? extends BaseEvent> listener);
} |
use compact_str::CompactString;
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use uuid::Uuid;
#[derive(Deserialize)]
pub struct PersonPostDTO {
#[serde(rename = "nome")]
pub name: CompactString,
#[serde(rename = "apelido")]
pub handle: CompactString,
#[serde(rename = "nascimento")]
pub birth: CompactString,
#[serde(rename = "stack")]
pub stacks: Option<SmallVec<[CompactString; 10]>>,
}
pub struct PersonEntity {
pub id: Uuid,
pub handle: CompactString,
pub payload: String,
pub search: String,
}
#[derive(Serialize)]
pub struct PersonPayload<'a> {
pub id: &'a Uuid,
#[serde(rename = "nome")]
pub name: &'a CompactString,
#[serde(rename = "apelido")]
pub handle: &'a CompactString,
#[serde(rename = "nascimento")]
pub birth: &'a CompactString,
#[serde(rename = "stack")]
pub stacks: &'a Option<SmallVec<[CompactString; 10]>>,
}
impl TryFrom<PersonPostDTO> for PersonEntity {
type Error = ();
fn try_from(value: PersonPostDTO) -> Result<Self, ()> {
if value.handle.len() > 32 {
return Err(());
}
if value.name.len() > 100 {
return Err(());
}
if value.birth.len() != 10 {
return Err(());
}
for (split, length) in value.birth.split('-').zip([4usize, 2, 2]) {
if split.len() != length {
return Err(());
}
if split.parse::<u32>().ok().is_none() {
return Err(());
}
}
if let Some(stacks) = &value.stacks {
if stacks.into_iter().any(|s| s.len() > 32) {
return Err(());
}
}
let id = Uuid::now_v7();
let payload = PersonPayload {
id: &id,
name: &value.name,
handle: &value.handle,
birth: &value.birth,
stacks: &value.stacks,
};
let mut search_buf = String::with_capacity(400);
search_buf.push_str(&value.handle);
search_buf.push(' ');
search_buf.push_str(&value.name);
search_buf.push(' ');
if let Some(stacks) = &value.stacks {
stacks.iter().for_each(|s| {
search_buf.push_str(s);
search_buf.push(' ');
})
}
Ok(Self {
id,
search: search_buf,
payload: serde_json::to_string(&payload).unwrap(),
handle: value.handle,
})
}
} |
import * as dotenv from "dotenv";
dotenv.config();
import mongoose from "mongoose";
function connectWithRetry() {
const dbUser = process.env.DB_USER;
const dbPassword = process.env.DB_PASS;
return new Promise((resolve, reject) => {
mongoose
.connect(
`mongodb+srv://${dbUser}:${dbPassword}@monkey.jfekfsv.mongodb.net/?retryWrites=true&w=majority&appName=monkey`
)
.then(() => {
console.log("Connected to MongoDB!");
resolve();
})
.catch((error) => {
console.error("Failed to connect to MongoDB:", error);
setTimeout(() => {
console.log("Retrying connection with the Database...");
connectWithRetry().then(resolve).catch(reject);
}, 3000); // Retry after 3 seconds
});
});
}
export { connectWithRetry }; |
import { Category } from '@shared/domain/entities/category'
import Link from 'next/link'
import styles from './CategoryCard.module.css'
export type CategoryCardProps = {
category: Category
href: string
}
export function CategoryCard({ category, href }: CategoryCardProps) {
const customStyles = {
'--image-url': `url(${category.image})`,
} as React.CSSProperties
return (
<Link href={href} legacyBehavior>
<a style={customStyles} className={styles.card}>
<h2>{category.name}</h2>
<p>{category.description}</p>
</a>
</Link>
)
} |
<template>
<policy-form
:model="model"
:insurance-companies="insuranceCompanies">
<div
slot="buttons"
class="form-footer text-right">
<el-button @click="cancel">
{{ __('Отменить') }}
</el-button>
<el-button
type="primary"
@click="update">
{{ __('Сохранить') }}
</el-button>
</div>
</policy-form>
</template>
<script>
import PolicyForm from './Form.vue';
import PolicyMixin from './mixin/policy';
export default {
mixins: [
PolicyMixin,
],
components: {
PolicyForm,
},
props: {
item: Object,
},
data() {
return {
model: this.item.clone(),
};
},
methods: {
update() {
this.$clearErrors();
this.model.validate().then((errors) => {
if (_.isEmpty(errors)) {
this.$info(__('Полис был успешно обновлен'));
this.$emit('saved', this.model);
return;
}
return this.$displayErrors({errors});
});
},
},
}
</script> |
= watsonx.ai Chat
With https://dataplatform.cloud.ibm.com/docs/content/wsj/getting-started/overview-wx.html?context=wx&audience=wdp[watsonx.ai] you can run various Large Language Models (LLMs) locally and generate text from them.
Spring AI supports the watsonx.ai text generation with `WatsonxAiChatModel`.
== Prerequisites
You first need to have a SaaS instance of watsonx.ai (as well as an IBM Cloud account).
Refer to https://eu-de.dataplatform.cloud.ibm.com/registration/stepone?context=wx&preselect_region=true[free-trial] to try watsonx.ai for free
TIP: More info can be found https://www.ibm.com/products/watsonx-ai/info/trial[here]
== Auto-configuration
Spring AI provides Spring Boot auto-configuration for the watsonx.ai Chat Client.
To enable it add the following dependency to your project's Maven `pom.xml` file:
[source,xml]
----
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-watsonx-ai-spring-boot-starter</artifactId>
</dependency>
----
or to your Gradle `build.gradle` build file.
[source,groovy]
----
dependencies {
implementation 'org.springframework.ai:spring-ai-watsonx-ai-spring-boot-starter'
}
----
=== Chat Properties
==== Connection Properties
The prefix `spring.ai.watsonx.ai` is used as the property prefix that lets you connect to watsonx.ai.
[cols="4,3,3"]
|====
| Property | Description | Default
| spring.ai.watsonx.ai.base-url | The URL to connect to | https://us-south.ml.cloud.ibm.com
| spring.ai.watsonx.ai.stream-endpoint | The streaming endpoint | generation/stream?version=2023-05-29
| spring.ai.watsonx.ai.text-endpoint | The text endpoint | generation/text?version=2023-05-29
| spring.ai.watsonx.ai.project-id | The project ID | -
| spring.ai.watsonx.ai.iam-token | The IBM Cloud account IAM token | -
|====
==== Configuration Properties
The prefix `spring.ai.watsonx.ai.chat` is the property prefix that lets you configure the chat model implementation for Watsonx.AI.
[cols="3,5,1"]
|====
| Property | Description | Default
| spring.ai.watsonx.ai.chat.enabled | Enable Watsonx.AI chat model. | true
| spring.ai.watsonx.ai.chat.options.temperature | The temperature of the model. Increasing the temperature will make the model answer more creatively. | 0.7
| spring.ai.watsonx.ai.chat.options.top-p | Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.2) will generate more focused and conservative text. | 1.0
| spring.ai.watsonx.ai.chat.options.top-k | Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative. | 50
| spring.ai.watsonx.ai.chat.options.decoding-method | Decoding is the process that a model uses to choose the tokens in the generated output. | greedy
| spring.ai.watsonx.ai.chat.options.max-new-tokens | Sets the limit of tokens that the LLM follow. | 20
| spring.ai.watsonx.ai.chat.options.min-new-tokens | Sets how many tokens must the LLM generate. | 0
| spring.ai.watsonx.ai.chat.options.stop-sequences | Sets when the LLM should stop. (e.g., ["\n\n\n"]) then when the LLM generates three consecutive line breaks it will terminate. Stop sequences are ignored until after the number of tokens that are specified in the Min tokens parameter are generated. | -
| spring.ai.watsonx.ai.chat.options.repetition-penalty | Sets how strongly to penalize repetitions. A higher value (e.g., 1.8) will penalize repetitions more strongly, while a lower value (e.g., 1.1) will be more lenient. | 1.0
| spring.ai.watsonx.ai.chat.options.random-seed | Produce repeatable results, set the same random seed value every time. | randomly generated
| spring.ai.watsonx.ai.chat.options.model | Model is the identifier of the LLM Model to be used. | google/flan-ul2
|====
== Runtime Options [[chat-options]]
The https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-watsonx-ai/src/main/java/org/springframework/ai/watsonx/WatsonxAiChatOptions.java[WatsonxAiChatOptions.java] provides model configurations, such as the model to use, the temperature, the frequency penalty, etc.
On start-up, the default options can be configured with the `WatsonxAiChatModel(api, options)` constructor or the `spring.ai.watsonxai.chat.options.*` properties.
At run-time you can override the default options by adding new, request specific, options to the `Prompt` call.
For example to override the default model and temperature for a specific request:
[source,java]
----
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates.",
WatsonxAiChatOptions.builder()
.withTemperature(0.4)
.build()
));
----
TIP: In addition to the model specific https://github.com/spring-projects/spring-ai/blob/main/models/spring-ai-watsonx-ai/src/main/java/org/springframework/ai/watsonx/WatsonxAiChatOptions.java[WatsonxAiChatOptions.java] you can use a portable https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/chat/prompt/ChatOptions.java[ChatOptions] instance, created with the https://github.com/spring-projects/spring-ai/blob/main/spring-ai-core/src/main/java/org/springframework/ai/chat/prompt/ChatOptionsBuilder.java[ChatOptionsBuilder#builder()].
NOTE: For more information go to https://dataplatform.cloud.ibm.com/docs/content/wsj/analyze-data/fm-model-parameters.html?context=wx[watsonx-parameters-info]
== Usage example
[source,java]
----
public class MyClass {
private final static String MODEL = "google/flan-ul2";
private final WatsonxAiChatModel chatModel;
@Autowired
MyClass(WatsonxAiChatModel chatModel) {
this.chatModel = chatModel;
}
public String generate(String userInput) {
WatsonxAiOptions options = WatsonxAiOptions.create()
.withModel(MODEL)
.withDecodingMethod("sample")
.withRandomSeed(1);
Prompt prompt = new Prompt(new SystemMessage(userInput), options);
var results = chatModel.call(prompt);
var generatedText = results.getResult().getOutput().getContent();
return generatedText;
}
public String generateStream(String userInput) {
WatsonxAiOptions options = WatsonxAiOptions.create()
.withModel(MODEL)
.withDecodingMethod("greedy")
.withRandomSeed(2);
Prompt prompt = new Prompt(new SystemMessage(userInput), options);
var results = chatModel.stream(prompt).collectList().block(); // wait till the stream is resolved (completed)
var generatedText = results.stream()
.map(generation -> generation.getResult().getOutput().getContent())
.collect(Collectors.joining());
return generatedText;
}
}
---- |
# Team Profile Generator
Project Repo: [Github-repo](https://github.com/timothymichaelcook/10_team_profile_generator)
## Description
The focus of this project was to create an application in that runs in the terminal, gathers user data about employees based on their job title. Every employee will be asked to input their name, id and email. Specific employees will be asked questions based on their job title. For examples, engineers will be asked to provide their GitHub username while interns will be asked what school they attended. The output file will display the user input in one CSS container and multiple CSS cards.
## User Story
```
- AS A manager
- I WANT to generate a webpage that displays my team's basic info
- SO THAT I have quick access to their emails and GitHub profiles
```
## Installation
- Inquirer package (for user prompts)
- Jest package (for running tests)
- npm i
- npm run test
- node index.js
## Usage
Users needs to be in the root folder of the project and 'npm i' or 'npm install' to install necessary dependencies. Once installed, users will need to run 'node index.js' to start the application in the terminal window. Once the user inputs the required fields, a prompt will ask if you would like to add another employee. If no, a file named team.html will be created in the dist directory. Open the html file in a browser to view the output file.
## Credits
University of Richmond Coding Bootcamp
## License
MIT License
## Screenshots/Videos


## Contact
Timothy Cook - [email protected] |
## What is Spring Boot
Spring Boot helps to quickly create Spring-based applications without having to write the same boilerplate
configuration over again.
Spring is a popular JavaEE framework for building web and enterprise applications.
Why is it popular
* Dependency injection
* Powerful database transaction management capabilities
* Can be integrated with other Java frameworks like JPA/Hibernate, Struts/JSF, etc.
* Web MVC (Model View Controller) framework for building web applications
Problems with Spring and how Spring Boot helps:
* Spring-based apps have lots of configurations: Component scan, Dispatcher Servlet, View resolver, Web jars, etc.
* If using Hibernate and JPA in the same Spring MVC app, you need to configure a Data source, Entity manager factory/session/factory, Transaction manager, etc.
* When you use cache, message queue, NoSQL in the same app, you need to configure Cache configuration, Messsage queue configuration, NoSQL database configuration.
* The need to maintain all integration of different Jar dependencies and compatible versions.
How Spring Boot helps:
* Spring Boot has auto configuration
* Spring Boot will automatically configure the application based on the added jar dependencies
* Spring Boot provides embedded Tomcat server
* Create a jar file and deploy it in an embdedded Tomcat server
* Spring Boot provides starter modules
* They are pre-configured with the most commonly used library dependencies
* It will also configure the commonly registered beans such as DispatcherServlet.
* It sucks to have to search for compatible library versions and configure them manually.
* Spring Boot actuator
* Production ready features such as rest endpoints.
* Externalized Configuations
* No need to externalize the configuration based on the environment (Develepment, testing, etc.)
Talk about Spring Boot starter parent dependency
Talk about annotation @springbootapplication
* it has 3 other annotations automatically
* @EnableAutoConfiguration
* @ComponentScan
* @Configuration
Because of that, you can define the beans within the main entry point of the program (Application class) without using a config file.
We don't have to manually create the application context |
using System;
using System.Collections.Generic;
namespace Decorator
{
//É o Decorator Concreto
public class Emprestado : Decorator
{
protected List<string> emprestados = new List<string>();
public Emprestado(ItemBiblioteca itemBiblioteca): base(itemBiblioteca)
{
}
public void EmprestarItem(string nome)
{
this.emprestados.Add(nome);
this.itemBiblioteca.NumeroCopias--;
}
public void DevolverItem(string nome)
{
this.emprestados.Remove(nome);
this.itemBiblioteca.NumeroCopias++;
}
public override void Exibe()
{
base.Exibe();
foreach (string item in emprestados)
{
Console.WriteLine("Emprestado : "+ item);
}
}
}
} |
import { useFormik } from "formik";
import { object, string, number } from "yup";
export default function RegistrationForm() {
const formik = useFormik({
initialValues: {
userName: "",
amount: "",
},
validationSchema: object({
userName: string()
.min(2, "Must be at least 10 characters")
.max(15, "Must be 15 character or less!")
.required("This field is required!"),
amount: number().required("This field is required!").positive(),
}),
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2));
},
});
return (
<>
<h2 className="text-2xl text-center mt-20">Investor Registration</h2>
<div className="flex justify-center mt-4">
<form
className="w-1/2 border-2 border-solid border-asparagus rounded-lg"
onSubmit={formik.handleSubmit}>
<div className="flex flex-col p-8">
<div className="mb-6 flex flex-col">
<label htmlFor="userName">Please enter you username</label>
<input
type="text"
id="userName"
name="userName"
onChange={formik.handleChange}
value={formik.values.userName}
placeholder="hyperienn..."
className="w-3/4 h-8 mt-2 pl-2 text-black rounded-md focus:outline-0 placeholder:italic"
/>
{formik.touched.userName && formik.errors.userName ? (
<div className="w-2/3 mt-2 bg-errorred rounded-lg">
<span className="p-2">{formik.errors.userName}</span>
</div>
) : null}
</div>
<div className="mb-6 flex flex-col">
<label htmlFor="amount">
Please enter the amount you want to keep in the contract
</label>
<input
type="number"
id="amount"
name="amount"
onChange={formik.handleChange}
value={formik.values.amount}
className="w-3/4 h-8 mt-2 pl-2 text-black rounded-md focus:outline-0"
/>
{formik.touched.amount && formik.errors.amount ? (
<div className="w-2/3 mt-2 bg-errorred rounded-lg">
<span className="p-2">{formik.errors.amount}</span>
</div>
) : null}
</div>
<button className="w-36 mt-4 mx-auto py-1.5 bg-asparagus rounded-3xl hover:bg-hovercolor">
Submit
</button>
</div>
</form>
</div>
</>
);
} |
//: Playground - noun: a place where people can play
import Cocoa
//Swift 语言提供Arrays、Sets和Dictionaries三种基本的集合类型用来存储集合数据。数组是有序数据的集。集合是无序无重复数据的集。字典是无序的键值对的集。
var someInts = [Int]()
someInts.append(3)
// someInts 现在包含一个 Int 值
someInts = []
// someInts 现在是空数组,但是仍然是 [Int] 类型的。
var threeDoubles = [Double](count: 3, repeatedValue:0.0)
// threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]
var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
// anotherThreeDoubles 被推断为 [Double],等价于 [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles
// sixDoubles 被推断为 [Double],等价于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
var threeInts = [Int](count: 3, repeatedValue: 1)
var tenString = [String](count: 10, repeatedValue: "test")
class Test {
init(){
}
func testTT(){
}
}
var fiveTest = [Test](count: 5, repeatedValue: Test())
var shoppingList: [String] = ["Eggs", "Milk"]
var shoppingList2 = ["Eggs", "Milk"]
//访问和修改数组
shoppingList.count
//使用布尔值属性isEmpty作为检查count属性的值是否为 0 的捷径:
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
//也可以使用append(_:)方法在数组后面添加新的数据项:
shoppingList.append("Flour")
shoppingList += ["Baking Powder"]
// shoppingList 现在有四项了
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList 现在有七项了
var firstItem = shoppingList[0]
// 第一项是 "Eggs"
//去掉一项
shoppingList[4...6] = ["Bananas", "Apples"]
shoppingList.insert("Maple Syrup", atIndex: 0)
// shoppingList 现在有7项
// "Maple Syrup" 现在是这个列表中的第一项
let mapleSyrup = shoppingList.removeAtIndex(0)
// 索引值为0的数据项被移除
// shoppingList 现在只有6项,而且不包括 Maple Syrup
// mapleSyrup 常量的值等于被移除数据项的值 "Maple Syrup"
let apples = shoppingList.removeLast()
// 数组的最后一项被移除了
// shoppingList 现在只有5项,不包括 cheese
// apples 常量的值现在等于 "Apples" 字符串
//enumerate()返回一个由每一个数据项索引值和数据值组成的元组。
for (index, value) in shoppingList.enumerate() {
print("Item \(String(index + 1)): \(value)")
}
//集合(Set)用来存储相同类型并且没有确定顺序的值。当集合元素顺序不重要时或者希望确保每个元素只出现一次时可以使用集合而不是数组。
//Set类型被写为Set<Element>,这里的Element表示Set中允许存储的类型,和数组不同的是,集合没有等价的简化形式。
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// 打印 "letters is of type Set<Character> with 0 items."
letters.insert("a")
// letters 现在含有1个 Character 类型的值
letters = []
// letters 现在是一个空的 Set, 但是它依然是 Set<Character> 类型
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
var favoriteGenres2: Set = ["Rock", "Classical", "Hip hop","hello","hi"]
//两个集合相交
favoriteGenres.intersect(favoriteGenres2)
//两个集合除了相交部分
favoriteGenres.exclusiveOr(favoriteGenres2)
//两个集合全部 不重复
favoriteGenres.union(favoriteGenres2)
//a集合中不包含b集合的部分
favoriteGenres.subtract(favoriteGenres2)
favoriteGenres2.subtract(favoriteGenres)
//你可以通过调用Set的remove(_:)方法去删除一个元素,如果该值是该Set的一个元素则删除该元素并且返回被删除的元素值,否则如果该Set不包含该值,则返回nil。另外,Set中的所有元素可以通过它的removeAll()方法删除。
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
//使用contains(_:)方法去检查Set中是否包含一个特定的值:
if favoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
}
// 打印 "It's too funky in here."
//Swift 的Set类型没有确定的顺序,为了按照特定顺序来遍历一个Set中的值可以使用sort()方法,它将根据提供的序列返回一个有序集合.
for genre in favoriteGenres.sort() {
print("\(genre)")
}
//集合操作
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
oddDigits.union(evenDigits).sort()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersect(evenDigits).sort()
// []
oddDigits.subtract(singleDigitPrimeNumbers).sort()
// [1, 9]
oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()
// [1, 2, 9]
//使用“是否相等”运算符(==)来判断两个集合是否包含全部相同的值。
//使用isSubsetOf(_:)方法来判断一个集合中的值是否也被包含在另外一个集合中。
//使用isSupersetOf(_:)方法来判断一个集合中包含另一个集合中所有的值。
//使用isStrictSubsetOf(_:)或者isStrictSupersetOf(_:)方法来判断一个集合是否是另外一个集合的子集合或者父集合并且两个集合并不相等。
//使用isDisjointWith(_:)方法来判断两个集合是否不含有相同的值。
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
houseAnimals.isSubsetOf(farmAnimals)
// true
farmAnimals.isSupersetOf(houseAnimals)
// true
farmAnimals.isDisjointWith(cityAnimals)
// true
//字典
//字典中的数据项并没有具体顺序。
//一个字典的Key类型必须遵循Hashable协议,就像Set的值类型。
var namesOfIntegers = [Int: String]()
// namesOfIntegers 是一个空的 [Int: String] 字典
var namesOfIntegers2 = [:]
//用字典字面量创建字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports["LHR"] = "London"
// airports 字典现在有三个数据项
airports["LHR"] = "London Heathrow"
// "LHR"对应的值 被改为 "London Heathrow
if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
print("The old value for DUB was \(oldValue).")
}
// 输出 "The old value for DUB was Dublin."
//字典的下标访问会返回对应值的类型的可选值。
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
airports["APL"] = "Apple Internation"
// "Apple Internation" 不是真的 APL 机场, 删除它
airports["APL"] = nil
// APL 现在被移除了
if let removedValue = airports.removeValueForKey("DUB") {
print("The removed airport's name is \(removedValue).")
} else {
print("The airports dictionary does not contain a value for DUB.")
}
// prints "The removed airport's name is Dublin Airport."
//字典遍历
for (airportCode, airportName) in airports {
print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow
for airportCode in airports.keys {
print("Airport code: \(airportCode)")
}
// Airport code: YYZ
// Airport code: LHR
for airportName in airports.values {
print("Airport name: \(airportName)")
}
// Airport name: Toronto Pearson
// Airport name: London Heathrow
let airportCodes = [String](airports.keys)
// airportCodes 是 ["YYZ", "LHR"]
let airportNames = [String](airports.values)
// airportNames 是 ["Toronto Pearson", "London Heathrow"]
// Swift 的字典类型是无序集合类型。为了以特定的顺序遍历字典的键或值,可以对字典的keys或values属性使用sort()方法。 |
import { useLocation } from 'react-router-dom';
import { searchGame } from './searchResultsViewModel';
import { useEffect, useState } from 'react';
import { SingleGameInterface } from '../../../API/apiMethods/gamesApi/gamesApi';
import { LoadingBackdrop } from '../../common/loadingModal/loadingmodal';
import { GameCard } from '../../common/gameCard/gameCard';
export function SearchResultsPage() {
const location = useLocation();
const [searchResults, setsearchResuls] = useState<SingleGameInterface[] | [] | null>(null);
const queryParams = new URLSearchParams(location.search);
const searchQuery = queryParams.get('query');
useEffect(() => {
(async () => {
setsearchResuls(null);
const response = await searchGame(searchQuery as string);
const searchResultsResponse = response.data?.length === 0 ? [] : response.data;
setsearchResuls(searchResultsResponse);
})();
}, [searchQuery]);
return (
<div>
{searchResults === null ? (
<LoadingBackdrop />
) : (
<div>
<div className="min-h-[110vh]">
<div className="mb-4 ">
<div>
<h2 className="sm:text-xl mb-1 font-bold lg:text-7xl">
{`Search results for ${searchQuery}`}
</h2>
<p className="sm:text-xs mb-4 lg:text-xl">
Based on player counts and release date
</p>
</div>
<div>
{/* <button className="p-1 text-sm bg-gray-700 text-white sm:mt-2 rounded-md">
Order by <span className="font-bold">{orderCriteria}</span>
<KeyboardArrowDownIcon />
</button> */}
</div>
</div>
<div>
<div className="md:flex md:flex-row md:flex-wrap">
{searchResults.length > 0
? searchResults.map((game, index) => {
return (
<div
key={`${game.slug}${index}`}
className="rounded-xl bg-[#282727] mb-4 overflow-hidden md:max-w-[23%] md:mr-3"
>
<GameCard
slug={game.slug}
gamename={game.name}
gameImage={game.background_image}
releaseDate={game.released}
/>
</div>
);
})
: null}
</div>
</div>
</div>
</div>
)}
</div>
);
} |
import { FaRegQuestionCircle } from "react-icons/fa";
import {
MdHome,
MdMenu,
MdOutlinePerson,
MdRequestQuote,
} from "react-icons/md";
import { NavLink, Outlet, Link } from "react-router-dom/dist";
import useDataUser from "../../../hooks/useUser/useDataUser";
import { AiFillProfile } from "react-icons/ai";
import { FcHome } from "react-icons/fc";
const Dashboard = () => {
const { userData } = useDataUser();
// console.log(userData)
// console.log(userData.role)
const dashboardLinks = (
<>
<li className="btn btn-ghost">
<Link to="/dashboard">
<MdHome className="text-xl" /> Home{" "}
</Link>
</li>
<li className="btn btn-ghost">
<NavLink to="/dashboard/profile">
<MdOutlinePerson className="text-xl" /> Profile{" "}
</NavLink>
</li>
<li className="btn btn-ghost">
<NavLink to="/dashboard/my-donation-requests">
<FaRegQuestionCircle /> My Donation Request{" "}
</NavLink>
</li>
<li className="btn btn-ghost">
<NavLink to="/dashboard/create-donation-request">
{" "}
Create Donation Request{" "}
</NavLink>
</li>
{userData?.role === "admin" && (
<>
<li className="btn btn-ghost">
<NavLink to="/dashboard/all-user">
<AiFillProfile /> All Users
</NavLink>
</li>
<li className="btn btn-ghost">
<NavLink to="/dashboard/all-blood-donation-request">
<MdRequestQuote /> All Donation Requests
</NavLink>
</li>
<li className="btn btn-ghost">
<NavLink to="/dashboard/content-management">
Content Management
</NavLink>
</li>
{/* <li className="btn btn-ghost mt-5 border-2 border-red-400">
<NavLink to="/">
<FcHome /> User Home
</NavLink>
</li> */}
</>
)}
{userData?.role === "volunteer" && (
<>
<li className="btn btn-ghost">
<NavLink to="/dashboard/all-blood-donation-request">
<MdRequestQuote /> All Donation Requests
</NavLink>
</li>
<li className="btn btn-ghost">
<NavLink to="/dashboard/content-management">
Content Management
</NavLink>
</li>
</>
)}
<li className="btn btn-ghost mt-5 border-2 border-red-400">
<NavLink to="/">
<FcHome /> User Home
</NavLink>
</li>
</>
);
return (
<div className="drawer lg:drawer-open bg-[#f4f7fc]">
<input id="my-drawer-2" type="checkbox" className="drawer-toggle" />
<label
htmlFor="my-drawer-2"
className=" m-5 drawer-button absolute lg:hidden"
>
<MdMenu className=" text-3xl text-black z-20" />
</label>
<div className=" rounded-lg lg:p-8 p-4 drawer-content bg-[#fefefe] flex flex-col items-center lg:m-5 mt-16">
{/* Page content here */}
<Outlet></Outlet>
</div>
<div className="drawer-side lg:bg-[#262D3F] text-white pt-10">
<label
htmlFor="my-drawer-2"
aria-label="close sidebar"
className="drawer-overlay"
></label>
<h3 className=" text-[#99E1D9] font-cinzel text-center text-2xl font-semibold">
Dashboard
</h3>
<div className=" w-full h-1 border-2 rounded-full border-cyan-200"></div>
<ul className="menu p-4 w-80 min-h-full">
{/* Sidebar content here */}
{dashboardLinks}
</ul>
</div>
</div>
);
};
export default Dashboard; |
##DESCRIPTION
##ENDDESCRIPTION
## DBsubject(Calculus - single variable)
## DBchapter(Techniques of integration)
## DBsection(Integration by parts (without trigonometric functions))
## Institution(Univeristy of Utah)
## Author(Utah ww group)
## MLT(notrig_01)
## Level(2)
## Static(1)
## TitleText1('Calculus II')
## AuthorText1('Jerrold Marsden and Alan Weinstein')
## EditionText1('2')
## Section1('.')
## Problem1('')
## KEYWORDS('calculus')
DOCUMENT(); # This should be the first executable line in the problem.
loadMacros(
"PGstandard.pl",
"PGchoicemacros.pl",
"PGcourse.pl"
);
TEXT(beginproblem());
TEXT(EV2(<<EOT));
Use integration by parts to find the following:
$PAR
\( \displaystyle\int (t + 7) e^{2t + 3} \,\hbox{d} t = \)
\{ans_rule(30)\} \( {}+C \)
EOT
$ans = "e**(2t+3) * ((t+7)/2 - 1/4)";
ANS(fun_cmp($ans, limits=>[1,3], mode=>"antider", vars=>"t"));
TEXT(EV3(<<'EOT'));
$BR $BBOLD Hint:$EBOLD Use the substitution
\[ u = t+7 \quad\hbox{and}\quad \hbox{d}v = e^{2t+3} \hbox{d}x \]
EOT
SOLUTION(EV3(<<'EOT'));
$BR $BBOLD Solution:$EBOLD We use the substitution
\[ u = t+7 , \hbox{d}v = e^{2t+3} \hbox{d}x \]
Thus
\[ \hbox{d}u = \hbox{d}t, v = \frac{1}{2} e^{2t+3} \]
Integration By Parts gives:
\[
\begin{array}{rcl}
I &=& \int (t + 7) e^{2t + 3} \,\hbox{d} t\\ \\
&=& \frac{t+7}{2}(e^{2t+3}) - \frac{1}{2} \int e^{2t+3} \,\hbox{d} t \\ \\
&=& \frac{t+7}{2}(e^{2t+3}) - \frac{1}{4} e^{2t+3} + C \\ \\
\end{array}
\]
EOT
ENDDOCUMENT(); # This should be the last executable line in the problem. |
/* manual_licenses.cpp
*
* Copyright (C) 1992-2023 Paul Boersma
*
* This code 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 2 of the License, or (at
* your option) any later version.
*
* This code 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 work. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ManPagesM.h"
#include "praat_version.h"
void manual_licenses_init (ManPages me);
void manual_licenses_init (ManPages me) {
MAN_PAGES_BEGIN
R"~~~(
################################################################################
"Acknowledgments"
© Paul Boersma 2002,2003,2005–2008,2010–2016,2020–2023
The following people contributed source code to Praat:
, Paul Boersma: user interface, graphics, @printing, @@Intro|sound@,
@@Intro 3. Spectral analysis|spectral analysis@, @@Intro 4. Pitch analysis|pitch analysis@,
@@Intro 5. Formant analysis|formant analysis@, @@Intro 6. Intensity analysis|intensity analysis@,
@@Intro 7. Annotation|annotation@, @@Intro 8. Manipulation|speech manipulation@, @@voice|voice report@,
@@ExperimentMFC|listening experiments@,
@@articulatory synthesis@, @@OT learning|optimality-theoretic learning@,
tables, @formulas, @scripting, and adaptation of PortAudio, GLPK, regular expressions, Opus and LAME.
, David Weenink:
@@feedforward neural networks@, @@principal component analysis@, @@multidimensional scaling@, @@discriminant analysis@, @LPC,
@VowelEditor,
and adaptation of GSL, LAPACK, fftpack, regular expressions, Espeak, Ogg Vorbis, Opus and LAME.
, Stefan de Konink and Franz Brauße: major help in port to GTK.
, Tom Naughton: major help in port to Cocoa.
, Erez Volk: adaptation of FLAC and MAD.
, Ola Söder: kNN classifiers, k-means clustering.
, Rafael Laboissière: adaptation of XIPA, audio bug fixes for Linux.
, Darryl Purnell created the first version of audio for Praat for Linux.
We included the following freely available software libraries in Praat (sometimes with adaptations):
, XIPA: IPA font for Unix by Fukui Rei (GPL).
, GSL: GNU Scientific Library by Gerard Jungman and Brian Gough (GPL 3 or later).
, GLPK: GNU Linear Programming Kit by Andrew Makhorin (GPL 3 or later);
contains AMD software by the same author (LGPL 2.1 or later).
, PortAudio: Portable Audio Library by Ross Bencina, Phil Burk, Bjorn Roche, Dominic Mazzoni, Darren Gibbs,
version 19.7.0 of April 2021 (CC-BY-like license).
, Espeak(-NG): text-to-speech synthesizer by Jonathan Duddington and Reece Dunn,
development version 1.52 of August 2023 (GPL 3 or later).
, MAD: MPEG Audio Decoder by Underbit Technologies (GPL 2 or later).
, LAME: MP3 encoding by Mike Cheng, Mark Taylor, Takehiro Tominaga, Robert Hegemann, Gabriel Bouvigne, Alexander Leidinger,
Naoki Shibata, John Dahlstrom, Jonathan Dee, Rogério Brito,
Frank Klemm, Don Melton, Albert L. Faber, Roberto Amorim, Josep Maria Antolín Segura, Dominique Duvivier,
Joseph Flynn, Peter Gubanov, Guillaume Lessard, Steve Lhomme, Darin Morrison, Dyle VanderBeek,
David Robinson, Glen Sawyer, Marcel Muller, Olcios, version 3.100 of October 2017 (GPL 2 or later).
, FLAC: Free Lossless Audio Codec by Josh Coalson and Xiph.Org, version 1.3.3 (@@FLAC BSD 3-clause license@).
, Ogg Vorbis: audio compression by Christopher Montgomery (@@Ogg Vorbis BSD 3-clause license@).
, Opus: audio compression by Jean-Marc Valin, Gregory Maxwell, Christopher Montgomery, Timothy Terriberry,
Koen Vos, Andrew Allen and others (@@Opus BSD 3-clause license@).
, SILK: audio compression by Skype Limited (@@Skype Limited BSD 3-clause license@).
, fftpack: public-domain Fourier transforms by Paul Swarztrauber, translated to C by Christopher Montgomery.
, @LAPACK: public-domain numeric algorithms by Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd.,
Courant Institute, Argonne National Lab, and Rice University,
C edition by Peng Du, Keith Seymour and Julie Langdou, version 3.2.1 of June 2009.
, Regular expressions by Henry Spencer, Mark Edel, Christopher Conrad, Eddy De Greef (GPL 2 or later).
, Unicode Character Database by Unicode Inc., version 14.0 of September 2021 (@@Unicode Inc. license agreement@)
Most of the source code of Praat is distributed under the General Public License, version 2 or later.
However, as Praat includes the above software written by others,
the whole of Praat is distributed under the General Public License, version 3 or later.
For their financial support during the development of Praat:
, Netherlands Organization for Scientific Research (NWO) (1996–1999).
, Nederlandse Taalunie (2006–2008).
, Talkbank project, Carnegie Mellon / Linguistic Data Consortium (2002–2003).
, Stichting Spraaktechnologie (2014–2016).
, Spoken Dutch Corpus (CGN) (1999–2001).
, Laboratorium Experimentele OtoRhinoLaryngologie, KU Leuven.
, DFG-Projekt Dialektintonation, Universität Freiburg.
, Department of Linguistics and Phonetics, Lund University.
, Centre for Cognitive Neuroscience, University of Turku.
, Linguistics Department, University of Joensuu.
, Laboratoire de Sciences Cognitives et Psycholinguistique, Paris.
, Department of Linguistics, Northwestern University.
, Department of Finnish and General Linguistics, University of Tampere.
, Institute for Language and Speech Processing, Paradissos Amaroussiou.
, Jörg Jescheniak, Universität Leipzig.
, The Linguistics Teaching Laboratory, Ohio State University.
, Linguistics & Cognitive Science, Dartmouth College, Hanover NH.
, Cornell Phonetics Lab, Ithaca NY.
Finally we thank:
, Ton Wempe and Dirk Jan Vet, for technical support and advice.
, Daniel Hirst and Daniel McCloy, for managing the Praat Users List.
, Rafael Laboissière and Andreas Tille, for maintaining the Debian package.
, Jason Bacon and Adriaan de Groot, for maintaining the FreeBSD port.
, José Joaquín Atria and Ingmar Steiner, for setting up the source-code repository on GitHub.
, Hundreds of Praat users, for sending suggestions and notifying us of problems and thus helping us to improve Praat.
################################################################################
"License"
© Paul Boersma 2021
Praat is free software distributed under the @@General Public License, version 3@ or higher.
See @Acknowledgments for details on the licenses of software libraries by others
that are included in Praat.
################################################################################
"FLAC BSD 3-clause license"
© Paul Boersma 2021
The Praat source code contains a copy of the FLAC software (see @Acknowledgments).
Here is the FLAC license text:
`
libFLAC - Free Lossless Audio Codec library
Copyright (C) 2001-2009 Josh Coalson
Copyright (C) 2011-2016 Xiph.Org Foundation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 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.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
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 FOUNDATION 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.
`
################################################################################
"Ogg Vorbis BSD 3-clause license"
© Paul Boersma 2020
The Praat source code contains a copy of the Ogg Vorbis software (see @Acknowledgments).
Here is the Ogg Vorbis license text:
`
Copyright (c) 2002-2020 Xiph.org Foundation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 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.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
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 FOUNDATION
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.
`
################################################################################
"Opus BSD 3-clause license"
© Paul Boersma 2021
The Praat source code contains a copy of the Opus software (see @Acknowledgments).
Here is the Opus license text:
`
Copyright (c) 2001-2011 Xiph.Org, Skype Limited, Octasic,
Jean-Marc Valin, Timothy B. Terriberry,
CSIRO, Gregory Maxwell, Mark Borgerding,
Erik de Castro Lopo
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- 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.
- Neither the name of Internet Society, IETF or IETF Trust, nor the
names of specific contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
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 FOUNDATION 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.
Opus is subject to the royalty-free patent licenses which are
specified at:
Xiph.Org Foundation:
https://datatracker.ietf.org/ipr/1524/
Microsoft Corporation:
https://datatracker.ietf.org/ipr/1914/
Broadcom Corporation:
https://datatracker.ietf.org/ipr/1526/
`
################################################################################
"Skype Limited BSD 3-clause license"
© Paul Boersma 2022
The Praat source code contains a copy of the SILK software (see @Acknowledgments).
Here is the Skype Limited license text:
`
Copyright (c) 2006-2011 Skype Limited. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- 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.
- Neither the name of Internet Society, IETF or IETF Trust, nor the
names of specific contributors, may be used to endorse or promote
products derived from this software without specific prior written
permission.
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.
`
################################################################################
"Unicode Inc. license agreement"
© Paul Boersma 2022
The Praat source code contains a copy of the Unicode Character Database,
as well as derived software (see @Acknowledgments).
Here is the Unicode Inc. license text:
`
UNICODE, INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE
See Terms of Use <https://www.unicode.org/copyright.html>
for definitions of Unicode Inc.’s Data Files and Software.
NOTICE TO USER: Carefully read the following legal agreement.
BY DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING UNICODE INC.'S
DATA FILES ("DATA FILES"), AND/OR SOFTWARE ("SOFTWARE"),
YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
TERMS AND CONDITIONS OF THIS AGREEMENT.
IF YOU DO NOT AGREE, DO NOT DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE
THE DATA FILES OR SOFTWARE.
COPYRIGHT AND PERMISSION NOTICE
Copyright © 1991-2022 Unicode, Inc. All rights reserved.
Distributed under the Terms of Use in https://www.unicode.org/copyright.html.
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Unicode data files and any associated documentation
(the "Data Files") or Unicode software and any associated documentation
(the "Software") to deal in the Data Files or Software
without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, and/or sell copies of
the Data Files or Software, and to permit persons to whom the Data Files
or Software are furnished to do so, provided that either
(a) this copyright and permission notice appear with all copies
of the Data Files or Software, or
(b) this copyright and permission notice appear in associated Documentation.
THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS
NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL
DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THE DATA FILES OR SOFTWARE.
Except as contained in this notice, the name of a copyright holder
shall not be used in advertising or otherwise to promote the sale,
use or other dealings in these Data Files or Software without prior
written authorization of the copyright holder.
`
################################################################################
"General Public License, version 3"
© Paul Boersma 2021
This is the license under which Praat as a whole is distributed.
`
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
`
################################################################################
"Privacy and security"
© Paul Boersma 2022
Praat is an “isolated” app. You download it from `praat.org`,
then record sounds into Praat (all in RAM) or open a sound file,
then analyse or manipulate that sound. The only way in which your results
are saved to disk (as e.g. a Pitch file, a TextGrid file, or a sound file),
is when you explicitly choose one of the #Save or #Export commands
from Praat’s menus; Praat will not by itself save any data files to disk
or send any information anywhere. When you create a picture in the Picture window,
the only way to move that picture anywhere else is if you save it explicitly
to a picture file (e.g. PNG) or if you Copy–Paste it to e.g. a text editing
app such as e.g. Microsoft Word; Praat will not by itself save any picture to disk
or to the clipboard or send any information anywhere.
Praat will run just fine on your computer if it does not have Internet access,
and in fact Praat cannot even notice whether you are in a network or not.
Praat works entirely stand-alone.
Praat does not call home
When you are using Praat, you can be assured that Praat does not attempt to send any of your data
or pictures or settings to the Praat team.
In fact, Praat never accesses the Internet, not even to @@checking for updates|check for updates@.
No telemetry
Praat does not send anything to the Praat team while you are using Praat:
- No surveillance
- No tracking
- No Google Analytics
- In general, no spying or data mining by the Praat team
What does Praat save to disk without asking you?
Praat will save your preferences to your own disk on your own computer,
in a folder of your own, when you close Praat.
This includes the settings in your Sound window (e.g. your last chosen Pitch range),
so that your Sound windows will look the same after you start Praat up again.
The goal of this is to provide a continuous user experience, and is what you probably expect,
because most apps that you use on your computer work this way.
What we do measure
As mentioned above, Praat does no telemetry, i.e. it does not send us anything while you are using Praat.
We %do% receive some information, though, when %you contact %us. This happens when you download
a new Praat version for your computer. We log the Praat downloads, so that we can potentially count
how often which edition and which version of Praat is downloaded.
Wouldn’t telemetry be useful for the quality of Praat?
Companies that use telemetry tend to justify that by arguing that gathering information on how their app is used
is useful for improving the quality of their app (by collecting error messages),
or to know which features are rarely used, so that those features can be removed.
We are skeptical. If we, as Praat developers, have made a programming error,
then we hope that an “assertion” will help solve the issue.
An assertion is a place in our code where Praat will crash if a certain assumption
is not met. A message window will pop up in Praat that says that Praat will crash, together
with the request to send some relevant information by email to us, the developers of Praat.
If you do send this crash information on to us (you can read it, as it is normal English without secrets),
we will then virtually always find out (sometimes with some more help from you,
such as the sound file or script that caused the crash)
what was wrong, and correct the mistake, so that our programming error (“bug”) no longer occurs
in the next version of Praat. We will also build an automatable test that checks, for all future
versions of Praat, that the bug does not reappear. In this way, every Praat version tends to be more stable and correct
than the previous version. We believe that this practice minimizes the problems with Praat sufficiently,
and no automated reporting of error messages and crash messages is necessary.
As for the removal of obsolete features, we are just very conservative.
Typically, file types from the 1980s and 1990s can typically still be opened in the 2020s,
and old Praat scripts should continue to run for at least 15 years after we marked a language feature
as “deprecated” or “obsolete” (and removed it from the manual).
This has not prevented us from also being able to open file types invented in the 2020s
or to have a modern scripting language that supports vectors, matrices and string arrays,
and backward compatibility hardly hampers the continual modernization of Praat.
Praat scripts and plug-ins
As with R scripts, Python scripts, and quite generally any kinds of scripts from any source,
you should consider Praat scripts written by others, such as plug-ins that you download,
as separate apps with their own privacy and security issues. Use a script or plug-in only
if you completely trust that script or plug-in and its creators.
################################################################################
"Checking for updates"
© Paul Boersma 2022
Updates for Praat are available from `www.praat.org`.
Your current version (if you are reading this from the manual inside the Praat program,
rather than from the website) is )~~~" stringize(PRAAT_VERSION_STR) R"~~~(,
from )~~~" stringize(PRAAT_MONTH) " " stringize(PRAAT_DAY) ", " stringize(PRAAT_YEAR) R"~~~(.
Given that we tend to release new Praat versions once or twice a month,
you can probably guess whether it would be worth your while to have a look at `www.praat.org`
to see what is new, and perhaps download a new version.
Praat improves continually, and old features will almost always continue to work,
so there should never be a reason to continue to work with older versions.
Why no automatic update checking?
Many apps automatically check for updates when you start them up.
This means that the owners of such an app are capable of recording which users use their app when,
which is information that can potentially harm your privacy, for instance when a government
or legal investigation demands that the app owners provide them with access to such information.
The Praat team wants to stay far away from the possibility of such situations occurring,
even if you may be convinced that usage of the Praat program cannot be regarded by anybody
as being anything other than perfectly innocent. For this resason, the Praat program
will never contact the Praat team and, more generally,
will never attempt to access the Internet by itself. For more information, see @@Privacy and security@.
################################################################################
"Reporting a problem"
© Paul Boersma 2022
Anything that you consider incorrect behaviour of Praat (a “bug”) can be reported
to the authors by email (`[email protected]`). This includes any crashes.
Questions about how to use Praat for your specific cases
can be posed to the Praat User List (`https://groups.io/g/Praat-Users-List`).
This includes any questions on why your self-written Praat script does something unexpected.
################################################################################
)~~~" MAN_PAGES_END
}
/* End of file manual_licenses.cpp */ |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './auth/login/login.component';
import { SignupComponent } from './auth/signup/signup.component';
import { ChatComponent } from './chat/chat.component';
import { HeaderComponent } from './header/header.component';
import { CreatePostComponent } from './home/create-post/create-post.component';
import { HomeComponent } from './home/home.component';
import { MyprofileComponent } from './myprofile/myprofile.component';
import { ProfileComponent } from './profile/profile.component';
const routes: Routes = [
{path: 'signup', component: SignupComponent},
{path: 'login', component: LoginComponent},
{path: 'home', component: HomeComponent},
{path: 'createpost', component: CreatePostComponent},
{path: 'users/:username', component: ProfileComponent},
{path: 'profile', component: MyprofileComponent},
{path: '', component: HomeComponent},
{path: 'users/:username/chat', component: ChatComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } |
<?php
namespace App\Mail\Myaccount\Admin;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class PickupRequest extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($packages)
{
$this->packages = $packages;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
$from_mail = '[email protected]';
$from_name = 'SHOPPRE.com';
$subject = 'Pickup from shoppre request';
return $this->view('myaccount.email.admin.pickup')
->from($from_mail, $from_name)
->replyTo($from_mail, $from_name)
->subject($subject)
->with(['packages' => $this->packages]);
}
} |
library(dplyr)
library(magrittr)
library(dplyr)
library(ggpubr)
mds <- function(data) {
# Compute MDS
mds <- data %>%
dist() %>%
cmdscale() %>%
as_tibble()
colnames(mds) <- c("Dim.1", "Dim.2")
# Plot MDS
plot <- ggscatter(mds, x = "Dim.1", y = "Dim.2",
label = rownames(data),
size = 1,
repel = TRUE)
return(plot)
}
data_0 <- read.csv("MDS_control_country_choice.csv", sep = ";", dec = ",")
row.names(data_0) <- data_0$Country
#Choice between Denmark and the UK
data <- data_0 %>%
dplyr::filter(Country %in% c("Denmark", "Italy", "United Kingdom")) %>%
dplyr:: mutate(Ask_merge = c(2015, 2016, 2016)) %>%
dplyr::select(-c(Country, Share.of.MVNO.subscription.over.mobile.subs......2018, Share.of.MNO.subscription.over.mobile.subs......2018, MNO.NUMBER.2017.Q4)) %>%
scale()
data = data[ , apply(data, 2, function(x) !any(is.na(x)))]
mds(data)
dist(data)
#Choice between Germany, Ireland and Norway
data <- data_0 %>%
dplyr::filter(Country %in% c("Germany", "Ireland", "Italy", "Norway")) %>%
dplyr:: mutate(Merge = c(2014.75, 2014.5, 2016.75, 2015)) %>%
dplyr::select(-c(Country, MNO.NUMBER.2017.Q4)) %>%
scale()
data = data[ , apply(data, 2, function(x) !any(is.na(x)))]
mds(data)
dist(data)
#Choice between Belgium, Bulgaria, Croatia, Cyprus, Czech Republic, Finland, Romania, Spain
data <- data_0 %>%
dplyr::filter(Country %in% c("Belgium", "Bulgaria", "Croatia", "Cyprus", "Czech Republic", "Finland", "Italy", "Romania", "Spain")) %>%
dplyr::select(-c(Country, Share.of.MVNO.subscription.over.mobile.subs......2018, Share.of.MNO.subscription.over.mobile.subs......2018)) %>%
scale()
data = data[ , apply(data, 2, function(x) !any(is.na(x)))]
mds(data)
dist(data) |
import Kwako from '../../Client'
import { Message, MessageEmbed, TextChannel } from 'discord.js'
import GuildConfig from '../../interfaces/GuildConfig';
module.exports.run = async (msg: Message, args: string[], guildConf: GuildConfig) => {
if (!msg.member.hasPermission('MANAGE_MESSAGES')) return;
if (args.length === 1 && msg.channel.type != 'dm') {
if (msg.mentions.everyone) return;
let mention = msg.mentions.members.first()
if (!mention) return;
if (mention.id === msg.author.id || mention.id === Kwako.user.id) return;
try {
await msg.delete();
} catch (error) {
Kwako.log.error(error);
}
if(mention.roles.cache.has(guildConf.muteRole)) {
const embed = new MessageEmbed()
.setColor(14349246)
.setTitle(`✅ **${mention.user.username}** has been unmuted`);
try {
await mention.roles.remove(guildConf.muteRole);
await Kwako.db.collection('mute').deleteOne({ _id: mention.id });
await msg.channel.send(embed);
} catch (err) {
await msg.channel.send({'embed':{
'title': ":x: > I can't unmute this person!"
}});
}
let modLogChannel = guildConf.modLogChannel;
if(modLogChannel) {
let channel = await Kwako.channels.fetch(modLogChannel);
const embedLog = new MessageEmbed()
.setTitle("Member unmuted")
.setDescription(`**Who:** ${mention.user.tag} (<@${mention.id}>)\n**By:** <@${msg.author.id}>`)
.setColor(14349246)
.setTimestamp(msg.createdTimestamp)
.setFooter("Date of unmute:")
.setAuthor(msg.author.username, msg.author.avatarURL({ format: 'png', dynamic: false, size: 128 }));
await (channel as TextChannel).send(embedLog);
}
} else {
await msg.channel.send({'embed':{
'title': ":x: This person isn't muted",
'color': 13864854
}})
}
Kwako.log.info({msg: 'unmute', author: { id: msg.author.id, name: msg.author.tag }, guild: { id: msg.guild.id, name: msg.guild.name }, target: { id: mention.id, name: mention.user.tag }})
}
};
module.exports.help = {
name: 'unmute',
usage: 'unmute (mention someone)',
staff: true,
perms: ['EMBED_LINKS', 'MANAGE_ROLES', 'MANAGE_MESSAGES', 'READ_MESSAGE_HISTORY']
} |
/*
* eGov SmartCity eGovernance suite aims to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) 2017 eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* 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
* 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/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
* Further, all user interfaces, including but not limited to citizen facing interfaces,
* Urban Local Bodies interfaces, dashboards, mobile applications, of the program and any
* derived works should carry eGovernments Foundation logo on the top right corner.
*
* For the logo, please refer http://egovernments.org/html/logo/egov_logo.png.
* For any further queries on attribution, including queries on brand guidelines,
* please contact [email protected]
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at [email protected].
*
*/
package org.egov.works.master.service;
import org.egov.common.entity.UOM;
import org.egov.infstr.services.PersistenceService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
public class UOMService extends PersistenceService<UOM, Long> {
@PersistenceContext
private EntityManager entityManager;
public UOMService() {
super(UOM.class);
}
public UOMService(Class<UOM> type) {
super(type);
}
public UOM getUOMById(final Long uomId) {
final UOM uom = entityManager.find(UOM.class, uomId);
return uom;
}
public List<UOM> getAllUOMs() {
final Query query = entityManager.createQuery("from UOM order by upper(uom)");
final List<UOM> uomList = query.getResultList();
return uomList;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.