text
stringlengths 184
4.48M
|
---|
---
id: Web MVC 核心
title: Web MVC 核心
cssclasses:
- wide-page
---
## SpringMvc 架构
### 基础架构-Servlet

Servlet 有以下的特点:
1. 请求模式: 请求/响应式(Request/Response)
2. 会屏蔽网络通信的细节,无需关注底层请求的处理
3. 包含完整的生命周期
Servlet 有以下的职责:
1. 处理请求
2. 资源管理 (连接数据库,处理本地资源...)
3. 视图的渲染
### 核心架构-前端控制器
> SpringMvc 核心架构使用 *前端控制器(FrontController)* 的模式

- 大致流程
- 首先客户端发送请求给前端控制器(FrontController)
- 然后前端控制器将请求"委派"给应用控制器(ApplicationController)处理
- 应用控制器收到请求后会将请求转发给具体的视图(View),同时还可能会执行某个服务,并将该服务产生的数据给到视图去"渲染"
- SpringMVC 中的具体实现类: `DispatcherServlet`
### SpringMvc 架构

## 认识 SpringMvc
### 一般认识
一般情况下,我们需要通过以下步骤来处理一个 http 请求:
1. 实现 Controller
2. 配置 Web MVC 组件
- ComponentScan
- RequestMappingHandlerMapping
- RequestMappingHandlerAdapter
- InternalResourceViewResolver
3. 部署 DispatcherServlet
首先需要创建一个 Controller:
```java
@Controller
public class AddressController {
/**
* 返回一个 View 的字符串名称
*/
@GetMapping("")
public String index() {
return "index";
}
}
```
然后在 webapp 目录下创建 WEB-INF/jsp 目录,用于存放 jsp 文件,然后新建 `WEB-INF/app-context.xml` 文件,也就是 MVC 的应用上下文配置文件
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--配置组件扫描-->
<context:component-scan base-package="com.pacos"/>
<!--配置 RequestMappingHandler--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
<!--配置视图解析器:jsp-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 相对于 webapp 目录下-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
```
最后在 webapp 下新建 web.xml, 来配置 `DispatcherServlert`
```xml
<web-app>
<servlet>
<servlet-name>app</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/app-context.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
```
### 重新认识
#### 核心组件
1. 处理器管理
- 映射: `HandlerMapping`
- 适配器: `HandlerAdapter`
- 执行链: `HandlerExecutionChain`
2. 页面渲染
- 视图解析: `ViewResolver`
- 国际化: `LocaleResolver`、`LocalContextResolver`
- 个性化: `ThemeResolver`
3. 异常处理
- 异常解析: `HandlerExceptionResolver`
下面是组件的说明:
1. [HandlerMapping](https://docs.spring.io/spring/docs/5.2.2.RELEASE/spring-framework-reference/web.html#mvc-handlermapping)
- 请求(Request) 与 处理器(Handler)和拦截器 (HandlerInterceptor) 的映射列表,其映射关系基于不同的 `HandlerMapping` 有不同的实现细节
- Handler 就是自定义的处理方法
- 有两种主要的 HandlerMapping 实现:
- `RequestMappingHandlerMapping` :支持标注 `@RequestMapping` 的方法
- SimpleUrlHandlerMapping: 维护精确的URI 路径与处理器的映射
2. HandlerAdapter
- 帮助 `DispatcherServlet` 调用请求处理器(Handler), 无需关注其中实际的调用细节。比如,调用注解实现的 Controller 需要解析其关联的注解
- **HandlerAdapter 的主要目的是为了屏蔽与 `DispatcherServlet` 之间的诸多细节**
3. [HandlerExceptionResolver](https://docs.spring.io/spring/docs/5.2.2.RELEASE/spring-framework-reference/web.html#mvc-exceptionhandlers)
- 解析异常相关
- 可能策略是将异常处理映射到其他处理器(Handlers), 或到某个 HTML 错误页面,或者其他
4. [ViewResolver](https://docs.spring.io/spring/docs/5.2.2.RELEASE/spring-framework-reference/web.html#mvc-viewresolver)
- 从处理器(Handler)返回字符类型的逻辑视图名称解析出实际的 `View` 对象,该对象将渲染后的内容输出到HTTP 响应中
5. LocaleResolver、LocaleContextResolver
- 从客户端解析出 `Locale`, 为其实现国际化视图
6. [MultipartResolver](https://docs.spring.io/spring/docs/5.2.2.RELEASE/spring-framework-reference/web.html#mvc-multipart)
- 解析多部分请求(如 Web 浏览器文件上传)的抽象实现
组件之间的交互在 `DispatcherServlet#doDispatch`,其中的大致流程如下:

#### 注解驱动
> 注解驱动下, 可以通过以下的注解、类来拓展 SpringMvc,其中很重要的就是 `@EnableWebMvc`
1. 配置注解: `@Configuration`
2. 组件激活: `@EnableWebMvc`
- 该注解会注册一些核心组件,比如*RequestMappingHandlerMapping*、*RequestMappingHandlerAdapter*...
1. 自定义组件: 实现 `WebMvcConfigurer` 接口中的目标方法,比如 *addInterceptors*
下面是 @EnableWebMvc 注解的基本处理功能,它 *@Import* 了 `DelegatingWebMvcConfiguration` 及其父类 `WebMvcConfigurationSupport`
```java
// @EnableWebMvc 注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
// DelegatingWebMvcConfiguration 类
@Bean
public RequestMappingHandlerMapping requestMappingHandlerMapping(...) {
// ... [注册 RequestMappingHandlerMapping]
}
@Bean
@Nullable
public HandlerMapping viewControllerHandlerMapping() {
// ... [注册 HandlerMapping]
}
@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(...){
// ... [注册 RequestMappingHandlerAdapter]
}
// ...
// WebMvcConfigurationSupport 类
@Bean
public HttpRequestHandlerAdapter httpRequestHandlerAdapter() {
return new HttpRequestHandlerAdapter();
}
@Bean
public HandlerExceptionResolver handlerExceptionResolver(...) {
// ...
}
// ...
```
下面使用注解的方式修改[代码](Web%20MVC%20核心#一般认识):
首先定义一个 SpringMvc 的配置注解类,**@EnableWebMvc 默认 注册的 ViewResolver 没有配置 prefix 和 suffix,所以需要调整**:
```java
/**
* SpringMvc 的配置注解类
*
* @author <a href="mailto:zhuyuliangm@gmail.com">yuliang zhu</a>
*
* @see Configuration
* @see EnableWebMvc
*/
@Configuration
@EnableWebMvc
public class WebMvcConfig {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
```
然后在 WEB-INF 下 的 SpringMvc 应用上下文配置文件中,配置启用包扫描(也会启用注解功能)
```xml
<!--配置组件扫描-->
<context:component-scan base-package="com.pacos"/>
```
#### 其他注解
SpringMvc 还有其他的一些注解:
1. 模型属性: `@ModelAttribute`
2. 请求头: `@RequestHeader`
3. Cookie: `@CookieValue`
4. 参数校验: `@Valid、@Validated` ,这个依赖于 Spring 本身的数据校验绑定
5. 异常处理: `@ExceptionHandler`
- 对应的 Resolver: `ExceptionHandlerExceptionResolver`
- 在 [WebMvcConfigurationSupport](Web%20MVC%20核心#注解驱动) 中进行注册
6. 切面通知: `@ControllerAdvice`
SpringMvc 中, 通常会注册 `RequestMappingHandlerAdapter`,它是[核心组件-HandlerAdapter 接口](Web%20MVC%20核心#核心组件) 的实现类,它还实现了 *InitializingBean*,所以在 它进行初始化的时候的时候会执行 *afterPropertiesSet* 方法,其中会有几个重要方法:
1. **getDefaultArgumentResolvers**: 返回处理方法参数的 Resolver,比如处理 @RequestParam、@RequestBody、@RequestHeader…
2. **getDefaultInitBinderArgumentResolvers**: 返回处理方法参数绑定的 Resolver,比如处理 @RequestParam、@PathVariable …
3. **getDefaultReturnValueHandlers**: 返回处理返回值的 Handler,比如处理@ResponseBody、@ModelAttribute、@RequestResponseBody…
```java
@Override
public void afterPropertiesSet() {
// Do this first, it may add ResponseBody advice beans
initControllerAdviceCache();
if (this.argumentResolvers == null) {
// 返回处理方法参数的 Resolver
List<HandlerMethodArgumentResolver> resolvers = getDefaultArgumentResolvers();
this.argumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
}
if (this.initBinderArgumentResolvers == null) {
// 返回处理方法参数绑定的 Resolver
List<HandlerMethodArgumentResolver> resolvers = getDefaultInitBinderArgumentResolvers();
this.initBinderArgumentResolvers = new HandlerMethodArgumentResolverComposite().addResolvers(resolvers);
}
if (this.returnValueHandlers == null) {
// 返回处理返回值的 Handler
List<HandlerMethodReturnValueHandler> handlers = getDefaultReturnValueHandlers();
this.returnValueHandlers = new HandlerMethodReturnValueHandlerComposite().addHandlers(handlers);
}
}
```
### SpringMvc 的启动
> 这里的 Servlet 容器以 Tomcat 为例
在 Servlet3.0 之前,我们需要定义 `web.xml`,比如下面的:
```xml
<web-app>
<!--
配置contextConfigLocation 初始化参数:指定Spring IoC容器配置文件路径
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 配置 ContextLoaderListerner:Spring MVC在Web容器中的启动类,负责Spring IoC容器在Web上下文中的初始化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>court</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- court-servlet.xml:定义WebAppliactionContext上下文中的bean -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:court-servlet.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>court</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
```
在 上述的 web.xml 配置文件中,有两个主要的配置:
1. `ContextLoaderListener` : SpringMvc 的 Web 容器中的启动类,并且负责 Spring IOC 容器在 Web 上下文中的初始化
2. `DispatcherServlet`: 前端控制器,主要用于接受的 HTTP 请求和转发 HTTP 请求
#### Tomcat 的启动
Tomcat 使用的 web.xml 有下面的节点(按照解析顺序)
- `context-param`: 为 ServletContext 提供键值对,即应用程序上下文信息
- `listener`
- `filter`
- `servlet`
- 用于定义 Servlet 的名称 和 类的限定名
- servlet 的初始化顺序按照 `load-on-startup` 元素指定的值
- 如果值为正数或零,则按照从小到大的顺序初始化
- 如果值为负数或未定义,则在第一次请求时初始化
- servlet-mapping 用于访问指定 servlet 的 URL, 且 servlet-mapping 必须出现在 servlet 之后
Tomcat 大致流程解析流程:
1. Tomcat 启动的时候会解析 `context-param`,然后创建 `ServletContext` 对象,并且将 context-param 转为键值对赋给 ServletContext
2. 然后解析 `listener` 标签,并且根据 listener-class 创建监听器实例
- 如果监听器类实现了 `ServletContextListener` 接口,那么它的 `contextInitialized(ServletContextEvent sce)` 和 `contextDestroyed(ServletContextEvent sce)`会在 ServletContext 对象创建和销毁时被调用
- Spring 的 `ContextLoaderListener` 就实现了 ServletContextListener 接口
#### 上下文的层次性
> **关于 DispatcherServlet、WebApplicationContext、ServletContext 的关系?**
首先看下 DispatcherServlet 的继承关系:
```mermaid
classDiagram
direction TB
class ApplicationContextAware {
<<Interface>>
}
class Aware {
<<Interface>>
}
class EnvironmentAware {
<<Interface>>
}
class EnvironmentCapable {
<<Interface>>
}
class DispatcherServlet {
# initStrategies(ApplicationContext) void
- initThemeResolver(ApplicationContext) void
- initLocaleResolver(ApplicationContext) void
- initMultipartResolver(ApplicationContext) void
- initHandlerAdapters(ApplicationContext) void
- initHandlerExceptionResolvers(ApplicationContext) void
- initViewResolvers(ApplicationContext) void
}
class FrameworkServlet {
# initServletBean() void
# initWebApplicationContext() WebApplicationContext
# postProcessWebApplicationContext(ConfigurableWebApplicationContext) void
# initFrameworkServlet() void
}
class GenericServlet {
+ service(ServletRequest, ServletResponse) void
+ getServletConfig() ServletConfig
+ getInitParameterNames() Enumeration~String~
+ getServletContext() ServletContext
+ getServletInfo() String
+ getServletName() String
+ getInitParameter(String) String
+ init() void
+ init(ServletConfig) void
}
class HttpServlet
class HttpServletBean {
# initServletBean() void
+ init() void
# initBeanWrapper(BeanWrapper) void
}
class Servlet {
<<Interface>>
}
class ServletConfig {
<<Interface>>
}
ApplicationContextAware --> Aware
DispatcherServlet --> FrameworkServlet
EnvironmentAware --> Aware
FrameworkServlet ..> ApplicationContextAware
FrameworkServlet --> HttpServletBean
GenericServlet ..> Servlet
GenericServlet ..> ServletConfig
HttpServlet --> GenericServlet
HttpServletBean ..> EnvironmentAware
HttpServletBean ..> EnvironmentCapable
HttpServletBean --> HttpServlet
```
首先需要了解 SpringMvc 的启动过程:
1. 首先对于一个 Web 应用来说, 我们会将其部署在 Tomcat 这种 Servlet 容器中, 容器提供了一个全局的上下文环境,这个上下文环境就是 `ServletContext`, 它为 SpringIOC 容器提供一个宿主环境
2. 然后在 Tomcat 启动的时候,会触发容器初始化事件, 配置的 `ContextLoaderListener` 会监听到这个事件,然后会触发 `contextInitialized` 方法
- SpringMvc 会创建一个 Spring Web 应用上下文(*根上下文*): `WebApplicationContext`, 它有一个实现类: `XmlWebApplicationContext`
- 在创建 WebApplicationContext 的时候,会通过 `ServletContext` 获取到 web.xml 中的 context-param 的值 [ param-name= contextConfigLocation], 然后在读取到值之后,就会将其设置给 Spring Web 应用上下文
- 当 Spring Web 应用上下文初始化完成后, 会将器存储在 `ServletContext` 中
3. 其次 ContextLoaderListener 监听器初始化完成之后, Tomcat 会开始初始化 web.xml 中配置的 Servlet,并执行其 `init` 方法,比如 `DispatcherServlet`:
- DispatcherServlet 就是前端控制器,用于转发、匹配、处理每一个 Servlet 请求, **并且它在初始化的时候会建立自己的 应用上下文**
- 它的`init` 方法在 `HttpServletBean` 这个类中实现,其主要工作是:
- 做一些初始化工作,将我们在web.xml中配置的参数书设置到Servlet中
- 然后再触发 `FrameworkServlet#initServletBean`方法,它有下面的作用:
- 初始化Spring子上下文,设置其父上下文,并将其放入ServletContext中
- 在调用 initServletBean() 的过程中同时会触发 DispatcherServlet#onRefresh()方法, 这个方法会初始化 SpringMvc 的各个功能组件。比如异常处理器、视图处理器、请求映射处理等。
- DispatcherServlet 初始化完成后,SpringMvc 会**以 Servlet 的名称作为 *key*, 也将其存储在 `ServletContext`中**, 这样每个 Servlet 都会有自己的 ApplicationContext 上下文
```java
// ContextLoaderListener
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
// highlight-start
public void contextInitialized(ServletContextEvent event) {
this.initWebApplicationContext(event.getServletContext());
}
public void contextDestroyed(ServletContextEvent event) {
this.closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
// highlight-end
}
// 初始化 WebApplicationContext
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
try {
if (this.context == null) {
// highlight-start
// 创建 WebApplicationContext
this.context = createWebApplicationContext(servletContext);
// highlight-end
}
if (this.context instanceof ConfigurableWebApplicationContext) {
// Servlet 自己的上下文
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
ApplicationContext parent = loadParentContext(servletContext);
// highlight-start
cwac.setParent(parent);
// highlight-end
}
// 配置和刷新 WebApplicationContext
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
// 将 WebApplicationContext 存储到 ServletContext
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}
return this.context;
}
catch (RuntimeException | Error ex) {
// ...
}
}
```
:::tip WebApplicationContext 和 DispatcherServlet 上下文的区别
1. WebApplicationContext 主要用于整个 Web 应用共享一些组件,而 DispatcherServlet 创建的 WebApplicationContext 主要用于该 Servlet 相关的组件,比如 Controller、ViewResolver
2. **对于作用范围而言,在 DispatcherServlet 中可以引用由 ContextLoaderListener 所创建的ApplicationContext, 而反过来不行**
3. 这两个 ApplicationContext 都通过 **ServletContext#setAttribute** 放在 ServletContext 中,但是 WebApplicationContext 会先存储进去,并且 DispatcherServlet 上下文会将 WebApplicationContext 作为自己的 parent-context
:::
#### 自动装配
##### ServletContainerInitializer
> - 自动装配依赖于 Servlet 3.0+, 在 Servlet 3.0 之后可以使用注解,比如 [@WebSevlet](基础知识#注册servlet组件注解)
> - 这种自动装配也是 SpringBoot 实现 web 应用部署在 嵌入式 Servlet 容器的实现方式
- Servlet 容器初始化接口: `ServletContainerInitializer`
- SpringMvc 的实现类: `SpringServletContainerInitializer`
- 处理类型注解: `@HandlesTypes`
- Spring Web 应用初始化器: `WebApplicationInitializer`
- 对应 ContextListener: `AbstractContextLoaderInitializer`
- 对应 DispatcherServlet [编码驱动]: `AbstractDispatcherServletInitializer`
- 对应 DispatcherServlet [注解驱动]: `AbstractAnnotationConfigDispatcherServletInitializer`
ServletContainerInitializer 是 Servlet 3.0+ 规范中提出 一个 **容器初始化器, 运行 Web 应用程序在启动的时候,通过编程的方式注册 Web 三大组件(Listener、Servlet、Filter),以取代 web.xml 配置**。并且 ServletContainerInitializer 是基于 java *SPI* 机制的,所以 Servlet 容器在启动的时候,通过 *SPI* 获取 放在 META-INF/service 目录下的 SPI 文件,然后执行其 `onStartUp` 方法,比如 SpringMvc 的 SpringServletContainerInitializer :
```txt title=spring-web-5.2.2.RELEASE.jar!/META-INF/services/javax.servlet.ServletContainerInitializer
org.springframework.web.SpringServletContainerInitializer
```
在 ServletContainerInitializer 上还可以使用 `@HandlesTypes` 注解,这样在执行 onStartup(Set<?>, ServletContext) 时,就会将指定处理类型的实现作为一个集合参数传入到方法中
##### SpringServletContainerInitializer
我们观察 SpringServletContainerInitializer 的源码:
1. Tomcat 会扫描所有实现了 `WebApplicationInitializer` 接口的子类,然后作为参数传给onStartup 方法中的第一个参数 Set 集合中
2. SpringMvc 获取到所有的实现类之后, 会分别调用实现类的 `onStartup` 方法,并且将 ServletContext 作为参数传入
```java
// highlight-start
@HandlesTypes(WebAp¬plicationInitializer.class)
// highlight-end
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses,
ServletContext servletContext) throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<>();
if (webAppInitializerClasses != null) {
for (Class<?> waiClass : webAppInitializerClasses) {
if (!waiClass.isInterface() &&
!Modifier.isAbstract(waiClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
try {
initializers.add((WebApplicationInitializer)ReflectionUtils.accessibleConstructor(waiClass).newInstance());
}
catch (Throwable ex) {
throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
}
}
}
}
if (initializers.isEmpty()) {
servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
return;
}
servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
initializer.onStartup(servletContext);
}
}
}
```
##### 基本示例
> 通过 SpringServletContainerInitializer 可以替代 web.xml,所以这里我们将 web.xml 注释掉,使用 WebApplicationInitializer 进行初始化
下面是使用示例,需要有以下的注意点:
1. 创建一个类实现抽象类: **AbstractAnnotationConfigDispatcherServletInitializer**
2. 定义 DispatcherServlet 配置类
- 由于没有 web.xml,所以不会SpringMvc 找不到根上下文的配置文件路径
- 可以通过重写 `getRootConfigClasses` 对根上下文进行配置
- `getServletConfigClasses` 方法返回的类会在 Servlet 应用上下文中进行注册,所以可以通过一些方式注册组件,比如 @ComponentScan 组件扫描
```java
// DispatcherServlet 配置类, ComponentScan 扫描组件
@ComponentScan("com.pacos")
public class DispatcherServletConfiguration {
}
/**
* {@link AbstractAnnotationConfigDispatcherServletInitializer} 的默认实现
* 用于配置 Servlet 组件
*
* @author <a href="mailto:zhuyuliangm@gmail.com">yuliang zhu</a>
* @see DispatcherServlet
*/
public class DefaultAbstractAnnotationConfigDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* 用于注册根应用上下文
* @return
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
/**
* 配置 servlet 配置类,用于注册 Servlet 应用上下文
* @return
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DispatcherServletConfiguration.class };
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
```
:::tip 为什么不直接实现 WebApplicationInitializer 接口?
WebApplicationInitializer 接口是顶层接口, 而 AbstractAnnotationConfigDispatcherServletInitializer 是子抽象类,已经实现了很多功能,所以只需要实现它进行拓展即可!
:::
### SpringBoot 的简化
> 在 SpringBoot 时代,我们既不需要定义 web.xml,也不需要手动实现 WebApplicationInitializer,而是引入 web 的 starter 就可以!
SpringBoot 中的 Mvc 有以下的特点:
1. 自动装配
- DispatcherServlet: DispatcherServletAutoConfiguration
- 替换 @EnableWebMvc: WebMvcAutoConfiguration
- Servlet 容器: ServletWebServerFactoryAutoConfiguration
2. 条件化装配
- Web 类型: @ConditionOnWebApplication
- API 依赖
- Bean 是否存在: @ConditionOnBean、@ConditionOnMissingBean
3. 外部化配置
- WebMvcProperties
以 SpringMvc 的 WebMvcAutoConfiguration 来说,它是 Mvc 相关 Bean 的自动装配配置类,并且在该配置类上还会标注 `@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)`,该注解表示如果 IOC 容器中不存在 WebMvcConfigurationSupport 类型的 Bean,则自动装配该配置类。而 WebMvcConfigurationSupport 则是为 @EnableWebMvc 注解提供自动装配的能力的类,这也是 SpringBoot 的条件化装配的能力。
#### 重构示例
首先需要引入 `tomcat-embed-jasper` 和 `jstl` 的依赖
```xml
<!-- 依赖引入 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- 引入插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
```
然后创建 SpringBoot 的启动引导类:
```java
// scanBasePackages 会扫描指定的路径的组件,包括 config/WebMvcConfig
@SpringBootApplication(scanBasePackages={"com.pacos"})
public class SpringBootWebMvcBootStrap {
public static void main(String[] args) {
new SpringApplicationBuilder(SpringBootWebMvcBootStrap.class)
.web(WebApplicationType.SERVLET)
.build()
.run(args);
}
}
```
然后为 ViewResolver 配置 prefix 和 suffix:
```yaml
spring:
mvc:
view:
prefix: /WEB-INF/jsp/
suffix: .jsp
```
:::caution 说明
如果使用了 @EnableWebMvc 注解启用 Mvc 功能,那么 SpringMvc 的自动装配就不会执行
```java
@AutoConfiguration(after = {
DispatcherServletAutoConfiguration.class,
TaskExecutionAutoConfiguration.class,
ValidationAutoConfiguration.class })
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
// highlight-start
// 这里的 WebMvcConfigurationSupport 就是 @EnableWebMvc 导入的类
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
// highlight-end
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class WebMvcAutoConfiguration {
// ...
}
```
:::
|
from django.shortcuts import render
from .form import ImageForm
from .models import Images
import pickle
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np
import requests
from bs4 import BeautifulSoup
import re
# Create your views here.
# Load the list from the file
with open("class_names.pkl", "rb") as file:
class_names = pickle.load(file)
# Load the model
model = load_model("food_model2.h5")
def home(request):
a = class_names
return render(request,"homepage.html", {'list':a})
def main(request):
if request.method == "POST":
form=ImageForm(data=request.POST,files=request.FILES)
if form.is_valid():
form.save()
obj=form.instance
imgg = image.load_img("."+obj.image.url, target_size=(224, 224))
x = image.img_to_array(imgg)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
pred = model.predict(images, batch_size=32)
prediction = class_names[np.argmax(pred)]
try:
url = 'https://www.google.com/search?&q=' + prediction + ' calories'
req = requests.get(url).text
scrap = BeautifulSoup(req, 'html.parser')
calories_table = scrap.find("table")
if calories_table:
calories = calories_table.text
a = calories.replace('%', '')
info = ''
else:
a = ""
info = "Information is not available right now"
except Exception as e:
a = ""
info = "Information is not available right now"
# Define regular expressions to extract different information
calories_regex = re.compile(r"১০০ gCalories \(kcal\) (\d+\.\d+)")
lipid_regex = re.compile(r"মান\*লিপিড (\d+\.\d+)")
carbohydrate_regex = re.compile(r"শর্করা (\d+)")
protein_regex = re.compile(r"প্রোটিন (\d+\.\d+)")
vitamin_c_regex = re.compile(r"ভিটামিন সি(\d+)")
calcium_regex = re.compile(r"ক্যালসিয়াম(\d+)")
iron_regex = re.compile(r"লোহা(\d+)")
vitamin_d_regex = re.compile(r"ভিটামিন ডি(\d+)")
magnesium_regex = re.compile(r"ম্যাগনেসিয়াম(\d+)")
sodium_regex = re.compile(r"সোডিয়াম (\d+)")
calories_match = calories_regex.search(a)
lipid_match = lipid_regex.search(a)
carbohydrate_match = carbohydrate_regex.search(a)
protein_match = protein_regex.search(a)
vitamin_c_match = vitamin_c_regex.search(a)
calcium_match = calcium_regex.search(a)
iron_match = iron_regex.search(a)
vitamin_d_match = vitamin_d_regex.search(a)
magnesium_match = magnesium_regex.search(a)
sodium_match = sodium_regex.search(a)
calories = calories_match.group(1) if calories_match else "N/A"
lipid = lipid_match.group(1) if lipid_match else "N/A"
carbohydrate = carbohydrate_match.group(1) if carbohydrate_match else "N/A"
protein = protein_match.group(1) if protein_match else "N/A"
vitamin_c = vitamin_c_match.group(1) if vitamin_c_match else "N/A"
calcium = calcium_match.group(1) if calcium_match else "N/A"
iron = iron_match.group(1) if iron_match else "N/A"
vitamin_d = vitamin_d_match.group(1) if vitamin_d_match else "N/A"
magnesium = magnesium_match.group(1) if magnesium_match else "N/A"
sodium = sodium_match.group(1) if sodium_match else "N/A"
def bn2en_number(number):
search_array = ["১", "২", "৩", "৪", "৫", "৬", "৭", "৮", "৯", "০"]
replace_array = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
en_number = number
for i in range(len(search_array)):
en_number = en_number.replace(search_array[i], replace_array[i])
return en_number
context = {
"info" : info,
"obj":obj,
"pred": class_names[np.argmax(pred)],
"Calories": bn2en_number(calories),
"Lipid" : bn2en_number(lipid),
"carbohydrate" : bn2en_number(carbohydrate),
"protein" : bn2en_number(protein),
"vitamin_c": bn2en_number(vitamin_c),
"calcium" : bn2en_number(calcium),
"iron": bn2en_number(iron),
"vitamin_d": bn2en_number(vitamin_d),
"magnesium": bn2en_number(magnesium),
"Sodium": bn2en_number(sodium),
}
return render(request,"main.html",context)
else:
form=ImageForm()
img=Images.objects.all()
return render(request,"main.html",{"img":img,"form":form})
|
import { useForm } from "@inertiajs/react";
import { useEffect, useState } from "react";
export default function CreateContact() {
const { data, setData, post, processing, errors } = useForm({
name: "",
type: "",
description: "",
});
const [isNotify, setIsNotify] = useState(false);
const submit = (e) => {
e.preventDefault();
post(route("setting.contact.store")),
{
onSuccess: () => {
setIsNotify("Contact created successfully");
},
onError: () => {
setIsNotify("Something went wrong");
},
};
};
useEffect(() => {
if (isNotify) {
setTimeout(() => {
setIsNotify(false);
}, 3000);
}
}, [isNotify]);
useEffect(() => {
setData({
name: "",
type: "",
description: "",
});
}, [processing]);
return (
<>
{isNotify && (
<div
className="bg-green-300 py-2 px-4 rounded-md text-green-800 fixed bottom-4 right-5 z-[1000]"
role="alert"
>
{isNotify}
</div>
)}
<form onSubmit={submit}>
<div className="mb-6">
<label
htmlFor="name"
className="block mb-2 text-sm font-medium text-gray-900"
>
Name
</label>
<input
type="text"
name="name"
value={data.name}
onChange={(e) => setData("name", e.target.value)}
className="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
/>
<p className="text-red-500">{errors.name}</p>
</div>
<div className="mb-6">
<label
htmlFor="type"
className="block mb-2 text-sm font-medium text-gray-900"
>
Type
</label>
<select
name="type"
value={data.type}
onChange={(e) => setData("type", e.target.value)}
className="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
>
<option value="">Select Type</option>
<option value="Customer">Customer</option>
<option value="Supplier">Supplier</option>
</select>
<p className="text-red-500">{errors.type}</p>
</div>
<div className="mb-6">
<label
htmlFor="description"
className="block mb-2 text-sm font-medium text-gray-900"
>
Description
</label>
<textarea
name="description"
value={data.description}
onChange={(e) => setData("description", e.target.value)}
className="shadow-sm bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5"
/>
<p className="text-red-500">{errors.description}</p>
</div>
<button
type="submit"
disabled={processing}
className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-md disabled:bg-slate-500 disabled:cursor-not-allowed"
>
{processing ? "Processing..." : "Submit"}
</button>
</form>
</>
);
}
|
<?php
/**
* @link http://github.com/hbhe/zantoto
* @copyright Copyright (c) 2020 Zantoto
* @license [New BSD License](http://www.opensource.org/licenses/bsd-license.php)
*/
namespace backend\controllers;
use common\models\Product;
use common\models\Sku;
use common\models\SkuSearch;
use Yii;
use yii\filters\VerbFilter;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
/**
* SkuController implements the CRUD actions for sku model.
*/
class SkuController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all sku models.
* @return mixed
*/
public function actionIndex()
{
$product = Product::findOne(['id' => Yii::$app->request->get('product_id')]);
if (Sku::findOne(['product_id' => $product->id]) === null) {
$product->initSku();
}
Yii::$app->user->setReturnUrl(Url::current());
$searchModel = new SkuSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
if (Yii::$app->request->isPost) {
$ids = Yii::$app->request->post('selection');
if (Yii::$app->request->post('begin')) {
$models = sku::findAll($ids);
foreach ($models as $model) {
$model->status = !$model->status;
$model->save(false);
}
}
}
return $this->render('index', [
'model' => $product,
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single sku model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new sku model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
if (isset($_POST['cancel'])) {
return $this->goBack();
}
$model = new sku();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->goBack();
// return $this->redirect(['index']);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing sku model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
if (isset($_POST['cancel'])) {
return $this->goBack();
}
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->goBack();
// return $this->redirect(['index']);
}
return $this->render('update', [
'model' => $model,
]);
}
/**
* Deletes an existing sku model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->goBack();
// return $this->redirect(['index']);
}
/**
* Finds the sku model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return sku the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = sku::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
|
Absolutely, in programming, you don't always need to implement data structures from scratch to use them.
--> You don't always need to implement data structures from scratch to use them
--> Use third-party libraries for DSA, or built-in or library implementations of common data structures and focus on solving the specific problem at hand
--> However, it is still important to have a basic understanding of the underlying principles of data structures and algorithms, as this will help you to choose the right library for your project and use it effectively.
--> (understand their basic properties, usage patterns, and performance characteristics,Focus on problem-solving strategie,Understand data structure usage patterns,Break down complex problems into smaller ones, practice)
Most programming languages, including TypeScript, Java, and Python, provide built-in or library implementations of common data structures.
Leveraging these pre-built data structures can save time and effort, allowing you to focus on solving the specific problem at hand.
Here's how you can use existing data structures in different languages:
### TypeScript:
1. **Arrays:**
TypeScript has built-in support for arrays. You can use them to store and manipulate collections of items.
```typescript
const myArray: number[] = [1, 2, 3, 4, 5];
```
2. **Objects/Maps:**
TypeScript supports objects and maps for key-value pairs.
```typescript
const myObject: Record<string, number> = { key: 42 };
```
3. **Sets:**
Sets are useful for maintaining a collection of unique values.
```typescript
const mySet: Set<number> = new Set([1, 2, 3]);
```
### Java:
Java has an extensive collection of data structures provided by the Java Collections Framework.
1. **ArrayList:**
```java
List<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
```
2. **HashMap:**
```java
Map<String, Integer> myMap = new HashMap<>();
myMap.put("key", 42);
```
3. **HashSet:**
```java
Set<Integer> mySet = new HashSet<>(Arrays.asList(1, 2, 3));
```
### Python:
Python offers a rich set of built-in data structures.
1. **List:**
```python
my_list = [1, 2, 3, 4, 5]
```
2. **Dictionary:**
```python
my_dict = {'key': 42}
```
3. **Set:**
```python
my_set = {1, 2, 3}
```
### Using Custom Libraries:
1. **Third-Party Libraries:**
Many languages have third-party libraries that offer specialized data structures and algorithms. For example, in TypeScript/JavaScript, you might use libraries like Lodash.
```typescript
import _ from 'lodash';
const myArray: number[] = [1, 2, 3, 4, 5];
const shuffledArray = _.shuffle(myArray);
```
2. **Standard Libraries:**
Leverage standard libraries and frameworks. For instance, in Java, the `java.util` package provides a wide range of data structures.
### General Approach:
1. **Understand Language Features:**
Learn about the built-in data structures and libraries that your programming language offers.
2. **Problem-Specific Choices:**
Choose the data structure that best fits the requirements of the problem you're solving.
3. **Efficiency:**
Understand the time and space complexity of the chosen data structure and algorithm.
4. **Abstraction:**
Use abstraction to encapsulate data structures within functions or classes, focusing on solving problems at a higher level.
In summary, while understanding how to implement data structures is valuable for learning and deeper insights, you can often use existing implementations provided by the language or third-party libraries to solve real-world problems more efficiently.
-----------------------------------------------------------------------------------------------------------------------------------------------------
Yes, data structures are fundamental components of programming and problem-solving. They provide efficient and organized ways to store, organize, and manipulate data, which is essential for developing effective algorithms and solving computational problems.
While it's valuable to understand the underlying principles and implementation of various data structures, you don't necessarily need to reinvent them from scratch every time you encounter a problem. Fortunately, most programming languages provide built-in data structure libraries or standard libraries that offer ready-to-use implementations of common data structures.
In languages like TypeScript, Java, and Python, you can leverage these built-in data structure libraries to solve problems without having to manually implement the data structures themselves. These libraries provide well-tested, optimized, and efficient implementations of data structures like arrays, linked lists, stacks, queues, trees, and maps.
For instance, in TypeScript, you can use the `Array` class to represent a collection of elements, the `Map` class to implement a hash table for efficient key-value lookup, and the `Set` class to maintain a collection of unique values. Similarly, in Java, the `ArrayList`, `HashMap`, and `HashSet` classes provide analogous functionalities.
Using built-in data structure libraries offers several advantages:
1. **Reduced development time:** You don't need to spend time implementing and debugging data structure implementations from scratch.
2. **Improved code readability:** Using well-known and standardized data structures makes your code more understandable and maintainable.
3. **Performance benefits:** Built-in data structures are often highly optimized for performance, ensuring efficient data manipulation and retrieval.
4. **Focus on problem-solving:** You can focus on the problem-solving aspects of your code rather than reinventing data structures.
To effectively use data structure libraries in your code, follow these guidelines:
1. **Familiarize yourself with the available data structures:** Understand the strengths, weaknesses, and usage patterns of the data structures provided by the language's standard library.
2. **Choose the right data structure for the problem:** Select the data structure that best suits the specific requirements of your problem, considering factors like access patterns, data relationships, and performance constraints.
3. **Utilize the library's methods and APIs:** Leverage the built-in methods and APIs provided by the data structure library to manipulate and access data efficiently.
4. **Understand the library's implementation details:** While you don't need to implement the data structures yourself, having a basic understanding of their underlying principles can help you choose the right structure and use it effectively.
By effectively utilizing built-in data structure libraries, you can significantly improve your programming productivity and focus on the problem-solving aspects of your code, ensuring efficient and reliable solutions.
-------------------------------------------------------------------------------------------------------------------------------
Data structures are indeed crucial in programming and problem-solving. They provide a way to organize and store data so that they can be accessed and worked with efficiently. Many programming languages, including TypeScript, Java, and Python, provide built-in data structures that you can use directly without having to implement them from scratch.
**TypeScript:**
In TypeScript, you can use built-in data structures like Arrays, Sets, Maps, and more. TypeScript also has support for classes and interfaces, which you can use to create custom data structures. Here's an example of a Stack implemented in TypeScript:
```typescript
class Stack<T> {
private items: T[] = [];
push(item: T) {
this.items.push(item);
}
pop(): T | undefined {
return this.items.pop();
}
peek(): T | undefined {
return this.items[this.items.length - 1];
}
}
```
In this example, the `Stack` class uses an array to store its items. The `push` method adds an item to the top of the stack, the `pop` method removes an item from the top of the stack, and the `peek` method returns the item at the top of the stack without removing it [Source 2](https://dev.to/glebirovich/typescript-data-structures-stack-and-queue-hld).
**Java:**
In Java, you can use built-in data structures like ArrayList, LinkedList, HashSet, HashMap, and more. Java also has support for classes and interfaces, which you can use to create custom data structures. Here's an example of a Stack implemented in Java:
```java
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
System.out.println(stack.pop()); // Output: 2
System.out.println(stack.peek()); // Output: 1
}
}
```
In this example, the `Stack` class is part of the Java standard library. The `push` method adds an item to the top of the stack, the `pop` method removes an item from the top of the stack, and the `peek` method returns the item at the top of the stack without removing it.
**Python:**
In Python, you can use built-in data structures like list, set, dict, and more. Python also has support for classes, which you can use to create custom data structures. Here's an example of a Stack implemented in Python:
```python
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
```
In this example, the `Stack` class uses a list to store its items. The `push` method adds an item to the top of the stack, the `pop` method removes an item from the top of the stack, and the `peek` method returns the item at the top of the stack without removing it.
In conclusion, many programming languages provide built-in data structures that you can use directly without having to implement them from scratch. These built-in data structures are ready for use and can help you solve problems more efficiently [Source 0](https://www.npmjs.com/package/data-structure-typed), [Source 1](https://www.geeksforgeeks.org/learn-data-structures-with-javascript-dsa-tutorial/), [Source 3](https://www.freecodecamp.org/news/data-structures-in-javascript-with-examples/), [Source 6](https://www.educative.io/blog/javascript-data-structures), [Source 7](https://dev.to/kartik2406/built-in-data-structures-in-javascript-hhl), [Source 8](https://www.freecodecamp.org/news/an-introduction-to-typescript/), [Source 9](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-oop.html).
....
|
import { useComment } from "../store/CommentContext";
import DeleteButton from "../ui/DeleteButton";
import EditButton from "../ui/EditButton";
import ReplyButton from "../ui/ReplyButton";
import { timeAgo } from "../utils/helpers";
/* eslint-disable react/prop-types */
const User = ({ user, createdAt, onReply, onEdit, onDelete }) => {
const { currentUser } = useComment();
const time = Number(createdAt);
console.log(time);
return (
<div className="flex gap-4 items-center justify-between flex-wrap ">
<div className="flex gap-4 items-center">
<img src={user.image.png} alt="user" className="w-12" />
<span className="font-bold">{user.username}</span>
{currentUser.username === user.username && (
<span className="bg-[#5457b6] text-white py-1 px-2 rounded-md">
YOU
</span>
)}
<span className="text-[#67727e]">
{isNaN(time) ? createdAt : timeAgo(time)}
</span>
</div>
{user.username === currentUser.username ? (
<div className="md:flex items-center gap-2 hidden">
<DeleteButton onClick={onDelete} />
<EditButton onEdit={onEdit} />
</div>
) : (
<ReplyButton
user={user}
onReply={onReply}
className="hidden md:flex items-center gap-2"
/>
)}
</div>
);
};
export default User;
|
package com.example.teammanagement.controller;
import com.example.teammanagement.model.Task;
import com.example.teammanagement.model.TaskStatus;
import com.example.teammanagement.model.dtos.AddTaskDto;
import com.example.teammanagement.model.dtos.TaskDto;
import com.example.teammanagement.model.dtos.UpdateTaskDto;
import com.example.teammanagement.service.TaskService;
import com.example.teammanagement.specification.TaskCriteria;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/task")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TaskController {
private final TaskService taskService;
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Long addTask(@RequestBody AddTaskDto addTaskDto) {
return taskService.addTask(addTaskDto);
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.CREATED)
public Long updateTask(@PathVariable Long id, @RequestBody UpdateTaskDto updateTaskDto) {
return taskService.updateTask(id, updateTaskDto);
}
@PutMapping("/{id}/status")
@ResponseStatus(HttpStatus.CREATED)
public Long changeStatus(@PathVariable Long id, @RequestParam TaskStatus taskStatus) {
return taskService.changeStatus(id, taskStatus);
}
@PutMapping("/{id}/users")
@ResponseStatus(HttpStatus.CREATED)
public Long addUsersToTask(@PathVariable Long id, @RequestParam List<Long> userIds) {
return taskService.addUsersToTask(id, userIds);
}
@GetMapping
public Page<TaskDto> getTasks(TaskCriteria taskCriteria, Pageable pageable) {
return taskService.getTasks(taskCriteria, pageable);
}
@DeleteMapping("/{id}")
public void deleteTasks(@PathVariable Long id) {
taskService.deleteTask(id);
}
}
|
TITLE Segment Example (main module, Seg2.asm)
; Startup module, which calls a procedure located in an
; external module. Build this program using the make16.bat
; file located in the same directory.
; Last update: 06/01/2006
EXTRN var2:WORD
;subroutine_1 PROTO ; replaced by the following line:
EXTERN subroutine_1:PROC ; required by MASM 8.0
cseg SEGMENT BYTE PUBLIC 'CODE'
ASSUME cs:cseg,ds:dseg, ss:sseg
main PROC
mov ax,dseg ; initialize DS
mov ds,ax
mov ax,var1 ; local variable
mov bx,var2 ; external variable
call subroutine_1 ; external procedure
mov ax,4C00h ; exit to OS
int 21h
main ENDP
cseg ENDS
dseg SEGMENT WORD PUBLIC 'DATA' ; local data segment
var1 WORD 1000h
dseg ends
sseg SEGMENT STACK 'STACK' ; stack segment
BYTE 100h dup('S')
sseg ENDS
END main
|
import { chunk } from "lodash";
import moment from "moment";
import { DayDate } from "../types";
import { NUM_DAYS_IN_WEEK } from "./constants";
const PADDING_DAY = {
year: -1,
month: -1,
day: -1,
};
/**
*
* @param year
* @returns
*/
export const getWeekChunksForYearGrid = (year: number): DayDate[][] => {
const yearMoment = moment(new Date(year, 0, 1)).startOf("year");
const daysBeforeYear: DayDate[] = Array.from(
Array(yearMoment.weekday()),
(_, i) => ({ ...PADDING_DAY })
);
const daysAfterYear: DayDate[] = Array.from(
Array(NUM_DAYS_IN_WEEK - (yearMoment.endOf("year").weekday() + 1)),
(_, i) => ({ ...PADDING_DAY })
);
const daysInYear: DayDate[] = [];
let iterYearMoment = yearMoment.startOf("year").clone();
while (iterYearMoment.year() === year) {
daysInYear.push(getDayDateFromMoment(iterYearMoment));
iterYearMoment = iterYearMoment.add(1, "day");
}
const chunks = chunk(
[...daysBeforeYear, ...daysInYear, ...daysAfterYear],
NUM_DAYS_IN_WEEK
);
return chunks;
};
/**
*
* @param param0
* @returns
*/
export const getDateKey = ({ year, month, day }: DayDate): string => {
const monthStr = month <= 9 ? `0${month}` : month;
const dayStr = day <= 9 ? `0${day}` : day;
return `${year}_${monthStr}_${dayStr}`;
};
/**
*
* @param param0
* @returns
*/
export const getMomentFromDayDate = ({
year,
month,
day,
}: DayDate): moment.Moment => {
return moment(new Date(year, month, day));
};
/**
*
* @param input
* @returns
*/
export const getDayDateFromMoment = (input: moment.Moment): DayDate => {
return { year: input.year(), month: input.month(), day: input.date() };
};
/**
*
* @param param0
* @returns
*/
export const isToday = ({ year, month, day }: DayDate): boolean => {
const inputMoment = getMomentFromDayDate({ year, month, day });
return inputMoment.isSame(moment(), "D");
};
/**
*
* @param param0
* @returns
*/
export const isYesterday = ({ year, month, day }: DayDate): boolean => {
const inputMoment = getMomentFromDayDate({ year, month, day });
return inputMoment.isSame(moment().add(-1, "day"), "day");
};
/**
*
* @returns
*/
export const getDayOfWeekLabels = (): string[] => {
const startMoment = moment(new Date()).startOf("week");
return Array.from(
Array(NUM_DAYS_IN_WEEK),
(_, i) => startMoment.weekday(i).format("dd")[0]
);
};
|
import React, { useState } from "react";
import axios from "axios";
// import uploader from "./../../images/uploader.png";
import swal from "sweetalert";
import "./Login.css";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import Cookies from "universal-cookie";
import { useDispatch } from "react-redux";
import { currentUserData } from "../../Redux/UserReducer";
import { setSideBar } from "../../Redux/UserReducer";
import { SERVERURL } from "../../ServerUrl";
const Login = () => {
const dispatch=useDispatch();
const navigate=useNavigate();
const [user, setUser] = useState({
email: "",
password: "",
});
const cookies = new Cookies();
const handleChange = (e) => {
const { name, value } = e.target;
setUser({ ...user, [name]: value });
};
const loginClicked = async () => {
try{
const response = await axios.post(`${SERVERURL}/login`, user);
console.log("response", response);
cookies.set("_id", response?.data?.user?._id, { path: "/" });
cookies.set("token", response?.data?.token, { path: "/" });
if(response?.data?.status)
{
dispatch(currentUserData(response?.data?.user))
dispatch(setSideBar("dashBoard"))
navigate('/dashboard')
swal ( "Successfully" , response?.data?.message , "success" )
}
}catch(error)
{
console.error("error",error);
swal ( "Failed" , error?.response?.data?.message, "error" )
}
};
return (
<>
<div className="mainLogin">
<div className="loginCard">
<div className="signInTxt">SIGN IN</div>
<input
className="inputLogin"
placeholder="Email"
type="email"
name="email"
onChange={handleChange}
/>
<input
className="inputLogin"
placeholder="Password"
type="password"
name="password"
onChange={handleChange}
/>
<div className="btnLogin" onClick={loginClicked}>
LOGIN
</div>
<Link to="/signup" style={{ textDecoration: "none" }}>
{" "}
<div className="creatAccTxt">Create new Account?</div>
</Link>
</div>
</div>
</>
);
};
export default Login;
|
import {
Body,
Controller,
Get,
Param,
Post,
Put,
Query,
Res,
UploadedFile,
UseGuards,
UseInterceptors,
UsePipes,
ValidationPipe,
} from '@nestjs/common';
import { FaceSwapperService } from './face-swapper.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { MinioService } from './minio/minio.service';
import { UsersService } from './users/users.service';
import { VkAuthGuard } from '../guards/vk-auth/vk-auth.guard';
import { Response } from 'express';
import { User } from '../decorators/User.decorator';
import { VkRequestAuthGuard } from '../guards/vk-auth/vk-request-auth.guard';
@Controller('api/face-swapper')
export class FaceSwapperController {
constructor(
private readonly minioService: MinioService,
private readonly faceSwapperService: FaceSwapperService,
private readonly usersService: UsersService,
) {}
@Get('image')
async getImage(@Res() res: Response, @Query('path') path: string) {
const stream = (await this.minioService.getFile(path)) as any;
res.setHeader('Content-Type', stream.headers['content-type']);
stream.pipe(res);
}
@UseGuards(VkAuthGuard)
@UsePipes(ValidationPipe)
@UseInterceptors(FileInterceptor('source'))
@Post()
async swapFace(
@User() user: string,
@UploadedFile() source: Express.Multer.File,
@Body('target') target: string,
) {
return await this.faceSwapperService.swapFace(user, source, target);
}
@UseGuards(VkAuthGuard)
@Get('result/:id')
async getGeneratedImage(@Param('id') id: string) {
return await this.faceSwapperService.getResult(id);
}
@UseGuards(VkAuthGuard)
@Get('base-images')
async getImages(@Query('sex') sex: string = 'male') {
return await this.minioService.getCategories(sex);
}
@UseGuards(VkAuthGuard)
@Get('limits')
async getLimit(@User() user: string) {
return this.usersService.getLimit(user);
}
@UseGuards(VkAuthGuard, VkRequestAuthGuard)
@Put('limits')
async setUser(@User() user: string, @Body('groupIds') groupIds?: number[]) {
return await this.usersService.setSubscription(user, groupIds);
}
}
|
import React, { useEffect } from 'react';
import { useState } from 'react';
import { storage } from '../../model/Storage';
import Days from './components/Days/Days';
import ThisDay from './components/ThisDay/ThisDay';
import ThisDayInfo from './components/ThisDayInfo/ThisDayInfo';
import s from './Home.module.scss';
import { useDispatch, useSelector } from 'react-redux';
import { getInfo } from '../../redux/actions';
import SkeletonThisDay from './SkeletonThisDay';
import SkeletonThisDayInfo from './SkeletonThisDayInfo';
function Home() {
const [city, setCity] = useState(storage.getItem("gorod"));
setInterval(() => {
setCity(storage.getItem("gorod"));
}, 1000);
const { info, loading } = useSelector((state) => {
return state.getWeatherInfoReducer;
});
const disptach = useDispatch();
useEffect(() => {
disptach(getInfo());
}, [city]);
return (
<div className={s.home}>
<div className={s.wrapper}>
{loading ? (
<SkeletonThisDay className={s.skeletonThisDay}/>
) : (
<ThisDay
className={s.this__day}
temp={info.main && Math.floor(info.main.temp)}
icon={info.weather && info.weather[0].icon}
/>
)}
{loading ? (
<SkeletonThisDayInfo className={s.skeletonThisDayInfo}/>
) : (
<ThisDayInfo
temp={info.main && Math.floor(info.main.temp)}
feelsLike={info.main && Math.floor(info.main.feels_like)}
pressure={info.main && info.main.pressure}
humidity={info.main && info.main.humidity}
speed={info.wind && Math.floor(info.wind.speed)}
/>
)}
</div>
<Days />
</div>
);
}
export default Home;
|
import {Component, OnDestroy} from '@angular/core';
import {combineLatest, Subscription} from "rxjs";
import {AuthService} from "../../core/service/auth/auth.service";
import {SnackbarService} from "../../core/service/snackbar.service";
import {StorageService} from "../../core/service/storage.service";
import {Router} from "@angular/router";
import {HttpService} from "../../core/service/http/http.service";
import {ItemCategoryDTO} from "../../shared/models/dto.models";
import {ItemResponse} from "../../shared/models/rest.models";
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css'],
})
export class HeaderComponent implements OnDestroy {
loggedIn: boolean = false;
userRoles?: string[];
private allSubscriptions: Subscription[] = [];
searchText: string;
itemCategories: string[] = [];
selectedCategory: string;
constructor(public authService: AuthService,
private snackbarService: SnackbarService,
private storageService: StorageService,
private httpService: HttpService,
private router: Router
) {
this.allSubscriptions.push(
combineLatest([this.authService.getIsLoggedIn(), this.storageService.getUserRoles()])
.subscribe(userData => {
this.loggedIn = userData[0];
this.userRoles = userData[1];
}));
this.allSubscriptions.push(
this.httpService.getAllItemCategories()
.subscribe({
next: (next: ItemResponse): void => {
this.itemCategories = next.itemCategories
.map((itemCategory: ItemCategoryDTO) => itemCategory.category);
}
})
);
}
logout(): void {
this.storageService.signOut();
this.authService.announceLogout();
this.snackbarService.openSnackBar('Logged out!');
this.router.navigate(['/']);
}
ngOnDestroy(): void {
this.allSubscriptions.forEach((subscription: Subscription) => subscription.unsubscribe());
}
navigateToCart(): void {
this.selectedCategory = 'all';
this.router.navigate(['/cart']);
}
navigateToAccountInformation(): void {
this.selectedCategory = 'all';
this.router.navigate(['/account']);
}
navigateToComplaints(): void {
this.selectedCategory = 'all';
this.router.navigate(['complaints']);
}
navigateToOrderHistory(): void {
this.selectedCategory = 'all';
this.router.navigate(['orders']);
}
navigateToAllOrders(): void {
this.selectedCategory = 'all';
this.router.navigate(['orders/all']);
}
navigateToItemCategories(): void {
this.selectedCategory = 'all';
this.router.navigate(['item-categories']);
}
checkEnterKeyPressed($event): void {
if ($event.key === 'Enter') {
this.navigateToSearch();
}
}
navigateToSearch(): void {
this.router.navigate(['/search'], {
queryParams: {
category: this.selectedCategory ? this.selectedCategory : 'all',
searchText: this.searchText ? this.searchText : 'all'
}
});
}
navigateToHome(): void {
this.searchText = '';
if (this.router.url !== '/') {
this.selectedCategory = 'all';
this.router.navigate(['/']);
} else {
window.location.reload();
}
}
navigateToItemList(): void {
this.router.navigate(['items']);
}
selectCategory(itemCategory: string): void {
this.selectedCategory = itemCategory;
}
}
|
import 'package:flutter/material.dart';
import 'package:feather_icons/feather_icons.dart';
class BMI2Screen extends StatefulWidget {
const BMI2Screen({Key? key}) : super(key: key);
@override
_BMI2ScreenState createState() => _BMI2ScreenState();
}
class _BMI2ScreenState extends State<BMI2Screen> {
String selectedGender = 'Male';
final List<String> genders = ['Male', 'Female'];
TextEditingController weightController = TextEditingController();
TextEditingController heightController = TextEditingController();
TextEditingController ageController = TextEditingController();
double bmiResult = 0.0;
String bmiCategory = "";
Color backgroundColor = Color(0xfff7f7f7);
Color textfieldColor = Color(0xfff7f7f7);
Color buttonColor = Color(0xFF8d8cd4);
Color textbuttonColor = Colors.white;
void calculateBMI() {
double weight = double.tryParse(weightController.text) ?? 0;
double height = double.tryParse(heightController.text) ?? 0;
int age = int.tryParse(ageController.text) ?? 0;
// Perhitungan BMI
if (weight > 0 && height > 0) {
double heightInMeters = height / 100;
double bmi = weight / (heightInMeters * heightInMeters);
setState(() {
bmiResult = bmi;
if (bmi < 18.5) {
bmiCategory = "Underweight";
backgroundColor = Color(0xFF87b1e2);
textfieldColor = Color(0xFF87b1e2);
buttonColor = Color(0xfff7f7f7);
textbuttonColor = Colors.black;
} else if (bmi < 24.9) {
bmiCategory = "Normal";
backgroundColor = Color(0xFFc1e898);
textfieldColor = Color(0xFFc1e898);
buttonColor = Color(0xfff7f7f7);
textbuttonColor = Colors.black;
} else if (bmi < 29.9) {
bmiCategory = "Overweight";
backgroundColor = Color(0xFFf9e485);
textfieldColor = Color(0xFFf9e485);
buttonColor = Color(0xfff7f7f7);
textbuttonColor = Colors.black;
} else {
bmiCategory = "Obesity";
backgroundColor = Color(0xFFf28a8a);
textfieldColor = Color(0xFFf28a8a);
buttonColor = Color(0xfff7f7f7);
textbuttonColor = Colors.black;
}
});
}
}
@override
Widget build(BuildContext context) {
return Material(
child: Container(
color: backgroundColor,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Padding(
padding: const EdgeInsets.only(top: 25.0),
child: IconButton(
onPressed: () {
Navigator.of(context).pop();
},
icon: Icon(
FeatherIcons.arrowLeft,
color: Colors.black,
size: 27,
),
),
),
],
),
Padding(
padding: const EdgeInsets.only(left: 50.0, top: 30),
child: Text(
"Health App",
style: TextStyle(
fontFamily: "poppinsmedium",
fontSize: 20,
color: Color(0xff838383),
),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 50.0),
child: Text(
"CALCULATE YOUR BMI",
style: TextStyle(
color: Colors.black,
fontFamily: "poppinssemibold",
fontSize: 30,
),
),
),
SizedBox(height: 200,),
Row(
children: [
Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 25.0),
child: Text(
"Gender",
style: TextStyle(
fontFamily: "poppinsmedium",
fontSize: 16,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 50.0),
child: DropdownButton<String>(
value: selectedGender,
onChanged: (String? newValue) {
setState(() {
selectedGender = newValue!;
});
},
items: genders
.map<DropdownMenuItem<String>>(
(String value) => DropdownMenuItem<String>(
value: value,
child: Text(value,
style: TextStyle(
color: Color(0xff838383),
fontFamily: "poppinsmedium",
fontSize: 16
),),
),
)
.toList(),
underline: Container(
height: 1,
color: Color(0xff838383),
),
),
),
],
),
SizedBox(width: 100,),
Column(
children: [
Padding(
padding: const EdgeInsets.only(right: 65),
child: Text(
"Age",
style: TextStyle(
fontFamily: "poppinsmedium",
fontSize: 16,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.only(bottom:10.0),
child: Container(
width: 100,
height: 40,
child: TextField(
keyboardType: TextInputType.number,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xff838383), width: 1), // Garis bawah saat input difokuskan
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xff838383), width: 1), // Garis bawah saat input tidak difokuskan
),
filled: true,
fillColor: textfieldColor,
contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
),
style: TextStyle(fontSize: 14),
),
),
),
],
),
],
),
Padding(
padding: const EdgeInsets.symmetric(horizontal:20.0, vertical: 20),
child: Row(
children: [
Column(
children: [
Padding(
padding: const EdgeInsets.only(left: 25.0),
child: Text(
"Height (cm)",
style: TextStyle(
fontFamily: "poppinsmedium",
fontSize: 16,
color: Colors.black,
),
),
),
Padding(
padding: const EdgeInsets.only(left: 30,bottom:10.0),
child: Container(
width: 100,
height: 40,
child: TextField(
controller: heightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xff838383), width: 1), // Garis bawah saat input difokuskan
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xff838383), width: 1), // Garis bawah saat input tidak difokuskan
),
filled: true,
fillColor: textfieldColor,
contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
),
style: TextStyle(fontSize: 14),
),
),
),
],
),
SizedBox(width: 82,),
Column(
children: [
Text(
"Weight (kg)",
style: TextStyle(
fontFamily: "poppinsmedium",
fontSize: 16,
color: Colors.black,
),
),
Padding(
padding: const EdgeInsets.only(bottom:10.0),
child: Container(
width: 100,
height: 40,
child: TextField(
controller: weightController,
keyboardType: TextInputType.number,
decoration: InputDecoration(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xff838383), width: 1), // Garis bawah saat input difokuskan
),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Color(0xff838383), width: 1), // Garis bawah saat input tidak difokuskan
),
filled: true,
fillColor: textfieldColor,
contentPadding: EdgeInsets.symmetric(vertical: 10, horizontal: 10),
),
style: TextStyle(fontSize: 14),
),
),
),
],
),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 50),
child: Center(
child: SizedBox(
height: 50,
width: 250,
child: Material(
color: buttonColor,
borderRadius: BorderRadius.circular(5),
child: InkWell(
onTap: calculateBMI,
// onTap: (){
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) => HomeScreen(),
// ));
// },
child: Padding(
padding:
EdgeInsets.symmetric(vertical: 5, horizontal: 40),
child: Center(
child: Text(
"CALCULATE",
style: TextStyle(
color: textbuttonColor,
fontSize: 16,
fontFamily: 'poppinsmedium',
),
),
),
),
)
),
),
),
),
bmiResult > 0
?
Padding(
padding: const EdgeInsets.only(top:20.0,),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"Your BMI: ${bmiResult.toStringAsFixed(2)}",
style: TextStyle(
fontFamily: "poppinsmedium",
fontSize: 18,
color: Colors.black,
),
),
SizedBox(width: 5,),
Text(
bmiCategory,
style: TextStyle(
fontFamily: "poppinsmedium",
fontSize: 18,
color: Colors.black,
),
),
],
),
)
: SizedBox(), // Tidak menampilkan jika hasil BMI adalah 0
],
),
),
);
}
}
|
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import { serverHost } from '@/config';
import Spinner from '@components/Spinner';
import styles from './InventoryDetails.module.css';
import useFetch from '../../hooks/useFetch';
import useToken from '../../hooks/useToken';
function InventoryDetails({ itemId }) {
const [info, setInfo] = useState({});
const [itemType, setItemType] = useState('');
const token = useToken();
const {
callFetch, result, error, loading,
} = useFetch();
useEffect(() => {
if (!result) return;
setInfo(() => (result[0]));
setItemType(() => result[0].type);
}, [result]);
useEffect(() => {
}, [error]);
useEffect(() => {
const uri = `${serverHost}/inventory?id=${itemId}`;
callFetch({
uri,
method: 'GET',
headers: { Authorization: token },
removeContentType: true,
});
}, []);
return (
<div className={styles.mainContainer}>
{loading && (
<Spinner />
)}
{!loading && !error && (
<div className={styles.detailsContainer}>
<span className={styles.title}>
{'Descripción del '}
{itemType.toLowerCase()}
</span>
<hr className={styles.divider} />
<div className={styles.rowContainer}>
<div className={styles.sectionContainer}>
<span className={styles.sectionTitle}>Descripción</span>
<span className={styles.sectionContent}>
{info.materialName}
</span>
</div>
<div className={styles.sectionContainer}>
<span className={styles.sectionTitle}>Categoría</span>
<span className={styles.sectionContent}>{info.materialType}</span>
</div>
</div>
<div className={styles.rowContainer}>
<div className={styles.sectionContainer}>
<span className={styles.sectionTitle}>Cantidad</span>
<span className={styles.sectionContent}>{`${info.quantity} ${info.measurementUnit}`}</span>
</div>
<div className={styles.sectionContainer}>
<span className={styles.sectionTitle}>Proveedor</span>
<span className={styles.sectionContent}>{info.supplier}</span>
</div>
</div>
<div className={styles.rowContainer}>
<div className={styles.sectionContainer}>
<span className={styles.sectionTitle}>Detalles</span>
<span className={styles.sectionContent}>{info.details}</span>
</div>
</div>
</div>
)}
{error && (
<span>Ocurrió un error al buscar los detalles de este artículo</span>
)}
</div>
);
}
InventoryDetails.propTypes = {
itemId: PropTypes.string.isRequired,
};
export default InventoryDetails;
|
<template>
<form @submit="checkData" class="login__form">
<input-data @passData="updateData" />
<div v-if="isErrorLogin" class="login__input__error">Введите логин.</div>
<div v-if="isErrorPass" class="login__input__error">Введите пароль.</div>
<login-checkbox @passData="updateFlagPass" />
<login-button />
</form>
</template>
<script>
import InputData from "./Input/InputData.vue";
import LoginCheckbox from "./LoginCheckbox.vue";
import LoginButton from "./LoginButton.vue";
export default {
components: {
InputData,
LoginCheckbox,
LoginButton,
},
data() {
return {
login: "",
isErrorLogin: false,
password: "",
isErrorPass: false,
memorizePass: false,
};
},
methods: {
updateData(data) {
this.login = data.login;
this.password = data.password;
},
updateFlagPass(value) {
this.memorizePass = value;
},
checkData(event) {
if (this.login == "" || this.password == "") {
event.preventDefault();
if (this.login) {
this.isErrorLogin = false;
} else {
this.isErrorLogin = true;
return false;
}
this.password ? (this.isErrorPass = false) : (this.isErrorPass = true);
} else {
this.sendData();
}
},
sendData() {
alert(`login: ${this.login} password: ${this.password} memorize password?: ${this.memorizePass ? "yes" : "no"}`);
},
},
};
</script>
|
package hust.soict.dsai.aims.media;
import java.time.LocalDate;
import java.util.Comparator;
public abstract class Media {
private String title;
private String category;
private float cost;
private int id;
private static int nbMedia;
public static final Comparator<Media> COMPARE_BY_TITLE_COST = new MediaComparatorByTitleCost();
public static final Comparator<Media> COMPARE_BY_COST_TITLE = new MediaComparatorByCostTitle();
public Media(String title) {
this.title = title;
nbMedia++;
this.id = nbMedia;
}
public Media(String title, float cost) {
this(title);
this.cost = cost;
}
public Media(String title, String category, float cost) {
this(title);
this.category = category;
this.cost = cost;
}
public int getID() {
return id;
}
public String getTitle() {
return title;
}
public String getCategory() {
return category;
}
public float getCost() {
return cost;
}
public boolean equals(Object medium) {
if (medium instanceof Media) {
try {
Media that = (Media) medium;
return this.title.toLowerCase().equals(that.getTitle().toLowerCase());
} catch (NullPointerException e1) {
return false;
} catch (ClassCastException e2) {
return false;
}
} else {
return false;
}
}
public boolean search(String title) {
return this.title.toLowerCase().contains(title.toLowerCase());
}
public abstract String toString();
}
|
import React, { Component } from 'react';
import { View, StyleSheet, Text, FlatList,TouchableOpacity } from 'react-native';
import { ListItem } from 'react-native-elements'
import firebase from 'firebase';
import db from '../Config'
import MyHeader from '../components/MyHeader';
import {SafeAreaProvider} from "react-native-safe-area-context";
export default class HomeScreen extends Component{
constructor(){
super();
this.state={
username: firebase.auth().currentUser.email,
requestedExchange : []
}
this.requestRef = null;
}
getExchangeRequests=()=>{
this.requestRef = db.collection("exchange_requests")
.onSnapshot((snapshot)=>{
var requestedExchange = snapshot.docs.map((doc) => doc.data())
this.setState({
requestedExchange: requestedExchange
});
})
}
componentDidMount(){
this.getExchangeRequests();
}
componentWillUnmount(){
this.requestRef = null;
}
keyExtractor = (item, index) => index.toString()
renderItem = ( {item, i} ) =>{
return (
<ListItem
key={i}
title={item.item_name}
subtitle={item.description}
titleStyle={{ color: 'black', fontWeight: 'bold' }}
rightElement={
<TouchableOpacity style={styles.button}>
<Text style={{color:'#ffff'}}>Exchange</Text>
</TouchableOpacity>
}
bottomDivider
/>
)
}
render(){
return(
<SafeAreaProvider>
<View style={{flex: 1}}>
<MyHeader title="Home Screen" navigation ={this.props.navigation}/>
<View style={{flex: 1}}>
{
this.state.requestedExchange.length === 0
?(
<View style={styles.subContainer}>
<Text style={{ fontSize: 20}}>List Of All Requested Exchange</Text>
</View>
)
:(
<FlatList
keyExtractor={this.keyExtractor}
data={this.state.requestedExchange}
renderItem={this.renderItem}
/>
)
}
</View>
</View>
</SafeAreaProvider>
)
}
}
const styles = StyleSheet.create({
subContainer:{
flex:1,
fontSize: 20,
justifyContent:'center',
alignItems:'center'
},
button:{
width:100,
height:30,
justifyContent:'center',
alignItems:'center',
backgroundColor:"#ff5722",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 8
}
}
})
|
"use client";
import React, { useEffect, useState, useTransition } from "react";
import {
DrawerProfile,
DrawerClose,
DrawerContent,
DrawerFooter,
DrawerHeader,
DrawerTrigger,
} from "../ui/drawer-profile";
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "@/components/ui/form";
import { zodResolver } from "@hookform/resolvers/zod";
import { cn, handleErrorApi } from "@/lib/utils";
import { useSidebarStore } from "@/stores/sidebar-stores";
import Image from "next/image";
import { Button } from "../ui/button";
import Link from "next/link";
import ProfileForm from "../admin/profile/profile-form";
import { Switch } from "../ui/switch";
import { Separator } from "../ui/separator";
import { UpgradeMembershipButton } from "./upgrade-membership-button";
import accountApiRequest from "@/app/apiRequests/account";
import { Skeleton } from "@/components/ui/skeleton";
import {
AccountResType,
AccountSchema,
UpdateAccountBodyType,
UserSubscriptionResType,
} from "@/schemas/account.schema";
import { LogOut } from "lucide-react";
import "@/app/globals.css";
import authApiRequest from "@/app/apiRequests/auth";
import { Input } from "../ui/input";
import { useToast } from "../ui/use-toast";
import { useRouter } from "next/navigation";
import { CreateChatbotBodyType } from "@/schemas/create-chatbot.schema";
import { useForm } from "react-hook-form";
const Profile = () => {
const { isMinimal, handleClose } = useSidebarStore();
const [account, setAccount] = useState<AccountResType | null>(null);
const [userSubscription, setUserSubscription] =
useState<UserSubscriptionResType | null>(null);
const [isEditing, setIsEditing] = useState(false);
const [loading, setLoading] = useState(false);
const [isPending, startTransition] = useTransition();
const { toast } = useToast();
const router = useRouter();
const form = useForm<UpdateAccountBodyType>({
resolver: zodResolver(AccountSchema),
defaultValues: {
email: "",
display_name: "",
},
});
const handleLogout = async () => {
try {
await authApiRequest.logoutFromNextClientToNextServer();
toast({
title: "Success",
description: "Sign out successfully!",
});
router.push("/");
router.refresh();
} catch (error) {
handleErrorApi({ error });
}
};
const handleEdit = () => {
setIsEditing(true);
};
const handleSave = async (event: React.FormEvent) => {
event.preventDefault(); // Ngăn form submit mặc định
setIsEditing(false);
await onSubmit(form.getValues());
};
useEffect(() => {
if (!isEditing) {
setLoading(false);
}
}, [isEditing]);
useEffect(() => {
const fetchAccount = async () => {
try {
const result = await accountApiRequest.accountClient();
setAccount(result.payload);
form.setValue("email", result.payload.email || "");
form.setValue("display_name", result.payload.display_name || "");
if (account?.is_active === false) {
toast({
title: "Error",
description: "The user has been banned from using the service!",
variant: "destructive",
});
router.push("/");
}
} catch (error) {
handleErrorApi({ error });
router.push("/");
router.refresh();
}
};
fetchAccount();
}, [form, router, account?.is_active, toast]);
useEffect(() => {
const fetchUserSubscription = async () => {
try {
if (account?.id) {
const result = await accountApiRequest.userSubscriptionIdClient(
account.id
);
setUserSubscription(result.payload);
}
} catch (error) {
handleErrorApi({ error });
}
};
fetchUserSubscription();
}, [router, account?.id]);
useEffect(() => {
const checkAndResetPlanId = async () => {
try {
if (
userSubscription?.expire_at &&
new Date(userSubscription.expire_at) <= new Date()
) {
const result = await accountApiRequest.resetPlanId(account?.id || "");
// setAccount(result.payload);
}
} catch (error) {
handleErrorApi({ error });
}
};
checkAndResetPlanId();
}, [account?.id, userSubscription?.expire_at]);
const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === "Enter") {
event.preventDefault();
}
};
async function onSubmit(values: UpdateAccountBodyType) {
if (loading) return;
setLoading(true);
try {
if (account?.id) {
const result = await accountApiRequest.updateAccount(
values,
account.id
);
toast({
title: "Success",
description: "Update successfully!",
});
}
} catch (error) {
handleErrorApi({
error,
setError: form.setError,
});
} finally {
setLoading(false);
}
}
return (
<DrawerProfile>
<div
onClick={handleClose}
className="flex items-center justify-between px-1"
>
<div className={cn(!isMinimal && "px-1")}>
{isMinimal && (
<DrawerTrigger asChild>
<Image
src="/Ellipse 1.svg"
alt="x"
width={24}
height={22}
className="w-9 h-9 rounded-full my-3"
></Image>
</DrawerTrigger>
)}
{!isMinimal && (
<div className="flex items-center justify-between pt-5 ">
<div className="flex items-center justify-between gap-5">
<DrawerTrigger asChild>
{account?.avatar_url && (
<Image
src={account.avatar_url}
alt="x"
width={24}
height={22}
className="w-9 h-9 rounded-full transition duration-500 ease-in-out hover:opacity-100 hover:scale-125"
></Image>
)}
</DrawerTrigger>
<div className="text-white text-sm font-normal leading-relaxed uppercase w-[180px] overflow-hidden whitespace-nowrap text-ellipsis">
{account?.display_name}
</div>
</div>
<Switch />
</div>
)}
</div>
</div>
<DrawerContent>
<div className="max-w-lg overflow-y-hidden">
<DrawerHeader>
<div className="relative text-[20px] leading-[30px] w-[440px] h-[170px] mb-20">
<Image
className="w-[440px] h-[170px] rounded-t-xl"
src="/Rectangle 3764.svg"
alt="x"
width={440}
height={170}
/>
<DrawerClose asChild>
<Image
src="/x 1.svg"
alt="x"
width={24}
height={24}
className="transition duration-500 ease-in-out hover:opacity-100 hover:scale-125 absolute inset-y-6 right-5"
></Image>
</DrawerClose>
<div>
<Image
src="/logo/Horizontal 2.svg"
alt="x"
width={26}
height={28}
className="transition duration-500 ease-in-out hover:opacity-100 hover:scale-125 absolute inset-x-[210px] inset-y-1/3 "
></Image>
<h1 className="text-white text-[21px] transition duration-500 ease-in-out hover:opacity-100 hover:scale-125 absolute inset-x-[190px] inset-y-[80px] ">
ALLYBY
</h1>
</div>
<div className="w-[110px] h-[110px] rounded-full bg-custom-gray-6 absolute inset-y-32 inset-x-5">
<div className="w-[110px] h-[110px] rounded-full bg-custom-gray-6 relative pt-5">
{account?.avatar_url && (
<Image
src={account.avatar_url}
alt="x"
width={100}
height={100}
className="w-[100px] h-[100px] rounded-full absolute inset-y-[5px] inset-x-[5px]"
></Image>
)}
</div>
</div>
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-6 space-x-6"
>
<div className="pl-36 pt-3 flex gap-1 relative">
<div>
<div className="flex items-center justify-start gap-1 ">
{isEditing ? (
<FormField
control={form.control}
name="display_name"
render={({ field }) => (
<FormItem>
<FormControl>
<Input
placeholder="Enter"
{...field}
disabled={isPending}
className="text-zinc-900 text-sm font-semibold leading-[30px] w-40 h-8"
onKeyDown={handleKeyDown}
/>
</FormControl>
<FormDescription>
{/* This is your public display email. */}
</FormDescription>
<FormMessage className="text-red-500 text-[14px] font-normal leading-[26px]" />
</FormItem>
)}
/>
) : (
<div className="text-xl font-semibold leading-[30px] ">
{account?.display_name}
</div>
)}
<div>
{isEditing ? (
<Button onClick={handleSave} variant="edit">
<Image
src="/icons/Fill - Save.svg"
alt="x"
width={15}
height={15}
className=""
></Image>
</Button>
) : (
<Button
onClick={handleEdit}
type="button"
variant="edit"
>
<Image
src="/Fill - Edit - Pen.svg"
alt="x"
width={15}
height={15}
className=""
></Image>
</Button>
)}
</div>
</div>
<div className="text-sm font-normal leading-tight w-40 overflow-hidden whitespace-nowrap text-ellipsis">
{account?.email}
</div>
</div>
<Skeleton className="bg-primary text-primary-foreground hover:bg-primary/90 flex justify-center items-center absolute right-5 ">
<Button onClick={handleLogout} type="button" className="">
<LogOut />
</Button>
</Skeleton>
</div>
</form>
</Form>
</div>
</DrawerHeader>
<div className="px-5">
<Separator className=" bg-slate-300" />
</div>
{account && <ProfileForm id={account?.id} />}
<DrawerFooter></DrawerFooter>
</div>
</DrawerContent>
</DrawerProfile>
);
};
export default Profile;
|
import { Button, Box } from '@mui/material'
import { useState } from 'react';
import './App.css';
import SudokuGrid from './components/SudokuGrid';
import { emptySudoku, stringToSudoku } from './utils/transform';
import { solve } from './utils/solve';
import sudokuLevels from "./utils/sudoku-db";
import { pt, Sudoku, SudokuSolution } from './utils/sudoku';
const levels = ["Easy", "Intermediate", "Hard", "Evil"];
const empty = emptySudoku();
const buttonTextClasses = (active: boolean) => {
const classes = ['Button-text'];
if (active) {
classes.push('Button-text-active');
}
return classes.join(' ');
}
function App() {
const [originalSudoku, setOriginalSudoku] = useState(empty);
const [rawSudoku, setRawSudoku] = useState(empty);
const [level, setLevel] = useState(0);
const [readonly, setReadonly] = useState(false);
const displayRandom = () => {
const collection = sudokuLevels[level];
const string = collection[Math.floor(collection.length * Math.random())];
const rawSudoku = stringToSudoku(string);
setReadonly(false);
setOriginalSudoku(rawSudoku);
setRawSudoku(rawSudoku);
}
const solveSudoku = () => {
const sudoku = new Sudoku(rawSudoku);
const solution = solve(sudoku) as SudokuSolution;
setReadonly(true);
setRawSudoku(solution.toRawArray());
}
const updateSudoku = (x: number, y: number, value: number) => {
const index = pt(x, y);
const newRawSudoku = [...rawSudoku];
newRawSudoku[index] = value;
setRawSudoku(newRawSudoku);
setOriginalSudoku(newRawSudoku);
}
const clearBoard = () => {
setRawSudoku(emptySudoku);
setOriginalSudoku(emptySudoku);
setReadonly(false);
}
const resetSudoku = () => {
setRawSudoku(originalSudoku);
setReadonly(false);
}
return (
<div className="App">
<header className="App-header">
<h1>¡Susanka!</h1>
</header>
<main>
<div className="App-container">
<div className="App-controls-container">
{levels.map((levelName, levelOption) => (
<Button
onClick={() => setLevel(levelOption)}
key={levelOption}
>
<span className={buttonTextClasses(levelOption === level)}>{levelName}</span>
</Button>
))}
</div>
<div className="Grid-container">
<SudokuGrid
value={rawSudoku}
readonly={readonly}
original={originalSudoku}
onUpdate={(update) => updateSudoku(update.x, update.y, update.value)}
/>
</div>
<div className="App-controls-container">
<Box display="flex" justifyContent="space-between">
<div className="App-left-controls">
<Button variant="outlined" onClick={() => displayRandom()}>
Random
</Button>
<Button variant="outlined" onClick={() => clearBoard()}>
Clear
</Button>
<Button variant="outlined" onClick={() => resetSudoku()}>
Reset
</Button>
</div>
<Button variant="contained" onClick={() => solveSudoku()}>
Solve
</Button>
</Box>
</div>
</div>
</main>
</div>
);
}
export default App;
|
// Copyright 2023 Dimitrij Drus <dadrus@gmx.de>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
package rules
import (
"github.com/goccy/go-json"
"github.com/rs/zerolog"
"github.com/dadrus/heimdall/internal/heimdall"
"github.com/dadrus/heimdall/internal/rules/mechanisms/subject"
"github.com/dadrus/heimdall/internal/x/stringx"
)
type conditionalSubjectHandler struct {
h subjectHandler
c executionCondition
}
func (h *conditionalSubjectHandler) Execute(ctx heimdall.Context, sub *subject.Subject) error {
logger := zerolog.Ctx(ctx.AppContext())
logger.Debug().Str("_id", h.h.ID()).Msg("Checking execution condition")
if logger.GetLevel() == zerolog.TraceLevel {
dump, err := json.Marshal(sub)
if err != nil {
logger.Trace().Err(err).Msg("Failed to dump subject")
} else {
logger.Trace().Msg("Subject: \n" + stringx.ToString(dump))
}
}
if canExecute, err := h.c.CanExecute(ctx, sub); err != nil {
return err
} else if canExecute {
return h.h.Execute(ctx, sub)
}
logger.Debug().Str("_id", h.h.ID()).Msg("Execution skipped")
return nil
}
func (h *conditionalSubjectHandler) ID() string { return h.h.ID() }
func (h *conditionalSubjectHandler) ContinueOnError() bool { return h.h.ContinueOnError() }
|
Sure, here's a basic documentation for the scientific calculator you've created:
## Scientific Calculator Documentation
The Scientific Calculator is a web-based tool designed to perform various mathematical calculations, including basic arithmetic operations, trigonometric functions, exponentiation, square roots, logarithms, and more. It provides a user-friendly interface with a range of buttons for input and interaction.
Features
1. **Arithmetic Operations**: The calculator supports basic arithmetic operations such as addition (+), subtraction (-), multiplication (*), and division (/). You can input numerical values and perform calculations using these operators.
2. **Numeric Input**: Numeric values from 0 to 9 can be input using dedicated buttons. This makes data entry quick and easy.
3. **Clear (AC)**: The "AC" button allows you to clear the current input or calculation result, providing a convenient way to start fresh.
4. **Trigonometric Functions**: The calculator includes buttons for sine (sin), cosine (cos), and tangent (tan) functions. These trigonometric functions work with radians and can be used to perform trigonometric calculations.
5. **Square Root (√)**: The square root button calculates the square root of the input value. It is particularly useful for finding the square root of a number.
6. **Exponentiation (^)**: The exponentiation button allows you to raise a number to a specified power. This feature is handy for performing exponentiation operations.
7. **Factorial (!)**: The factorial button calculates the factorial of a non-negative integer input. It's useful for calculating factorials in mathematical expressions.
8. **Logarithm (log)**: The logarithm button calculates the natural logarithm (base e) of the input value. It can be utilized for logarithmic calculations.
9. **Decimal Point (.)**: The decimal point button adds a decimal point to the input, allowing you to work with decimal numbers.
10. **Delete (Del)**: The delete button removes the last character from the input, helping you correct mistakes during data entry.
11. **Equals (=)**: The equals button computes and displays the result of the entered mathematical expression. It's used to perform the actual calculation.
12. **Keyboard Support**: The calculator also supports keyboard input. Numeric keys, operators, and the Enter key can be used to input and calculate expressions.
User Interface
The user interface of the Scientific Calculator is designed to be intuitive and user-friendly. The calculator features a responsive design, ensuring compatibility with various devices and screen sizes. Circular buttons provide a modern touch, and their colors help differentiate different types of operations.
Glowing Calculator Name
The "Scientific Calculator" name at the top of the interface has a special effect. It has an orange color and a glowing animation, making it visually appealing and enhancing the user experience.
Styling
The calculator is styled using Cascading Style Sheets (CSS) to achieve a clean and professional appearance. Colors, fonts, and button styles have been carefully chosen to enhance usability and aesthetics.
Usage
1. Click the numeric buttons to enter values.
2. Use the operation buttons (+, -, *, /, etc.) for basic calculations.
3. Utilize the special function buttons (sin, cos, tan, sqrt, etc.) for scientific calculations.
4. Press the "AC" button to clear the input or result.
5. Use the "=" button to calculate the result of the expression.
6. If needed, input decimal numbers using the decimal point button.
7. Correct input mistakes using the "Del" button.
8. Keyboard input is also supported for convenience.
Conclusion
The Scientific Calculator provides a comprehensive set of features for performing mathematical calculations, from basic arithmetic to advanced scientific functions. Its user-friendly design and responsive interface make it suitable for both casual and professional use.
Note: This documentation provides a general overview of the calculator's features and usage. Depending on the actual implementation and future updates, specific details may vary.
|
import numpy as np
import pytest
from pandas._libs import index as libindex
import pandas as pd
from pandas import Categorical
import pandas._testing as tm
from pandas.core.indexes.api import CategoricalIndex, Index
from ..common import Base
class TestCategoricalIndex(Base):
_holder = CategoricalIndex
@pytest.fixture
def index(self, request):
return tm.makeCategoricalIndex(100)
def create_index(self, categories=None, ordered=False):
if categories is None:
categories = list("cab")
return CategoricalIndex(list("aabbca"), categories=categories, ordered=ordered)
def test_can_hold_identifiers(self):
idx = self.create_index(categories=list("abcd"))
key = idx[0]
assert idx._can_hold_identifiers_and_holds_name(key) is True
@pytest.mark.parametrize(
"func,op_name",
[
(lambda idx: idx - idx, "__sub__"),
(lambda idx: idx + idx, "__add__"),
(lambda idx: idx - ["a", "b"], "__sub__"),
(lambda idx: idx + ["a", "b"], "__add__"),
(lambda idx: ["a", "b"] - idx, "__rsub__"),
(lambda idx: ["a", "b"] + idx, "__radd__"),
],
)
def test_disallow_addsub_ops(self, func, op_name):
# GH 10039
# set ops (+/-) raise TypeError
idx = pd.Index(pd.Categorical(["a", "b"]))
msg = f"cannot perform {op_name} with this index type: CategoricalIndex"
with pytest.raises(TypeError, match=msg):
func(idx)
def test_method_delegation(self):
ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
result = ci.set_categories(list("cab"))
tm.assert_index_equal(
result, CategoricalIndex(list("aabbca"), categories=list("cab"))
)
ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
result = ci.rename_categories(list("efg"))
tm.assert_index_equal(
result, CategoricalIndex(list("ffggef"), categories=list("efg"))
)
# GH18862 (let rename_categories take callables)
result = ci.rename_categories(lambda x: x.upper())
tm.assert_index_equal(
result, CategoricalIndex(list("AABBCA"), categories=list("CAB"))
)
ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
result = ci.add_categories(["d"])
tm.assert_index_equal(
result, CategoricalIndex(list("aabbca"), categories=list("cabd"))
)
ci = CategoricalIndex(list("aabbca"), categories=list("cab"))
result = ci.remove_categories(["c"])
tm.assert_index_equal(
result,
CategoricalIndex(list("aabb") + [np.nan] + ["a"], categories=list("ab")),
)
ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
result = ci.as_unordered()
tm.assert_index_equal(result, ci)
ci = CategoricalIndex(list("aabbca"), categories=list("cabdef"))
result = ci.as_ordered()
tm.assert_index_equal(
result,
CategoricalIndex(list("aabbca"), categories=list("cabdef"), ordered=True),
)
# invalid
msg = "cannot use inplace with CategoricalIndex"
with pytest.raises(ValueError, match=msg):
ci.set_categories(list("cab"), inplace=True)
def test_append(self):
ci = self.create_index()
categories = ci.categories
# append cats with the same categories
result = ci[:3].append(ci[3:])
tm.assert_index_equal(result, ci, exact=True)
foos = [ci[:1], ci[1:3], ci[3:]]
result = foos[0].append(foos[1:])
tm.assert_index_equal(result, ci, exact=True)
# empty
result = ci.append([])
tm.assert_index_equal(result, ci, exact=True)
# appending with different categories or reordered is not ok
msg = "all inputs must be Index"
with pytest.raises(TypeError, match=msg):
ci.append(ci.values.set_categories(list("abcd")))
with pytest.raises(TypeError, match=msg):
ci.append(ci.values.reorder_categories(list("abc")))
# with objects
result = ci.append(Index(["c", "a"]))
expected = CategoricalIndex(list("aabbcaca"), categories=categories)
tm.assert_index_equal(result, expected, exact=True)
# invalid objects
msg = "cannot append a non-category item to a CategoricalIndex"
with pytest.raises(TypeError, match=msg):
ci.append(Index(["a", "d"]))
# GH14298 - if base object is not categorical -> coerce to object
result = Index(["c", "a"]).append(ci)
expected = Index(list("caaabbca"))
tm.assert_index_equal(result, expected, exact=True)
def test_append_to_another(self):
# hits Index._concat
fst = Index(["a", "b"])
snd = CategoricalIndex(["d", "e"])
result = fst.append(snd)
expected = Index(["a", "b", "d", "e"])
tm.assert_index_equal(result, expected)
def test_insert(self):
ci = self.create_index()
categories = ci.categories
# test 0th element
result = ci.insert(0, "a")
expected = CategoricalIndex(list("aaabbca"), categories=categories)
tm.assert_index_equal(result, expected, exact=True)
# test Nth element that follows Python list behavior
result = ci.insert(-1, "a")
expected = CategoricalIndex(list("aabbcaa"), categories=categories)
tm.assert_index_equal(result, expected, exact=True)
# test empty
result = CategoricalIndex(categories=categories).insert(0, "a")
expected = CategoricalIndex(["a"], categories=categories)
tm.assert_index_equal(result, expected, exact=True)
# invalid
msg = (
"cannot insert an item into a CategoricalIndex that is not "
"already an existing category"
)
with pytest.raises(TypeError, match=msg):
ci.insert(0, "d")
# GH 18295 (test missing)
expected = CategoricalIndex(["a", np.nan, "a", "b", "c", "b"])
for na in (np.nan, pd.NaT, None):
result = CategoricalIndex(list("aabcb")).insert(1, na)
tm.assert_index_equal(result, expected)
def test_delete(self):
ci = self.create_index()
categories = ci.categories
result = ci.delete(0)
expected = CategoricalIndex(list("abbca"), categories=categories)
tm.assert_index_equal(result, expected, exact=True)
result = ci.delete(-1)
expected = CategoricalIndex(list("aabbc"), categories=categories)
tm.assert_index_equal(result, expected, exact=True)
with tm.external_error_raised((IndexError, ValueError)):
# Either depending on NumPy version
ci.delete(10)
@pytest.mark.parametrize(
"data, non_lexsorted_data",
[[[1, 2, 3], [9, 0, 1, 2, 3]], [list("abc"), list("fabcd")]],
)
def test_is_monotonic(self, data, non_lexsorted_data):
c = CategoricalIndex(data)
assert c.is_monotonic_increasing is True
assert c.is_monotonic_decreasing is False
c = CategoricalIndex(data, ordered=True)
assert c.is_monotonic_increasing is True
assert c.is_monotonic_decreasing is False
c = CategoricalIndex(data, categories=reversed(data))
assert c.is_monotonic_increasing is False
assert c.is_monotonic_decreasing is True
c = CategoricalIndex(data, categories=reversed(data), ordered=True)
assert c.is_monotonic_increasing is False
assert c.is_monotonic_decreasing is True
# test when data is neither monotonic increasing nor decreasing
reordered_data = [data[0], data[2], data[1]]
c = CategoricalIndex(reordered_data, categories=reversed(data))
assert c.is_monotonic_increasing is False
assert c.is_monotonic_decreasing is False
# non lexsorted categories
categories = non_lexsorted_data
c = CategoricalIndex(categories[:2], categories=categories)
assert c.is_monotonic_increasing is True
assert c.is_monotonic_decreasing is False
c = CategoricalIndex(categories[1:3], categories=categories)
assert c.is_monotonic_increasing is True
assert c.is_monotonic_decreasing is False
def test_has_duplicates(self):
idx = CategoricalIndex([0, 0, 0], name="foo")
assert idx.is_unique is False
assert idx.has_duplicates is True
idx = CategoricalIndex([0, 1], categories=[2, 3], name="foo")
assert idx.is_unique is False
assert idx.has_duplicates is True
idx = CategoricalIndex([0, 1, 2, 3], categories=[1, 2, 3], name="foo")
assert idx.is_unique is True
assert idx.has_duplicates is False
@pytest.mark.parametrize(
"data, categories, expected",
[
(
[1, 1, 1],
[1, 2, 3],
{
"first": np.array([False, True, True]),
"last": np.array([True, True, False]),
False: np.array([True, True, True]),
},
),
(
[1, 1, 1],
list("abc"),
{
"first": np.array([False, True, True]),
"last": np.array([True, True, False]),
False: np.array([True, True, True]),
},
),
(
[2, "a", "b"],
list("abc"),
{
"first": np.zeros(shape=(3), dtype=np.bool_),
"last": np.zeros(shape=(3), dtype=np.bool_),
False: np.zeros(shape=(3), dtype=np.bool_),
},
),
(
list("abb"),
list("abc"),
{
"first": np.array([False, False, True]),
"last": np.array([False, True, False]),
False: np.array([False, True, True]),
},
),
],
)
def test_drop_duplicates(self, data, categories, expected):
idx = CategoricalIndex(data, categories=categories, name="foo")
for keep, e in expected.items():
tm.assert_numpy_array_equal(idx.duplicated(keep=keep), e)
e = idx[~e]
result = idx.drop_duplicates(keep=keep)
tm.assert_index_equal(result, e)
@pytest.mark.parametrize(
"data, categories, expected_data, expected_categories",
[
([1, 1, 1], [1, 2, 3], [1], [1]),
([1, 1, 1], list("abc"), [np.nan], []),
([1, 2, "a"], [1, 2, 3], [1, 2, np.nan], [1, 2]),
([2, "a", "b"], list("abc"), [np.nan, "a", "b"], ["a", "b"]),
],
)
def test_unique(self, data, categories, expected_data, expected_categories):
idx = CategoricalIndex(data, categories=categories)
expected = CategoricalIndex(expected_data, categories=expected_categories)
tm.assert_index_equal(idx.unique(), expected)
def test_repr_roundtrip(self):
ci = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True)
str(ci)
tm.assert_index_equal(eval(repr(ci)), ci, exact=True)
# formatting
str(ci)
# long format
# this is not reprable
ci = CategoricalIndex(np.random.randint(0, 5, size=100))
str(ci)
def test_isin(self):
ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"])
tm.assert_numpy_array_equal(
ci.isin(["c"]), np.array([False, False, False, True, False, False])
)
tm.assert_numpy_array_equal(
ci.isin(["c", "a", "b"]), np.array([True] * 5 + [False])
)
tm.assert_numpy_array_equal(
ci.isin(["c", "a", "b", np.nan]), np.array([True] * 6)
)
# mismatched categorical -> coerced to ndarray so doesn't matter
result = ci.isin(ci.set_categories(list("abcdefghi")))
expected = np.array([True] * 6)
tm.assert_numpy_array_equal(result, expected)
result = ci.isin(ci.set_categories(list("defghi")))
expected = np.array([False] * 5 + [True])
tm.assert_numpy_array_equal(result, expected)
def test_identical(self):
ci1 = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True)
ci2 = CategoricalIndex(["a", "b"], categories=["a", "b", "c"], ordered=True)
assert ci1.identical(ci1)
assert ci1.identical(ci1.copy())
assert not ci1.identical(ci2)
def test_ensure_copied_data(self, index):
# gh-12309: Check the "copy" argument of each
# Index.__new__ is honored.
#
# Must be tested separately from other indexes because
# self.values is not an ndarray.
# GH#29918 Index.base has been removed
# FIXME: is this test still meaningful?
_base = lambda ar: ar if getattr(ar, "base", None) is None else ar.base
result = CategoricalIndex(index.values, copy=True)
tm.assert_index_equal(index, result)
assert _base(index.values) is not _base(result.values)
result = CategoricalIndex(index.values, copy=False)
assert _base(index.values) is _base(result.values)
def test_equals_categorical(self):
ci1 = CategoricalIndex(["a", "b"], categories=["a", "b"], ordered=True)
ci2 = CategoricalIndex(["a", "b"], categories=["a", "b", "c"], ordered=True)
assert ci1.equals(ci1)
assert not ci1.equals(ci2)
assert ci1.equals(ci1.astype(object))
assert ci1.astype(object).equals(ci1)
assert (ci1 == ci1).all()
assert not (ci1 != ci1).all()
assert not (ci1 > ci1).all()
assert not (ci1 < ci1).all()
assert (ci1 <= ci1).all()
assert (ci1 >= ci1).all()
assert not (ci1 == 1).all()
assert (ci1 == Index(["a", "b"])).all()
assert (ci1 == ci1.values).all()
# invalid comparisons
with pytest.raises(ValueError, match="Lengths must match"):
ci1 == Index(["a", "b", "c"])
msg = (
"categorical index comparisons must have the same categories "
"and ordered attributes"
"|"
"Categoricals can only be compared if 'categories' are the same. "
"Categories are different lengths"
"|"
"Categoricals can only be compared if 'ordered' is the same"
)
with pytest.raises(TypeError, match=msg):
ci1 == ci2
with pytest.raises(TypeError, match=msg):
ci1 == Categorical(ci1.values, ordered=False)
with pytest.raises(TypeError, match=msg):
ci1 == Categorical(ci1.values, categories=list("abc"))
# tests
# make sure that we are testing for category inclusion properly
ci = CategoricalIndex(list("aabca"), categories=["c", "a", "b"])
assert not ci.equals(list("aabca"))
# Same categories, but different order
# Unordered
assert ci.equals(CategoricalIndex(list("aabca")))
# Ordered
assert not ci.equals(CategoricalIndex(list("aabca"), ordered=True))
assert ci.equals(ci.copy())
ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"])
assert not ci.equals(list("aabca"))
assert not ci.equals(CategoricalIndex(list("aabca")))
assert ci.equals(ci.copy())
ci = CategoricalIndex(list("aabca") + [np.nan], categories=["c", "a", "b"])
assert not ci.equals(list("aabca") + [np.nan])
assert ci.equals(CategoricalIndex(list("aabca") + [np.nan]))
assert not ci.equals(CategoricalIndex(list("aabca") + [np.nan], ordered=True))
assert ci.equals(ci.copy())
def test_equals_categorical_unordered(self):
# https://github.com/pandas-dev/pandas/issues/16603
a = pd.CategoricalIndex(["A"], categories=["A", "B"])
b = pd.CategoricalIndex(["A"], categories=["B", "A"])
c = pd.CategoricalIndex(["C"], categories=["B", "A"])
assert a.equals(b)
assert not a.equals(c)
assert not b.equals(c)
def test_frame_repr(self):
df = pd.DataFrame({"A": [1, 2, 3]}, index=pd.CategoricalIndex(["a", "b", "c"]))
result = repr(df)
expected = " A\na 1\nb 2\nc 3"
assert result == expected
@pytest.mark.parametrize(
"dtype, engine_type",
[
(np.int8, libindex.Int8Engine),
(np.int16, libindex.Int16Engine),
(np.int32, libindex.Int32Engine),
(np.int64, libindex.Int64Engine),
],
)
def test_engine_type(self, dtype, engine_type):
if dtype != np.int64:
# num. of uniques required to push CategoricalIndex.codes to a
# dtype (128 categories required for .codes dtype to be int16 etc.)
num_uniques = {np.int8: 1, np.int16: 128, np.int32: 32768}[dtype]
ci = pd.CategoricalIndex(range(num_uniques))
else:
# having 2**32 - 2**31 categories would be very memory-intensive,
# so we cheat a bit with the dtype
ci = pd.CategoricalIndex(range(32768)) # == 2**16 - 2**(16 - 1)
ci.values._codes = ci.values._codes.astype("int64")
assert np.issubdtype(ci.codes.dtype, dtype)
assert isinstance(ci._engine, engine_type)
def test_reindex_base(self):
# See test_reindex.py
pass
def test_map_str(self):
# See test_map.py
pass
def test_format_different_scalar_lengths(self):
# GH35439
idx = CategoricalIndex(["aaaaaaaaa", "b"])
expected = ["aaaaaaaaa", "b"]
assert idx.format() == expected
|
/* Compiled by Kathrin Meyer, University of Fribourg, July 2006 */
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAXWORD 100
typedef struct tnode *Treeptr;
typedef struct tnode { /* the tree node --- kr146 */
char *word; /* points to the next */
int count; /* number of occurrences */
Treeptr left; /* left child */
Treeptr right; /* right child */
} Treenode;
Treeptr addtree(struct tnode *, char *);
void treeprint(struct tnode *);
int getword(char *, int);
main() /* word frequency count --- kr140 */
{
Treeptr root;
char word[MAXWORD];
root = NULL;
while (getword(word, MAXWORD) != EOF)
if (isalpha(word[0]))
root = addtree(root, word);
treeprint(root);
return 0;
}
/* ----------------------------------------- */
/* addtree, treeprint "module" --- kr141-142 */
/* ----------------------------------------- */
Treeptr talloc(void);
char *my_strdup(char *);
/* addtree: add a node with w, at or below p --- kr141 */
Treeptr addtree(struct tnode *p, char *w)
{
int cond;
if (p == NULL) { /* a new word has arrived */
p = talloc(); /* make a new node */
p->word = my_strdup(w);
p->count = 1;
p->left = p->right = NULL;
} else if ((cond = strcmp(w, p->word)) == 0)
p->count++; /* repeated word */
else if (cond < 0) /* less than into left subtree */
p->left = addtree(p->left, w);
else /* greater than into right subtree */
p->right = addtree(p->right, w);
return p;
}
/* treeprint: in-order print of tree p --- kr142 */
void treeprint(struct tnode *p)
{
if (p != NULL) {
treeprint(p->left);
printf("%4d %s\n", p->count, p->word);
treeprint(p->right);
}
}
/* ---------------------------------------- */
/* talloc, my_strdup "module" --- kr142-143 */
/* ---------------------------------------- */
/* talloc: make a tnode --- kr142 */
Treeptr talloc(void)
{
return (Treeptr) malloc(sizeof(Treenode));
}
char *my_strdup(char *s) /* make a duplicate of s --- kr143 */
{
char *p;
p = (char *) malloc(strlen(s)+1); /* +1 for '\0' */
if (p != NULL)
strcpy(p,s);
return p;
}
/* -------------------------------- */
/* getch, ungetch "module" --- kr79 */
/* -------------------------------- */
#define BUFSIZE 100
char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */
int getch(void) /* get a (possibly pushed back) character */
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c) /* push character back on input */
{
if ( bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
/* getword: get next word or character from input --- kr136 */
int getword(char *word, int lim)
{
int c, getch(void);
void ungetch(int);
char *w = word;
while (isspace(c = getch()))
;
if (c != EOF)
*w++ = c;
if (!isalpha(c)){
*w = '\0';
return c;
}
for ( ; --lim > 0; w++)
if (!isalnum(*w = getch())) {
ungetch(*w);
break;
}
*w = '\0';
return word[0];
}
|
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
/*
Sonic Visualiser
An audio file viewer and annotation editor.
Centre for Digital Music, Queen Mary, University of London.
This file copyright 2006 Chris Cannam.
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 2 of the
License, or (at your option) any later version. See the file
COPYING included with this distribution for more information.
*/
#ifndef SV_AUDIO_PLAY_SOURCE_H
#define SV_AUDIO_PLAY_SOURCE_H
#include "BaseTypes.h"
struct Auditionable {
virtual ~Auditionable() { }
};
/**
* Simple interface for audio playback. This should be all that the
* ViewManager needs to know about to synchronise with playback by
* sample frame, but it doesn't provide enough to determine what is
* actually being played or how. See the audioio directory for a
* concrete subclass.
*/
class AudioPlaySource
{
public:
virtual ~AudioPlaySource() { }
/**
* Start playing from the given frame. If playback is already
* under way, reseek to the given frame and continue.
*/
virtual void play(sv_frame_t startFrame) = 0;
/**
* Stop playback.
*/
virtual void stop() = 0;
/**
* Return whether playback is currently supposed to be happening.
*/
virtual bool isPlaying() const = 0;
/**
* Return the frame number that is currently expected to be coming
* out of the speakers. (i.e. compensating for playback latency.)
*/
virtual sv_frame_t getCurrentPlayingFrame() = 0;
/**
* Return the current (or thereabouts) output levels in the range
* 0.0 -> 1.0, for metering purposes. The values returned are
* peak values since the last call to this function was made
* (i.e. calling this function also resets them).
*/
virtual bool getOutputLevels(float &left, float &right) = 0;
/**
* Return the sample rate of the source material -- any material
* that wants to play at a different rate will sound wrong.
*/
virtual sv_samplerate_t getSourceSampleRate() const = 0;
/**
* Return the sample rate set by the target audio device (or 0 if
* the target hasn't told us yet). If the source and target
* sample rates differ, resampling will occur.
*
* Note that we don't actually do any processing at the device
* sample rate. All processing happens at the source sample rate,
* and then a resampler is applied if necessary at the interface
* between application and driver layer.
*/
virtual sv_samplerate_t getDeviceSampleRate() const = 0;
/**
* Get the block size of the target audio device. This may be an
* estimate or upper bound, if the target has a variable block
* size; the source should behave itself even if this value turns
* out to be inaccurate.
*/
virtual int getTargetBlockSize() const = 0;
/**
* Get the number of channels of audio that will be provided
* to the play target. This may be more than the source channel
* count: for example, a mono source will provide 2 channels
* after pan.
*/
virtual int getTargetChannelCount() const = 0;
/**
* Set a plugin or other subclass of Auditionable as an
* auditioning effect.
*/
virtual void setAuditioningEffect(Auditionable *) = 0;
};
#endif
|
package everyone.delivery.demo.common.exception.error;
import everyone.delivery.demo.common.response.ResponseError;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.springframework.http.HttpStatus;
import java.util.EnumSet;
/***
* 미리 정의해 둔 에러들
*/
@AllArgsConstructor
public enum CommonError implements RestError{
UNAUTHORIZED_JWT_TOKEN(HttpStatus.UNAUTHORIZED,"JWT: 해당 리소스에 접근할 권한이 없습니다.(토큰은 있으나 권한 없음)"),
NOT_INCLUDE_JWT_TOKEN(HttpStatus.UNAUTHORIZED,"JWT: 해당 리소스에 접근할 권한이 없습니다.(토큰 없음)"),
INVALID_DATA(HttpStatus.BAD_REQUEST,"요청 오류 입니다.(의미상 오류: api 스팩은 맞지만 논리상 안맞는 요청)"),
BAD_REQUEST(HttpStatus.BAD_REQUEST, "요청 오류 입니다.(형식상 오류: api 스팩에 안맞는 요청)"),
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, "서버 오류 입니다.");
private HttpStatus httpStatus;
private String errorMsg;
@Override
public String toString(){
return this.name();
}
@Override
public ResponseError toResponseError(){
return ResponseError.builder()
.errorCode(this.name())
.errorMessage(this.errorMsg).build();
}
@Override
public HttpStatus getHttpStatus() {
return this.httpStatus;
}
@Override
public String getErrorMsg() {
return this.errorMsg;
}
}
|
Feature: Register to Alta-shop Account
As an user
I want to register to access alta shop feature
So that I can login to the website
Scenario: Register with valid data
Given I am on the alta-shop login page
When I go to the alta-shop register page
And I input correct fullname for register
And I input correct email for register
And I input correct password for register
And I click on the register button
Then I should be redirected to login page
Scenario: Register without fill the fullname
Given I am on the alta-shop login page
When I go to the alta-shop register page
And I input nothing in fullname for register
And I input correct email for register
And I input correct password for register
When I click on the register button
Then I should see the error message
Scenario: Register without fill the email
Given I am on the alta-shop login page
When I go to the alta-shop register page
And I input correct fullname for register
And I input nothing in email for register
And I input correct password for register
When I click on the register button
Then I should see the error message
Scenario: Register without fill the password
Given I am on the alta-shop login page
When I go to the alta-shop register page
And I input correct fullname for register
And I input correct email for register
And I input nothing in password for register
When I click on the register button
Then I should see the error message
Scenario: Register with existed email
Given I am on the alta-shop login page
When I go to the alta-shop register page
And I input correct fullname for register
And I input existed email for register
And I input correct password for register
When I click on the register button
Then I should see the error message
|
import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import DashboardView from './DashboardView';
import _ from 'lodash';
import util from '../../util';
import {removePassword} from '../../actions/UserActions';
import {Platform} from 'react-native';
class DashboardController extends React.Component {
constructor() {
super();
this.state = {};
}
static propTypes = {};
static defaultProps = {};
async componentDidMount() {
Platform.OS === 'android'
? await this.registerAppWithFCM()
: await this.requestPermission();
/*checking if user has successfully completed the onboarding
process,so that the password can be stores to keychain for future use*/
const {passData} = this.props;
//if passData is not empty user have recently completed the onboarding and passData needs to be stored in keychain
if (!_.isEmpty(passData)) {
util.setGenericPassword(passData.phone, passData.pass);
//once password is saved. remove it so on next login it dose not update the password
this.props.removePassword();
}
}
async requestPermission() {
const granted = messaging().requestPermission();
if (granted) {
// console.log('User granted messaging permissions!');
await this.registerAppWithFCM();
} else {
// console.log('User declined messaging permissions :(');
}
}
async registerAppWithFCM() {
await messaging().registerForRemoteNotifications();
}
render() {
return <DashboardView {...this.props} />;
}
}
const mapStateToProps = ({user}) => ({passData: user.passData});
const actions = {removePassword};
export default connect(mapStateToProps, actions)(DashboardController);
|
// 初始化关注页面、好 P 友页面、粉丝页面
import { InitPageBase } from '../crawl/InitPageBase'
import { Colors } from '../Colors'
import { lang } from '../Lang'
import { options } from '../setting/Options'
import { API } from '../API'
import { store } from '../store/Store'
import { log } from '../Log'
import { Tools } from '../Tools'
import { createCSV } from '../utils/CreateCSV'
import { Utils } from '../utils/Utils'
import { states } from '../store/States'
import { Config } from '../Config'
import { setTimeoutWorker } from '../SetTimeoutWorker'
interface UserInfo {
userId: string
userName: string
homePage: string
userComment: string
profileImageUrl: string
}
type PageType = 0 | 1 | 2
class InitFollowingPage extends InitPageBase {
constructor() {
super()
this.getPageType()
this.init()
}
private baseOffset = 0 // 开始抓取时,记录初始的偏移量
private readonly onceNumber = 24 // 每页 24 个画师
private pageType: PageType = 0 // 页面子类型
// 0 我的关注
// 1 我的好 P 友
// 2 我的粉丝
private getUserListNo = 0 // 获取用户列表时,记录请求的次数
private readonly limit = 100 // 每次请求多少个用户
private totalNeed = Number.MAX_SAFE_INTEGER
private myId = ''
private rest: 'show' | 'hide' = 'show'
private tag = ''
private userList: string[] = []
private index = 0 // getIdList 时,对 userList 的索引
private userInfoList: UserInfo[] = [] // 储存用户列表,包含 id 和用户名
private downUserList = false // 下载用户列表的标记
private readonly homePrefix = 'https://www.pixiv.net/users/' // 用户主页的通用链接前缀
private getPageType() {
const pathname = window.location.pathname
if (pathname.includes('/following')) {
this.pageType = 0
} else if (pathname.includes('/mypixiv')) {
this.pageType = 1
} else if (pathname.includes('/followers')) {
this.pageType = 2
}
}
protected addCrawlBtns() {
Tools.addBtn(
'crawlBtns',
Colors.bgBlue,
'_开始抓取',
'_默认下载多页'
).addEventListener('click', () => {
this.readyCrawl()
})
Tools.addBtn('crawlBtns', Colors.bgGreen, '_下载用户列表').addEventListener(
'click',
() => {
this.downUserList = true
this.readyCrawl()
}
)
}
protected setFormOption() {
// 个数/页数选项的提示
options.setWantPageTip({
text: '_抓取多少页面',
tip: '_从本页开始下载提示',
rangTip: '_数字提示1',
})
}
protected getWantPage() {
this.crawlNumber = this.checkWantPageInput(
lang.transl('_从本页开始下载x页'),
lang.transl('_下载所有页面')
)
}
protected nextStep() {
this.setSlowCrawl()
this.readyGet()
log.log(lang.transl('_正在抓取'))
this.getPageType()
this.getUserList()
}
protected readyGet() {
this.rest = location.href.includes('rest=hide') ? 'hide' : 'show'
this.tag = Utils.getURLPathField(window.location.pathname, 'following')
// 获取抓取开始时的页码
const nowPage = Utils.getURLSearchField(location.href, 'p')
// 计算开始抓取时的偏移量
if (nowPage !== '') {
this.baseOffset = (parseInt(nowPage) - 1) * this.onceNumber
} else {
this.baseOffset = 0
}
// 要抓取多少个用户
this.totalNeed = Number.MAX_SAFE_INTEGER
if (this.crawlNumber !== -1) {
this.totalNeed = this.onceNumber * this.crawlNumber
}
// 获取用户自己的 id
const test = /users\/(\d*)\//.exec(location.href)
if (test && test.length > 1) {
this.myId = test[1]
} else {
const msg = `Get the user's own id failed`
log.error(msg, 2)
throw new Error(msg)
}
}
// 获取用户列表
private async getUserList() {
const offset = this.baseOffset + this.getUserListNo * this.limit
let res
try {
switch (this.pageType) {
case 0:
res = await API.getFollowingList(
this.myId,
this.rest,
this.tag,
offset
)
break
case 1:
res = await API.getMyPixivList(this.myId, offset)
break
case 2:
res = await API.getFollowersList(this.myId, offset)
break
}
} catch {
this.getUserList()
return
}
const users = res.body.users
if (users.length === 0) {
// 用户列表抓取完毕
return this.getUserListComplete()
}
for (const userData of users) {
// 保存用户 id
this.userList.push(userData.userId)
// 如果需要下载用户列表
if (this.downUserList) {
this.userInfoList.push({
userId: userData.userId,
userName: userData.userName,
homePage: this.homePrefix + userData.userId,
userComment: userData.userComment,
profileImageUrl: userData.profileImageUrl,
})
}
if (this.userList.length >= this.totalNeed) {
// 抓取到了指定数量的用户
return this.getUserListComplete()
}
}
log.log(
lang.transl('_当前有x个用户', this.userList.length.toString()),
1,
false
)
this.getUserListNo++
this.getUserList()
}
private getUserListComplete() {
log.log(lang.transl('_当前有x个用户', this.userList.length.toString()))
if (this.userList.length === 0) {
return this.getIdListFinished()
}
// 处理下载用户列表的情况
if (this.downUserList) {
this.toCSV()
return this.getIdListFinished()
}
this.getIdList()
}
private toCSV() {
// 添加用户信息
const data: string[][] = this.userInfoList.map((item) => {
return Object.values(item)
})
// 添加用户信息的标题字段
data.unshift(Object.keys(this.userInfoList[0]))
const csv = createCSV.create(data)
const csvURL = URL.createObjectURL(csv)
const csvName = Tools.getPageTitle()
Utils.downloadFile(csvURL, Utils.replaceUnsafeStr(csvName) + '.csv')
}
// 获取用户的 id 列表
protected async getIdList() {
let idList = []
try {
idList = await API.getUserWorksByType(this.userList[this.index])
} catch {
this.getIdList()
return
}
store.idList = store.idList.concat(idList)
this.index++
log.log(
`${lang.transl('_已抓取x个用户', this.index.toString())}, ${lang.transl(
'_当前作品个数',
store.idList.length.toString()
)}`,
1,
false
)
if (this.index >= this.userList.length) {
return this.getIdListFinished()
}
if (states.slowCrawlMode) {
setTimeoutWorker.set(() => {
this.getIdList()
}, Config.slowCrawlDealy)
} else {
this.getIdList()
}
}
protected resetGetIdListStatus() {
this.userList = []
this.userInfoList = []
this.downUserList = false
this.getUserListNo = 0
this.index = 0
}
protected sortResult() {
// 把作品数据按 id 倒序排列,id 大的在前面,这样可以先下载最新作品,后下载早期作品
store.result.sort(Utils.sortByProperty('id'))
}
}
export { InitFollowingPage }
|
import {Component, OnInit} from '@angular/core';
import {AuthService} from "../shared/services/auth.service";
import {Router} from "@angular/router";
import {MessageService} from "../shared/services/message.service";
import {Message} from "../shared/types/message.type";
@Component({
selector: 'app-nav',
templateUrl: './nav.component.html',
styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
private _messages: Message[] = [];
constructor(
private readonly _authService: AuthService,
private readonly _router: Router,
private readonly _messagesService: MessageService) {
}
ngOnInit(): void {
this._messagesService.findAll(this._authService.email).subscribe((data: Message[]) => {
this._messages = data;
});
}
get messages(): Message[] {
return this._messages;
}
get numberOfMessages(): number {
return this._messages.length;
}
updateMessages(messages: Message[]): void {
this._messages = messages;
}
logout(): void {
this._authService.logout();
this._router.navigate(['/login']);
}
get isLoginPage(): boolean {
return window.location.pathname === '/login';
}
get isStudent(): boolean {
// check user role is student
return this._authService.isStudent();
}
get isAdmin(): boolean {
// check user role is admin
return this._authService.isAdmin();
}
get isProfessor(): boolean {
// check user role is professor
return this._authService.isProfessor();
}
get firstName(): string {
// get user first name
return this._authService.firstName;
}
get lastName(): string {
// get user last name
return this._authService.lastName;
}
}
|
import React, { useEffect } from "react";
import {
BrowserRouter as Routing,
Route,
Routes,
redirect,
useNavigate,
Navigate,
} from "react-router-dom";
import App from "./App";
import Blog from "./pages/Blog";
import Register from "./pages/Register";
import Login from "./pages/Login";
import Friends from "./pages/Friends";
import Settings from "./pages/Settings";
import Account from "./pages/Account";
import { useDispatch, useSelector } from "react-redux";
import { getUserById } from "./features/Auth/AuthSlice";
import Navbar from "./core/Navbar";
import CreatePost from "./components/Editor";
import Article from "./pages/Article";
function Router() {
const userFromLocalStorage = JSON.parse(localStorage.getItem("auth"));
const dispatch = useDispatch();
useEffect(() => {
dispatch(getUserById(userFromLocalStorage?._id));
}, []);
useEffect(() => {
const userFromLocalStorage = JSON.parse(localStorage.getItem("auth"));
console.log(userFromLocalStorage);
if (userFromLocalStorage === undefined) window.localStorage.clear();
}, []);
const hello = () => {
return (
<div>
<Navbar />
<h1 className="my-3 text-center">Page Not Found</h1>
</div>
);
};
return (
<div>
<Routing>
<Routes>
<Route element={<App />} path="/" />
<Route element={<Blog />} path="/blog" />
<Route element={<Register />} path="/register" />
<Route element={<Login />} path="/login" />
<Route element={<Account />} path="/account" />
<Route element={<Settings />} path="/settings" />
<Route element={<CreatePost />} path="/post/new" />
<Route element={<Friends />} path="/friends" />
<Route element={<Article />} path="/article/:id" />
<Route element={hello()} path="*" />
</Routes>
</Routing>
</div>
);
}
export default Router;
|
#pragma once
#include <memory>
/*
As with any singleton object destruction cannot be completely guarded. As its currently instantiated it is possible to delete
the underlying object from the shared_ptrs. But as they are smart pointers an explicit delete should never be required, this would just
help protect against poorly written code
There are a multitude of different ways to solve this but each has their own benefits and drawbacks. Here are some that I have come up with
which theoretically should work
1. Just leave it alone. In order for the underlying object to get deleted the raw pointer would have to be extracted from the smart pointer,
Then delete would have to be called on it. This would be very poor coding practice and should never be done in the first place so this situation
is not hard to avoid
2. Define a protected destructor and friend the smart_pointer class. This protects against any explicit deletions but does require adding
friend classes, which is something this class has been written to avoid. If you do declare a friend class you can also declare the constructor
protected instead of private and the "new" in the get function can be replaced with std::make_shared<Singleton>(), which is slightly more proper
3. Define a public destructor and a static global bDeleted variable. The destructor sets bDeleted to true, the get function checks bDeleted
along with Instance.expired() and makes a new object if either are true then sets bDeleted to false. This ensures that if its deleted
any get will return a valid object, even if it was deleted without the smart pointers knowing. However this will cause the entire class
to reset and requires a global variable
- This could be extended to having every method check this bDeleted variable as well. Which would help protect existing smart pointers too
*/
class Singleton
{
private:
Singleton();
// Delete copy constructor and assignment operator to prevent singleton violations
Singleton(const Singleton&) = delete;
void operator= (const Singleton&) = delete;
public:
static std::shared_ptr<Singleton> Get();
};
|
import { Modal } from "antd";
import ElectroForm from "../../../components/form/ElectroForm";
import { FieldValues } from "react-hook-form";
import ElectroInput from "../../../components/form/ElectroInput";
import ElectroButton from "../../../components/form/ElectroButton";
import { productsApi } from "../../../redux/features/products/productsApi";
import { TProduct } from "../../../redux/features/products/productSlice";
import { toast } from "sonner";
import { errorFormatToObj, errorFormatToString } from "../../../utilies/errorFormatter";
import ElectroFileInput from "../../../components/form/ElectroFileInput";
import { useRef } from "react";
type TAddProductModalProps = {
defaultProduct?: TProduct
openModal: boolean
isEditedProduct: boolean;
onCloseModal: ()=>void;
}
const AddProductModal = ({defaultProduct, openModal, onCloseModal, isEditedProduct}:TAddProductModalProps) => {
const [addProductMutation,{isLoading,error}] = productsApi.useAddProductMutation()
const [editProductByIdMutation,{isLoading:isEditLoading,error:editError}] = productsApi.useEditProductByIdMutation()
const previewImageRef = useRef<HTMLImageElement | null>(null);
const handleOk = () => {
console.log("clicked ok");
};
const onFileChange = (file:File|undefined) => {
if (file instanceof File) {
const imgUrl = URL.createObjectURL(file)
if (previewImageRef.current) {
previewImageRef.current.src = imgUrl;
}
}
};
const onAddProduct = async(data: FieldValues ) => {
const toastId = toast.loading(isEditedProduct ? "Updating product....." :'creating new product');
try {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const {slug,...restData} = data;
if (data.img && data.img instanceof File) {
const imgBBApi = import.meta.env.VITE_IMGBB_API_KEY;
const formData = new FormData();
formData.append('key',imgBBApi);
formData.append('image',data.img);
formData.append('name', data.name)
console.log(Object.fromEntries(formData));
const uploadRes = await fetch('https://api.imgbb.com/1/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
if (uploadRes.success) {
restData.img = uploadRes.data?.url;
}
}
const dimension = {
height: Number(data.dimension.height),
width: Number(data.dimension.width),
depth: Number(data.dimension.depth),
}
const formattedData = {
...restData,
price: Number(data.price),
quantity: Number(data.quantity),
releaseDate: new Date(data.releaseDate).toISOString(),
dimension,
}
if (isEditedProduct) {
// call edit API
const result = await editProductByIdMutation({productId: data._id, product:formattedData})
if ('data' in result) {
if (previewImageRef.current) {
previewImageRef.current.src = '';
}
toast.success("Product Edited successfully",{id:toastId,duration:2000})
onCloseModal();
}else{
toast.error('Failed to update product',{id:toastId,duration:2000})
}
}else{
// call create API
const result = await addProductMutation(formattedData as TProduct)
if ('data' in result) {
if (previewImageRef.current) {
previewImageRef.current.src = '';
}
toast.success("Product created successfully",{id:toastId,duration:2000})
onCloseModal();
}else{
console.log(result);
toast.error('Failed to create product',{id:toastId,duration:2000})
}
}
} catch (err) {
console.log(err);
toast.error(errorFormatToString(err),{id:toastId,duration:2000})
}
};
const fields = [
{
label:"Product Name",
name:"name",
errKey:"name",
type:"text",
placeholder:"type gadget name",
},
{
label:"Product Price",
name:"price",
errKey:"price",
type:"number",
placeholder:"type the price",
},
{
label:"Product Quantity",
name:"quantity",
errKey:"quantity",
type:"number",
placeholder:"type quantity",
},
{
label:"Release Date",
name:"releaseDate",
errKey:"releaseDate",
type:"date",
placeholder:"",
defaultValue: new Date().toISOString().split("T")[0]
},
{
label:"Brand Name",
name:"brand",
errKey:"brand",
type:"text",
placeholder:"",
},
{
label:"Model Name or ID",
name:"model",
errKey:"model",
type:"text",
placeholder:"",
},
{
label:"Product category",
name:"category",
errKey:"category",
type:"text",
placeholder:"",
},
{
label:"Connectivity",
name:"connectivity",
errKey:"connectivity",
type:"text",
placeholder:"",
},
{
label:"Power Source",
name:"powerSource",
errKey:"powerSource",
type:"text",
placeholder:"",
},
{
label:"Camera Resolution",
name:"features.cameraResolution",
type:"text",
errKey:"cameraResolution",
placeholder:"",
},
{
label:"Storage Capacity",
name:"features.storageCapacity",
errKey:"storageCapacity",
type:"text",
placeholder:"",
},
{
label:"Screen Size",
name:"features.screenSize",
errKey:"screenSize",
type:"text",
placeholder:"",
},
{
label:"Height",
name:"dimension.height",
errKey:"height",
type:"number",
placeholder:"900",
},
{
label:"Weight",
name:"dimension.width",
errKey:"width",
type:"number",
placeholder:"400",
},
{
label:"Depth",
name:"dimension.depth",
errKey:"depth",
type:"number",
placeholder: '200',
},
{
label:"Weight",
name:"weight",
errKey:"weight",
type:"text",
placeholder:"200g",
defaultValue:""
},
]
console.log(defaultProduct,previewImageRef.current);
return (
<>
{/* <Button
type="dashed"
className="bg-blue-300 ml-auto block my-2 font-bold"
onClick={onOpenModal}
>
Add Gadget
</Button> */}
<Modal
title={isEditedProduct ? "Edit Electric Gadget": "Add an Electric Gadget"}
open={openModal}
onOk={handleOk}
confirmLoading={isLoading || isEditLoading}
onCancel={()=>{onCloseModal();}}
okText={"Create Product"}
okButtonProps={{
className: "bg-green-400 text-green-900 font-bold",
}}
footer={null}
width={'auto'}
style={{maxWidth:"700px"}}
>
<ElectroForm
className="border p-4 rounded-lg shadow-md"
onSubmit={onAddProduct}
defaultValues={{...defaultProduct,releaseDate: new Date(defaultProduct?.releaseDate || new Date()).toISOString().split("T")[0]} as FieldValues}
>
<div className="grid md:grid-cols-2 gap-2">
{
fields.map((field, idx) =>{
return <ElectroInput
type={field.type}
label={field.label}
name={field.name}
placeHolder={field.placeholder}
defaultValue={field.defaultValue}
key={idx}
error={errorFormatToObj(error || editError)[field.errKey]}
/>
})
}
<div>
{/* <img ref={imgRef} className={`h-[${previewImageRef.current||defaultProduct?.img ? 150:0}px]`} src={previewImageRef.current||defaultProduct?.img} alt="" /> */}
<img ref={previewImageRef} className={`h-[${defaultProduct?.img ? 150:0}px]`} src={defaultProduct?.img} alt="" />
<ElectroFileInput
label="Image"
name="img"
onFileChange={onFileChange}
/>
</div>
</div>
<div >
<ElectroButton loading={isLoading || isEditLoading} disabled={isLoading || isEditLoading} type="submit">{isEditedProduct ? "Update" : "Create"} Product</ElectroButton>
</div>
<span className="text-red-500">{errorFormatToObj(error || editError)[""] ? "Name already exist": null}</span>
</ElectroForm>
</Modal>
</>
);
};
export default AddProductModal;
|
import os
import numpy as np
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_absolute_percentage_error
from sklearn.metrics import mean_squared_log_error
def MAE(y_true, y_pred):
""" Mean Absolute Error """
# print(f'{y_true.shape = }')
# print(f'{y_pred.shape = }')
# print(f'{(y_true - y_pred).shape = }')
# return np.mean(np.abs(y_true - y_pred))
return mean_absolute_error(y_true=y_true, y_pred=y_pred)
def MSE(y_true, y_pred):
""" Mean Squared Error """
# return np.mean((y_true - y_pred) ** 2)
return mean_squared_error(y_true=y_true, y_pred=y_pred)
def RMSE(y_true, y_pred):
""" Root Mean Squared Error """
return np.sqrt(np.mean((y_true-y_pred)**2))
def MSLE(y_true, y_pred):
""" Mean Squared Logarithmic Error """
return mean_squared_log_error(y_true=y_true, y_pred=y_pred)
def MAPE(y_true, y_pred):
""" Mean Absolute Percentage Error """
# return np.mean(np.abs((y_true-y_pred) / (y_true + 1e-10))) * 100
return mean_absolute_percentage_error(y_true=y_true, y_pred=y_pred)
def sMAPE(y_true, y_pred):
""" Symmetric Mean Absolute Percentage Error """
return np.mean(np.abs(y_pred - y_true) / ((np.abs(y_pred) + np.abs(y_true))/2)) * 100
def R2(y_true, y_pred):
# return 1 - (np.sum(np.power(y - yhat, 2)) / np.sum(np.power(y - np.mean(y), 2)))
# 1 - np.sum(np.square(y_true - y_pred)) / np.sum(np.square(y_true - np.mean(y_true)))
return r2_score(y_true, y_pred)
def numpy_normalised_quantile_loss(y_true, y_pred, quantile):
"""Computes normalised quantile loss for numpy arrays.
Uses the q-Risk metric as defined in the "Training Procedure" section of the
main TFT paper.
Args:
y_true: Targets
y_pred: Predictions
quantile: Quantile to use for loss calculations (between 0 & 1)
Returns:
Float for normalised quantile loss.
"""
assert 0 <= quantile <= 1, "Number should be within the range [0, 1]."
prediction_underflow = y_true - y_pred
weighted_errors = quantile * np.maximum(prediction_underflow, 0.) + (1. - quantile) * np.maximum(-prediction_underflow, 0.)
quantile_loss = weighted_errors.mean()
normaliser = abs(y_true).mean()
return 2 * quantile_loss / normaliser
metric_dict = {
'R2' : R2,
'MAE' : MAE,
'MSE' : MSE,
'RMSE' : RMSE,
'MAPE' : MAPE,
'sMAPE' : sMAPE,
'nQL.5': lambda y_true, y_pred: numpy_normalised_quantile_loss(y_true=y_true, y_pred=y_pred, quantile=0.5),
'nQL.9': lambda y_true, y_pred: numpy_normalised_quantile_loss(y_true=y_true, y_pred=y_pred, quantile=0.9),
}
def score(y,
yhat,
r,
scaler={}):
if scaler != {}:
if scaler['method'] == 'minmax':
y = y * (scaler['max'] - scaler['min']) + scaler['min']
yhat = yhat * (scaler['max'] - scaler['min']) + scaler['min']
elif scaler['method'] == 'standard':
y = y * scaler['std'] + scaler['mean']
yhat = yhat * scaler['std'] + scaler['mean']
elif scaler['method'] == 'robust':
y = y * scaler['iqr'] + scaler['median']
yhat = yhat * scaler['iqr'] + scaler['median']
if len(yhat.shape) == 3:
nsamples, nx, ny = yhat.shape
yhat = yhat.reshape((nsamples,nx*ny))
y = np.squeeze(y)
yhat = np.squeeze(yhat)
print(f'{y.shape = }')
print(f'{yhat.shape = }')
if r != -1:
results = [str(np.round(np.float64(metric_dict[key](y, yhat)), r)) for key in metric_dict.keys()]
else:
results = [str(metric_dict[key](y, yhat)) for key in metric_dict.keys()]
print(results)
return results
|
package LectureLambda;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author hooman
*/
import java.util.*;
class Program1
{
public static void main(String[] args)
{
List<Integer> numsA = Arrays.asList (1, 2, 3, 4, 5);
int result1 = reduceByAdd (numsA);
System.out.println (result1);
int result2 = reduceBy (numsA, (x,y)->x*y);
System.out.println (result2);
Function2<Integer> reduceB = (x,y)->x*y;
int result3 = reduceB.reduce (1, numsA);
System.out.println (result3);
}
public static int reduceBy (List<Integer> vals, IntFunction21 f)
{
if (vals.isEmpty ())
return 0;
if (vals.size () == 1)
return vals.get (0);
int subTotal = vals.get (0);
for (int i = 1; i < vals.size (); i++)
subTotal = f.apply (subTotal, vals.get (i));
return subTotal;
}
public static int reduceByAdd (List<Integer> vals)
{
if (vals.isEmpty ())
return 0;
if (vals.size () == 1)
return vals.get (0);
int subTotal = vals.get (0);
for (int i = 1; i < vals.size (); i++)
subTotal += vals.get (i);
return subTotal;
}
public static void stage2 ()
{
List<Integer> numsA = Arrays.asList (1, 2, 3, 4, 5);
List<Integer> result1 = filterBy (numsA, x->x > 2);
System.out.println (result1);
List<String> names = Arrays.asList ("joe", "jill", "sue", "jack", "kim");
Predicate<String> jNames = x->x.startsWith ("j");
List<String> result2 = jNames.filterBy (names);
System.out.println (result2);
}
public static void stage1 ()
{
List<Integer> numsA = Arrays.asList (1, 2, 3, 4, 5);
ArrayList<Integer> numsB = new ArrayList<>(numsA);
numsB.replaceAll (x->x*2);
numsB.removeIf (x->x < 5);
numsB.forEach (System.out::println);
}
public static List<Integer> filterBy (List<Integer> nums, IntPredicate p)
{
List<Integer> result = new ArrayList<Integer>();
for (Integer num : nums)
{
if (p.predicate(num))
result.add (num);
}
return result;
}
}
interface IntPredicate
{
boolean predicate (int val);
}
interface Predicate<T>
{
boolean predicate (T val);
public default List<T> filterBy (List<T> nums)
{
List<T> result = new ArrayList<T>();
for (T num : nums) {
if (predicate(num))
result.add (num);
}
return result;
}
}
interface IntFunction21
{
Integer apply (Integer a, Integer b);
}
interface Function2<T>
{
T apply (T a, T b);
// The 'reduceBy' method has been moved into this interface and made
// generic in the same way as was done for filterBy. Again all the
// 'int' types have been changed to 'T'.
//
// A default value parameter was needed as '0' is an integer, and this
// interface could be for any type 'T'.
default T reduce (T emptyValue, List<T> vals)
{
if (vals.isEmpty ())
return emptyValue;
if (vals.size () == 1)
return vals.get (0);
T subTotal = vals.get (0);
for (int i = 1; i < vals.size (); i++)
subTotal = apply (subTotal, vals.get (i));
return subTotal;
}
}
|
/* Copyright or (C) or Copr. GET / ENST, Telecom-Paris, Ludovic Apvrille
*
* ludovic.apvrille AT enst.fr
*
* This software is a computer program whose purpose is to allow the
* edition of TURTLE analysis, design and deployment diagrams, to
* allow the generation of RT-LOTOS or Java code from this diagram,
* and at last to allow the analysis of formal validation traces
* obtained from external tools, e.g. RTL from LAAS-CNRS and CADP
* from INRIA Rhone-Alpes.
*
* This software is governed by the CeCILL license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL license and that you accept its terms.
*/
package ui.tmldd;
import myutil.GraphicLib;
import myutil.TraceManager;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import tmltranslator.HwFPGA;
import tmltranslator.modelcompiler.ArchUnitMEC;
import ui.*;
import ui.util.IconManager;
import ui.window.JDialogFPGANode;
import javax.swing.*;
import java.awt.*;
import java.util.Vector;
/**
* Class TMLFPGACPUNode Node. To be used in TML architecture diagrams. Creation:
* 07/02/2018
*
* @author Ludovic APVRILLE, Matteo BERTOLINO
* @version 1.1 07/02/2018
*/
public class TMLArchiFPGANode extends TMLArchiNode
implements SwallowTGComponent, WithAttributes, TMLArchiElementInterface {
// Issue #31
// Issue #31
private static final int DERIVATION_X = 2;
private static final int DERIVATION_Y = 3;
private static final int MARGIN_Y_2 = 30;
// private int textY1 = 15;
// private int textY2 = 30;
// private int derivationx = 2;
// private int derivationy = 3;
private String stereotype = "FPGA";
private int byteDataSize = HwFPGA.DEFAULT_BYTE_DATA_SIZE;
private int goIdleTime = HwFPGA.DEFAULT_GO_IDLE_TIME;
private int maxConsecutiveIdleCycles = HwFPGA.DEFAULT_MAX_CONSECUTIVE_IDLE_CYCLES;
private int execiTime = HwFPGA.DEFAULT_EXECI_TIME;
private int execcTime = HwFPGA.DEFAULT_EXECC_TIME;
private int capacity = HwFPGA.DEFAULT_CAPACITY;
private int mappingPenalty = HwFPGA.DEFAULT_MAPPING_PENALTY;
private int reconfigurationTime = HwFPGA.DEFAULT_RECONFIGURATION_TIME;
private String operation = "";
private String scheduling = "";
public TMLArchiFPGANode(int _x, int _y, int _minX, int _maxX, int _minY, int _maxY, boolean _pos,
TGComponent _father, TDiagramPanel _tdp) {
super(_x, _y, _minX, _maxX, _minY, _maxY, _pos, _father, _tdp);
// Issue #31
// width = 250;
// height = 200;
minWidth = 150;
minHeight = 100;
textY = 15;
nbConnectingPoint = 16;
connectingPoint = new TGConnectingPoint[16];
connectingPoint[0] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.0, 0.0);
connectingPoint[1] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.5, 0.0);
connectingPoint[2] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 1.0, 0.0);
connectingPoint[3] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.0, 0.5);
connectingPoint[4] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 1.0, 0.5);
connectingPoint[5] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.0, 1.0);
connectingPoint[6] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.5, 1.0);
connectingPoint[7] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 1.0, 1.0);
connectingPoint[8] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.25, 0.0);
connectingPoint[9] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.75, 0.0);
connectingPoint[10] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.0, 0.25);
connectingPoint[11] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 1.0, 0.25);
connectingPoint[12] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.0, 0.75);
connectingPoint[13] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 1.0, 0.75);
connectingPoint[14] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.25, 1.0);
connectingPoint[15] = new TMLArchiConnectingPoint(this, 0, 0, false, true, 0.75, 1.0);
addTGConnectingPointsComment();
// Issue #31
initScaling(250, 200);
nbInternalTGComponent = 0;
moveable = true;
editable = true;
removable = true;
userResizable = true;
name = tdp.findNodeName("FPGA");
value = "name";
myImageIcon = IconManager.imgic1120;
}
@Override
protected void internalDrawing(Graphics g) {
Color c = g.getColor();
g.draw3DRect(x, y, width, height, true);
// Top lines
// Issue #31
final int derivationX = scale(DERIVATION_X);
final int derivationY = scale(DERIVATION_Y);
g.drawLine(x, y, x + derivationX, y - derivationY);
g.drawLine(x + width, y, x + width + derivationX, y - derivationY);
g.drawLine(x + derivationX, y - derivationY, x + width + derivationX, y - derivationY);
// Right lines
g.drawLine(x + width, y + height, x + width + derivationX, y - derivationY + height);
g.drawLine(x + derivationX + width, y - derivationY, x + width + derivationX, y - derivationY + height);
// Filling color
g.setColor(ColorManager.CPU_BOX_1);
g.fill3DRect(x + 1, y + 1, width - 1, height - 1, true);
g.setColor(c);
// Strings
String ster = "<<" + stereotype + ">>";
int w = g.getFontMetrics().stringWidth(ster);
Font f = g.getFont();
g.setFont(f.deriveFont(Font.BOLD));
drawSingleString(g, ster, x + (width - w) / 2, y + textY); // Issue #31
g.setFont(f);
w = g.getFontMetrics().stringWidth(name);
// Issue #31
final int marginY2 = scale(MARGIN_Y_2);
drawSingleString(g, name, x + (width - w) / 2, y + marginY2);
// Icon
// Issue #31
final int margin = scale(4);
g.drawImage(scale(IconManager.imgic1120.getImage()), x + margin, y + margin, null);
// g.drawImage(IconManager.img9, x + width - 20, y + 4, null);
}
@Override
public TGComponent isOnOnlyMe(int x1, int y1) {
Polygon pol = new Polygon();
pol.addPoint(x, y);
// Issue #31
final int derivationx = scale(DERIVATION_X);
final int derivationy = scale(DERIVATION_Y);
pol.addPoint(x + derivationx, y - derivationy);
pol.addPoint(x + derivationx + width, y - derivationy);
pol.addPoint(x + derivationx + width, y + height - derivationy);
pol.addPoint(x + width, y + height);
pol.addPoint(x, y + height);
if (pol.contains(x1, y1)) {
return this;
}
return null;
}
public String getNodeName() {
return name;
}
@Override
public boolean editOnDoubleClick(JFrame frame) {
boolean error = false;
String errors = "";
int tmp;
String tmpName;
JDialogFPGANode dialog = new JDialogFPGANode(getTDiagramPanel().getMainGUI(), frame, "Setting FPGA attributes",
this);
dialog.setSize(700, 500);
GraphicLib.centerOnParent(dialog, 500, 450);
// dialog.show(); // blocked until dialog has been closed
dialog.setVisible(true);
if (!dialog.isRegularClose()) {
return false;
}
if (dialog.getNodeName().length() != 0) {
tmpName = dialog.getNodeName();
tmpName = tmpName.trim();
if (!TAttribute.isAValidId(tmpName, false, false, false)) {
error = true;
errors += "Name of the node ";
} else {
name = tmpName;
}
}
if (dialog.getCapacity().length() != 0) {
try {
tmp = capacity;
capacity = Integer.decode(dialog.getCapacity()).intValue();
if (capacity <= 0) {
capacity = tmp;
error = true;
errors += "Capacity ";
}
} catch (Exception e) {
error = true;
errors += "Capacity ";
}
}
if (dialog.getMappingPenalty().length() != 0) {
try {
tmp = mappingPenalty;
mappingPenalty = Integer.decode(dialog.getMappingPenalty()).intValue();
if (mappingPenalty < 0) {
mappingPenalty = tmp;
error = true;
errors += "Mapping penalty ";
}
} catch (Exception e) {
error = true;
errors += "Mapping penalty ";
}
}
if (dialog.getReconfigurationTime().length() != 0) {
try {
tmp = reconfigurationTime;
reconfigurationTime = Integer.decode(dialog.getReconfigurationTime()).intValue();
if (reconfigurationTime <= 0) {
reconfigurationTime = tmp;
error = true;
errors += "Reconfiguration time ";
}
} catch (Exception e) {
error = true;
errors += "Reconfiguration time ";
}
}
if (dialog.getByteDataSize().length() != 0) {
try {
tmp = byteDataSize;
byteDataSize = Integer.decode(dialog.getByteDataSize()).intValue();
if (byteDataSize <= 0) {
byteDataSize = tmp;
error = true;
errors += "Data size ";
}
} catch (Exception e) {
error = true;
errors += "Data size ";
}
}
if (dialog.getGoIdleTime().length() != 0) {
try {
tmp = goIdleTime;
goIdleTime = Integer.decode(dialog.getGoIdleTime()).intValue();
if (goIdleTime < 0) {
goIdleTime = tmp;
error = true;
errors += "Go idle time ";
}
} catch (Exception e) {
error = true;
errors += "Go idle time ";
}
}
if (dialog.getMaxConsecutiveIdleCycles().length() != 0) {
try {
tmp = goIdleTime;
maxConsecutiveIdleCycles = Integer.decode(dialog.getMaxConsecutiveIdleCycles()).intValue();
if (maxConsecutiveIdleCycles < 0) {
maxConsecutiveIdleCycles = tmp;
error = true;
errors += "Max consecutive idle cycles ";
}
} catch (Exception e) {
error = true;
errors += "Max consecutive idle cycles ";
}
}
if (dialog.getExeciTime().length() != 0) {
try {
tmp = execiTime;
execiTime = Integer.decode(dialog.getExeciTime()).intValue();
if (execiTime < 0) {
execiTime = tmp;
error = true;
errors += "execi time ";
}
} catch (Exception e) {
error = true;
errors += "execi time ";
}
}
if (dialog.getExeccTime().length() != 0) {
try {
tmp = execcTime;
execcTime = Integer.decode(dialog.getExeccTime()).intValue();
if (execcTime < 0) {
execcTime = tmp;
error = true;
errors += "execc time ";
}
} catch (Exception e) {
error = true;
errors += "execc time ";
}
}
if (dialog.getClockRatio().length() != 0) {
try {
tmp = clockRatio;
clockRatio = Integer.decode(dialog.getClockRatio()).intValue();
if (clockRatio < 1) {
clockRatio = tmp;
error = true;
errors += "Clock divider ";
}
} catch (Exception e) {
error = true;
errors += "Clock divider ";
}
}
customData = dialog.getCustomData();
TraceManager.addDev("Custom Data=" + customData);
operation = dialog.getOperation().trim();
scheduling = dialog.getScheduling().trim();
if (error) {
JOptionPane.showMessageDialog(frame, "Invalid value for the following attributes: " + errors, "Error",
JOptionPane.INFORMATION_MESSAGE);
return false;
}
return true;
}
@Override
public int getType() {
return TGComponentManager.TMLARCHI_FPGANODE;
}
@Override
public boolean acceptSwallowedTGComponent(TGComponent tgc) {
return tgc instanceof TMLArchiArtifact;
}
@Override
public boolean addSwallowedTGComponent(TGComponent tgc, int x, int y) {
// Set its coordinates
if (tgc instanceof TMLArchiArtifact) {
tgc.setFather(this);
tgc.setDrawingZone(true);
tgc.resizeWithFather();
addInternalComponent(tgc, 0);
return true;
}
return false;
}
@Override
public void removeSwallowedTGComponent(TGComponent tgc) {
removeInternalComponent(tgc);
}
public Vector<TMLArchiArtifact> getArtifactList() {
Vector<TMLArchiArtifact> v = new Vector<TMLArchiArtifact>();
for (int i = 0; i < nbInternalTGComponent; i++) {
if (tgcomponent[i] instanceof TMLArchiArtifact) {
v.add((TMLArchiArtifact) tgcomponent[i]);
}
}
return v;
}
// Issue #31
// public void hasBeenResized() {
// for(int i=0; i<nbInternalTGComponent; i++) {
// if (tgcomponent[i] instanceof TMLArchiArtifact) {
// tgcomponent[i].resizeWithFather();
// }
// }
// }
@Override
protected String translateExtraParam() {
StringBuffer sb = new StringBuffer("<extraparam>\n");
sb.append("<info stereotype=\"" + stereotype + "\" nodeName=\"" + name);
sb.append("\" />\n");
sb.append("<attributes capacity=\"" + capacity + "\" byteDataSize=\"" + byteDataSize + "\" ");
sb.append(" mappingPenalty=\"" + mappingPenalty + "\" ");
sb.append(" reconfigurationTime=\"" + reconfigurationTime + "\" ");
sb.append(" goIdleTime=\"" + goIdleTime + "\" ");
sb.append(" maxConsecutiveIdleCycles=\"" + maxConsecutiveIdleCycles + "\" ");
sb.append(" execiTime=\"" + execiTime + "\"");
sb.append(" execcTime=\"" + execcTime + "\"");
sb.append(" clockRatio=\"" + clockRatio + "\"");
sb.append(" operation =\"" + operation + "\" ");
sb.append(" scheduling =\"" + scheduling + "\" ");
sb.append("/>\n");
sb.append("</extraparam>\n");
return new String(sb);
}
@Override
public void loadExtraParam(NodeList nl, int decX, int decY, int decId) throws MalformedModelingException {
//
try {
NodeList nli;
Node n1, n2;
Element elt;
// int t1id;
String sstereotype = null, snodeName = null;
// String operationTypesTmp;
for (int i = 0; i < nl.getLength(); i++) {
n1 = nl.item(i);
//
if (n1.getNodeType() == Node.ELEMENT_NODE) {
nli = n1.getChildNodes();
// Issue #17 copy-paste error on j index
for (int j = 0; j < nli.getLength(); j++) {
n2 = nli.item(j);
//
if (n2.getNodeType() == Node.ELEMENT_NODE) {
elt = (Element) n2;
if (elt.getTagName().equals("info")) {
sstereotype = elt.getAttribute("stereotype");
snodeName = elt.getAttribute("nodeName");
}
if (sstereotype != null) {
stereotype = sstereotype;
}
if (snodeName != null) {
name = snodeName;
}
if (elt.getTagName().equals("attributes")) {
try {
// the "try" statement is for retro compatibility
capacity = Integer.decode(elt.getAttribute("capacity")).intValue();
} catch (Exception e) {
}
byteDataSize = Integer.decode(elt.getAttribute("byteDataSize")).intValue();
mappingPenalty = Integer.decode(elt.getAttribute("mappingPenalty")).intValue();
goIdleTime = Integer.decode(elt.getAttribute("goIdleTime")).intValue();
reconfigurationTime = Integer.decode(elt.getAttribute("reconfigurationTime"))
.intValue();
if ((elt.getAttribute("execiTime") != null)
&& (elt.getAttribute("execiTime").length() > 0)) {
execiTime = Integer.decode(elt.getAttribute("execiTime")).intValue();
}
if ((elt.getAttribute("execcTime") != null)
&& (elt.getAttribute("execcTime").length() > 0)) {
execcTime = Integer.decode(elt.getAttribute("execcTime")).intValue();
}
if ((elt.getAttribute("maxConsecutiveIdleCycles") != null)
&& (elt.getAttribute("maxConsecutiveIdleCycles").length() > 0)) {
maxConsecutiveIdleCycles = Integer
.decode(elt.getAttribute("maxConsecutiveIdleCycles")).intValue();
}
if ((elt.getAttribute("clockRatio") != null)
&& (elt.getAttribute("clockRatio").length() > 0)) {
clockRatio = Integer.decode(elt.getAttribute("clockRatio")).intValue();
}
if ((elt.getAttribute("MECType") != null)
&& (elt.getAttribute("MECType").length() > 0)) {
if (elt.getAttribute("MECType").length() > 1) { // old format
MECType = ArchUnitMEC.Types.get(0);
} else {
MECType = ArchUnitMEC.Types.get(Integer.valueOf(elt.getAttribute("MECType")));
}
}
operation = elt.getAttribute("operation");
if (operation == null) {
operation = "";
}
scheduling = elt.getAttribute("scheduling");
if (scheduling == null) {
scheduling = "";
}
}
}
}
}
}
} catch (Exception e) {
throw new MalformedModelingException(e);
}
}
@Override
public int getDefaultConnector() {
return TGComponentManager.CONNECTOR_NODE_TMLARCHI;
}
public int getCapacity() {
return capacity;
}
public int getByteDataSize() {
return byteDataSize;
}
public int getReconfigurationTime() {
return reconfigurationTime;
}
public int getGoIdleTime() {
return goIdleTime;
}
public int getMaxConsecutiveIdleCycles() {
return maxConsecutiveIdleCycles;
}
public int getExeciTime() {
return execiTime;
}
public int getExeccTime() {
return execcTime;
}
public int getMappingPenalty() {
return mappingPenalty;
}
public String getOperation() {
return operation;
}
public String getScheduling() {
return scheduling;
}
@Override
public String getAttributes() {
String attr = "";
attr += "Data size (in byte) = " + byteDataSize + "\n";
attr += "Capacity = " + capacity + "\n";
attr += "Mapping penalty (percentage) = " + mappingPenalty + "\n";
attr += "Reconfiguration time = " + reconfigurationTime + "\n";
attr += "Go in idle mode (in cycle) = " + goIdleTime + "\n";
attr += "Idle cycles to go idle = " + maxConsecutiveIdleCycles + "\n";
attr += "EXECI exec. time (in cycle) = " + execiTime + "\n";
attr += "EXECC exec. time (in cycle) = " + execcTime + "\n";
attr += "Operation = " + operation + "\n";
attr += "Clock divider = " + clockRatio + "\n";
return attr;
}
@Override
public int getComponentType() {
return CONTROLLER;
}
}
|
import { Sun, Moon } from "lucide-react";
import { Theme } from "~/utils/theme-provider";
const iconThemeMap = new Map([
[Theme.LIGHT, Sun],
[Theme.DARK, Moon],
]);
export interface ThemeToggleIconProps {
theme: Theme;
checked: boolean;
}
export const ThemeToggleIcon = ({ theme, checked }: ThemeToggleIconProps) => {
const Component = iconThemeMap.get(theme);
if (Component) {
return (
<Component
key={theme}
width={23}
className={checked ? "fill-text-primary dark:fill-d-text-primary" : ""}
/>
);
}
return <></>;
};
export default ThemeToggleIcon;
|
import * as vscode from 'vscode';
export default class Terminal {
private _instance: vscode.Terminal;
constructor(
name: string,
shellPath?: string,
shellArgs?: string,
location?: vscode.TerminalLocation
) {
this._instance = vscode.window.createTerminal({
name,
shellPath,
shellArgs,
location: location ? location : vscode.TerminalLocation.Panel,
});
}
public get name() {
return this._instance.name;
}
public show() {
this._instance.show();
}
public sendText(text: string) {
this._instance.sendText(text);
}
public async close(): Promise<vscode.TerminalExitStatus> {
// Reference: https://stackoverflow.com/questions/55943439/how-to-wait-until-vscode-windows-terminal-operation-is-over
// this.sendText('exit');
return new Promise((resolve, reject) => {
const disposeToken = vscode.window.onDidCloseTerminal((closedTerminal) => {
if (closedTerminal === this._instance) {
disposeToken.dispose();
// No forcible close
if (this._instance.exitStatus !== undefined) {
resolve(this._instance.exitStatus);
return;
}
reject('Terminal exited with undefined status');
}
});
});
}
}
|
import { Link } from 'react-router-dom';
import Header from "../components/Header.jsx";
import {ProductContext} from "../context/ProductContext.jsx";
import {useContext} from "react";
import {CartContext} from "../context/CartContext.jsx";
export default function CatalogPage() {
const { products, isLoading, error } = useContext(ProductContext);
const { addToCart } = useContext(CartContext);
const handleAddToCart = (item) => {
addToCart(item);
alert("Added!");
}
return (
<>
<Header />
{isLoading ? <div className={"loading"}><h1>Fetching data...</h1></div> : error ? <div className={"error"}><h1>❌ Error while fetching data: {error}</h1></div> :
<div className={"products-wrapper"}>
{products.map(product => (
<div className={"product"} key={product.id}>
<Link to={`/catalog/product/${product.id}`} state={{product}}>
<img src={product.image} alt={product.title} style={{width: "100px"}}/>
<h3>{product.title}</h3>
</Link>
<hr/>
<div className={"price-wrapper"}>
<p>${product.price}</p>
<button onClick={() => handleAddToCart(product)}>Buy</button>
</div>
</div>
))}
</div>
}
</>
);
}
|
use rustler::{Atom, Error, NifResult, Binary};
use rustler::types::atom;
use rustix::io::Errno;
use std::io;
// Sucess means it will be encoded as an atom (from static string)
// Failure means it will be encoded as a string
fn io_error_to_atom(err: io::Error) -> Result<&'static str, String> {
if let Some(code) = err.raw_os_error() {
match Errno::from_raw_os_error(code) {
Errno::TOOBIG => Ok("e2big"),
Errno::ACCESS => Ok("eacces"),
Errno::INVAL => Ok("einval"),
Errno::IO => Ok("eio"),
Errno::NODATA => Ok("enodata"),
Errno::NOENT => Ok("enoent"),
Errno::NOMEM => Ok("enomem"),
Errno::NOSPC => Ok("enospc"),
Errno::PERM => Ok("eperm"),
Errno::ROFS => Ok("erofs"),
Errno::NOTSUP => Ok("enotsup"),
_ => Err(err.to_string()),
}
} else if err.kind() == io::ErrorKind::Unsupported {
Ok("enotsup")
} else {
Err(err.to_string())
}
}
#[rustler::nif]
fn supported_platform() -> bool {
xattr::SUPPORTED_PLATFORM
}
#[rustler::nif]
fn get_xattr(path: String, name: String) -> NifResult<Option<Vec<u8>>> {
match xattr::get(path, name) {
Ok(Some(value)) => Ok(Some(value)),
Ok(None) => Ok(None),
Err(e) => match io_error_to_atom(e) {
Ok(atom_str) => Err(Error::Atom(atom_str)),
Err(msg) => Err(Error::Term(Box::new(msg))),
},
}
}
#[rustler::nif]
fn set_xattr(path: String, name: String, value: Binary) -> NifResult<Atom> {
match xattr::set(path, name, value.as_slice()) {
Ok(_) => Ok(atom::ok()),
Err(e) => match io_error_to_atom(e) {
Ok(atom_str) => Err(Error::Atom(atom_str)),
Err(msg) => Err(Error::Term(Box::new(msg))),
},
}
}
#[rustler::nif]
fn list_xattr(path: String) -> NifResult<Vec<String>> {
match xattr::list(path) {
Ok(attrs) => attrs.map(|attr| {
attr.into_string().map_err(|_| Error::Term(Box::new("Failed to convert OsString".to_string())))
}).collect(),
Err(e) => match io_error_to_atom(e) {
Ok(atom_str) => Err(Error::Atom(atom_str)),
Err(msg) => Err(Error::Term(Box::new(msg))),
},
}
}
#[rustler::nif]
fn remove_xattr(path: String, name: String) -> NifResult<Atom> {
match xattr::remove(path, name) {
Ok(_) => Ok(atom::ok()),
Err(e) => match io_error_to_atom(e) {
Ok(atom_str) => Err(Error::Atom(atom_str)),
Err(msg) => Err(Error::Term(Box::new(msg))),
},
}
}
rustler::init!("Elixir.ExAttr.Nif", [
supported_platform,
get_xattr,
set_xattr,
list_xattr,
remove_xattr,
]);
|
import { useQuery } from '@tanstack/react-query';
import { format } from 'date-fns';
import React, { useState } from 'react';
import Loading from '../../Shared/Loading/Loading';
import BookingModal from '../BookingModal/BookingModal';
import AppointmentOption from '../AppointmentOptions/AppointmentOption';
import './AvailableAppointments.css';
const AvailableAppointments = ({ selectedDate }) => {
const [treatment, setTreatment] = useState(null);
const date = format(selectedDate, 'PP');
const { data: appointmentOptions = [], refetch, isLoading } = useQuery({
queryKey: ['appointmentOptions', date],
queryFn: async () => {
const res = await fetch(`https://booking-app-server-green.vercel.app/v2/appointmentOptions?date=${date}`);
const data = await res.json();
return data;
}
});
if (isLoading) {
return <Loading></Loading>
}
return (
<section className=''>
<header className='my-24 max-w-[1200px] mx-auto container all-option'>
<p className='text-center top-service'>Our Services</p>
<p className='text-center time'>Available Services on {format(selectedDate, 'PP')}</p>
<div className=' card grid gap-7 sm:gap-6 lg:gap-6 grid-cols-1 md:grid-cols-1 lg:grid-cols-3 max-sm:mt-6 mx-auto'>
{
appointmentOptions.map(option => <AppointmentOption
key={option._id}
appointmentOption={option}
setTreatment={setTreatment}
></AppointmentOption>)
}
</div>
{
treatment &&
<BookingModal
selectedDate={selectedDate}
treatment={treatment}
setTreatment={setTreatment}
refetch={refetch}
></BookingModal>}
</header>
</section>
);
};
export default AvailableAppointments;
|
import React from 'react';
import { Label } from '../../components/SignUp/Label';
import { Input } from '../../components/SignUp/Input';
import { cn } from '../../utils/cn';
import { IconBrandFacebook, IconBrandGoogle } from '@tabler/icons-react';
import { Form, Link, redirect } from 'react-router-dom';
import { Textarea } from '../../components/SignUp/Textarea';
import { BsHouses } from 'react-icons/bs';
import ImagePicker from '../../ui/ImagePicker/ImagePicker';
import { GiJumpingDog } from 'react-icons/gi';
import { FaBusinessTime } from 'react-icons/fa';
export function SignupForm() {
// const handleSubmit = (e) => {
// e.preventDefault();
// console.log('Form submitted');
// };
return (
<div className="max-w-xl w-full mx-auto mt-20 rounded-none md:rounded-2xl p-4 md:p-8 shadow-input bg-white dark:bg-black">
<h2 className="font-bold text-xl text-[#2D3250] dark:text-neutral-200">
Welcome to AniCCare Hub
</h2>
<p className="text-[#2D3250] text-sm max-w-sm mt-2 dark:text-neutral-300">
Welcome onboard, please sign up to aniccarehub.
</p>
<Form className="my-8" method="post">
<div className="flex flex-col md:flex-row space-y-2 md:space-y-0 md:space-x-2 mb-4">
<LabelInputContainer>
<Label htmlFor="firstname" className="text-[#2D3250]">
First name
</Label>
<Input
id="firstname"
placeholder="Abiodun"
type="text"
name="first-name"
required
/>
</LabelInputContainer>
<LabelInputContainer>
<Label htmlFor="lastname" className="text-[#2D3250]">
Last name
</Label>
<Input
id="lastname"
placeholder="Olajide"
type="text"
name="last-name"
required
/>
</LabelInputContainer>
</div>
<LabelInputContainer className="mb-4">
<Label htmlFor="school-name" className="text-[#2D3250]">
Name of School
</Label>
<Input
id="school-name"
placeholder="my school name"
type="text"
name="school-name"
required
/>
</LabelInputContainer>
<LabelInputContainer className="mb-4">
<Label htmlFor="address" className="text-[#2D3250]">
School Address
</Label>
<Textarea
id="address"
placeholder="6 Wale Ojerinde Street, Iroko Town, Ajegunle Bus-Stop, Sango Ota, Ogun State"
required
name="address"
></Textarea>
</LabelInputContainer>
<LabelInputContainer className="mb-4">
<Label htmlFor="email" className="text-[#2D3250]">
Email Address
</Label>
<Input
id="email"
placeholder="specialthanks@toGod.com"
type="email"
name="email"
required
/>
</LabelInputContainer>
<LabelInputContainer className="mb-4">
<Label htmlFor="password" className="text-[#2D3250]">
Password
</Label>
<Input
id="password"
placeholder="••••••••"
type="password"
name="password"
title="Minimum 6 characters at least 1 Alphabet and 1 Number"
pattern="^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$"
required
/>
</LabelInputContainer>
<fieldset className="mb-4">
<legend className="mb-4 font-semibold text-gray-900 dark:text-white">
Select Service with the required Number of Pictures
</legend>
<ul className="w-full text-sm font-medium text-gray-900 bg-white border border-gray-200 rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
<li className="w-full border-b border-gray-200 rounded-t-lg dark:border-gray-600">
<div className="">
<label
htmlFor="boarding-facility"
className="peer flex items-center ps-2 gap-2 w-full py-3 ms-2 text-sm font-medium text-gray-900 dark:text-gray-300 pe-5"
>
<span className="flex items-center gap-5 w-full">
<BsHouses className="h-5 w-5 text-[#2D3250] dark:text-[#7E8EF1]" />
Boarding facility
</span>
<input
id="boarding-facility"
type="radio"
value=""
required
name="image-picker"
className="peer/boarding-facility w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-700 dark:focus:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
/>
</label>
<div className="hidden peer-has-[:checked]:block">
<ImagePicker />
<ImagePicker />
<ImagePicker />
<ImagePicker />
</div>
</div>
</li>
<li className="w-full border-b border-gray-200 rounded-t-lg dark:border-gray-600">
<div className="">
<label
htmlFor="dog-school"
className="peer flex items-center ps-2 gap-2 w-full py-3 ms-2 text-sm font-medium text-gray-900 dark:text-gray-300 pe-5"
>
<span className="flex items-center gap-5 w-full">
<GiJumpingDog className="h-5 w-5 text-[#2D3250] dark:text-[#7E8EF1]" />
Dog School
</span>
<input
id="dog-school"
type="radio"
value=""
required
name="image-picker"
className="peer/boarding-facility w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-700 dark:focus:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
/>
</label>
<div className="hidden peer-has-[:checked]:block">
<ImagePicker />
</div>
</div>
</li>
<li className="w-full border-b border-gray-200 rounded-t-lg dark:border-gray-600">
<div className="">
<label
htmlFor="dog-sale"
className="peer flex items-center ps-2 gap-2 w-full py-3 ms-2 text-sm font-medium text-gray-900 dark:text-gray-300 pe-5"
>
<span className="flex items-center gap-5 w-full">
<FaBusinessTime className="h-5 w-5 text-[#2D3250] dark:text-[#7E8EF1]" />
Dog Sale
</span>
<input
id="dog-sale"
type="radio"
value=""
required
name="image-picker"
className="peer/boarding-facility w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-700 dark:focus:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"
/>
</label>
<div className="hidden peer-has-[:checked]:block">
<ImagePicker />
</div>
</div>
</li>
</ul>
</fieldset>
<button
className="bg-gradient-to-br relative group/btn from-[#FFBF9B] dark:from-zinc-900 dark:to-zinc-900 to-[#F6B17A] block dark:bg-zinc-800 w-full text-[#2D3250] dark:text-[#7E8EF1] rounded-md h-10 font-medium shadow-[0px_1px_0px_0px_#ffffff40_inset,0px_-1px_0px_0px_#ffffff40_inset] dark:shadow-[0px_1px_0px_0px_var(--zinc-800)_inset,0px_-1px_0px_0px_var(--zinc-800)_inset]"
type="submit"
>
Sign up →
<BottomGradient />
</button>
<div className="bg-gradient-to-r from-transparent via-neutral-300 dark:via-neutral-700 to-transparent my-8 h-[1px] w-full" />
<div className="flex flex-col space-y-4">
<button
className=" relative group/btn flex space-x-2 items-center justify-start px-4 w-full text-black rounded-md h-10 font-medium shadow-input bg-gray-50 dark:bg-zinc-900 dark:shadow-[0px_0px_1px_1px_var(--neutral-800)]"
type="submit"
>
<IconBrandFacebook className="h-4 w-4 text-neutral-800 dark:text-neutral-300" />
<span className="text-[#2D3250] dark:text-neutral-300 text-sm">
Facebook
</span>
<BottomGradient />
</button>
<button
className=" relative group/btn flex space-x-2 items-center justify-start px-4 w-full text-black rounded-md h-10 font-medium shadow-input bg-gray-50 dark:bg-zinc-900 dark:shadow-[0px_0px_1px_1px_var(--neutral-800)]"
type="submit"
>
<IconBrandGoogle className="h-4 w-4 text-neutral-800 dark:text-neutral-300" />
<span className="text-[#2D3250] dark:text-neutral-300 text-sm">
Google
</span>
<BottomGradient />
</button>
</div>
</Form>
</div>
);
}
const BottomGradient = () => {
return (
<>
<span className="group-hover/btn:opacity-100 block transition duration-500 opacity-0 absolute h-px w-full -bottom-px inset-x-0 bg-gradient-to-r from-transparent via-cyan-500 to-transparent" />
<span className="group-hover/btn:opacity-100 blur-sm block transition duration-500 opacity-0 absolute h-px w-1/2 mx-auto -bottom-px inset-x-10 bg-gradient-to-r from-transparent via-indigo-500 to-transparent" />
</>
);
};
const LabelInputContainer = ({ children, className }) => {
return (
<div className={cn('flex flex-col space-y-2 w-full', className)}>
{children}
</div>
);
};
export async function action({ request }) {
const url = 'http://localhost:8000/posts';
const formData = await request.formData();
const postData = Object.fromEntries(formData);
const response = await fetch(url, {
methods: 'POST',
body: JSON.stringify(postData),
headers: {
'Content-Type': 'application/json',
},
});
return redirect('/');
}
|
package com.example.springapp.controller;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springapp.model.Employee;
import com.example.springapp.services.EmployeeService;
@RestController
@RequestMapping("/api")
public class EmployeeController {
private EmployeeService employeeServices;
public EmployeeController(EmployeeService employeeServices)
{
this.employeeServices = employeeServices;
}
@PostMapping("/employee")
public ResponseEntity<Employee> addData(@RequestBody Employee employee)
{
if(employeeServices.addemployee(employee))
{
return new ResponseEntity<Employee>(employee, HttpStatus.CREATED);
}
else{
System.out.println("Cannot add Object");
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping("/employee")
public ResponseEntity<List<Employee>> getList()
{
List<Employee> employees = employeeServices.getemployees();
if(employees.size() > 0)
{
return new ResponseEntity<List<Employee>>(employees, HttpStatus.OK);
}
else{
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@GetMapping("/employee/{employeeId}")
public ResponseEntity<Employee> getemployeeById(@PathVariable int employeeId){
Employee employee = employeeServices.getemployeeById(employeeId);
if(employee != null)
{
return new ResponseEntity<Employee>(employee, HttpStatus.OK);
}
else{
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
|
<?php
/*
* $Id: DeleteTask.php 321 2007-12-14 18:00:25Z hans $
*
* 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.
*
* This software consists of voluntary contributions made by many individuals
* and is licensed under the LGPL. For more information please see
* <http://phing.info>.
*/
require_once 'phing/Task.php';
/**
* Deletes a file or directory, or set of files defined by a fileset.
*
* @version $Revision: 1.13 $
* @package phing.tasks.system
*/
class DeleteTask extends Task {
protected $file;
protected $dir;
protected $filesets = array();
protected $includeEmpty = false;
protected $quiet = false;
protected $failonerror = true;
protected $verbosity = Project::MSG_VERBOSE;
/** Any filelists of files that should be deleted. */
private $filelists = array();
/**
* Set the name of a single file to be removed.
* @param PhingFile $file
*/
function setFile(PhingFile $file) {
$this->file = $file;
}
/**
* Set the directory from which files are to be deleted.
* @param PhingFile $dir
*/
function setDir(PhingFile $dir) {
$this->dir = $dir;
}
/**
* Used to force listing of all names of deleted files.
* @param boolean $verbosity
*/
function setVerbose($verbosity) {
if ($verbosity) {
$this->verbosity = Project::MSG_INFO;
} else {
$this->verbosity = Project::MSG_VERBOSE;
}
}
/**
* If the file does not exist, do not display a diagnostic
* message or modify the exit status to reflect an error.
* This means that if a file or directory cannot be deleted,
* then no error is reported. This setting emulates the
* -f option to the Unix rm command. Default is false
* meaning things are verbose
*/
function setQuiet($bool) {
$this->quiet = $bool;
if ($this->quiet) {
$this->failonerror = false;
}
}
/** this flag means 'note errors to the output, but keep going' */
function setFailOnError($bool) {
$this->failonerror = $bool;
}
/** Used to delete empty directories.*/
function setIncludeEmptyDirs($includeEmpty) {
$this->includeEmpty = (boolean) $includeEmpty;
}
/** Nested creator, adds a set of files (nested fileset attribute). */
function createFileSet() {
$num = array_push($this->filesets, new FileSet());
return $this->filesets[$num-1];
}
/** Nested creator, adds a set of files (nested fileset attribute). */
function createFileList() {
$num = array_push($this->filelists, new FileList());
return $this->filelists[$num-1];
}
/** Delete the file(s). */
function main() {
if ($this->file === null && $this->dir === null && count($this->filesets) === 0 && count($this->filelists) === 0) {
throw new BuildException("At least one of the file or dir attributes, or a fileset element, or a filelist element must be set.");
}
if ($this->quiet && $this->failonerror) {
throw new BuildException("quiet and failonerror cannot both be set to true", $this->location);
}
// delete a single file
if ($this->file !== null) {
if ($this->file->exists()) {
if ($this->file->isDirectory()) {
$this->log("Directory " . $this->file->__toString() . " cannot be removed using the file attribute. Use dir instead.");
} else {
$this->log("Deleting: " . $this->file->__toString());
try {
$this->file->delete();
} catch(Exception $e) {
$message = "Unable to delete file " . $this->file->__toString() .": " .$e->getMessage();
if($this->failonerror) {
throw new BuildException($message);
} else {
$this->log($message, $this->quiet ? Project::MSG_VERBOSE : Project::MSG_WARN);
}
}
}
} else {
$this->log("Could not find file " . $this->file->getAbsolutePath() . " to delete.",Project::MSG_VERBOSE);
}
}
// delete the directory
if ($this->dir !== null && $this->dir->exists() && $this->dir->isDirectory()) {
if ($this->verbosity === Project::MSG_VERBOSE) {
$this->log("Deleting directory " . $this->dir->__toString());
}
$this->removeDir($this->dir);
}
// delete the files in the filelists
foreach($this->filelists as $fl) {
try {
$files = $fl->getFiles($this->project);
$this->removeFiles($fl->getDir($this->project), $files, $empty=array());
} catch (BuildException $be) {
// directory doesn't exist or is not readable
if ($this->failonerror) {
throw $be;
} else {
$this->log($be->getMessage(), $this->quiet ? Project::MSG_VERBOSE : Project::MSG_WARN);
}
}
}
// delete the files in the filesets
foreach($this->filesets as $fs) {
try {
$ds = $fs->getDirectoryScanner($this->project);
$files = $ds->getIncludedFiles();
$dirs = $ds->getIncludedDirectories();
$this->removeFiles($fs->getDir($this->project), $files, $dirs);
} catch (BuildException $be) {
// directory doesn't exist or is not readable
if ($this->failonerror) {
throw $be;
} else {
$this->log($be->getMessage(), $this->quiet ? Project::MSG_VERBOSE : Project::MSG_WARN);
}
}
}
}
/**
* Recursively removes a directory.
* @param PhingFile $d The directory to remove.
*/
private function removeDir($d) {
$list = $d->listDir();
if ($list === null) {
$list = array();
}
foreach($list as $s) {
$f = new PhingFile($d, $s);
if ($f->isDirectory()) {
$this->removeDir($f);
} else {
$this->log("Deleting " . $f->__toString(), $this->verbosity);
try {
$f->delete();
} catch (Exception $e) {
$message = "Unable to delete file " . $f->__toString() . ": " . $e->getMessage();
if($this->failonerror) {
throw new BuildException($message);
} else {
$this->log($message, $this->quiet ? Project::MSG_VERBOSE : Project::MSG_WARN);
}
}
}
}
$this->log("Deleting directory " . $d->getAbsolutePath(), $this->verbosity);
try {
$d->delete();
} catch (Exception $e) {
$message = "Unable to delete directory " . $d->__toString() . ": " . $e->getMessage();
if($this->failonerror) {
throw new BuildException($message);
} else {
$this->log($message, $this->quiet ? Project::MSG_VERBOSE : Project::MSG_WARN);
}
}
}
/**
* remove an array of files in a directory, and a list of subdirectories
* which will only be deleted if 'includeEmpty' is true
* @param PhingFile $d directory to work from
* @param array &$files array of files to delete; can be of zero length
* @param array &$dirs array of directories to delete; can of zero length
*/
private function removeFiles(PhingFile $d, &$files, &$dirs) {
if (count($files) > 0) {
$this->log("Deleting " . count($files) . " files from " . $d->__toString());
for ($j=0,$_j=count($files); $j < $_j; $j++) {
$f = new PhingFile($d, $files[$j]);
$this->log("Deleting " . $f->getAbsolutePath(), $this->verbosity);
try {
$f->delete();
} catch (Exception $e) {
$message = "Unable to delete file " . $f->__toString() . ": " . $e->getMessage();
if($this->failonerror) {
throw new BuildException($message);
} else {
$this->log($message, $this->quiet ? Project::MSG_VERBOSE : Project::MSG_WARN);
}
}
}
}
if (count($dirs) > 0 && $this->includeEmpty) {
$dirCount = 0;
for ($j=count($dirs)-1; $j>=0; --$j) {
$dir = new PhingFile($d, $dirs[$j]);
$dirFiles = $dir->listDir();
if ($dirFiles === null || count($dirFiles) === 0) {
$this->log("Deleting " . $dir->__toString(), $this->verbosity);
try {
$dir->delete();
$dirCount++;
} catch (Exception $e) {
$message="Unable to delete directory " . $dir->__toString();
if($this->failonerror) {
throw new BuildException($message);
} else {
$this->log($message, $this->quiet ? Project::MSG_VERBOSE : Project::MSG_WARN);
}
}
}
}
if ($dirCount > 0) {
$this->log("Deleted $dirCount director" . ($dirCount==1 ? "y" : "ies") . " from " . $d->__toString());
}
}
}
}
|
import tinycolor from 'tinycolor2'
import { nanoid } from 'nanoid'
import { Template, CanvasElement } from '@/types/canvas'
import { ElementNames } from '@/types/elements'
// import { PPTElement, PPTLineElement, Slide } from '@/types/slides'
interface RotatedElementData {
left: number
top: number
width: number
height: number
rotate: number
}
/**
* 计算元素在画布中的矩形范围旋转后的新位置范围
* @param element 元素的位置大小和旋转角度信息
*/
export const getRectRotatedRange = (element: RotatedElementData) => {
const { left, top, width, height, rotate = 0 } = element
const radius = Math.sqrt( Math.pow(width, 2) + Math.pow(height, 2) ) / 2
const auxiliaryAngle = Math.atan(height / width) * 180 / Math.PI
const tlbraRadian = (180 - rotate - auxiliaryAngle) * Math.PI / 180
const trblaRadian = (auxiliaryAngle - rotate) * Math.PI / 180
const middleLeft = left + width / 2
const middleTop = top + height / 2
const xAxis = [
middleLeft + radius * Math.cos(tlbraRadian),
middleLeft + radius * Math.cos(trblaRadian),
middleLeft - radius * Math.cos(tlbraRadian),
middleLeft - radius * Math.cos(trblaRadian),
]
const yAxis = [
middleTop - radius * Math.sin(tlbraRadian),
middleTop - radius * Math.sin(trblaRadian),
middleTop + radius * Math.sin(tlbraRadian),
middleTop + radius * Math.sin(trblaRadian),
]
return {
xRange: [Math.min(...xAxis), Math.max(...xAxis)],
yRange: [Math.min(...yAxis), Math.max(...yAxis)],
}
}
/**
* 计算元素在画布中的矩形范围旋转后的新位置与旋转之前位置的偏离距离
* @param element 元素的位置大小和旋转角度信息
*/
export const getRectRotatedOffset = (element: RotatedElementData) => {
const { xRange: originXRange, yRange: originYRange } = getRectRotatedRange({
left: element.left,
top: element.top,
width: element.width,
height: element.height,
rotate: 0,
})
const { xRange: rotatedXRange, yRange: rotatedYRange } = getRectRotatedRange({
left: element.left,
top: element.top,
width: element.width,
height: element.height,
rotate: element.rotate,
})
return {
offsetX: rotatedXRange[0] - originXRange[0],
offsetY: rotatedYRange[0] - originYRange[0],
}
}
/**
* 计算元素在画布中的位置范围
* @param element 元素信息
*/
// export const getElementRange = (element: PPTElement) => {
// let minX, maxX, minY, maxY
// if (element.type === 'line') {
// minX = element.left
// maxX = element.left + Math.max(element.start[0], element.end[0])
// minY = element.top
// maxY = element.top + Math.max(element.start[1], element.end[1])
// }
// else if ('rotate' in element && element.rotate) {
// const { left, top, width, height, rotate } = element
// const { xRange, yRange } = getRectRotatedRange({ left, top, width, height, rotate })
// minX = xRange[0]
// maxX = xRange[1]
// minY = yRange[0]
// maxY = yRange[1]
// }
// else {
// minX = element.left
// maxX = element.left + element.width
// minY = element.top
// maxY = element.top + element.height
// }
// return { minX, maxX, minY, maxY }
// }
// /**
// * 计算一组元素在画布中的位置范围
// * @param elementList 一组元素信息
// */
// export const getElementListRange = (elementList: PPTElement[]) => {
// const leftValues: number[] = []
// const topValues: number[] = []
// const rightValues: number[] = []
// const bottomValues: number[] = []
// elementList.forEach(element => {
// const { minX, maxX, minY, maxY } = getElementRange(element)
// leftValues.push(minX)
// topValues.push(minY)
// rightValues.push(maxX)
// bottomValues.push(maxY)
// })
// const minX = Math.min(...leftValues)
// const maxX = Math.max(...rightValues)
// const minY = Math.min(...topValues)
// const maxY = Math.max(...bottomValues)
// return { minX, maxX, minY, maxY }
// }
export interface AlignLine {
value: number
range: [number, number]
}
/**
* 将一组对齐吸附线进行去重:同位置的的多条对齐吸附线仅留下一条,取该位置所有对齐吸附线的最大值和最小值为新的范围
* @param lines 一组对齐吸附线信息
*/
export const uniqAlignLines = (lines: AlignLine[]) => {
const uniqLines: AlignLine[] = []
lines.forEach(line => {
const index = uniqLines.findIndex(_line => _line.value === line.value)
if (index === -1) uniqLines.push(line)
else {
const uniqLine = uniqLines[index]
const rangeMin = Math.min(uniqLine.range[0], line.range[0])
const rangeMax = Math.max(uniqLine.range[1], line.range[1])
const range: [number, number] = [rangeMin, rangeMax]
const _line = { value: line.value, range }
uniqLines[index] = _line
}
})
return uniqLines
}
/**
* 以页面列表为基础,为每一个页面生成新的ID,并关联到旧ID形成一个字典
* 主要用于页面元素时,维持数据中各处页面ID原有的关系
* @param slides 页面列表
*/
export const createTemplateIdMap = (templates: Template[]) => {
const templateIdMap = {}
for (const template of templates) {
templateIdMap[template.id] = nanoid(10)
}
return templateIdMap
}
/**
* 以元素列表为基础,为每一个元素生成新的ID,并关联到旧ID形成一个字典
* 主要用于复制元素时,维持数据中各处元素ID原有的关系
* 例如:原本两个组合的元素拥有相同的groupId,复制后依然会拥有另一个相同的groupId
* @param elements 元素列表数据
*/
export const createElementIdMap = (elements: CanvasOption[]) => {
const groupIdMap = {}
const elIdMap = {}
for (const element of elements) {
const groupId = element.type === ElementNames.GROUP ? element.id : ''
if (groupId && !groupIdMap[groupId]) {
groupIdMap[groupId] = nanoid(10)
}
elIdMap[element.id] = nanoid(10)
}
return {
groupIdMap,
elIdMap,
}
}
/**
* 根据表格的主题色,获取对应用于配色的子颜色
* @param themeColor 主题色
*/
export const getTableSubThemeColor = (themeColor: string) => {
const rgba = tinycolor(themeColor)
return [
rgba.setAlpha(0.3).toRgbString(),
rgba.setAlpha(0.1).toRgbString(),
]
}
// /**
// * 获取线条元素路径字符串
// * @param element 线条元素
// */
// export const getLineElementPath = (element: PPTLineElement) => {
// const start = element.start.join(',')
// const end = element.end.join(',')
// if (element.broken) {
// const mid = element.broken.join(',')
// return `M${start} L${mid} L${end}`
// }
// else if (element.curve) {
// const mid = element.curve.join(',')
// return `M${start} Q${mid} ${end}`
// }
// else if (element.cubic) {
// const [c1, c2] = element.cubic
// const p1 = c1.join(',')
// const p2 = c2.join(',')
// return `M${start} C${p1} ${p2} ${end}`
// }
// return `M${start} L${end}`
// }
|
%% This script is derived from simCCEPLoop, except an outer loop varies the amplitude of brown noise (mulitiplicative coefficient)
% We simulate 30 reps for each combination of SNR and responsiveness and test CARLA's accuracy
% Generate data with responses at 0, 10, 20, 30, 40, 50, 60, 70, 80 percent of all channels
% The last section of this script saves examples of how the same signal looks at varying levels of SNR (Figure S2A)
%
% 2024/02/12
%
% If this code is used in a publication, please cite the manuscript:
% "CARLA: Adjusted common average referencing for cortico-cortical evoked potential data"
% by H Huang, G Ojeda Valencia, NM Gregg, GM Osman, MN Montoya,
% GA Worrell, KJ Miller, and D Hermes.
%
% CARLA manuscript package.
% Copyright (C) 2023 Harvey Huang
%
% 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/>.
%
%% Control parameters of simulated data
srate = 4800;
tt = -0.5:1/srate:1-1/srate;
nchs = 50; % number of simulated channels
ntrs = 12; % number of trials
reps = 30; % number of reps
cmSens = [1, 165/255, 0]; % use orange as color for the sensitive optimum
Aglobal = 0;
% window to calculate SNR on. Use same window as for calculating responses
snrWin = [0.01, 0.3];
%% Outer loop through brown noise level
% Set seed depending on where brown coef range is starting, for reproducibility when parallelizing.
% This is configured in main
rng(brownCoefRange(1));
for brownCoef = brownCoefRange(1):0.1:brownCoefRange(2)
fprintf('Brown noise coefficient = %0.1f\n', brownCoef);
%% Inner loop through number of responsive channels
for nresp = 0:5:40 % 0 to 80% responsiveness
%% Create data
fprintf('%d of %d channels responsive\n', nresp, nchs);
outdir = fullfile('output', 'simLoopSNR', sprintf('noise%0.1f_nchs%d-%d', brownCoef, nchs, nresp));
mkdir(outdir);
chsResp = 1:nresp; % first x channels responsive, for ease. order doesn't matter. will sort and color them red
%%
for rr = 1:reps % multiple repetitions at each significance
% i) artifact only
V0 = zeros(length(tt), nchs);
Aart = 50 + rand(nchs, 1)*5; % slightly different artifact amplitudes for each channel
artifact = sin(2*pi*600*tt)';
artifact(tt < 0 | tt > 0.002) = 0;
V0 = V0 + artifact*Aart';
% A) Add the evoked potentials
A = 100;
V1 = V0;
sig = genRandSig(tt, length(chsResp), A);
V1(:, chsResp) = V0(:, chsResp) + sig;
% B) Option to add a global noise
if Aglobal
sigCommon = genRandSig(tt, 1, Aglobal);
else
sigCommon = 0;
end
V2 = V1 + sigCommon;
% C) Add common noise to all channels at each trial
V3 = repmat(V2', 1, 1, ntrs); % ch x time points x trial
phLN = rand(ntrs, 3)*2*pi; % LN phases
LN = zeros(length(tt), ntrs);
for ii = 1:ntrs
LN(:, ii) = 8*sin(2*pi*60*tt - phLN(ii, 1)) + 2*sin(2*pi*120*tt - phLN(ii, 2)) + 1*sin(2*pi*180*tt - phLN(ii, 3));
end
% brown noise shared across channels
BN = cumsum(brownCoef*randn(2*length(tt), ntrs)); % variable brown noise coefficient now
BN = ieeg_highpass(BN, srate, true);
BN = BN((0.5*length(tt)+1) : 1.5*length(tt), :);
noiseCommon = LN + BN;
V3 = V3 + shiftdim(noiseCommon, -1);
% D) add random brown noise
noiseRand = cumsum(brownCoef*randn(nchs, 2*length(tt), ntrs), 2); % give double the number of time points so we can highpass it
for ii = 1:nchs
noiseRand(ii, :, :) = ieeg_highpass(squeeze(noiseRand(ii, :, :)), srate, true);
end
noiseRand = noiseRand(:, (0.5*length(tt)+1) : 1.5*length(tt), :);
V4 = V3 + noiseRand;
%% Calculate SNR
if nresp == 0
Psig = nan;
PnoiseRand = squeeze(sum(noiseRand(chsResp, tt >= snrWin(1) & tt < snrWin(2), :).^2, 2) / diff(snrWin));
snr = nan;
else
% power of signal (for each responsive channel created)
Psig = sum(sig(tt >= snrWin(1) & tt < snrWin(2), :).^2)' / diff(snrWin); % express as per second
% power of the aperiodic noise (common brown noise + random noise), calculated separately for each trial
noiseSum = noiseRand + shiftdim(BN, -1);
PnoiseRand = squeeze(sum(noiseSum(chsResp, tt >= snrWin(1) & tt < snrWin(2), :).^2, 2) / diff(snrWin));
% calculate snr for each trial separately (same Psig for all trials at one channel)
snr = repmat(Psig, 1, ntrs) ./ PnoiseRand;
% for simplicity, we only vary and consider random noise in SNR, assuming that periodic noise can be mostly attenuated by filtering
end
fprintf('%0.2f ', geomean(snr, 'all')); % geometric mean since power is lognormal
%% Apply CARLA and plot outputs
[Vout, CAR, stats] = CARLA(tt, V4, srate, true); % get the sensitive output
% number of channels used for the CAR
nCAR = length(stats.chsUsed);
[~, nCARglob] = max(mean(stats.zMinMean, 2)); % number of channels at global maximum
% Plot average zmin across trials
figure('Position', [200, 200, 400, 300], 'Visible', 'off'); hold on
errorbar(mean(stats.zMinMean, 2), std(stats.zMinMean, 0, 2), 'k-o');
plot(nCARglob, mean(stats.zMinMean(nCARglob, :), 2), 'b*'); % global max as blue
if nCARglob ~= nCAR; plot(nCAR, mean(stats.zMinMean(nCAR, :), 2), '*', 'Color', cmSens); end
yline(0, 'Color', 'k');
saveas(gcf, fullfile(outdir, sprintf('zmin_rep%d', rr)), 'png');
saveas(gcf, fullfile(outdir, sprintf('zmin_rep%d', rr)), 'svg');
% Sort and plot channels by increasing covariance, draw line at cutoff
V4MeanSorted = mean(V4(stats.order, :, :), 3);
respBool = antifind(chsResp, nchs);
respBool = respBool(stats.order); % logical array of where responsive channels are
cm = zeros(nchs, 3);
cm(respBool, 1) = 1; % make red
figure('Position', [200, 200, 250, 600], 'Visible', 'off');
yspace = 80;
ys = ieeg_plotTrials(tt, V4MeanSorted', yspace, [], cm, 'LineWidth', 1);
yline(ys(nCARglob)-yspace/2, 'Color', 'b', 'LineWidth', 1.5);
if nCARglob ~= nCAR; yline(ys(nCAR)-yspace/2, 'Color', cmSens, 'LineWidth', 1.5); end
xlim([-0.1, 0.5]); set(gca, 'xtick', [0, 0.5]);
xlabel('Time (s)'); ylabel('Channels');
saveas(gcf, fullfile(outdir, sprintf('chsSorted_rep%d', rr)), 'png');
saveas(gcf, fullfile(outdir, sprintf('chsSorted_rep%d', rr)), 'svg');
close all;
% Accuracy values. positive means responsive/excluded from CAR
% We keep these variables as named here, but note that FN and FP are now renamed RCM and NCM in the manuscript.
TP = sum(find(respBool) > nCAR); % responsive channels successfully excluded from CAR (above the cutoff)
TN = sum(find(~respBool) <= nCAR); % NR channels successfully below or at cutoff
FN = sum(find(respBool) <= nCAR); % responsive channels incorrectly included in CAR. *This matters most
FP = sum(find(~respBool) > nCAR); % NR channels incorrectly excluded from CAR
% same for the global threshold
TPglob = sum(find(respBool) > nCARglob);
TNglob = sum(find(~respBool) <= nCARglob);
FNglob = sum(find(respBool) <= nCARglob);
FPglob = sum(find(~respBool) > nCARglob);
fid = fopen(fullfile(outdir, sprintf('accuracy_rep%d.txt', rr)), 'w');
fprintf(fid, 'TP\t%d\nTN\t%d\nFN\t%d\nFP\t%d\n', TP, TN, FN, FP);
fprintf(fid, 'TPglob\t%d\nTNglob\t%d\nFNglob\t%d\nFPglob\t%d', TPglob, TNglob, FNglob, FPglob);
fclose(fid);
% save snr info
save(fullfile(outdir, sprintf('snr_rep%d.mat', rr)), 'snr', 'Psig', 'PnoiseRand');
end
fprintf('\n');
end
end
%return
%% Save a few examples of how the channels look with the same signal but variable SNR
outdir = fullfile('output', 'simLoopSNR');
rng(25); % a representative seed with the 3 channels showing comparable SNR to the population geomeans
nchsEx = 4;
chsResp = 1:3;
% i) artifact only
V0 = zeros(length(tt), nchsEx);
Aart = 50 + rand(nchsEx, 1)*5; % slightly different artifact amplitudes for each channel
artifact = sin(2*pi*600*tt)';
artifact(tt < 0 | tt > 0.002) = 0;
V0 = V0 + artifact*Aart';
% A) Add the evoked potentials
A = 100;
V1 = V0;
sig = genRandSig(tt, length(chsResp), A);
V1(:, chsResp) = V0(:, chsResp) + sig;
% no global noise, copy V1 over
V2 = V1;
% keep the line noise the same for all
phLN = rand(ntrs, 3)*2*pi; % LN phases
LN = zeros(length(tt), ntrs);
for ii = 1:ntrs
LN(:, ii) = 8*sin(2*pi*60*tt - phLN(ii, 1)) + 2*sin(2*pi*120*tt - phLN(ii, 2)) + 1*sin(2*pi*180*tt - phLN(ii, 3));
end
% create the same series of random noise for all noise levels, just varying amplitude
BNBase = randn(2*length(tt), ntrs);
noiseRandBase = randn(nchsEx, 2*length(tt), ntrs);
for brownCoef = 0.4:0.1:1.0
% C) Add common noise to all channels at each trial
V3 = repmat(V2', 1, 1, ntrs); % ch x time points x trial
% brown noise shared across channels
BN = cumsum(brownCoef*BNBase); % variable brown noise coefficient now
BN = ieeg_highpass(BN, srate, true);
BN = BN((0.5*length(tt)+1) : 1.5*length(tt), :);
noiseCommon = LN + BN;
V3 = V3 + shiftdim(noiseCommon, -1);
% D) add random brown noise
noiseRand = cumsum(brownCoef*noiseRandBase, 2); % give double the number of time points so we can highpass it
for ii = 1:nchsEx
noiseRand(ii, :, :) = ieeg_highpass(squeeze(noiseRand(ii, :, :)), srate, true);
end
noiseRand = noiseRand(:, (0.5*length(tt)+1) : 1.5*length(tt), :);
V4 = V3 + noiseRand;
% Calculate the SNRs in the example
Psig = sum(sig(tt >= snrWin(1) & tt < snrWin(2), :).^2)' / diff(snrWin); % express as per second
noiseSum = noiseRand + shiftdim(BN, -1);
PnoiseRand = squeeze(sum(noiseSum(chsResp, tt >= snrWin(1) & tt < snrWin(2), :).^2, 2) / diff(snrWin));
snr = repmat(Psig, 1, ntrs) ./ PnoiseRand;
snrByCh = geomean(snr, 2); % average across trials for each channel
fprintf('%0.2f, ', snrByCh(:)); fprintf('\n');
% Plot and save
yspace = 200;
figure('Position', [200, 200, 600, 600]);
ys = ieeg_plotTrials(tt, mean(V4, 3)', yspace, [], 'k', 'LineWidth', 1);
hold on
for jj = 1:4 % plot the individual trials
plot(tt, ys(jj) + squeeze(V4(jj, :, :)), 'Color', [0.5, 0.5, 0.5]);
end
hold off
ylim([ys(end)-yspace, yspace]);
kids = get(gca, 'Children');
set(gca, 'Children', [kids(end-1:-2:end-7); kids(1:end-8); kids(end:-2:end-6)]); % first (top) the means, then the trials, lastly the horzline
xlabel('Time from Stim. (s)');
saveas(gcf, fullfile(outdir, sprintf('exampleSNRs_noise%0.1f_nchs%d-%d.png', brownCoef, nchsEx, length(chsResp))));
saveas(gcf, fullfile(outdir, sprintf('exampleSNRs_noise%0.1f_nchs%d-%d.svg', brownCoef, nchsEx, length(chsResp))));
close(gcf);
end
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* execution.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: hmorand <hmorand@student.42lausanne.ch> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/08 15:50:49 by hmorand #+# #+# */
/* Updated: 2024/05/08 15:50:49 by hmorand ### ########.ch */
/* */
/* ************************************************************************** */
#include "pipex.h"
void add_pid(pid_t pid, pid_t *cpids)
{
while (*cpids)
cpids++;
*cpids++ = pid;
*cpids = 0;
}
int wait_for_children(pid_t *cpids)
{
int status;
while (*cpids)
{
waitpid(*cpids, &status, 0);
cpids++;
}
if (WIFEXITED(status))
return (WEXITSTATUS(status));
if (WIFSIGNALED(status))
return (WTERMSIG(status) + 128);
return (0);
}
void execute(t_pipex *pipex, int fds[2], int fd_in)
{
close(fd_in);
close(fds[0]);
close(fds[1]);
if (!pipex->commands[pipex->current].path)
{
ft_printf(STDERR_FILENO, "pipex: %s: command not found\n",
pipex->commands[pipex->current].name);
exit(127);
}
execve(pipex->commands[pipex->current].path,
pipex->commands[pipex->current].args, pipex->env);
perror("Execve");
exit(EXIT_FAILURE);
}
int piping(t_pipex *pipex, char *infile, char *outfile, int fd_in)
{
int fds[2];
pid_t pid;
if (!outfile)
pipe(fds);
pid = fork();
if (pid == 0)
{
if (infile)
fd_in = redirect_input(infile);
dup2(fd_in, STDIN_FILENO);
if (outfile)
redirect_output(outfile);
else
dup2(fds[1], STDOUT_FILENO);
execute(pipex, fds, fd_in);
}
add_pid(pid, pipex->cpids);
if (!outfile)
{
close(fds[1]);
return (fds[0]);
}
close(fds[0]);
return (-1);
}
t_pipex initialise_pipex(char **argv, char **env, int argc)
{
t_pipex pipex;
pipex.commands = parse_commands(argv, argc, env);
pipex.cpids = galloc(sizeof(pid_t) * (argc - 2));
if (!pipex.cpids)
{
perror("malloc cpids");
exit(EXIT_FAILURE);
}
pipex.env = env;
pipex.infile = argv[1];
pipex.outfile = argv[argc - 1];
pipex.current = 0;
return (pipex);
}
|
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 2.2 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2009 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007. |
| |
| CiviCRM 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 Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License along with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2009
* $Id$
*
*/
require_once 'CiviTestCase.php';
class Browser_Contact_Profile extends CiviTestCase
{
var $webUser;
function get_info()
{
return array(
'name' => 'Profile',
'description' => 'Test Profile Functionality like Profile Create, Edit, View, Search (gid=1).',
'group' => 'CiviCRM Browser Tests',
);
}
function setUp()
{
parent::setUp();
$this->drupalModuleEnable('civicrm');
$this->webUser = $this->drupalCreateUserRolePerm(
array ( 0 => 'access CiviCRM',
1 => 'edit all contacts',
2 => 'add contacts',
3 => 'profile listings and forms') );
$this->drupalLoginUser($this->webUser);
}
/**
* Test to create profile without required fields (first + last are required)
*/
function testCreateProfileContactWithMissingParams( )
{
$first_name = '';
$last_name = '';
$params = array( 'first_name' => $first_name,
'last_name' => $last_name );
//goto profile form
$this->civiGet('civicrm/profile/create', 'gid=1&reset=1' );
$this->drupalPost( NULL, $params, '_qf_Edit_next');
$this->assertWantedRaw( 'First Name', 'Name and Address' );
$this->assertWantedRaw( 'Last Name', 'Name and Address' );
$this->assertDBNull( 'CRM_Contact_DAO_Contact', $last_name . ', ' .$first_name, 'id', 'sort_name',
'Database check, Individual created successfully.' );
}
/**
* Test to create profile with
* valid parameters
*/
function testCreateProfileContactwithNames( )
{
$first_name = 'Jane';
$last_name = 'Doe';
$params = array( 'first_name' => $first_name,
'last_name' => $last_name );
//goto profile form
$this->civiGet('civicrm/profile/create', 'gid=1&reset=1' );
$this->drupalPost( NULL, $params, '_qf_Edit_next');
$this->assertText( 'First Name' );
$this->assertText( 'Last Name' );
$this->assertText( $first_name );
$this->assertText( $last_name );
// Now check DB for contact and cleanup by deleting the contact
$contactId = $this->assertDBNotNull( 'CRM_Contact_DAO_Contact', $last_name . ', ' .$first_name, 'id', 'sort_name',
'Checking database for the record.' );
Contact::delete( $contactId );
}
/**
* Test to create profile with address data (primary location)
*
*/
function testCreateProfileContactwithAddress( )
{
$first_name = 'John';
$last_name = 'Smith';
$params = array ( 'first_name' => $first_name,
'last_name' => $last_name,
'street_address-1' => 'Saint Helier St',
'city-1' => 'Newark',
'postal_code-1' => 12345,
'state_province-1' => 1029,
'country-1' => 1228
);
//goto profile form
$this->civiGet('civicrm/profile/create', 'gid=1&reset=1' );
$this->drupalPost( NULL, $params, '_qf_Edit_next');
$this->assertText( 'First Name' );
$this->assertText( 'Last Name' );
$this->assertText( $first_name );
$this->assertText( $last_name );
// Now check DB for contact and cleanup by deleting the contact
$contactId = $this->assertDBNotNull( 'CRM_Contact_DAO_Contact', $last_name . ', ' .$first_name, 'id', 'sort_name',
'Checking database for the record.' );
Contact::delete( $contactId );
}
/**
* Test to search contact with first name and last name
*
*/
function testSearchContactWithNames( )
{
$first_name = 'John';
$last_name = 'Smith';
$params = array ( 'first_name' => $first_name,
'last_name' => $last_name );
$contactId = Contact::create( $params );
//goto profile search form
$this->civiGet( 'civicrm/profile/search', 'gid=1&reset=1' );
//Search Contact with first name and last name
$this->drupalPost( NULL, $params, '_qf_Search_refresh' );
$this->assertText( 'New Search' );
$this->assertText( 'Displaying contacts where' );
$this->assertText( 'Name' );
$this->assertText( 'State (Home)' );
$this->assertText( "{$last_name}, {$first_name}" );
//Now check DB for contact and cleanup by deleting the contact
$contactId = $this->assertDBNotNull( 'CRM_Contact_DAO_Contact', $last_name . ', ' .$first_name, 'id', 'sort_name',
'Checking database for the record.' );
Contact::delete( $contactId );
}
/**
* Test to search contact with name and address
*
*/
function testSearchContactWithAll( )
{
$first_name = 'John';
$last_name = 'Smith';
$params = array ( 'first_name' => $first_name,
'last_name' => $last_name,
'state_province-1' => 1004,
'country-1' => 1228 );
$contactId = Contact::create( $params );
//goto profile search form
$this->civiGet( 'civicrm/profile/search', 'gid=1&reset=1' );
//Search Contact with name and address
$this->drupalPost( NULL, $params, '_qf_Search_refresh' );
$this->assertText( 'Displaying contacts where' );
$this->assertText( 'New Search' );
$this->assertText( 'Name' );
$this->assertText( 'State (Home)' );
$this->assertText( "{$last_name}, {$first_name}" );
$this->assertText( 'CA' );
//Now check DB for contact and cleanup by deleting the contact
$contactId = $this->assertDBNotNull( 'CRM_Contact_DAO_Contact', $last_name . ', ' .$first_name, 'id', 'sort_name', 'Checking database for the record.' );
Contact::delete( $contactId );
}
/**
* Test profile edit mode
*
*/
function testProfileEditMode( )
{
$first_name = 'John';
$last_name = 'Smith';
$params = array ( 'first_name' => $first_name,
'last_name' => $last_name,
'street_address-1' => 'Saint Helier St',
'city-1' => 'Newark',
'postal_code-1' => 12345,
'state_province-1' => 1029,
'country-1' => 1228
);
//goto profile form
$this->civiGet('civicrm/profile/create', 'gid=1&reset=1' );
$this->drupalPost( NULL, $params, '_qf_Edit_next');
$this->assertText( 'First Name' );
$this->assertText( 'Last Name' );
$this->assertText( $first_name );
$this->assertText( $last_name );
// Now check DB for contact and cleanup by deleting the contact
$contactId = $this->assertDBNotNull( 'CRM_Contact_DAO_Contact', $last_name . ', ' .$first_name, 'id', 'sort_name',
'Checking database for the record.' );
// updated params
$first_name = 'Sam';
$last_name = 'Adams';
$params = array ( 'first_name' => $first_name,
'last_name' => $last_name,
'street_address-1' => 'Casper St',
'city-1' => 'San Francisco',
);
$this->civiGet('civicrm/profile/edit', "gid=1&reset=1&id={$contactId}" );
$this->drupalPost( NULL, $params, '_qf_Edit_next');
$this->assertText( 'First Name' );
$this->assertText( 'Last Name' );
$this->assertText( $first_name );
$this->assertText( $last_name );
Contact::delete( $contactId );
}
/**
* Test profile view mode
*
*/
function testProfileViewMode( )
{
$first_name = 'John';
$last_name = 'Smith';
$params = array ( 'first_name' => $first_name,
'last_name' => $last_name,
'street_address-1' => 'Saint Helier St',
'city-1' => 'Newark',
'postal_code-1' => 12345,
'state_province-1' => 1029,
'country-1' => 1228
);
//goto profile form
$this->civiGet( 'civicrm/profile/create', 'gid=1&reset=1' );
$this->drupalPost( NULL, $params, '_qf_Edit_next');
$this->assertText( 'First Name' );
$this->assertText( 'Last Name' );
$this->assertText( $first_name );
$this->assertText( $last_name );
//Now check DB for contact
$contactId = $this->assertDBNotNull( 'CRM_Contact_DAO_Contact', $last_name . ', ' .$first_name, 'id', 'sort_name',
'Checking database for the record.' );
$this->civiGet( 'civicrm/profile/view', "gid=1&reset=1&id={$contactId}" );
$this->assertText( 'First Name' );
$this->assertText( 'Last Name' );
$this->assertText( $first_name );
$this->assertText( $last_name );
//cleanup DB by deleting the contact
Contact::delete( $contactId );
}
}
?>
|
package br.com.hmigl.hrzonbank.conta;
import static org.junit.jupiter.api.Assertions.*;
import br.com.hmigl.hrzonbank.compartilhado.CustomMockMvc;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import java.util.Map;
@SpringBootTest
@AutoConfigureMockMvc
class ContaControllerTest {
private static final String URI = "/contas";
private @Autowired CustomMockMvc mockMvc;
@DisplayName("Deve cadastrar duas contas de tipos diferentes para uma pessoa")
@ParameterizedTest
@CsvSource({"1,09557205,4,CORRENTE", "1,1043815,7,POUPANCA"})
@DirtiesContext
void test(Long pessoaId, String numero, String digito, TipoConta tipoConta) throws Exception {
mockMvc.post(
"/pessoas",
Map.of("nome", "fulano", "telefone", "94996457774", "cpf", "20487101154"));
mockMvc.post(
URI,
Map.of(
"pessoaId",
pessoaId,
"numero",
numero,
"digito",
digito,
"tipoConta",
tipoConta))
.andExpect(MockMvcResultMatchers.status().is2xxSuccessful());
}
@DisplayName("Deve falhar ao cadastrar duas contas de mesmo tipo para uma pessoa")
@ParameterizedTest
@CsvSource({"1,09557205,4,CORRENTE,201", "1,1043815,7,CORRENTE,400"})
void test2(Long pessoaId, String numero, String digito, TipoConta tipoConta, int status)
throws Exception {
mockMvc.post(
"/pessoas",
Map.of("nome", "fulano", "telefone", "94996457774", "cpf", "77040052601"));
mockMvc.post(
URI,
Map.of(
"pessoaId",
pessoaId,
"numero",
numero,
"digito",
digito,
"tipoConta",
tipoConta))
.andExpect(MockMvcResultMatchers.status().is(status));
}
}
|
import React from "react";
import ReactModal from "react-modal";
import styles from "./Modal.module.scss";
import classNames from "classnames/bind";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCircleXmark } from "@fortawesome/free-solid-svg-icons";
const cx = classNames.bind(styles);
ReactModal.setAppElement("#root");
const Modal = ({
children,
open,
setOpen,
title,
className,
handleAfterClose,
}) => {
return (
<ReactModal
isOpen={open}
onRequestClose={() => {
setOpen(false);
handleAfterClose && handleAfterClose();
}}
className={cx("modal", className)}
overlayClassName={cx("overlay")}
>
{title && <h2 className={cx("title")}>{title}</h2>}
<FontAwesomeIcon
icon={faCircleXmark}
className={cx("close-icon")}
onClick={() => {
setOpen(false);
handleAfterClose && handleAfterClose();
}}
/>
<div className={cx("wrapper")}>{children}</div>
</ReactModal>
);
};
export default Modal;
|
import React, { Fragment, useState } from "react";
import { Link } from "react-router-dom";
import axios from "axios";
const Login = () => {
const [formData, setFormData] = useState({
email: "",
password: "",
});
const { email, password } = formData;
const onChange = (e) =>
setFormData({ ...formData, [e.target.name]: e.target.value });
const onSubmit = async (e) => {
e.preventDefault();
console.log(formData);
const existUser = {
email,
password,
};
try {
const config = {
headers: {
"Content-Type": "application/json",
},
};
const body = JSON.stringify(existUser);
const res = await axios.post("/api/auth", body, config);
console.log(res.data);
} catch (error) {
console.error(error.response.data);
}
};
return (
<Fragment>
<h1 className='large text-primary'>Sign In</h1>
<p className='lead'>
<i className='fas fa-user'></i> Sign In to Your Account
</p>
<form className='form' onSubmit={(e) => onSubmit(e)}>
<div className='form-group'>
<input
type='email'
placeholder='Email Address'
name='email'
value={email}
onChange={(e) => onChange(e)}
required
/>
</div>
<div className='form-group'>
<input
type='password'
placeholder='Password'
name='password'
minLength='6'
value={password}
onChange={(e) => onChange(e)}
required
/>
</div>
<input type='submit' className='btn btn-primary' value='Login' />
</form>
<p className='my-1'>
Create an account? <Link to='/register'>Sign Up</Link>
</p>
</Fragment>
);
};
export default Login;
|
"use server";
import axios from "axios";
import { redirect } from "next/navigation";
import { z } from "zod";
import { deleteCookie, getCookie, setCookie } from "../lib/cookie";
export type AccountInitialState = {
errors?: {
firstName?: string[];
lastName?: string[];
email?: string[];
password?: string[];
token?: string[];
confirmPassword?: string[];
};
message?: string | null;
};
const AccountSchema = z.object({
firstName: z
.string({
invalid_type_error: "First name is a required field",
})
.min(3, {
message:
"First name is required Field. Should be more than three characters",
})
.trim(),
lastName: z
.string({
required_error: "Last name is a required field",
invalid_type_error: "Last name is required field ",
})
.min(3, {
message:
"Last name is required Field. Should be more than three characters",
})
.trim(),
token: z.string(),
email: z.string().email({ message: "Provide a valid email" }),
password: z
.string({
invalid_type_error: "Password is a required field",
})
.min(6, { message: "Password should not be less 6 characters" }),
confirmPassword: z.string({
invalid_type_error: "Confirm password in a required field",
}),
});
const CreateUserAccount = AccountSchema.omit({ token: true }).refine(
(schema) => schema.confirmPassword === schema.password,
{
message: "Passwords don't match",
path: ["confirmPassword"],
}
);
const LoginUser = AccountSchema.omit({
firstName: true,
lastName: true,
token: true,
confirmPassword: true,
});
const ResetPasswod = AccountSchema.omit({
firstName: true,
lastName: true,
email: true,
}).refine((schema) => schema.confirmPassword === schema.password, {
message: "Passwords don't match",
path: ["confirmPassword"],
});
const ChangePassword = AccountSchema.omit({
firstName: true,
lastName: true,
email: true,
token: true,
});
const ForgotPassword = AccountSchema.omit({
firstName: true,
lastName: true,
password: true,
token: true,
confirmPassword: true,
});
export async function createUserAccount(
prevState: AccountInitialState,
formData: FormData
) {
const validatedFields = CreateUserAccount.safeParse({
firstName: formData.get("firstName"),
lastName: formData.get("lastName"),
email: formData.get("email"),
password: formData.get("password"),
confirmPassword: formData.get("confirmPassword"),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Missing some fields. Failed to create user",
};
}
try {
const response = await axios.post(
`${process.env.ROOT_URL}/api/accounts`,
validatedFields.data
);
if (response.data.status === "fail") {
return {
message: response.data.message,
};
}
} catch (error: any) {
return {
message: error.message,
};
}
redirect("/accounts/login");
}
export async function loginUser(
formState: AccountInitialState,
formData: FormData
) {
const validatedFields = LoginUser.safeParse({
email: formData.get("email"),
password: formData.get("password"),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Some required field are empty",
};
}
try {
const response = await axios.post(
`${process.env.ROOT_URL}/api/accounts/login`,
validatedFields.data
);
if (response.data.status === "fail") {
return {
message: response.data.message,
};
}
setCookie("access_token_auth", response.data.accessToken);
} catch (error) {
return {
message: "Error login",
};
}
redirect("/accounts/profile");
}
export async function logout() {
try {
const response = await axios.post(
`${process.env.ROOT_URL}/api/accounts/logout`
);
if (response.data.status === "fail") {
return {
message: response.data.message,
};
}
deleteCookie("access_token_auth");
} catch (error) {
return {
message: "Logout failed",
};
}
redirect("/accounts/login");
}
export async function resetPassword(
formState: AccountInitialState,
formData: FormData
) {
const validatedFields = ResetPasswod.safeParse({
password: formData.get("password"),
token: formData.get("token"),
confirmPassword: formData.get("confirmPassword"),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Some required field are empty",
};
}
try {
const response = await axios.post(
`${process.env.ROOT_URL}/api/accounts/password/reset`,
validatedFields.data
);
if (response.data.status === "fail") {
return {
message: response.data.message,
};
}
} catch (error) {
return {
message: "Password reset failed",
};
}
redirect("/accounts/login");
}
export async function forgotPassword(
formState: AccountInitialState,
formData: FormData
) {
const validatedFields = ForgotPassword.safeParse({
email: formData.get("email"),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Some field are invalid",
};
}
try {
const response = await axios.post(
`${process.env.ROOT_URL}/api/accounts/password/forgot`,
validatedFields.data
);
if (response.data.status === "fail") {
return {
message: response.data.message,
};
}
} catch (error) {
console.log({ ERROR_RESET_INSTRUCTIONS: error });
return {
message: "Error sending reset instructions",
};
}
redirect("/accounts/password/forgot?instructions_sent=true");
}
export async function changePassword(
formState: AccountInitialState,
formData: FormData
) {
const validatedFields = ChangePassword.safeParse({
password: formData.get("password"),
confirmPassword: formData.get("confirmPassword"),
});
if (!validatedFields.success) {
return {
errors: validatedFields.error.flatten().fieldErrors,
message: "Some required field are empty",
};
}
try {
// Request expects currentPassword and newPassword
const data = {
currentPassword: validatedFields.data.password,
newPassword: validatedFields.data.confirmPassword,
};
const response = await axios.post(
`${process.env.ROOT_URL}/api/accounts/password/change`,
data,
{
headers: {
Cookie: `access_token_auth=${getCookie("access_token_auth")}`,
},
}
);
if (response.data.status === "fail") {
return {
message: response.data.message,
};
}
deleteCookie("access_token_auth");
} catch (error: any) {
console.log({ PASSWORD_CHANGE_ERROR: error });
return {
message: error.message,
};
}
redirect("/accounts/login");
}
|
const chargingIcon = document.querySelector(".charging_icon");
const batteryLevel = document.querySelector(".battery_level");
const chargingBar = document.querySelector(".charging_bar");
const dischargingTime = document.querySelector(".discharging_time");
const otherInfo = document.querySelector(".other_info");
// Promise is called by battery
navigator.getBattery().then((battery) => {
/* Updating all the battery information which is a combination of multiple functions */
function updateAllBatteryInfo() {
updateChargeInfo();
updateLevelInfo();
updateDischargingInfo();
}
// Running as the promise returns battery
updateAllBatteryInfo();
// Event Listener, when the charging status changes
// it checks that does your device is plugged in or not
battery.addEventListener("chargingchange",() =>{
updateAllBatteryInfo();
});
// Event Listener, when the Battery Level Changes
battery.addEventListener("levelchange",() => {
updateAllBatteryInfo();
});
// Event Listener, when the discharging Time Change
// it checks that does your device is plugged in or not
battery.addEventListener("dischargingtimechange", () => {
updateAllBatteryInfo();
});
// Updating the battery Level container and the charging bar width
function updateLevelInfo() {
batteryLevel.textContent = `${+(battery.level * 100)}%`; //instead of + you can use parseInt
console.log("ParseInt Conversion:",typeof(parseInt(battery.level * 100)));
console.log("+ operator Conversion:",typeof(+(battery.level * 100)));
chargingBar.style.width = `${+(battery.level * 100)}%`; //instead of + you can use parseInt
}
function updateChargeInfo() {
//ternary operator for checking the battery is charging or not
battery.charging
? ((chargingBar.style.animationIterationCount = "infinite"),
(chargingIcon.style.display = "inline-flex"),
(otherInfo.style.display = "none"))
: ((chargingIcon.style.display = "none"),
(otherInfo.style.display = "inline-flex"),
(chargingBar.style.animationIterationCount = "initial"));
}
// updating the Discharging Information changes
function updateDischargingInfo() {
const dischargeTime = parseInt(battery.dischargingTime / 60) ? true : false;
dischargeTime
? ((dischargingTime.textContent = `${parseInt(
battery.dischargingTime / 60
)} minutes`),
(otherInfo.style.display = "flex"))
: (otherInfo.style.display = "none");
}
});
|
namespace LazyLoadingVsEagerLoadingEF;
public static class Seeder
{
public static void SeedData(DataContext context)
{
context.Database.EnsureCreated();
if (context.Authors.Any())
{
Console.WriteLine("Database already seeded.");
return;
}
var authors = new List<Author>
{
new Author { Name = "J.K. Rowling", Books = new List<Book>
{
new Book { Title = "Harry Potter and the Philosopher's Stone" },
new Book { Title = "Harry Potter and the Chamber of Secrets" }
}
},
new Author { Name = "George R.R. Martin", Books = new List<Book>
{
new Book
{
Title = "A Game of Thrones",
Reviews = new List<Review>
{
new Review { ReviewText = "Epic and unpredictable." },
new Review { ReviewText = "Characters that stay with you." }
}
},
new Book
{
Title = "A Clash of Kings",
Reviews = new List<Review>
{
new Review { ReviewText = "A masterpiece of political intrigue." },
new Review { ReviewText = "Couldn't put it down." }
}
}
}
}
};
context.Authors.AddRange(authors);
context.SaveChanges();
Console.WriteLine("Database seeded successfully.");
}
}
|
import BigNumber from "bignumber.js";
import { DRE, increaseTime, waitForTx } from "../helpers/misc-utils";
import { APPROVAL_AMOUNT_LENDING_POOL, MAX_UINT_AMOUNT, oneEther, ONE_DAY } from "../helpers/constants";
import { convertToCurrencyDecimals } from "../helpers/contracts-helpers";
import { makeSuite } from "./helpers/make-suite";
import { ProtocolErrors } from "../helpers/types";
import { MaliciousHackerERC721Factory, MaliciousHackerERC721 } from "../types";
import { getDebtToken, getDeploySigner } from "../helpers/contracts-getters";
const chai = require("chai");
const { expect } = chai;
makeSuite("LendPool: Malicious Hacker Rentrant", (testEnv) => {
let maliciousHackerErc721: MaliciousHackerERC721;
before("Before: set config", async () => {
BigNumber.config({ DECIMAL_PLACES: 0, ROUNDING_MODE: BigNumber.ROUND_DOWN });
maliciousHackerErc721 = await new MaliciousHackerERC721Factory(await getDeploySigner()).deploy(
testEnv.pool.address
);
});
after("After: reset config", async () => {
BigNumber.config({ DECIMAL_PLACES: 20, ROUNDING_MODE: BigNumber.ROUND_HALF_UP });
});
it("Malicious hacker try to reentrant (should revert)", async () => {
const { weth, bayc, pool, users } = testEnv;
const depositor = users[0];
const borrower = users[1];
const user2 = users[2];
const user3 = users[3];
// delegates borrowing power
await maliciousHackerErc721.approveDelegate(weth.address, borrower.address);
// depositor mint and deposit 100 WETH
await weth.connect(depositor.signer).mint(await convertToCurrencyDecimals(weth.address, "100"));
await weth.connect(depositor.signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL);
const amountDeposit = await convertToCurrencyDecimals(weth.address, "100");
await pool.connect(depositor.signer).deposit(weth.address, amountDeposit, depositor.address, "0");
// borrower mint NFT and borrow 10 WETH
await weth.connect(borrower.signer).mint(await convertToCurrencyDecimals(weth.address, "5"));
await weth.connect(borrower.signer).approve(pool.address, APPROVAL_AMOUNT_LENDING_POOL);
await bayc.connect(borrower.signer).mint("101");
await bayc.connect(borrower.signer).setApprovalForAll(pool.address, true);
const amountBorrow = await convertToCurrencyDecimals(weth.address, "10");
await pool
.connect(borrower.signer)
.borrow(weth.address, amountBorrow.toString(), bayc.address, "101", maliciousHackerErc721.address, "0");
// borrower repay and hacker try to do reentrant action
console.log("hacker do reentrant action: ACTION_DEPOSIT");
await maliciousHackerErc721.simulateAction(await maliciousHackerErc721.ACTION_DEPOSIT());
await expect(pool.connect(borrower.signer).repay(bayc.address, "101", MAX_UINT_AMOUNT)).to.be.revertedWith(
"ReentrancyGuard: reentrant call"
);
console.log("hacker do reentrant action: ACTION_WITHDRAW");
await maliciousHackerErc721.simulateAction(await maliciousHackerErc721.ACTION_WITHDRAW());
await expect(pool.connect(borrower.signer).repay(bayc.address, "101", MAX_UINT_AMOUNT)).to.be.revertedWith(
"ReentrancyGuard: reentrant call"
);
console.log("hacker do reentrant action: ACTION_BORROW");
await maliciousHackerErc721.simulateAction(await maliciousHackerErc721.ACTION_BORROW());
await expect(pool.connect(borrower.signer).repay(bayc.address, "101", MAX_UINT_AMOUNT)).to.be.revertedWith(
"ReentrancyGuard: reentrant call"
);
console.log("hacker do reentrant action: ACTION_REPAY");
await maliciousHackerErc721.simulateAction(await maliciousHackerErc721.ACTION_REPAY());
await expect(pool.connect(borrower.signer).repay(bayc.address, "101", MAX_UINT_AMOUNT)).to.be.revertedWith(
"ReentrancyGuard: reentrant call"
);
console.log("hacker do reentrant action: ACTION_BUYITNOW");
await maliciousHackerErc721.simulateAction(await maliciousHackerErc721.ACTION_BUYITNOW());
await expect(pool.connect(borrower.signer).repay(bayc.address, "101", MAX_UINT_AMOUNT)).to.be.revertedWith(
"ReentrancyGuard: reentrant call"
);
console.log("hacker do reentrant action: ACTION_REDEEM");
await maliciousHackerErc721.simulateAction(await maliciousHackerErc721.ACTION_REDEEM());
await expect(pool.connect(borrower.signer).repay(bayc.address, "101", MAX_UINT_AMOUNT)).to.be.revertedWith(
"ReentrancyGuard: reentrant call"
);
console.log("hacker do reentrant action: ACTION_LIQUIDATE");
await maliciousHackerErc721.simulateAction(await maliciousHackerErc721.ACTION_LIQUIDATE());
await expect(pool.connect(borrower.signer).repay(bayc.address, "101", MAX_UINT_AMOUNT)).to.be.revertedWith(
"ReentrancyGuard: reentrant call"
);
});
});
|
<div class="wrapper">
<form [formGroup]="authForm" (ngSubmit)="onSubmit()">
<mat-form-field *ngIf="!showLoginForm">
<mat-label>Enter your name</mat-label>
<input matInput placeholder="John Doe" type="text" formControlName="name">
<mat-error>Name is required</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Enter your email</mat-label>
<input matInput placeholder="example@mail.com" type="email" formControlName="email">
<mat-error>Email is required</mat-error>
</mat-form-field>
<mat-form-field>
<mat-label>Enter your password</mat-label>
<input [type]="hidePassword ? 'password' : 'text'" matInput formControlName="password" />
<button mat-icon-button matSuffix (click)="hidePassword = !hidePassword">
<mat-icon>{{hidePassword ? 'visibility_off' :'visibility'}}</mat-icon>
</button>
<mat-error>Password is required</mat-error>
</mat-form-field>
<button mat-raised-button color="primary" type="submit">
{{showLoginForm ? 'Log in' : 'Register'}}
</button>
<mat-hint>
{{showLoginForm ? "Don't have an account?" : 'Already have an account?' }}
<a (click)="showLoginForm = !showLoginForm">click here</a>
</mat-hint>
</form>
</div>
|
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
const app = Vue.createApp({
data() {
return {
playerHealth: 100,
monsterHealth: 100,
currentRound: 0,
winner: null,
logMessages: []
};
},
methods: {
attackMonster() {
this.currentRound++;
const attackValue = getRandomNumber(5, 12);
this.monsterHealth -= attackValue;
this.addLogMessage('player', 'attack', attackValue);
this.attackPlayer();
},
attackPlayer() {
this.currentRound++;
const attackValue = getRandomNumber(8, 15);
this.addLogMessage('monster', 'attack', attackValue);
this.playerHealth -= attackValue;
},
useSpecialAttack() {
this.currentRound++;
const attackValue = getRandomNumber(10, 18);
this.monsterHealth -= attackValue;
this.addLogMessage('player', 'attack', attackValue);
this.attackPlayer();
},
useHeal() {
this.currentRound++;
const healValue = getRandomNumber(10, 18);
if (this.playerHealth + healValue > 100) {
this.playerHealth = 100;
} else {
this.playerHealth += healValue;
}
this.addLogMessage('player', 'heal', healValue);
this.attackPlayer();
},
surrender(){
this.winner = 'monster'
},
restartGame(){
this.playerHealth = 100;
this.monsterHealth = 100;
this.currentRound = 0;
this.winner = null;
this.logMessages = []
},
addLogMessage(who, what, value){
this.logMessages.unshift({
actionBy: who,
actionType: what,
actionValue: value
});
}
},
computed: {
monsterHealthBar() {
if (this.monsterHealth <= 0) {
this.monsterHealth = 0;
}
return { width: this.monsterHealth + "%" };
},
playerHealthBar() {
if (this.playerHealth <= 0) {
this.playerHealth = 0;
}
return { width: this.playerHealth + "%" };
},
canUseSpecial() {
return this.currentRound % 3 !== 0;
},
},
watch: {
monsterHealth(value) {
if (value <= 0 && this.playerHealth <= 0) {
this.winner = "draw";
} else if(value <= 0) {
this.winner = "player";
}
},
playerHealth(value) {
if (value <= 0 && this.monsterHealth <= 0) {
this.winner = "draw";
} else if(value <= 0) {
this.winner = "monster";
}
},
},
});
app.mount("#game");
|
import React from 'react';
import FetcherMetroEstacions from './FetcherMetroEstacions';
import MetroEstacio from './MetroEstacio';
import './List.css';
import Loader from './Loader';
function MetroEstacioList() {
return (
<FetcherMetroEstacions>
{({ data, loading, error }) => {
if (loading) {
return <Loader />; // Mostrar l'indicador de càrrega mentre es carreguen les dades
}
if (error) {
return <div className="error">{error.message}</div>; // Mostrar missatge d'error en cas d'error
}
return (
<div className="listContainer">
<h2>Estacions de Metro</h2>
<ul className="cardContainer">
{data.map(metroEstacio => (
metroEstacio.properties ? (
<MetroEstacio key={metroEstacio.id} metroEstacio={metroEstacio.properties} /> // Renderitzar la llista d'estacions de metro
) : null
))}
</ul>
</div>
);
}}
</FetcherMetroEstacions>
);
}
export default MetroEstacioList;
|
package com.siddydevelops.Database;
import com.siddydevelops.Database.domain.dto.AuthorDto;
import com.siddydevelops.Database.domain.dto.BookDto;
import com.siddydevelops.Database.domain.entities.AuthorEntity;
import com.siddydevelops.Database.domain.entities.BookEntity;
public class TestDataUtil {
private TestDataUtil() {
}
public static AuthorEntity createTestAuthorA() {
return AuthorEntity.builder()
.id(1L)
.name("John Doe")
.age(72)
.build();
}
public static AuthorEntity createTestAuthorB() {
return AuthorEntity.builder()
.id(2L)
.name("Siddhartha Singh")
.age(21)
.build();
}
public static AuthorEntity createTestAuthorC() {
return AuthorEntity.builder()
.id(3L)
.name("Rose Marie")
.age(32)
.build();
}
public static AuthorDto createTestAuthorDtoA() {
return AuthorDto.builder()
.id(1L)
.name("John Doe")
.age(72)
.build();
}
public static BookEntity createTestBookA(final AuthorEntity authorEntity) {
return BookEntity.builder()
.isbn("8794-454L-8521")
.title("The Shadow in the Attic: Part 1")
.authorEntity(authorEntity)
.build();
}
public static BookEntity createTestBookB(final AuthorEntity authorEntity) {
return BookEntity.builder()
.isbn("8794-454L-8522")
.title("The Shadow in the Attic: Part 2")
.authorEntity(authorEntity)
.build();
}
public static BookEntity createTestBookC(final AuthorEntity authorEntity) {
return BookEntity.builder()
.isbn("8794-454L-8523")
.title("The Shadow in the Attic: Part 3")
.authorEntity(authorEntity)
.build();
}
public static BookDto createTestBookDtoA(final AuthorDto authorEntity) {
return BookDto.builder()
.isbn("8794-454L-8521")
.title("The Shadow in the Attic: Part 1")
.author(authorEntity)
.build();
}
}
|
Description:
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
Solution:
一开始想法是内部交换,发现怎么搞都顺序不大对,很难通过交换来达到最终目的。
后来发现可以用链表的性质,可以直接把基数结点连接在一起,偶数结点连接在一起,然后把两条链连接。
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head == NULL|| head -> next == NULL || head -> next -> next == NULL) return head;
ListNode* oddHead = head;
ListNode* evenHead = head->next;
ListNode* odd = oddHead;
ListNode* even = evenHead;
ListNode* p = evenHead -> next;
while(p) {
odd -> next = p;
odd = odd -> next;
p = p -> next;
even -> next = p;
even = even -> next;
if (p) {
p = p -> next;
}
}
odd -> next = evenHead;
return oddHead;
}
};
|
import { Link } from "react-router-dom";
import { fadeInAnimation } from "../../util/animation";
import styles from "./Home.module.css";
import { motion } from "framer-motion";
import PageTransitionAnimation from "../PageTransitionAnimation/PageTransitionAnimation";
export const Home = () => {
return (
<PageTransitionAnimation>
<section className={styles.slogan}>
<motion.h1
whileInView={fadeInAnimation.title}
transition={fadeInAnimation.transition}
>
It's your time to relax!
</motion.h1>
<motion.div
whileHover={{ scale: 1.2, transition: { duration: 0.3 } }}
whileTap={{ scale: 0.9 }}
className={styles.btnContact}
>
<Link to="/villas">Book Now</Link>
</motion.div>
</section>
<motion.section className={styles.about}>
<motion.h2
whileInView={fadeInAnimation.text}
transition={fadeInAnimation.transition}
>
About Us
</motion.h2>
<motion.p
whileInView={fadeInAnimation.text}
transition={fadeInAnimation.transition}
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam
venenatis quis ex id mollis. Quisque volutpat efficitur sagittis.
Suspendisse quis scelerisque eros. Nam vel leo magna. Praesent
hendrerit justo sapien, ac varius felis pharetra ultricies. Morbi
eleifend eros lacus, sit amet efficitur erat aliquam quis. Donec arcu
lectus, dapibus sed tortor in, euismod gravida metus. In molestie in
metus eu cursus. Curabitur at molestie ante, in vulputate lacus.
Phasellus turpis urna, sollicitudin non eleifend non, sagittis id
libero. Quisque mollis velit id gravida aliquam. Curabitur imperdiet
dapibus ex molestie egestas. Orci varius natoque penatibus et magnis
dis parturient montes, nascetur ridiculus mus. Duis quis fermentum
nisl. Quisque feugiat nisi at augue vulputate viverra.
</motion.p>
<motion.p
whileInView={fadeInAnimation.text}
transition={fadeInAnimation.transition}
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam
venenatis quis ex id mollis. Quisque volutpat efficitur sagittis.
Suspendisse quis scelerisque eros. Nam vel leo magna. Praesent
hendrerit justo sapien, ac varius felis pharetra ultricies. Morbi
eleifend eros lacus, sit amet efficitur erat aliquam quis. Donec arcu
lectus, dapibus sed tortor in, euismod gravida metus. In molestie in
metus eu cursus. Curabitur at molestie ante, in vulputate lacus.
Phasellus turpis urna, sollicitudin non eleifend non, sagittis id
libero. Quisque mollis velit id gravida aliquam. Curabitur imperdiet
dapibus ex molestie egestas. Orci varius natoque penatibus et magnis
dis parturient montes, nascetur ridiculus mus. Duis quis fermentum
nisl. Quisque feugiat nisi at augue vulputate viverra.
</motion.p>
<motion.p
whileInView={fadeInAnimation.text}
transition={fadeInAnimation.transition}
>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam
venenatis quis ex id mollis. Quisque volutpat efficitur sagittis.
Suspendisse quis scelerisque eros. Nam vel leo magna. Praesent
hendrerit justo sapien, ac varius felis pharetra ultricies. Morbi
eleifend eros lacus, sit amet efficitur erat aliquam quis. Donec arcu
lectus, dapibus sed tortor in, euismod gravida metus. In molestie in
metus eu cursus. Curabitur at molestie ante, in vulputate lacus.
Phasellus turpis urna, sollicitudin non eleifend non, sagittis id
libero. Quisque mollis velit id gravida aliquam. Curabitur imperdiet
dapibus ex molestie egestas. Orci varius natoque penatibus et magnis
dis parturient montes, nascetur ridiculus mus. Duis quis fermentum
nisl. Quisque feugiat nisi at augue vulputate viverra.
</motion.p>
</motion.section>
</PageTransitionAnimation>
);
};
|
package assign06;
import java.net.URL;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A class that creates and simulates a web browser
* @author Aiden Fornalski
* @version 2023-10-19
*/
public class WebBrowser {
private Stack<URL> back;
private Stack<URL> forward;
private URL current;
public WebBrowser() {
this.back = new LinkedListStack<>();
this.forward = new LinkedListStack<>();
}
public WebBrowser(SinglyLinkedList<URL> history) {
this.current = history.getFirst(); //set current webpage to first in the history list
this.back = new LinkedListStack<>();
this.forward = new LinkedListStack<>();
Iterator<URL> iterator = history.iterator();
LinkedListStack<URL> tempBack = new LinkedListStack<>();
iterator.next();
while (iterator.hasNext()) { //add history list to a temp stack
tempBack.push(iterator.next());
}
for (int i = 0; i < history.size()-1; i++) { //add temp stack to back stack to correctly order the back stack
back.push(tempBack.pop());
}
}
/**
* Simulates visiting a webpage.
*
* @param webpage - the webpage you wish to "visit"
*/
public void visit(URL webpage) {
if (current != null) { //checking to see if current is null or not
forward.clear();
back.push(current);
}
current = webpage; //set current webpage to the visited webpage
}
/**
* Simulates pressing the back button on a webpage
*
* @return - the first webpage from the back stack
* @throws NoSuchElementException - if the back stack is empty
*/
public URL back() throws NoSuchElementException {
if (back.isEmpty()) { //check to see if back stack is empty
throw new NoSuchElementException();
}
forward.push(current); //add current webpage to forward stack
current = back.pop(); //set current to first webpage from back stack and remove that webpage from the back stack
return current;
}
/**
* Simulates pressing the forward button on a webpage
*
* @return - the first webpage from the forward stack
* @throws NoSuchElementException - if the forward stack is empty
*/
public URL forward() throws NoSuchElementException {
if (forward.isEmpty()) { //check to see if forward stack is empty
throw new NoSuchElementException();
}
back.push(current); //add current webpage to the back stack
current = forward.pop(); //set current to first webpage from forward stack and remove that webpage from the forward stack
return current;
}
/**
* Simulates checking the browser history (only for the back stack and current webpage)
*
* @return - a SinglyLinkedList of the browser history
*/
public SinglyLinkedList<URL> history() {
SinglyLinkedList<URL> history = new SinglyLinkedList<>();
LinkedListStack<URL> flippedBack = new LinkedListStack<>();
int size = back.size();
for (int i = 0; i < size; i++) { //reverse the back stack and set it to a temp stack
flippedBack.push(back.pop());
}
for (int i = 0; i < size; i++) { //add temp stack to history AND reload the back stack
URL temp = flippedBack.pop();
history.insertFirst(temp);
back.push(temp);
}
history.insertFirst(current); //add current webpage to the top of the history list
return history;
}
}
|
package strategies.years;
import databases.Database;
import entities.Child;
import entities.Gift;
import enums.Category;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Collectors;
public interface YearStrategy {
/**
* Assigns gifts to all the children in the database.
*/
void assignGifts();
/**
* Assigns gifts to a given child.
*/
static void assignGiftsToChild(Child child) {
double budget = child.getAssignedBudget();
for (Category category : child.getGiftsPreferences()) {
Gift receivedGift = null;
ArrayList<Gift> giftsList = Database.getDatabase().getGifts().stream()
.filter(g -> g.getCategory().equals(category))
.sorted(Comparator.comparing(Gift::getPrice))
.collect(Collectors.toCollection(ArrayList::new));
if (giftsList.isEmpty()) {
continue;
}
for (Gift gift : giftsList) {
if (gift.getQuantity() == 0) {
continue;
}
receivedGift = gift;
break;
}
if (receivedGift == null || receivedGift.getPrice() > budget) {
continue;
}
child.getReceivedGifts().add(receivedGift);
budget -= receivedGift.getPrice();
receivedGift.decreaseQuantity();
}
}
}
|
import Foundation
import Algorithms
struct Day13: Challenge {
let input: String
func run() -> String {
var output = ""
// output.append("Part 1: \(part1())\n")
output.append("Part 2: \(part2())")
return output
}
enum Signal: Equatable {
case int(Int)
case list([Signal])
static func parse(_ string: some StringProtocol) -> Self {
let scanner = Scanner(string: String(string))
return parse(using: scanner)!
}
private static func parse(using scanner: Scanner, indentLevel: Int = 0) -> Self? {
// [1]
// [1,2]
// [[1], 2]
// [[1],[2,3,4]]
// eat any commas
_ = scanner.scanString(",")
if let _ = scanner.scanString("[") {
// parse list
var list: [Signal] = []
while let signal = parse(using: scanner, indentLevel: indentLevel + 1) {
list.append(signal)
}
return .list(list)
} else if let _ = scanner.scanString("]") {
// end of list
return nil
} else {
var int: Int = 0
if scanner.scanInt(&int) {
return .int(int)
} else {
return nil
}
}
}
}
func comparison(_ left: Signal, _ right: Signal, indent: Int = 0) -> ComparisonResult {
let ind = Array(repeating: " ", count: indent + 1).joined()
switch (left, right) {
case let (.int(l), .int(r)):
print("\(ind)- Compare \(l) with \(r)")
if l == r {
return .orderedSame
}
return l < r ? .orderedAscending : .orderedDescending
case let (.list(l), .list(r)):
print("\(ind)- Compare \(l) with \(r)")
// [1, 2, 3, 4] [1, 2, 3]
var leftList = l
var rightList = r
while !leftList.isEmpty && !rightList.isEmpty {
let leftSignal = leftList.remove(at: 0)
let rightSignal = rightList.remove(at: 0)
let result = comparison(leftSignal, rightSignal, indent: indent + 1)
if result != .orderedSame {
return result
}
}
// all elements were in order
if l.count == r.count {
return .orderedSame
}
return l.count < r.count ? .orderedAscending : .orderedDescending
case (.list, _):
print("\(ind)- Mixed types, convert right to list and retry")
return comparison(left, .list([right]), indent: indent + 1)
case (_, .list):
print("\(ind)- Mixed types, convert left to list and retry")
return comparison(.list([left]), right, indent: indent + 1)
}
}
func part1() -> String {
let signals = input.lines().filter { !$0.isEmpty }.map(Signal.parse)
var indices: [Int] = []
for (index, pair) in signals.chunks(ofCount: 2).enumerated() {
let left = pair.first!
let right = pair.last!
print("L: ", left)
print("R: ", right)
if comparison(left, right) != .orderedDescending {
print("ORDERED")
indices.append(index + 1)
} else {
print("(not ordered)")
}
print("-----")
print("")
}
return "Sum of ordered indices: \(indices.reduce(0, +))"
}
func part2() -> String {
let dividerPacket1 = Signal.list([.list([.int(2)])])
let dividerPacket2 = Signal.list([.list([.int(6)])])
let signals = input.lines()
.filter { !$0.isEmpty }
.map(Signal.parse)
+ [dividerPacket1, dividerPacket2]
let sorted = signals.sorted(by: { a, b in
comparison(a, b) != .orderedDescending
})
print("sorted:")
var signalProduct = 1
sorted.enumerated().forEach { (index, signal) in
print("\(index + 1):", signal)
if signal == dividerPacket1 || signal == dividerPacket2 {
signalProduct *= (index + 1)
}
}
print(sorted)
return "Product of indices of signal packet is: \(signalProduct)"
}
}
extension Day13.Signal: CustomStringConvertible {
var description: String {
switch self {
case .int(let x): return "\(x)"
case .list(let signals):
return "[" + signals.map(\.description).joined(separator: ",") + "]"
}
}
}
|
<?xml version="1.0" encoding="UTF-8"?>
<knimeNode
icon="./shp-wkt-writer-icon.png"
type="Sink"
xmlns="http://knime.org/node/v2.8"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://knime.org/node/v2.10 http://knime.org/node/v2.10.xsd">
<name>Write Geometries into Shapefile</name>
<shortDescription>
Stores Spatial Data into a shapefile.
</shortDescription>
<fullDescription>
<intro>
Creates a <a href="https://en.wikipedia.org/wiki/Shapefile">shapefile in ESRI format</a>,
and stores the geometries found in the column "the_geom" expected to be in <a href="https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry">WKT format</a>.
<p>
Only one type of geometry (point, line, polyline...) can be stored per shapefile (this is a limitation of the shapefile format).
This type will be detected automatically from the content of the input table.
If several types are present, the writing will fail.
</p>
<p>
Other columns are written as attributes of the features, with an automatic conversion of classical KNIME types:
String, Double, Long, Integer, Boolean. Other attribute types are mapped to String attributes.
</p>
<p>
Due to limitations of the shapefile format:
<ul>
<li>A maximum of 255 fields (columns) can be stored; additional columns will be ignored.</li>
<li>Field names (column names) should be of max 10 characters; longer names will be truncated.</li>
<li>String values can only store 254 characters; longer ones will be truncated.</li>
</ul>
In case these limitations apply your data, warnings will be written in the console.
</p>
<p>
The actual processing is done by the wonderful <a href="https://geotools.org/">geotools library</a>.
</p>
</intro>
<option name="filename">File to create or erase</option>
</fullDescription>
<ports>
<inPort index="0" name="WKT data">Table with a the_geom column</inPort>
</ports>
</knimeNode>
|
/*
* Copyright (c) 2022-2022, Arumugam Jeganathan
*
* 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.
*/
import androidx.compose.ui.Alignment
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.WindowState
import androidx.compose.ui.window.application
import com.wbtwzd.logdog.command.DeviceListCmd
import com.wbtwzd.logdog.ui.App
import com.wbtwzd.logdog.util.Log
import kotlinx.coroutines.runBlocking
import java.io.File
import kotlin.system.exitProcess
fun main(args: Array<String>) {
val log = Log("LogDog")
// Parse the command line parameters
val argList = args.asList().toMutableList()
while (argList.isNotEmpty()) {
when (val param = argList.removeFirst()) {
"--debug", "-d" -> Log.logLevel = "debug"
"--info" -> Log.logLevel = "info"
"--warn", "-w" -> Log.logLevel = "error"
"--output" -> {
val dir = argList.removeFirstOrNull()
dir?.let {
val outputDir = File(it)
if (outputDir.isDirectory) {
AppOptions.outputDir = outputDir
} else {
log.e("Output directory does not exist")
printUsage()
}
} ?: run {
log.e("Missing output location")
printUsage()
}
}
else -> {
log.e("Unknown option $param")
printUsage()
}
}
}
// Check for `adb` installation location.
System.getenv("PATH")?.let { path ->
val adbFile = path.split(File.pathSeparator)
.flatMap { File(it).listFiles()?.toList() ?: emptyList<File>() }
.firstOrNull { it.name == "adb" }
adbFile?.let { AppOptions.adb = it.absolutePath }
}
log.i(AppOptions)
startApp()
}
private fun printUsage() {
println(
"""
Options:
--debug, -d - Enable logging debug messages
--warn, -w - Log only warning messages
--output - Output directory to write the log output to
""".trimIndent()
)
exitProcess(-1)
}
private fun startApp() = application {
Window(
onCloseRequest = ::exitApplication,
title = "LogDog",
state = WindowState(width = 1000.dp, height = 800.dp, position = WindowPosition(Alignment.Center)
)
) {
App()
}
}
object AppOptions {
var outputDir: File? = null
var adb: String = "adb"
}
|
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { ResultComponent } from './result.component';
import { StatNamePipe } from '../pipes/stat-name.pipe';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from '../app-routing.module';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable, of, throwError } from 'rxjs';
import { HttpService } from '../services/http.service';
import { colors } from '../data/colors';
describe('ResultComponent', () => {
let component: ResultComponent;
let fixture: ComponentFixture<ResultComponent>;
let mockActivatedRoute: any;
let mockRouter: any;
let httpService: HttpService;
beforeEach(async () => {
mockActivatedRoute = {
snapshot: {
paramMap: {
get: jasmine.createSpy('get').and.returnValue('someNameOrId'),
},
},
};
mockRouter = {
navigate: jasmine.createSpy('navigate'),
};
await TestBed.configureTestingModule({
declarations: [
ResultComponent,
StatNamePipe,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule
],
providers: [
{ provide: ActivatedRoute, useValue: mockActivatedRoute },
{ provide: Router, useValue: mockRouter },
HttpService
],
})
.compileComponents();
httpService = TestBed.inject(HttpService);
fixture = TestBed.createComponent(ResultComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should navigate to notFoundPage if name or id is not provided', () => {
mockActivatedRoute.snapshot.paramMap.get.and.returnValue(null);
component.ngOnInit();
expect(mockRouter.navigate).toHaveBeenCalledWith(['404']);
});
it('should get lowercase nameid and call getPokemonData if name or id is provided', () => {
const spy = spyOn(component, 'getPokemonData');
component.ngOnInit();
expect(spy).toHaveBeenCalled();
expect(component.nameid).toBe('somenameorid');
});
it('should call putPokemonData on successful data retrieval', fakeAsync(() => {
const mockData = { id : 10, name : "Pikachu" };
spyOn(httpService, 'getPokemon').and.returnValue(of(mockData));
spyOn(component, 'setPokemonData');
component.getPokemonData();
tick();
expect(component.setPokemonData).toHaveBeenCalledWith(mockData);
component.nameid = null;
component.getPokemonData();
tick();
expect(httpService.getPokemon).toHaveBeenCalledWith("");
}));
it('should correctly set Pokemon data', () => {
const color = "#F7CF43";
spyOn(component, 'getPokemonSpeciesData');
spyOn(component, 'setImgUrl');
spyOn(component, 'setPokemonStats');
spyOn(component, 'getcolorfromcolorslist').and.returnValue(color);
const mockData = {
name: 'Pikachu',
id: 25,
types: [{ type: { name: 'electric' } }],
};
component.setPokemonData(mockData);
expect(component.pokemon.name).toBe('Pikachu');
expect(component.pokemon.id).toBe(25);
expect(component.pokemon.types).toEqual([{ type: { name: 'electric' } }]);
expect(component.pokemon.color).toEqual(color);
});
it('should call getPokemonSpeciesData and setImgUrl and setPokemonStats', () => {
spyOn(component, 'getPokemonSpeciesData');
spyOn(component, 'setImgUrl');
spyOn(component, 'setPokemonStats');
const mockData = { name: 'Pikachu', id: 25, };
component.setPokemonData(mockData);
expect(component.getPokemonSpeciesData).toHaveBeenCalled();
expect(component.setImgUrl).toHaveBeenCalledWith(mockData);
expect(component.setPokemonStats).toHaveBeenCalledWith(mockData);
});
it('should correctly set Pokemon stats', () => {
const mockData = {
stats: [
{ stat: { name: 'hp' }, base_stat: 80 },
{ stat: { name: 'attack' }, base_stat: 100 },
],
};
component.setPokemonStats(mockData);
expect(component.pokemon.stats).toEqual([
{ name: 'hp', value: 80 },
{ name: 'attack', value: 100 },
]);
});
it('should not modify pokemon.stats if stats data is not provided', () => {
component.pokemon.stats = [{ name: 'hp', value: 80 }];
const mockData = {stats: []};
component.setPokemonStats(mockData);
expect(component.pokemon.stats).toEqual([]);
});
it('should navigate to notFoundPage when pokemon id is not available', () => {
component.pokemon.id = null;
component.getPokemonSpeciesData();
expect(mockRouter.navigate).toHaveBeenCalledWith(['404']);
});
it('should call setPokemonSpeciesData on successful data retrieval', fakeAsync(() => {
component.pokemon.id = 25;
const mockData = { };
spyOn(httpService, 'getPokemonSpecies').and.returnValue(of(mockData));
spyOn(component, 'setPokemonSpeciesData');
component.getPokemonSpeciesData();
tick();
expect(component.setPokemonSpeciesData).toHaveBeenCalled();
}));
it('should set Pokemon description', () => {
const mockData = {
flavor_text_entries: [
{ flavor_text: 'Description 1', language: { name: 'en' }, version: { name: 'alpha-sapphire' } },
],
};
component.setPokemonDescription(mockData);
expect(component.pokemon.description).toBe('Description 1');
});
it('should set default description if no flavor text entries are available', () => {
const mockData = {
flavor_text_entries: [],
};
component.setPokemonDescription(mockData);
expect(component.pokemon.description).toBe('no description available');
});
it('should call setPokemonEvols on successful evolution chain retrieval', fakeAsync(() => {
const mockEvolutionData = {
evolution_chain: { url: 'evolution-chain-url' },
};
spyOn(httpService, 'getEvolutionChain').and.returnValue(of(mockEvolutionData));
spyOn(component, 'setPokemonDescription');
spyOn(component, 'setPokemonEvols');
component.setPokemonSpeciesData(mockEvolutionData);
tick();
expect(component.setPokemonDescription).toHaveBeenCalled();
expect(component.setPokemonEvols).toHaveBeenCalled();
}));
it('should correctly set chain names recursively', () => {
const mockEvolutionChain = {
species: { name: 'pokemon1' },
evolves_to: [
{
species: { name: 'pokemon2' },
evolves_to: [
{ species: { name: 'pokemon3' }, evolves_to: [] },
],
},
],
};
const chainNames = component.setChain(mockEvolutionChain.evolves_to, [mockEvolutionChain.species.name]);
expect(chainNames).toEqual(['pokemon1', 'pokemon2', 'pokemon3']);
});
it('should set img URL and type from dream_world', () => {
const mockData = {
sprites: {
other: {
dream_world: {
front_default: 'dream_world_url',
},
},
},
};
component.setImgUrl(mockData);
expect(component.imgUrl).toBe('dream_world_url');
expect(component.imgType).toBe('svg');
});
it('should set img URL and type from home', () => {
const mockData = {
sprites: {
other: {
home: {
front_default: 'home_url',
},
},
},
};
component.setImgUrl(mockData);
expect(component.imgUrl).toBe('home_url');
expect(component.imgType).toBe('png');
});
it('should set img URL and type from official-artwork', () => {
const mockData = {
sprites: {
other: {
'official-artwork': {
front_default: 'official_url',
},
},
},
};
component.setImgUrl(mockData);
expect(component.imgUrl).toBe('official_url');
expect(component.imgType).toBe('png');
});
it('should set img URL and type from default', () => {
const mockData = {
sprites: {
front_default: 'default_url',
},
};
component.setImgUrl(mockData);
expect(component.imgUrl).toBe('default_url');
expect(component.imgType).toBe('png');
});
it('should return style for active tab', () => {
component.activeTab = 'STATS';
component.pokemon.color = 'red';
const result = component.getButtonTabStyle('STATS');
expect(result).toEqual({
'background-color': 'red',
'color': 'white',
'box-shadow': '0px 0px 10px 0px rgba(93, 190, 98, 0.70)',
});
});
it('should return style for inactive tab', () => {
component.activeTab = 'MOVES';
component.pokemon.color = 'red';
const result = component.getButtonTabStyle('STATS');
expect(result).toEqual({
'color': 'red',
'background-color': 'white',
});
});
it('should set activeTab correctly', () => {
component.setActiveTab('MOVES');
expect(component.activeTab).toBe('MOVES');
component.setActiveTab('STATS');
expect(component.activeTab).toBe('STATS');
});
it('should retrieve color from colors list', () => {
let result = component.getcolorfromcolorslist('normal');
expect(result).toBe('#A8A87B');
result = component.getcolorfromcolorslist('water');
expect(result).toBe('#559EDF');
result = component.getcolorfromcolorslist('fire');
expect(result).toBe('#EE803B');
});
});
|
import { Component, OnInit } from '@angular/core';
import { Pessoa } from '../models/pessoa';
import { PessoaService } from '../services/pessoa.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-pessoa-list',
templateUrl: './pessoa-list.component.html',
styleUrls: ['./pessoa-list.component.css']
})
export class PessoaListComponent implements OnInit {
pessoas: Pessoa[] = [];
displayedColumns: string[] = ['id', 'nome', 'cpf', 'email', 'telefone', 'endereco', 'acoes'];
pessoaSelecionada: Pessoa | null = null;
constructor(private pessoaService: PessoaService, private router: Router) {}
ngOnInit() {
this.obterPessoas();
}
obterPessoas() {
this.pessoaService.getPessoas().subscribe(pessoas => {
this.pessoas = pessoas;
});
}
editarPessoa(pessoa: Pessoa) {
// Implemente a lógica para editar a pessoa
//this.router.navigate(['/editar-pessoa', pessoa.id]);
this.pessoaSelecionada = { ...pessoa };
this.pessoaSelecionada.endereco = { ...pessoa.endereco };
}
salvarEdicao() {
if (this.pessoaSelecionada) {
this.pessoaService.atualizarPessoa(this.pessoaSelecionada)
.subscribe(
() => {
console.log('Pessoa atualizada com sucesso!');
this.pessoaSelecionada = null; // Limpa a pessoa selecionada
},
error => {
console.error('Erro ao atualizar pessoa:', error);
}
);
}
}
deletarPessoa(id: number) {
this.pessoaService.deletarPessoa(id).subscribe(
() => {
console.log('Pessoa deletada com sucesso!');
// Atualizar a lista de pessoas após a exclusão
this.obterPessoas();
},
error => {
console.error('Erro ao deletar pessoa:', error);
}
);
}
cancelarEdicao() {
this.pessoaSelecionada = null;
}
buscarEnderecoPorCep() {
if (this.pessoaSelecionada && this.pessoaSelecionada.endereco && this.pessoaSelecionada.endereco.cep) {
const cep = this.pessoaSelecionada.endereco.cep;
// Chame o serviço/API para buscar o endereço pelo CEP
// Exemplo:
this.pessoaService.buscarEnderecoPorCep(cep).subscribe(endereco => {
// Atualize o endereço da pessoa selecionada com os dados retornados
if (this.pessoaSelecionada && this.pessoaSelecionada.endereco) {
this.pessoaSelecionada.endereco.logradouro = endereco.logradouro;
this.pessoaSelecionada.endereco.numero = endereco.numero;
this.pessoaSelecionada.endereco.bairro = endereco.bairro;
this.pessoaSelecionada.endereco.cidade = endereco.cidade;
this.pessoaSelecionada.endereco.uf = endereco.uf;
}
});
}
}
}
|
package requstid
import (
"context"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const (
// ContextRequestIDKey context request id for context
ContextRequestIDKey = "request_id"
// HeaderXRequestIDKey http header request id key
HeaderXRequestIDKey = "X-Request-ID"
)
// CtxKeyString for context.WithValue key type
type CtxKeyString string
// RequestIDKey "request_id"
var RequestIDKey = CtxKeyString(ContextRequestIDKey)
// RequestID is an interceptor that injects a 'X-Request-ID' into the context and request/response header of each request.
func RequestID() gin.HandlerFunc {
return func(c *gin.Context) {
// Check for incoming header, use it if exists
requestID := c.Request.Header.Get(HeaderXRequestIDKey)
// Create request id
if requestID == "" {
requestID := uuid.New().String()
c.Request.Header.Set(HeaderXRequestIDKey, requestID)
// Expose it for use in the application
c.Set(ContextRequestIDKey, requestID)
}
// Set X-Request-ID header
c.Writer.Header().Set(HeaderXRequestIDKey, requestID)
c.Next()
}
}
// GetCtxRequestID get request id from gin.Context
func GetCtxRequestID(c *gin.Context) string {
if v, isExist := c.Get(ContextRequestIDKey); isExist {
if requestID, ok := v.(string); ok {
return requestID
}
}
return ""
}
// CtxRequestID get request id from context.Context
func CtxRequestID(ctx context.Context) string {
v := ctx.Value(ContextRequestIDKey)
if str, ok := v.(string); ok {
return str
}
return ""
}
// HeaderRequestID get request id from the header
func HeaderRequestID(c *gin.Context) string {
return c.Request.Header.Get(HeaderXRequestIDKey)
}
|
# School API VI
By the end of this assignment you will have a fully serviceable CRUD API with user authentication capabilities that will allow School staff to easily manage students and scholastic equipment.
## All Students
Build an API endpoint of `http://127.0.0.1:8000/api/v1/students/` with the name of `all_students`, that will return all students inside the the database in the following format:
```json
[
{
"name": "Francisco R. Avila",
"student_email": "francisco@school.com",
"personal_email": "francisco@gmail.com",
"locker_number": 1,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "Python",
"professor": "Professor Adam",
"students": 6,
"grade_average": 54.05,
}
],
},
{
"name": "Adam B. Cahan",
"student_email": "adam@school.com",
"personal_email": "adam@gmail.com",
"locker_number": 2,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "Python",
"professor": "Professor Adam",
"students": 6,
"grade_average": 54.05,
},
{
"subject_name": "Javascript",
"professor": "Professor Zaynab",
"students": 4,
"grade_average": 41.33,
},
{
"subject_name": "C#",
"professor": "Professor Benjamin",
"students": 6,
"grade_average": 42.54,
},
],
},
{
"name": "This I. Zaynab",
"student_email": "zaynab@school.com",
"personal_email": "zaynab@gmail.com",
"locker_number": 3,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "C#",
"professor": "Professor Benjamin",
"students": 6,
"grade_average": 42.54,
},
{
"subject_name": "History",
"professor": "Professor Nick",
"students": 5,
"grade_average": 25.39,
},
{
"subject_name": "Philosophy",
"professor": "Professor Avila",
"students": 5,
"grade_average": 51.37,
},
],
},
{
"name": "Tanjaro D. Kamado",
"student_email": "tanjaro@school.com",
"personal_email": "tanjaro@gmail.com",
"locker_number": 4,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "Javascript",
"professor": "Professor Zaynab",
"students": 4,
"grade_average": 41.33,
},
{
"subject_name": "C#",
"professor": "Professor Benjamin",
"students": 6,
"grade_average": 42.54,
},
{
"subject_name": "History",
"professor": "Professor Nick",
"students": 5,
"grade_average": 25.39,
},
],
},
{
"name": "Mark M. Grayson",
"student_email": "mark@school.com",
"personal_email": "mark@gmail.com",
"locker_number": 5,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "Python",
"professor": "Professor Adam",
"students": 6,
"grade_average": 54.05,
},
{
"subject_name": "C#",
"professor": "Professor Benjamin",
"students": 6,
"grade_average": 42.54,
},
{
"subject_name": "Philosophy",
"professor": "Professor Avila",
"students": 5,
"grade_average": 51.37,
},
],
},
{
"name": "Ash A. Katchum",
"student_email": "ash@school.com",
"personal_email": "ash@gmail.com",
"locker_number": 6,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "Python",
"professor": "Professor Adam",
"students": 6,
"grade_average": 54.05,
},
{
"subject_name": "Javascript",
"professor": "Professor Zaynab",
"students": 4,
"grade_average": 41.33,
},
{
"subject_name": "C#",
"professor": "Professor Benjamin",
"students": 6,
"grade_average": 42.54,
},
],
},
{
"name": "Nezuko M. Kamato",
"student_email": "nezuko@school.com",
"personal_email": "nezuko@gmail.com",
"locker_number": 7,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "C#",
"professor": "Professor Benjamin",
"students": 6,
"grade_average": 42.54,
},
{
"subject_name": "History",
"professor": "Professor Nick",
"students": 5,
"grade_average": 25.39,
},
{
"subject_name": "Philosophy",
"professor": "Professor Avila",
"students": 5,
"grade_average": 51.37,
},
],
},
{
"name": "Monkey D. Luffy",
"student_email": "monkey@school.com",
"personal_email": "monkey@gmail.com",
"locker_number": 8,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "Python",
"professor": "Professor Adam",
"students": 6,
"grade_average": 54.05,
},
{
"subject_name": "History",
"professor": "Professor Nick",
"students": 5,
"grade_average": 25.39,
},
{
"subject_name": "Philosophy",
"professor": "Professor Avila",
"students": 5,
"grade_average": 51.37,
},
],
},
{
"name": "Monkey D. Ace",
"student_email": "ace@school.com",
"personal_email": "ace@gmail.com",
"locker_number": 9,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "History",
"professor": "Professor Nick",
"students": 5,
"grade_average": 25.39,
}
],
},
{
"name": "Nick M. Smith",
"student_email": "nick@school.com",
"personal_email": "nick@gmail.com",
"locker_number": 10,
"locker_combination": "12-12-12",
"good_student": true,
"subjects": [
{
"subject_name": "Python",
"professor": "Professor Adam",
"students": 6,
"grade_average": 54.05,
},
{
"subject_name": "Javascript",
"professor": "Professor Zaynab",
"students": 4,
"grade_average": 41.33,
},
{
"subject_name": "Philosophy",
"professor": "Professor Avila",
"students": 5,
"grade_average": 51.37,
},
],
},
]
```
## All Subjects
Build an API endpoint of `http://127.0.0.1:8000/api/v1/subjects/` with the name of `all_subjects`, that will return all subjects inside the the database in the following format:
```json
[
{
"subject_name": "Python",
"professor": "Professor Adam",
"students": 6,
"grade_average": 54.05,
},
{
"subject_name": "Javascript",
"professor": "Professor Zaynab",
"students": 4,
"grade_average": 41.33,
},
{
"subject_name": "C#",
"professor": "Professor Benjamin",
"students": 6,
"grade_average": 42.54,
},
{
"subject_name": "History",
"professor": "Professor Nick",
"students": 5,
"grade_average": 25.39,
},
{
"subject_name": "Philosophy",
"professor": "Professor Avila",
"students": 5,
"grade_average": 51.37,
},
]
```
## Running Tests
Delete all the test files inside of each individual application. Add the `tests` folder inside of this repository to your projects ROOT directory.
```bash
python manage.py test tests
```
- `.` means a test passed
- `E` means an unhandled error populated on a test
- `F` means a test completely failed to run
## Considerations
You just made some changes to your student model, meaning you may have to adjust your tests regarding `serializers` to match the new output. Ensure to write serializers and validators to the best of your ability
## Tasks
- Create and/or Update Serializers to return the correct Data
- Ensure test 18 and 19 of test_models.py are passing (confirms serializers are returning the proper data)
- Create app urls.py files with url patterns and paths
- Create APIViews for GET requests that will Respond with the correct serialized data
- Ensure url paths contain the proper url pattern, Class Based View (as_view()), and name
|
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'CCompiler') }}</title>
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<link rel="stylesheet" href="/css/proposal.css">
</head>
<body>
<div class="bg-cabang">
<div id="app">
<nav class="navbar navbar-expand-md navbar-light">
<div class="container">
<a class="navbar-brand" href="{{ url('/') }}">
<img src="/image/ccomp%20hd-white.png" alt="" width="100px">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<!-- Left Side Of Navbar -->
<ul class="navbar-nav mr-auto">
</ul>
<!-- Right Side Of Navbar -->
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<div class="dropdown">
<button class="btn2 btn-primary2" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<a href="#lomba" style="text-decoration: none; color: #F9FBFC;">Lomba</a>
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="{{ url('/kompetisi/cp') }}">Competitive Programming</a>
<a class="dropdown-item" href="{{ url('/kompetisi/ctf') }}">Capture The Flag</a>
<a class="dropdown-item" href="{{ url('/kompetisi/ppl') }}">Pengembangan Perangkat Lunak</a>
<a href="{{ url('/kompetisi/iot') }}" class="dropdown-item">Internet of Things</a>
<a href="{{ url('/kompetisi/ux') }}" class="dropdown-item">User eXperience</a>
</div>
</div>
</li>
<!-- Authentication Links -->
@guest
<li class="nav-item">
<a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
</li>
@if (Route::has('register'))
<li class="nav-item">
<a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
</li>
@endif
@else
<li class="nav-item dropdown">
<a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
{{ Auth::user()->name }} <span class="caret"></span>
</a>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="{{ route('logout') }}" onclick="event.preventDefault();
document.getElementById('logout-form').submit();">
{{ __('Logout') }}
</a>
<form id="logout-form" action="{{ route('logout') }}" method="POST" style="display: none;">
@csrf
</form>
</div>
</li>
@endguest
</ul>
</div>
</div>
</nav>
<main class="py-4">
@yield('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card-header2">Kuy, Upload Proposal!</div>
<div class="card">
<div class="card-body">
<form method="POST" action="/peserta/proposal" enctype="multipart/form-data">
@csrf
<div class="card-button">
<img src="/image/icon-upload.png" alt="" width="120px">
</div>
<div class="text-upload card-button" style="margin-bottom: 0px;">
UPLOAD
</div>
<div class="description" style="text-align: center; margin-bottom: 30px;">
Silakan upload file dalam bentuk pdf
</div>
<div class="form-group row">
<label for="cabang" class="col-md-4 col-form-label text-md-right" style="display: none;">{{ __('Upload proposal anda') }}</label>
<div class="upload">
<input type="file" name="proposal" id="proposal" accept=".pdf" class="input">
</div>
</div>
<div class="">
<div class="card-button">
<button type="submit" class="btn btn-primary">
{{ __('UPLOAD') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
</body>
</html>
|
import 'package:app/common/data/my_cart_change_notifier.dart';
import 'package:app/p4/p4_catalog_page.dart';
import 'package:app/p4/p4_my_cart_page.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class P4App extends StatelessWidget {
const P4App({super.key});
@override
Widget build(BuildContext context) {
// ⭐️ Insert ChangeNotifierProvider with ChangeNotifier in Widget tree.
return ChangeNotifierProvider(
create: (context) => MyCartChangeNotifier(),
child: MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.yellow),
useMaterial3: true,
),
initialRoute: '/',
routes: {
'/': (context) => const P4CatalogPage(),
'/my_cart': (context) => const P4MyCartPage(),
},
),
);
}
}
|
import 'package:crypto_portfolio/data/gecko_api/dto/all_coins_list/all_coins_list.dart';
import 'package:crypto_portfolio/data/gecko_api/dto/get_coin_params/get_coin_params.dart';
extension GetCoinId on AllCoinsListDto {
String getId(GetCoinParams params) {
final List<CoinParamsDto> idsBySymbols = coins.where((e) {
return e.symbol.toUpperCase() == params.symbol.toUpperCase();
}).toList();
final List<CoinParamsDto> idsByNames = idsBySymbols.where((e) {
return e.name == params.name;
}).toList();
if (idsByNames.isEmpty) {
return idsBySymbols.first.id;
} else {
return idsByNames.first.id;
}
}
}
|
<!DOCTYPE html>
<html lang="en">
<!--
The intent behind this section is to have a form in which people can drop a review on race they've attended.
This page is to include features of the example of Chapter 7.
-->
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/Homework1.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="Formula 1, Review, Motorsport">
<meta name="description" content="Review Submission for Formula 1 Race Attendees">
<meta name="author" content="Leo Hsu">
<title>Formula 1 2023/24 Season</title>
</head>
<body>
<div class="header">
<img src="../images/formula1headerlogo.png" alt="" height="85px" width="300px">
<div class="nav">
<a href="../index.html">HOME</a>
|
<a href="../html/Circuits.html">CIRCUITS</a>
|
<a href="../html/Champions.html">CHAMPIONS</a>
|
<a href="../html/Headquarters.html">HEADQUARTERS</a>
|
<a href="../html/Contact.html">CONTACT</a>
</div>
</div>
<div class="contact">
<form action="/formresults.php" method="get">
<img src="../images/f1contact.avif" alt="" width="850px" height="500px">
<fieldset>
<legend>YOUR DETAILS:</legend>
<label>
NAME:
<input type="text" name="name" size="30" maxlength="100">
</label>
<label>
EMAIL:
<input type="text" name="email" size="30" maxlength="100">
</label>
</fieldset>
</form>
<br>
<fieldset>
<legend>YOUR RACE REVIEW:</legend>
<label>HAVE YOU BEEN TO A RACE ON THE 23/24 CALENDAR?</label>
<label>
<input type="radio" name="rating" value="yes">
YES
</label>
<label>
<input type="radio" name="rating" value="no">
NO
</label>
<p>
<legend>WHICH GRAND PRIX DID YOU ATTEND?</legend>
<select name="race" id="raceAttended">
<option value="Bahrain">BAHRAIN GP</option>
<option value="Saudi Arabia">SAUDI ARABIA GP</option>
<option value="Australia">AUSTRALIA GP</option>
<option value="Azerbaijan">AZERBAIJAN GP</option>
<option value="Miami">MIAMI GP</option>
<option value="Monaco">MONACO GP</option>
<option value="Spain">SPAIN GP</option>
<option value="Canada">CANADA GP</option>
<option value="Austria">AUSTRALIA GP</option>
<option value="Silverstone">SILVERSTONE GP</option>
<option value="Hungary">HUNGARY GP</option>
<option value="Belgium">BELGIUM GP</option>
<option value="Netherlands">NETHERLANDS GP</option>
<option value="Italy">ITALY GP</option>
</select>
</p>
<label for="comments">COMMENTS:</label>
<br>
<textarea id="comments" cols="50" rows="4"></textarea>
<br>
<input type="submit" value="Submit review">
</fieldset>
</div>
<div class="footer">
<img src="../images/formula1footerlogo.png" alt="">
<p id="contentBy">Website Generated By Leo Hsu | Content by © 2003-2023 Formula One World Championship Limited</p>
</div>
</body>
</html>
|
package com.ousl.tastytakeaway.model;
import android.os.Parcel;
import android.os.Parcelable;
public class Menu implements Parcelable {
private String name;
private String rating;
private float price;
private int totalInCart;
private String url;
public int getTotalInCart() {
return totalInCart;
}
public void setTotalInCart(int totalInCart) {
this.totalInCart = totalInCart;
}
protected Menu(Parcel in) {
name = in.readString();
rating = in.readString();
price = in.readFloat();
url = in.readString();
totalInCart = in.readInt();
}
public static final Creator<Menu> CREATOR = new Creator<Menu>() {
@Override
public Menu createFromParcel(Parcel in) {
return new Menu(in);
}
@Override
public Menu[] newArray(int size) {
return new Menu[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(rating);
dest.writeFloat(price);
dest.writeString(url);
dest.writeInt(totalInCart);
}
}
|
import { createContext, useState } from "react";
const RulesContext = createContext();
export const RulesProvider = ({ children }) => {
const [rules, setRules] = useState([]);
const addRule = (newRule) => {
setRules([newRule, ...rules]);
};
const removeRule = (id) => {
setRules(rules.filter((rule) => rule.id !== id));
};
const updateRule = (newUpdateRule, id) => {
setRules(
rules.map((rule) =>
rule.id === id ? { ...rule, ...newUpdateRule } : rule
)
);
};
return (
<RulesContext.Provider
value={{
rules,
setRules,
addRule,
removeRule,
updateRule,
}}
>
{children}
</RulesContext.Provider>
);
};
export default RulesContext;
|
<template>
<div>
<h1>
DataCenter
</h1>
<h2>
{{ dataCenter.name }}
</h2>
<form class="form">
<label for="dcName">
Name:
<input ref="dcName" :value="dataCenter.name" type="text" />
</label>
<br />
<label for="dcLat">
Breitengrad:
<input ref="dcLat" :value="dataCenter.lat" type="number" />
</label>
<br />
<label for="dcLong">
Längengrad:
<input ref="dcLong" :value="dataCenter.long" type="number" />
</label>
<br />
<label for="dcClusterNum">
Cluster-Anzahl:
<input ref="dcClusterNum" :value="dataCenter.numClusters" type="number"
/>
</label>
<br />
<input ref="submit" type="button"
value="Änderungen Speichern"
@click="saveChanges()"
/>
</form>
<Map
@dcCreated="dcCreated"
@dcClicked="dcClicked"
/>
</div>
</template>
<script>
import Map from '@/components/Map.vue';
import { mapGetters, mapActions } from 'vuex';
export default {
name: 'DataCenter',
data: () => ({
dataCenter: undefined,
}),
components: {
Map,
},
computed: {
...mapGetters(['dataCenters']),
},
created() {
this.loadDataCenters();
},
mounted() {
this.init();
},
methods: {
...mapActions(['saveDataCenters', 'updateDataCenter', 'loadDataCenters']),
dcCreated(dc) {
console.log('dcCreated', dc);
},
dcClicked(n) {
console.log('dcClicked', n);
},
saveChanges() {
this.dataCenter = {
name: this.$refs.dcName.value,
lat: this.$refs.dcLat.value,
long: this.$refs.dcLong.value,
numClusters: this.$refs.dcClusterNum.value,
};
this.updateDataCenter({ i: this.$route.params.dcIndex, dc: this.dataCenter });
this.$router.go(this.$router.currentRoute);
},
init() {
this.dataCenter = this.dataCenters[this.$route.params.dcIndex];
},
},
watch: {
'$route.params.dcIndex': function () {
this.init();
},
},
};
</script>
|
import React, { useState } from 'react';
const IconButton = ({ icon, onClick, disabled = false, size = 'm', variant = 'standard' }) => {
const [isHovered, setIsHovered] = useState(false);
const [isDisabled, setIsDisabled] = useState(disabled);
const handleMouseOver = () => {
setIsHovered(true);
};
const handleMouseLeave = () => {
setIsHovered(false);
};
const handleClick = () => {
if (!isDisabled) {
console.log('Button clicked'); // Aquí puedes realizar las acciones que desees al hacer clic
}
};
const getSizePercentage = () => {
switch (size.toLowerCase()) {
case 'xs':
return '24px';
case 's':
return '32px';
case 'm':
return '40px';
case 'l':
return '48px';
case 'xl':
return '56px';
default:
return '32px';
}
};
const getIconClass = () => {
switch (variant) {
case 'standard':
return 'standard-icon';
case 'filled-round':
return 'filled-round-icon';
case 'filled-square':
return 'filled-square-icon';
default:
return '';
}
};
return (
<button
className={`icon-button ${variant} ${isHovered ? 'hover' : ''} ${isDisabled ? 'disabled' : ''}`}
style={{ height: getSizePercentage(), width: getSizePercentage() }}
onClick={handleClick}
onMouseOver={handleMouseOver}
onMouseLeave={handleMouseLeave}
disabled={isDisabled}
>
<div className={getIconClass()} />
{icon}
<style>{`
.icon-button {
border: none;
background: transparent;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
padding: 5px;
}
.standard:hover {
background-color: #D2F5D2;
border-radius: 98%;
padding: 10px;
}
.icon-button.disabled .standard-icon {
color: #999999;
}
.icon-button:hover .standard-icon {
color: #0B520C;
}
.standard .standard-icon {
color: #1CCC1D;
}
/* Round */
.filled-round {
background-color: #1CCC1D;
border-radius: 98%;
}
.filled-round .filled-round-icon {
color: #FFFFFF;
}
.filled-round:hover {
background-color: #0B520C;
}
.icon-button:hover .filled-round-icon {
color: #E5E5E5;
}
.filled-round.disabled {
background-color: #E5E5E5;
}
.icon-button.disabled .filled-round-icon {
color: lightgray;
}
/* Square */
.filled-square {
background-color: #1CCC1D;
border-radius: 10%;
}
.filled-square:hover {
background-color: #0B520C;
}
.filled-square.disabled {
background-color: #f0f0f0;
}
.filled-square .filled-square-icon {
color: #E5E5E5;
}
.icon-button:hover .filled-square-icon {
color: #E5E5E5;
}
.icon-button.disabled .filled-square-icon {
color: lightgray;
}
`}</style>
</button>
);
};
export default IconButton;
|
import type { Network } from "./Network";
import type { ServicePort } from "./ServicePort";
import type { ServiceVolume } from "./ServiceVolume";
export type ServiceLoggingMap = {
none: any;
local: any;
"json-file": {
"max-size"?: string;
"max-file"?: string | number;
};
syslog: {
"syslog-address"?: string;
};
journald: any;
gelf: any;
fluentd: any;
awslogs: any;
splunk: any;
etwlogs: any;
gcplogs: any;
logentries: any;
};
export type ServiceLogging = {
[K in keyof ServiceLoggingMap]: {
driver: K;
options?: ServiceLoggingMap[K];
};
}[keyof ServiceLoggingMap];
/**
* @link https://linux.die.net/man/7/capabilities
*/
type Cap =
| "AUDIT_CONTROL"
| "AUDIT_WRITE"
| "BLOCK_SUSPEND"
| "CHOWN"
| "DAC_OVERRIDE"
| "DAC_READ_SEARCH"
| "FOWNER"
| "DAC_OVERRIDE"
| "DAC_READ_SEARCH"
| "FSETID"
| "IPC_LOCK"
| "IPC_OWNER"
| "KILL"
| "LEASE"
| "LINUX_IMMUTABLE"
| "MAC_ADMIN"
| "MAC_OVERRIDE"
| "MKNOD"
| "NET_ADMIN"
| "NET_BIND_SERVICE"
| "NET_BROADCAST"
| "NET_RAW"
| "SETGID"
| "SETFCAP"
| "SETPCAP"
| "SETPCAP"
| "SETPCAP"
| "SETUID"
| "SYS_ADMIN"
| "SYSLOG"
| "SYS_BOOT"
| "SYS_CHROOT"
| "SYS_MODULE"
| "SYS_NICE"
| "SYS_PACCT"
| "SYS_PTRACE"
| "SYS_RAWIO"
| "SYS_RESOURCE"
| "SYS_RESOURCE"
| "SYS_TIME"
| "SYS_TTY_CONFIG"
| "SYSLOG"
| "WAKE_ALARM";
export type ServiceSpec = {
build?: {
args?: Record<string, string> | string[];
cache_from?: string[];
context?: string;
dockerfile?: string;
labels?: string[];
network?: string;
shm_size?: string | number;
target?: string;
};
cap_add?: (Cap | "all")[];
cap_drop?: Cap[];
cgroup_parent?: string;
command?: string | string[];
container_name?: string;
credential_spec?: {
config?: string;
file?: string;
registry?: string;
};
depends_on?: (string | Service)[];
devices?: string | string[];
dns_search?: string | string[];
dns?: string | string[];
entrypoint?: string | string[];
env_file?: string | string[];
environment?: Record<string, string> | string[];
expose?: string[];
external_links?: string[];
extra_hosts?: (string | [string, string])[];
healthcheck?: {
disable?: boolean;
interval?: string;
retries?: number;
start_period?: string;
test?: string | string[];
timeout?: string;
};
image?: string;
init?: boolean;
labels?: string[];
logging?: ServiceLogging;
network_mode?:
| "bridge"
| "host"
| "none"
| { service: string | Service }
| { container: string };
networks?: (string | Network)[];
pid?: string;
ports?: (string | ServicePort)[];
privileged?: boolean;
profiles?: string[];
restart?: "no" | "on-failure" | "always" | "unless-stopped";
security_opt?: string[];
stop_grace_period?: string;
stop_signal?: string;
sysctls?: Record<string, string | number> | string[];
tmpfs?: string | string[];
ulimits?: {
nproc?: number;
nofile?: {
hard?: number;
soft?: number;
};
};
userns_mode?: string;
volumes_from?: (string | Service)[];
volumes?: (string | ServiceVolume)[];
working_dir?: string;
};
export class Service {
readonly name: string;
readonly type: "service";
readonly spec: ServiceSpec;
constructor(
readonly data: {
name: string;
spec: ServiceSpec;
}
) {
this.name = data.name;
this.type = "service";
this.spec = data.spec;
}
toJSON() {
const resolveName = (v: string | Service | Network) =>
typeof v === "string" ? v : v.name;
return {
...this.spec,
...(this.spec.extra_hosts && {
extra_hosts: this.spec.extra_hosts.map((v) =>
typeof v === "string" ? v : v.join(":")
),
}),
...(this.spec.volumes && {
volumes: this.spec.volumes.filter(
(v) => typeof v === "string" || v.source !== false
),
}),
...(this.spec.volumes_from && {
volumes_from: this.spec.volumes_from.map(resolveName),
}),
...(this.spec.network_mode && {
network_mode:
typeof this.spec.network_mode === "string"
? this.spec.network_mode
: "service" in this.spec.network_mode
? `service:${resolveName(this.spec.network_mode.service)}`
: "container" in this.spec.network_mode
? `container:${this.spec.network_mode.container}`
: undefined,
}),
} as any;
}
}
|
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";
import { NavLink } from "react-router-dom";
import { logout } from "../reducers/userReducer";
import logo from '../images/logo.jpg';
import { useEffect, useState } from "react";
const Nav = () => {
const dispatch = useDispatch();
const isAuth = useSelector(state => state.user.isAuth);
const [name, setName] = useState('');
useEffect(() => {
setName(localStorage.getItem('userName'));
}, []);
return (
<div>
<div className='nav'>
<div className='logo'>
<img src={logo} alt=''/>
</div>
{!isAuth && <div className='navLink'>
<NavLink to='/registration'>Register</NavLink>
</div>}
{!isAuth && <div className='navLink'>
<NavLink to='/login'>Login</NavLink>
</div>}
{isAuth && <div>Welcome {name}</div>}
{isAuth && <div className='navLink' onClick={() => dispatch(logout())}>Logout</div>}
</div>
</div>
);
}
export default Nav;
|
import {
action,
autorun,
makeObservable,
observable,
runInAction,
toJS,
} from "mobx";
import { KVStore, PrefixKVStore } from "@keplr-wallet/common";
import { simpleFetch } from "@keplr-wallet/simple-fetch";
import Joi from "joi";
interface VersionHistory {
version: string;
scenes: {
title: string;
image?: {
default: string;
light: string;
};
aspectRatio?: string;
paragraph: string;
}[];
}
const Schema = Joi.object<{
versions: VersionHistory[];
}>({
versions: Joi.array()
.items(
Joi.object({
version: Joi.string().required(),
scenes: Joi.array()
.items(
Joi.object({
title: Joi.string().required(),
image: Joi.object({
default: Joi.string().required(),
light: Joi.string().required(),
}).optional(),
aspectRatio: Joi.string().optional(),
paragraph: Joi.string().required(),
})
)
.min(1)
.required(),
})
)
.required(),
});
export class ChangelogConfig {
protected readonly kvStore: KVStore;
@observable.ref
protected _lastInfo:
| {
lastVersion: string;
currentVersion: string;
cleared: boolean;
histories: VersionHistory[];
}
| undefined = undefined;
constructor(kvStore: KVStore) {
this.kvStore = new PrefixKVStore(kvStore, "change-log-config");
makeObservable(this);
}
async init(lastVersion: string, currentVersion: string): Promise<void> {
{
const saved = await this.kvStore.get<ChangelogConfig["_lastInfo"]>(
"lastInfo"
);
if (saved) {
runInAction(() => {
this._lastInfo = saved;
});
}
}
if (lastVersion !== currentVersion) {
// should not ignore
this.fetchVersion(lastVersion, currentVersion);
}
autorun(() => {
this.kvStore.set<ChangelogConfig["_lastInfo"]>(
"lastInfo",
toJS(this._lastInfo)
);
});
}
protected async fetchVersion(
lastVersion: string,
currentVersion: string
): Promise<void> {
try {
const res = await simpleFetch<{
versions: VersionHistory[];
}>(
process.env["KEPLR_EXT_CONFIG_SERVER"],
`/changelog/${lastVersion}/${currentVersion}`
);
const validated = await Schema.validateAsync(res.data);
runInAction(() => {
this._lastInfo = {
lastVersion,
currentVersion,
cleared: false,
histories: validated.versions,
};
});
} catch (e) {
// ignore error
console.log(e);
}
}
@action
clearLastInfo() {
if (this._lastInfo) {
this._lastInfo = {
...this._lastInfo,
cleared: true,
};
}
}
get showingInfo(): VersionHistory[] {
if (!this._lastInfo) {
return [];
}
if (this._lastInfo.cleared) {
return [];
}
return this._lastInfo.histories;
}
}
|
<script>
import API from './../../api'
export default {
data: () => ({
dialog: false,
valid: true,
titre: '',
description: '',
musique: null,
musiqueUrl: '',
image: null,
imageUrl: '',
champs: [(v) => !!v || 'Merci de remplir le champs']
}),
props: {
musique: {
type: Object
},
updateMusique: {
type: Function
},
},
created() {
this.titre = '' + this.musique.titre
this.description = '' + this.musique.description
this.musiqueUrl = '' + this.musique.musique
this.imageUrl = '' + this.musique.img
},
methods: {
connect() {
API.addMusique(this.titre, this.musiqueUrl, this.description, this.imageUrl).then((result) => {
console.log(result)
this.updateMusique()
this.titre = ""
this.musiqueUrl = ""
this.description = ""
this.imageUrl = ""
this.musique = ""
this.image = ""
this.dialog = false
})
},
changeMusique() {
if (!this.musique) {
return;
}
else {
const reader = new FileReader();
reader.onload = e => {
if (e.target !== null) {
this.musiqueUrl = e.target.result;
console.log(e.target.result)
}
};
reader.readAsDataURL(this.musique);
}
},
changeImage() {
if (!this.image) {
return;
}
else {
const reader = new FileReader();
reader.onload = e => {
if (e.target !== null) {
this.imageUrl = e.target.result;
console.log(e.target.result)
}
};
reader.readAsDataURL(this.image);
}
}
}
}
</script>
<template>
<v-row justify="center">
<v-dialog v-model="dialog" persistent max-width="600px">
<template v-slot:activator="{ on, attrs }">
<v-btn color="orange" dark v-bind="attrs" v-on="on">
+
</v-btn>
</template>
<v-card>
<v-card-title>
<span class="text-h5">Ajouter une musique</span>
</v-card-title>
<v-card-text>
<v-container>
<v-row>
<v-col cols="12" sm="12" md="12">
<v-text-field label="Titre*" v-model="titre" required></v-text-field>
</v-col>
<v-col cols="12">
<v-textarea v-model="description" label="Description*" required></v-textarea>
</v-col>
<v-col cols="12" sm="6">
<v-file-input v-model="musique" label="Musique" accept="audio/*" prepend-icon="mdi-camera-image"
@change="changeMusique(e)"></v-file-input>
<audio ref="audio" :src="musiqueUrl" loop controls id="audio"></audio>
</v-col>
<v-col cols="12" sm="6">
<v-file-input v-model="image" label="Image" accept="image/*" prepend-icon="mdi-camera-image"
@change="changeImage(e)"></v-file-input>
<v-img :src="imageUrl" />
</v-col>
</v-row>
</v-container>
<small>*indicates required field</small>
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="blue darken-1" text @click="dialog = false">
Close
</v-btn>
<v-btn color="blue darken-1" text @click="connect">
Save
</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
</v-row>
</template>
|
---
title: "[Updated] Drafting Dynamic Denouements for 2024"
date: 2024-06-05T12:52:05.604Z
updated: 2024-06-06T12:52:05.604Z
tags:
- ai video
- ai youtube
categories:
- ai
- youtube
description: "This Article Describes [Updated] Drafting Dynamic Denouements for 2024"
excerpt: "This Article Describes [Updated] Drafting Dynamic Denouements for 2024"
keywords: "Denouement Writing,Plot Twists Techniques,Climactic Endings,Engaging Conclusions,Creative Storytelling,Narrative Dynamics,Resolution Crafting"
thumbnail: https://www.lifewire.com/thmb/6fzTu-E9_IJ8bYlrPxcbcoxehmg=/400x300/filters:no_upscale():max_bytes(150000):strip_icc()/iPhone-Flashlight-On-Dark-Table-8629938-64ad24bfa7684e2eaefe47292a89faeb.jpg
---
## Drafting Dynamic Denouements
Nowadays, having a strong online presence is more important than ever. One of the best ways to do that is to create engaging content for your YouTube channel, and you can achieve this by adding a solid intro and outro to your videos.
To keep viewers engaged, the outros on your videos must be strong and captivating to make a positive impression and leave viewers wanting more.
In this article, we'll discuss how to create **news outro templates** for your videos or get an editable or non-editable template online.
## Part 1\. Before Starting, Learn _What Is a Good YouTube Outro_?
Before we investigate where to find an appropriate News Style Outro for your video in Part 2, let's figure out what elements a good outro should include firstly.
A good outro will typically include a call to action, such as subscribing to a channel, checking out a website, or following on social media. You can also use engaging music or make your outros visually appealing with graphics, animations, or both to keep your viewers hooked.
Furthermore, it should include a brief summary of the video, and what viewers can expect for the things to come. You can find outros templates online or [make your own outstanding YouTube outros](https://tools.techidaily.com/wondershare/filmora/download/) in just a few clicks.
## Part 2\. Recommendation: Where Can You Find News Style Outro?
Now that you've understood what a good YouTube outro is, you might wonder where you can find News Style outros for your videos/presentations to add a bit of flair.
Multiple platforms offer editable or non-editable news styles outros to content creators. Below we've recommended top websites/platforms where you can get your required templates without any issues. Some even offer non-copyright content to their users.
1. [Editable News Outro Template Websites](#part2-1)
1. [Filmstock](#part2-1-1)
2. [Canva](#part2-1-2)
3. [Flexclip](#part2-1-3)
4. [Placeit](#part2-1-4)
2. [Non-Editable News Outro Template Websites](#part2-2)
1. [Storyblock](#part2-2-1)
2. [Videvo](#part2-2-2)
3. [Videezy](#part2-2-3)
4. [Shutterstock](#part2-2-4)
5. [iStock](#part2-2-5)
### Editable News Outro Template Websites
An editable **news outro template** can provide a quick and easy way to create or customize an outro that is both professional and engaging. Here are four websites we have chosen for you to find editable news outro templates.
##### Filmstock
Filmstock is a platform offering free and paid editable templates for content creators. With dozens of editable templates to choose from on [Filmstock](https://filmstock.wondershare.com/p/news-style-pack.html?af=6), you can find the perfect news style outro for your videos in just a few clicks. First, however, you need to install [Filmora](https://tools.techidaily.com/wondershare/filmora/download/) on your PC to use the platform.

Filmora is a popular video editor with a built-in filmstock library offering hundreds of non-copyright editable templates for every occasion. With the software, you can find and add your [news style outros](https://filmstock.wondershare.com/p/news-report-pack.html) to your videos with just a few clicks. The only disadvantage is that it isn't completely free. The paid version offers two options: A standard plan that costs **$9.99** per month and a Premium plan that will cost you **$49.99** per month.
You can also find detailed video tutorials to facilitate your video creation through [Filmora](https://www.youtube.com/c/FilmoraWondershare) and [Filmstock's](https://www.youtube.com/c/WondershareFilmstock) official YouTube Channels, as well as video sources set presentation on the two channels. Here is an example of News Set video on Filmora's YouTube Channel. Go to watch it and check are there any ideal news outro!
**Video of News Set in Filmora Effects Store**
##### Canva
[Canva](https://www.canva.com/search/templates?q=News%20Style%20Outros) is a user-friendly graphic design free and paid tool that is quickly becoming a popular choice for businesses of all sizes. Canva offers a range of templates for creating professional-looking designs.

With a wide range of templates to choose from, you can easily find one that fits your needs and style. Best of all, you can create your outro template in minutes without hiring a designer or spending hours learning complex design software.
The software is easy-to-use and does not require any editor to customize and use the templates. The paid version is divided into 2 tiers: Canva Pro **($54.99 per year**) and Canva for team (**$84\. 90/year)**. One disadvantage of the Canva free version is that it is limited resolution options when exporting your file.
##### Flexclip
[Flexclip](https://www.flexclip.com/template/?search=news%20outro)is a free, powerful, and easy-to-use online video maker that helps you create beautiful and engaging content for your business. With Flexclip, you can easily create editable news style outros for your videos from scratch or choose a template and edit it according to your requirements.

You can add text, music, elements, overlays, and branding to your templates to make them more stunning and captivating.
The platform offers 3 paid plans starting at **$8.99/month.** The con here is that the free version is only limited to the export quality of 480p, single royalty-free stock use, and 12 projects limit.
##### Placeit
[Placeit](https://placeit.net/?search=news+outros) is an online editor giving you the ability to create and customize your video content in no time. The editor also includes a stock image library, giving you access to several customizable templates.

Placeit is easy to use and offers a variety of templates for different purposes, including outros for news stories, video blogs, and even gaming videos. The platform offers an unlimited subscription plan starting from **$7.47 /month.**
However, the design rendering process of the editor is slow, there is no AI tool, and you even cannot import fonts that are not available on the platform.
### Non-Editable News Outro Template Websites
Some platforms offer non-editable high-resolution news outros that you can integrate into your videos using software programs like [Filmora (guidance in Part 3),](#%5FHow%5FTo%5FEdit) After Effects, etc.
##### Storyblock
Searching for high-quality templates for your next project?[Storyblock](https://www.storyblocks.com/video/search/news+outros) is a website that comes with royalty-free, non-customizable news style outros.

You can use these templates to create high-quality news intros and outros for your podcast or videos. The platform offers two pricing plans for individual content creators, starting at **$15** per month. While businesses can customize their plans as per their requirements.
Limitations of the Storyblock are that the footage quality is very poor in the free version, and the paid versions might be tricky to avail sometimes.
##### Videvo
[Videvo](https://www.videvo.net/search/news%20outros/) is a great resource for anyone looking for royalty-free video templates. They have over 300,000 free and premium videos, which you can download in clips or full with 4K resolution. However, their stock library is not much vast. The platform comes with a two-tier subscription plan starting from **$14.99/month** or **$144/year.**

You can find templates for both commercial and non-commercial use, so whatever your needs are, Videvo is likely to have a template that will work for you, i.e., news style. Some features of the platform include high-resolution download options, numerous music, sound effects, images and videos library, and a video compression option.
##### Videezy
[Videezy](https://www.videezy.com/free-video/news-outros) is a royalty-free video site that offers free and premium video templates. The website has a variety of options to choose from, including news style outros, all of which are geared towards creating engaging content.

The templates are all ready-made and royalty-free. You can download them for use in your own projects and attach them to your video using any video editing app/software.
The pricing of the platform starts at **$19/file**, which might be expensive for some users. Moreover, in the free version, too many ads are displayed.
##### Shutterstock
[Shutterstock](https://www.shutterstock.com/video/clip-1089743161-world-map-news-intro-blue-background-digital) has various affordable, royalty-free outro templates that you can use for your video/podcast. With a wide selection of styles and price points, this platform has the perfect content for your needs.

On Shutterstock, the free trial only offers 10 images, and you will be charged **$0.22-$14.50/image** once the trial limit is over. On the other hand, the Extended license will cost you **$67.96-$99.50.** The downside is that you have to purchase the content pack separately.
##### iStock
[iStock](https://www.istockphoto.com/search/2/image?phrase=news%20outro) is a premium website offering royalty-free stock photos, illustrations, and videos divided into numerous categories for easy access. The platform also offers a variety of non-editable **news outro templates** that you can add to your videos or podcasts.

The free trial on the platform is limited to 10 images, and after that, you will be charged **$0.22-$9.90/image**, while the Extended license will cost you **$144-$216.** The support system on the platform is slow and doesn't respond on time.
## Part 3\. A Bonus Tip: How To Edit Your News Outro For Your YouTube Video?
After knowing the websites providing News Style Outro, we hope you can find an ideal outro successfully. However, how to use the material you have found, integrate it into your YouTube video, and improve the quality of it?
Like mentioned before, we highly recommend Filmora to fulfill all your editing needs and even provide royalty-free templates to use. Below are the steps to edit your news outros and make your content more appealing. Let's start it without any hassle:
Step1 Download **Filmora** software from the official website and install it on your PC. Launch the software and click **"New Project."**

Step2 Drag and drop your media file or import it using the **"Click Here to Import Media File"** option. Now, drag your file and drop it in the **Timeline.**
Step3 Adjust your clip in the **Timeline** and click the **"Stock Media"** option. Search for **"News Outros,"** select the one you like, and add it to the **Timeline.**

Step4 Next, adjust the template on your video, and once you are satisfied, click the "**Export"** option. Finally, do the necessary settings and click **"Export"** again or share your video directly to YouTube.
[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
## Conclusion
In this article, we've provided a detailed guide on how to create **news outro templates** with simple and easy-to-follow instructions. We also discussed various platforms/editors where you can find customizable and non-customizable templates.
Hopefully, you find this guide informative and can now create strong news style outros for your videos.
##### Canva
[Canva](https://www.canva.com/search/templates?q=News%20Style%20Outros) is a user-friendly graphic design free and paid tool that is quickly becoming a popular choice for businesses of all sizes. Canva offers a range of templates for creating professional-looking designs.

With a wide range of templates to choose from, you can easily find one that fits your needs and style. Best of all, you can create your outro template in minutes without hiring a designer or spending hours learning complex design software.
The software is easy-to-use and does not require any editor to customize and use the templates. The paid version is divided into 2 tiers: Canva Pro **($54.99 per year**) and Canva for team (**$84\. 90/year)**. One disadvantage of the Canva free version is that it is limited resolution options when exporting your file.
##### Flexclip
[Flexclip](https://www.flexclip.com/template/?search=news%20outro)is a free, powerful, and easy-to-use online video maker that helps you create beautiful and engaging content for your business. With Flexclip, you can easily create editable news style outros for your videos from scratch or choose a template and edit it according to your requirements.

You can add text, music, elements, overlays, and branding to your templates to make them more stunning and captivating.
The platform offers 3 paid plans starting at **$8.99/month.** The con here is that the free version is only limited to the export quality of 480p, single royalty-free stock use, and 12 projects limit.
##### Placeit
[Placeit](https://placeit.net/?search=news+outros) is an online editor giving you the ability to create and customize your video content in no time. The editor also includes a stock image library, giving you access to several customizable templates.

Placeit is easy to use and offers a variety of templates for different purposes, including outros for news stories, video blogs, and even gaming videos. The platform offers an unlimited subscription plan starting from **$7.47 /month.**
However, the design rendering process of the editor is slow, there is no AI tool, and you even cannot import fonts that are not available on the platform.
### Non-Editable News Outro Template Websites
Some platforms offer non-editable high-resolution news outros that you can integrate into your videos using software programs like [Filmora (guidance in Part 3),](#%5FHow%5FTo%5FEdit) After Effects, etc.
##### Storyblock
Searching for high-quality templates for your next project?[Storyblock](https://www.storyblocks.com/video/search/news+outros) is a website that comes with royalty-free, non-customizable news style outros.

You can use these templates to create high-quality news intros and outros for your podcast or videos. The platform offers two pricing plans for individual content creators, starting at **$15** per month. While businesses can customize their plans as per their requirements.
Limitations of the Storyblock are that the footage quality is very poor in the free version, and the paid versions might be tricky to avail sometimes.
##### Videvo
[Videvo](https://www.videvo.net/search/news%20outros/) is a great resource for anyone looking for royalty-free video templates. They have over 300,000 free and premium videos, which you can download in clips or full with 4K resolution. However, their stock library is not much vast. The platform comes with a two-tier subscription plan starting from **$14.99/month** or **$144/year.**

You can find templates for both commercial and non-commercial use, so whatever your needs are, Videvo is likely to have a template that will work for you, i.e., news style. Some features of the platform include high-resolution download options, numerous music, sound effects, images and videos library, and a video compression option.
##### Videezy
[Videezy](https://www.videezy.com/free-video/news-outros) is a royalty-free video site that offers free and premium video templates. The website has a variety of options to choose from, including news style outros, all of which are geared towards creating engaging content.

The templates are all ready-made and royalty-free. You can download them for use in your own projects and attach them to your video using any video editing app/software.
The pricing of the platform starts at **$19/file**, which might be expensive for some users. Moreover, in the free version, too many ads are displayed.
##### Shutterstock
[Shutterstock](https://www.shutterstock.com/video/clip-1089743161-world-map-news-intro-blue-background-digital) has various affordable, royalty-free outro templates that you can use for your video/podcast. With a wide selection of styles and price points, this platform has the perfect content for your needs.

On Shutterstock, the free trial only offers 10 images, and you will be charged **$0.22-$14.50/image** once the trial limit is over. On the other hand, the Extended license will cost you **$67.96-$99.50.** The downside is that you have to purchase the content pack separately.
##### iStock
[iStock](https://www.istockphoto.com/search/2/image?phrase=news%20outro) is a premium website offering royalty-free stock photos, illustrations, and videos divided into numerous categories for easy access. The platform also offers a variety of non-editable **news outro templates** that you can add to your videos or podcasts.

The free trial on the platform is limited to 10 images, and after that, you will be charged **$0.22-$9.90/image**, while the Extended license will cost you **$144-$216.** The support system on the platform is slow and doesn't respond on time.
## Part 3\. A Bonus Tip: How To Edit Your News Outro For Your YouTube Video?
After knowing the websites providing News Style Outro, we hope you can find an ideal outro successfully. However, how to use the material you have found, integrate it into your YouTube video, and improve the quality of it?
Like mentioned before, we highly recommend Filmora to fulfill all your editing needs and even provide royalty-free templates to use. Below are the steps to edit your news outros and make your content more appealing. Let's start it without any hassle:
Step1 Download **Filmora** software from the official website and install it on your PC. Launch the software and click **"New Project."**

Step2 Drag and drop your media file or import it using the **"Click Here to Import Media File"** option. Now, drag your file and drop it in the **Timeline.**
Step3 Adjust your clip in the **Timeline** and click the **"Stock Media"** option. Search for **"News Outros,"** select the one you like, and add it to the **Timeline.**

Step4 Next, adjust the template on your video, and once you are satisfied, click the "**Export"** option. Finally, do the necessary settings and click **"Export"** again or share your video directly to YouTube.
[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
## Conclusion
In this article, we've provided a detailed guide on how to create **news outro templates** with simple and easy-to-follow instructions. We also discussed various platforms/editors where you can find customizable and non-customizable templates.
Hopefully, you find this guide informative and can now create strong news style outros for your videos.
<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>
## Guiding You Through YouTube's View Limitations
# How to Change the Privacy Setting on Your YouTube Videos

##### Richard Bennett
Mar 27, 2024• Proven solutions
Privacy settings on YouTube allow you to control who can see your videos. There are three settings — Public, unlisted, and private. This article will give you a brief introduction of what those three settings mean, and how to use them.
* [**Part1: Public VS Unlisted VS Private**](#part1)
* [**Part2: How to Change Privacy Settings**](#part2)
* [**Part2: Sharing Private Videos**](#part3)
---
Want to make your YouTube videos more beautiful within minutes? Here we recommend an easy-to-use video editing software for beginner for your reference - [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
---
## Part 1: Public VS Unlisted VS Private
Let's figure out some terms before runing into the how-to part.
**Public Videos**
These are videos that everyone can view. This is the majority of YouTube videos, and just about every one you’ve ever watched will have been public. You'll want this if you want lots of people to watch your video.
**Unlisted**
Unlisted videos are ones that anybody can view so long as they have the link. The video won’t show up on search results or in "related" or "suggested" videos.
This is a great setting for sharing a video amongst small groups. You might have a rough edit you want to show a few people, or you might have a show reel that you only want certain people to see.
**Private**
Completely private videos cannot be watched by anyone who doesn’t have permission. You grant people permission by allowing their Google accounts to access the video. Nobody else can see the video, regardless of whether they have the link.
It won’t show up on searches, as related or suggested videos, or even when imbedded in other sites. This is the best setting for a video you need to share with only very specific people, if anyone. Below is a comparison table to know more about [privacy settings](https://support.google.com/youtube/answer/157177?co=GENIE.Platform%3DDesktop&hl=en&oco=1).

## Part 2: How to Change Privacy Settings
There are two ways to change the privacy settings: firstly, when you upload the video, and secondly through Creator Studio.
**Method 1:**
When you upload a video to YouTube you'll see on the right hand side an option that says "privacy". This is defaulted to "public", but you can use the drop-down menu on the button to change the setting. This will apply your privacy setting the second the video finishes uploading and processing.

**Method 2:**
To change the privacy setting later, go to Creator Studio, then Video Manager. On the right-hand side you’ll see one of three icons: a world, a chain, and a lock. The world means **"public"**, the chain means **"unlisted"**, and the lock is for **"private"**.

To change the privacy, click the icon. You’ll be taken to the video's info and settings page. Down below where you see the thumbnails you'll see the selected privacy setting. Click this to open a drop down menu, and select your desired privacy level.
## Part 3: Sharing Private Videos
If a video is set to "private', you'll have the option to share it with specific people. Below where it says "private" on the info and settings page you'll see a button labeled "share". Click this and type in the email addresses of the people you want to be able to watch the video. You’ll also have the option of notifying the people via email that you’ve shared the video with them.

## Conclusion
And that's all there is to it! Changing the privacy setting on YouTube videos is a simple, helpful tool to allow you to control the audience of you work. Enjoy!
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Mar 27, 2024• Proven solutions
Privacy settings on YouTube allow you to control who can see your videos. There are three settings — Public, unlisted, and private. This article will give you a brief introduction of what those three settings mean, and how to use them.
* [**Part1: Public VS Unlisted VS Private**](#part1)
* [**Part2: How to Change Privacy Settings**](#part2)
* [**Part2: Sharing Private Videos**](#part3)
---
Want to make your YouTube videos more beautiful within minutes? Here we recommend an easy-to-use video editing software for beginner for your reference - [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
---
## Part 1: Public VS Unlisted VS Private
Let's figure out some terms before runing into the how-to part.
**Public Videos**
These are videos that everyone can view. This is the majority of YouTube videos, and just about every one you’ve ever watched will have been public. You'll want this if you want lots of people to watch your video.
**Unlisted**
Unlisted videos are ones that anybody can view so long as they have the link. The video won’t show up on search results or in "related" or "suggested" videos.
This is a great setting for sharing a video amongst small groups. You might have a rough edit you want to show a few people, or you might have a show reel that you only want certain people to see.
**Private**
Completely private videos cannot be watched by anyone who doesn’t have permission. You grant people permission by allowing their Google accounts to access the video. Nobody else can see the video, regardless of whether they have the link.
It won’t show up on searches, as related or suggested videos, or even when imbedded in other sites. This is the best setting for a video you need to share with only very specific people, if anyone. Below is a comparison table to know more about [privacy settings](https://support.google.com/youtube/answer/157177?co=GENIE.Platform%3DDesktop&hl=en&oco=1).

## Part 2: How to Change Privacy Settings
There are two ways to change the privacy settings: firstly, when you upload the video, and secondly through Creator Studio.
**Method 1:**
When you upload a video to YouTube you'll see on the right hand side an option that says "privacy". This is defaulted to "public", but you can use the drop-down menu on the button to change the setting. This will apply your privacy setting the second the video finishes uploading and processing.

**Method 2:**
To change the privacy setting later, go to Creator Studio, then Video Manager. On the right-hand side you’ll see one of three icons: a world, a chain, and a lock. The world means **"public"**, the chain means **"unlisted"**, and the lock is for **"private"**.

To change the privacy, click the icon. You’ll be taken to the video's info and settings page. Down below where you see the thumbnails you'll see the selected privacy setting. Click this to open a drop down menu, and select your desired privacy level.
## Part 3: Sharing Private Videos
If a video is set to "private', you'll have the option to share it with specific people. Below where it says "private" on the info and settings page you'll see a button labeled "share". Click this and type in the email addresses of the people you want to be able to watch the video. You’ll also have the option of notifying the people via email that you’ve shared the video with them.

## Conclusion
And that's all there is to it! Changing the privacy setting on YouTube videos is a simple, helpful tool to allow you to control the audience of you work. Enjoy!
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Mar 27, 2024• Proven solutions
Privacy settings on YouTube allow you to control who can see your videos. There are three settings — Public, unlisted, and private. This article will give you a brief introduction of what those three settings mean, and how to use them.
* [**Part1: Public VS Unlisted VS Private**](#part1)
* [**Part2: How to Change Privacy Settings**](#part2)
* [**Part2: Sharing Private Videos**](#part3)
---
Want to make your YouTube videos more beautiful within minutes? Here we recommend an easy-to-use video editing software for beginner for your reference - [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
---
## Part 1: Public VS Unlisted VS Private
Let's figure out some terms before runing into the how-to part.
**Public Videos**
These are videos that everyone can view. This is the majority of YouTube videos, and just about every one you’ve ever watched will have been public. You'll want this if you want lots of people to watch your video.
**Unlisted**
Unlisted videos are ones that anybody can view so long as they have the link. The video won’t show up on search results or in "related" or "suggested" videos.
This is a great setting for sharing a video amongst small groups. You might have a rough edit you want to show a few people, or you might have a show reel that you only want certain people to see.
**Private**
Completely private videos cannot be watched by anyone who doesn’t have permission. You grant people permission by allowing their Google accounts to access the video. Nobody else can see the video, regardless of whether they have the link.
It won’t show up on searches, as related or suggested videos, or even when imbedded in other sites. This is the best setting for a video you need to share with only very specific people, if anyone. Below is a comparison table to know more about [privacy settings](https://support.google.com/youtube/answer/157177?co=GENIE.Platform%3DDesktop&hl=en&oco=1).

## Part 2: How to Change Privacy Settings
There are two ways to change the privacy settings: firstly, when you upload the video, and secondly through Creator Studio.
**Method 1:**
When you upload a video to YouTube you'll see on the right hand side an option that says "privacy". This is defaulted to "public", but you can use the drop-down menu on the button to change the setting. This will apply your privacy setting the second the video finishes uploading and processing.

**Method 2:**
To change the privacy setting later, go to Creator Studio, then Video Manager. On the right-hand side you’ll see one of three icons: a world, a chain, and a lock. The world means **"public"**, the chain means **"unlisted"**, and the lock is for **"private"**.

To change the privacy, click the icon. You’ll be taken to the video's info and settings page. Down below where you see the thumbnails you'll see the selected privacy setting. Click this to open a drop down menu, and select your desired privacy level.
## Part 3: Sharing Private Videos
If a video is set to "private', you'll have the option to share it with specific people. Below where it says "private" on the info and settings page you'll see a button labeled "share". Click this and type in the email addresses of the people you want to be able to watch the video. You’ll also have the option of notifying the people via email that you’ve shared the video with them.

## Conclusion
And that's all there is to it! Changing the privacy setting on YouTube videos is a simple, helpful tool to allow you to control the audience of you work. Enjoy!
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
##### Richard Bennett
Mar 27, 2024• Proven solutions
Privacy settings on YouTube allow you to control who can see your videos. There are three settings — Public, unlisted, and private. This article will give you a brief introduction of what those three settings mean, and how to use them.
* [**Part1: Public VS Unlisted VS Private**](#part1)
* [**Part2: How to Change Privacy Settings**](#part2)
* [**Part2: Sharing Private Videos**](#part3)
---
Want to make your YouTube videos more beautiful within minutes? Here we recommend an easy-to-use video editing software for beginner for your reference - [Wondershare Filmora](https://tools.techidaily.com/wondershare/filmora/download/).
[](https://tools.techidaily.com/wondershare/filmora/download/)[Download Mac Version](https://images.wondershare.com/filmora/guide/download-btn-mac.jpg)](https://tools.techidaily.com/wondershare/filmora/download/)
---
## Part 1: Public VS Unlisted VS Private
Let's figure out some terms before runing into the how-to part.
**Public Videos**
These are videos that everyone can view. This is the majority of YouTube videos, and just about every one you’ve ever watched will have been public. You'll want this if you want lots of people to watch your video.
**Unlisted**
Unlisted videos are ones that anybody can view so long as they have the link. The video won’t show up on search results or in "related" or "suggested" videos.
This is a great setting for sharing a video amongst small groups. You might have a rough edit you want to show a few people, or you might have a show reel that you only want certain people to see.
**Private**
Completely private videos cannot be watched by anyone who doesn’t have permission. You grant people permission by allowing their Google accounts to access the video. Nobody else can see the video, regardless of whether they have the link.
It won’t show up on searches, as related or suggested videos, or even when imbedded in other sites. This is the best setting for a video you need to share with only very specific people, if anyone. Below is a comparison table to know more about [privacy settings](https://support.google.com/youtube/answer/157177?co=GENIE.Platform%3DDesktop&hl=en&oco=1).

## Part 2: How to Change Privacy Settings
There are two ways to change the privacy settings: firstly, when you upload the video, and secondly through Creator Studio.
**Method 1:**
When you upload a video to YouTube you'll see on the right hand side an option that says "privacy". This is defaulted to "public", but you can use the drop-down menu on the button to change the setting. This will apply your privacy setting the second the video finishes uploading and processing.

**Method 2:**
To change the privacy setting later, go to Creator Studio, then Video Manager. On the right-hand side you’ll see one of three icons: a world, a chain, and a lock. The world means **"public"**, the chain means **"unlisted"**, and the lock is for **"private"**.

To change the privacy, click the icon. You’ll be taken to the video's info and settings page. Down below where you see the thumbnails you'll see the selected privacy setting. Click this to open a drop down menu, and select your desired privacy level.
## Part 3: Sharing Private Videos
If a video is set to "private', you'll have the option to share it with specific people. Below where it says "private" on the info and settings page you'll see a button labeled "share". Click this and type in the email addresses of the people you want to be able to watch the video. You’ll also have the option of notifying the people via email that you’ve shared the video with them.

## Conclusion
And that's all there is to it! Changing the privacy setting on YouTube videos is a simple, helpful tool to allow you to control the audience of you work. Enjoy!
[](https://tools.techidaily.com/wondershare/filmora/download/)[](https://tools.techidaily.com/wondershare/filmora/download/)

Richard Bennett
Richard Bennett is a writer and a lover of all things video.
Follow @Richard Bennett
<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://facebook-video-share.techidaily.com/new-in-2024-elevating-youtube-performance-consistency-in-cc-usage/"><u>[New] In 2024, Elevating YouTube Performance Consistency in CC Usage</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/updated-top-10-recruiting-gems-amp-up-engagement/"><u>[Updated] Top 10 Recruiting Gems Amp Up Engagement</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/updated-in-2024-channel-success-story-optimal-themes-and-ideas-to-boost-content/"><u>[Updated] In 2024, Channel Success Story Optimal Themes and Ideas to Boost Content</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/tailoring-titles-and-tags-for-top-youtube-performance-for-2024/"><u>Tailoring Titles and Tags for Top YouTube Performance for 2024</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/new-echoes-of-entertainment-discovering-6-free-android-apps-for-your-youtube-playlists-for-2024/"><u>[New] Echoes of Entertainment Discovering 6 Free Android Apps for Your YouTube Playlists for 2024</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/new-your-first-impression-matters-8-must-try-youtube-tools-for-thumbnails/"><u>[New] Your First Impression Matters 8 Must-Try YouTube Tools for Thumbnails</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/updated-how-to-compose-captivating-youtube-intros-for-free/"><u>[Updated] How To Compose Captivating YouTube Intros for FREE</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/new-a-compreayers-guide-to-monetizing-videos-critical-view-figures-for-2024/"><u>[New] A Compreayer's Guide to Monetizing Videos Critical View Figures for 2024</u></a></li>
<li><a href="https://facebook-video-share.techidaily.com/updated-rapid-audience-expansion-without-breaking-the-bank/"><u>[Updated] Rapid Audience Expansion Without Breaking the Bank</u></a></li>
<li><a href="https://extra-resources.techidaily.com/a-new-era-of-visual-clarity-the-10-list-of-top-monitors-for-macs-for-2024/"><u>A New Era of Visual Clarity The #10 List of Top Monitors for Macs for 2024</u></a></li>
<li><a href="https://sound-optimizing.techidaily.com/in-2024-dynamic-sound-mixing-implementing-audio-ducking-techniques-to-subtly-reduce-background-tracks/"><u>In 2024, Dynamic Sound Mixing Implementing Audio Ducking Techniques to Subtly Reduce Background Tracks</u></a></li>
<li><a href="https://smart-video-creator.techidaily.com/new-in-2024-the-art-of-cinematic-editing-a-final-cut-pro-x-tutorial/"><u>New In 2024, The Art of Cinematic Editing A Final Cut Pro X Tutorial</u></a></li>
<li><a href="https://location-fake.techidaily.com/5-best-route-generator-apps-you-should-try-on-htc-u23-drfone-by-drfone-virtual-android/"><u>5 Best Route Generator Apps You Should Try On HTC U23 | Dr.fone</u></a></li>
<li><a href="https://facebook-clips.techidaily.com/new-2024-approved-seamless-media-exchange-transferring-facebook-content-to-whatsapp/"><u>[New] 2024 Approved Seamless Media Exchange Transferring Facebook Content to WhatsApp</u></a></li>
<li><a href="https://some-guidance.techidaily.com/unveiling-prime-hdr-cameras-a-comprehensive-guide-for-2024/"><u>Unveiling Prime HDR Cameras A Comprehensive Guide for 2024</u></a></li>
<li><a href="https://some-knowledge.techidaily.com/updated-go-big-or-go-home-selecting-the-most-satisfying-1tbplus-cloud-services/"><u>[Updated] Go Big or Go Home - Selecting the Most Satisfying 1TB+ Cloud Services</u></a></li>
<li><a href="https://facebook-video-files.techidaily.com/updated-2024-approved-yogo-profile-picture-guide-dimensions-in-mm-aspect-ratio-minutes/"><u>[Updated] 2024 Approved YoGo Profile Picture Guide Dimensions in Mm², Aspect Ratio, Minutes</u></a></li>
<li><a href="https://discord-videos.techidaily.com/updated-in-2024-discounted-artisan-logos-best-free-emblem-tools/"><u>[Updated] In 2024, Discounted Artisan Logos Best Free Emblem Tools</u></a></li>
<li><a href="https://twitter-videos.techidaily.com/in-2024-rapid-rise-of-tweets-top-hotties-on-twitterscape/"><u>In 2024, Rapid Rise of Tweets Top Hotties on Twitterscape</u></a></li>
</ul></div>
|
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';
import { Injectable, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { InvalidDataFormatException } from '../exceptions/invalid_data_format.exception';
export interface EncryptConfig {
APP_ENCRYPT_PASSWORD: string;
}
const IV_LENGTH = 16; // For AES, this is always 16
const PASSWORD_LENGTH = 32; // For AES, this is always 32
@Injectable()
export class EncryptService {
private password: string;
constructor(private readonly configService: ConfigService<EncryptConfig>) {
this.password = this.configService.get<string>('APP_ENCRYPT_PASSWORD');
if (this.password?.length !== PASSWORD_LENGTH) {
throw new InvalidDataFormatException([
`Password length must be ${PASSWORD_LENGTH}`,
]);
}
}
encrypt(plain: string): string {
const iv = randomBytes(IV_LENGTH);
const cipher = createCipheriv(
'aes-256-cbc',
Buffer.from(this.password),
iv,
);
let encrypted = cipher.update(plain);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
}
decrypt(encrypted: string): string {
const textParts = encrypted.split(':');
const iv = Buffer.from(textParts.shift(), 'hex');
const encryptedText = Buffer.from(textParts.join(':'), 'hex');
const decipher = createDecipheriv(
'aes-256-cbc',
Buffer.from(this.password),
iv,
);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
}
@Module({
imports: [ConfigModule],
providers: [EncryptService],
exports: [EncryptService],
})
export class EncryptModule {}
|
<?php
namespace App\DataTables;
use App\Models\Claim;
use Illuminate\Database\Eloquent\Builder as QueryBuilder;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\Html\Builder as HtmlBuilder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
class ClaimDataTable extends DataTable
{
/**
* Build the DataTable class.
*
* @param QueryBuilder $query Results from query() method.
*/
public function dataTable(QueryBuilder $query): EloquentDataTable
{
return (new EloquentDataTable($query))
->addColumn('action', function($query){
$delete = '<a href="'.route('admin.listing-claims.destroy', $query->id).'" class="delete-item btn btn-sm btn-danger ml-2"><i class="fas fa-trash"></i></a>';
return $delete;
})
->addColumn('listing', function($query) {
$html = "<a target='_blank' href='".route('listing.show', $query->listing->slug)."'>".$query->listing->title."</a>";
return $html;
})
->filterColumn('listing', function ($query, $keyword) {
$query->orWhereHas('listing', function($subQuery) use ($keyword){
$subQuery->where('title', 'like', '%'.$keyword.'%');
});
})
->rawColumns(['action', 'listing'])
->setRowId('id');
}
/**
* Get the query source of dataTable.
*/
public function query(Claim $model): QueryBuilder
{
return $model->newQuery();
}
/**
* Optional method if you want to use the html builder.
*/
public function html(): HtmlBuilder
{
return $this->builder()
->setTableId('claim-table')
->columns($this->getColumns())
->minifiedAjax()
//->dom('Bfrtip')
->orderBy(0)
->selectStyleSingle()
->buttons([
Button::make('excel'),
Button::make('csv'),
Button::make('pdf'),
Button::make('print'),
Button::make('reset'),
Button::make('reload')
]);
}
/**
* Get the dataTable columns definition.
*/
public function getColumns(): array
{
return [
Column::make('id'),
Column::make('name'),
Column::make('email'),
Column::make('claim'),
Column::make('listing'),
Column::computed('action')
->exportable(false)
->printable(false)
->width(60)
->addClass('text-center'),
];
}
/**
* Get the filename for export.
*/
protected function filename(): string
{
return 'Claim_' . date('YmdHis');
}
}
|
import PostsService from '../services/posts.service'
// const user = JSON.parse(localStorage.getItem('user'))
const initialState = {
posts: [],
post: null
}
export const posts = {
namespaced: true,
state: initialState,
actions: {
getPosts({ commit }) {
return PostsService.getPosts().then(
(data) => {
commit('postsSuccess', data)
return Promise.resolve(data)
},
(error) => {
commit('postsFailure')
return Promise.reject(error)
}
)
},
getPost({ commit }, id) {
return PostsService.getPost(id).then(
(data) => {
commit('postSuccess', data)
console.log('module', data.post)
return Promise.resolve(data)
},
(error) => {
commit('postsFailure')
return Promise.reject(error)
}
)
}
},
mutations: {
postsSuccess(state, data) {
state.posta = data.posts
},
postsFailure(state) {
state.message = ''
},
postSuccess(state, data) {
state.post = data.post
}
}
}
|
import argparse
import json
import random
import logging
import sys
from typing import Dict, Callable
import evaluate
import numpy as np
import pandas as pd
import os
from datasets import Dataset, DatasetDict
from datasets import load_metric, concatenate_datasets
from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer, InputFeatures, \
AutoModelForSeq2SeqLM, DataCollatorForSeq2Seq, Seq2SeqTrainingArguments, Seq2SeqTrainer, EvalPrediction, \
PreTrainedTokenizerBase, BitsAndBytesConfig
from transformers import AutoTokenizer, AutoConfig, EarlyStoppingCallback
import torch
import utils
import shutil
from pathlib import Path
from predict_with_generative_models import format_prompts
from peft import prepare_model_for_kbit_training, PeftConfig
import torch.distributed as dist
TRAIN_VERSION="1.0"
label2id = {
'negative': 0,
'positive': 1,
'neutral': 2,
}
def read_file(file):
df = pd.read_csv(file)
df = df[['text', 'label']]
return Dataset.from_pandas(df)
dataset = DatasetDict()
dataset['train'] = read_file(train_file)
dataset['validation'] = read_file(dev_file)
dataset['test'] = read_file(test_file)
return dataset
def preprocess_and_tokenize(model_name, dataset, hypothesis_template, tokenizer, model,
max_seq_length):
def lower_label_for_bart(label, model_name):
if 'bart' in model_name:
out = label.lower()
elif 'DeBERTa' in model_name or 'deberta-v3' in model_name:
out = label.lower()
elif 'roberta' in model_name or 'deberta' in model_name:
out = label
else:
raise ValueError(f"Model {model_name} not supported")
return out
labels = [model.config.label2id[lower_label_for_bart(lbl, model_name)] for lbl in dataset['label']]
tokenized = []
for text, cls, label, dataset_name in zip(
dataset['text'], dataset['class'], labels, dataset['dataset_name']
):
hypothesis = hypothesis_template.format(cls)
try:
inputs = (tokenizer.encode_plus(text, hypothesis, return_tensors='pt',
add_special_tokens=True, pad_to_max_length=True,
max_length=max_seq_length, truncation='only_first'))
except:
print(hypothesis, text, cls, label, dataset_name)
continue
if "deberta" in model_name.lower():
tokenized.append(InputFeatures(input_ids=inputs['input_ids'].squeeze(0),
attention_mask=inputs['attention_mask'].squeeze(0),
token_type_ids=inputs['token_type_ids'],
label=label))
elif "roberta" in model_name or "bart" in model_name:
tokenized.append(InputFeatures(input_ids=inputs['input_ids'].squeeze(0),
attention_mask=inputs['attention_mask'].squeeze(0),
# token_type_ids=inputs['token_type_ids'],
label=label))
else:
raise NotImplementedError('only supporting deberta roberta and bart models')
random.shuffle(tokenized)
return tokenized
def remove_checkpoints(output_dir):
for p in Path(output_dir).glob('checkpoint-*'):
try:
shutil.rmtree(str(p))
except:
pass # ok, sometime somebody else removes the checkpoint, TODO check it and move to back to train.py
def get_model_for_config(base_model):
if 'roberta' in base_model:
return 'roberta-large-mnli'
elif 'bart' in base_model:
return 'facebook/bart-large-mnli'
elif 'microsoft/deberta-v3-large' in base_model:
return 'MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli'
elif 'MoritzLaurer/DeBERTa' in base_model and 'large' in base_model:
return 'MoritzLaurer/DeBERTa-v3-large-mnli-fever-anli-ling-wanli'
elif 'MoritzLaurer/DeBERTa' in base_model and 'small' in base_model:
return 'MoritzLaurer/DeBERTa-v3-small-mnli-fever-docnli-ling-2c'
elif 'deberta' in base_model:
return 'Narsil/deberta-large-mnli-zero-cls'
return None
def prepare_label(label, class_name, prompt):
if "pair_wise_option" not in prompt:
if label.lower() == "yes":
return class_name
else:
return "not " + class_name
else:
return label.lower()
# raise Exception(f"prompt {prompt} not supported in flan pair-wise training")
# TODO: improve run-time by removing tokenization
def preprocess_and_tokenize_t5(dataset, prompt, tokenizer,
max_seq_length, joint_metadata, output_path):
def preprocess_func(examples):
inputs = (
tokenizer(examples['text'], truncation=True)) ###CHECK
labels = tokenizer(examples['label'],
truncation=True)
inputs['labels'] = labels['input_ids']
return inputs
examples = preprocess_t5_multi_class(dataset, prompt, tokenizer,
max_seq_length, joint_metadata)
examples.to_csv(output_path, index=False)
tokenized_datasets = examples.map(preprocess_func, batched=True)
return tokenized_datasets.remove_columns(
examples.column_names) # needed because of this thread https://github.com/huggingface/transformers/issues/15505
def preprocess_t5_multi_class(dataset, prompt, tokenizer,
max_seq_length, joint_metadata):
df = dataset.to_pandas()
data_grouped_by_dataset = df.groupby('dataset_name')
all_texts = []
all_labels = []
for name, df in data_grouped_by_dataset:
all_classes = joint_metadata[name]['labels']
texts = format_prompts(prompt, df['text'],
all_classes, tokenizer, max_seq_length, shuffle_classes=True)
all_labels.extend(df['label'])
all_texts.extend(texts)
examples = Dataset.from_dict({'text': all_texts, 'label': all_labels})
return examples
def print_trainable_parameters(model):
"""
Prints the number of trainable parameters in the model.
"""
trainable_params = 0
all_param = 0
for _, param in model.named_parameters():
all_param += param.numel()
if param.requires_grad:
trainable_params += param.numel()
print(
f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}"
)
def get_eval_func(tokenizer: PreTrainedTokenizerBase, metric_id: str) -> Callable:
def eval_func(eval_preds: EvalPrediction):
preds = eval_preds.predictions
labels = eval_preds.label_ids
preds = np.where(preds != -100, preds, tokenizer.pad_token_id)
decoded_preds = tokenizer.batch_decode(preds, skip_special_tokens=True)
labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
decoded_labels = tokenizer.batch_decode(labels.tolist(), skip_special_tokens=True)
metric = evaluate.load(metric_id)
res = metric.compute(references=decoded_labels, predictions=decoded_preds)
return res
return eval_func
def finetune_t5_model(base_model, seed, train_df,
dev_df,
learning_rate, batch_size,
prompt,
out_dir, max_seq_length, num_epochs,
select_best_model,
fp16, joint_metadata, gradient_accumulation_steps, use_lora,
evaluation_and_save_strategy, save_steps):
from peft import TaskType, LoraConfig, get_peft_model
train_dataset = Dataset.from_pandas(train_df)
if dev_df is not None:
dev_dataset = Dataset.from_pandas(dev_df)
else:
dev_dataset = None
tokenizer = AutoTokenizer.from_pretrained(base_model, use_fast=True,
model_max_length=max_seq_length)
os.makedirs(out_dir, exist_ok=True)
tokenized_train = preprocess_and_tokenize_t5(train_dataset, prompt, tokenizer,
max_seq_length, joint_metadata, os.path.join(out_dir, "train.csv"))
tokenized_dev = preprocess_and_tokenize_t5(dev_dataset, prompt, tokenizer,
max_seq_length, joint_metadata, os.path.join(out_dir, "dev.csv"))
bnb_config = None
model_loading_args = {
"pretrained_model_name_or_path": base_model,
"quantization_config": bnb_config,
"trust_remote_code": True,
"torch_dtype": None,
"load_in_8bit": False,
# "device_map": "auto"
}
model = AutoModelForSeq2SeqLM.from_pretrained(**model_loading_args)
if use_lora:
task_type = TaskType.SEQ_2_SEQ_LM
config = LoraConfig(
r=16,
lora_alpha=32,
target_modules=None,
lora_dropout=0.05,
bias="none",
task_type=task_type
)
model = get_peft_model(model, config)
print_trainable_parameters(model)
data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer,
model=model,
padding=True,
label_pad_token_id=tokenizer.eos_token_id
)
training_args = Seq2SeqTrainingArguments(
output_dir=out_dir,
num_train_epochs = num_epochs,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
logging_strategy=evaluation_and_save_strategy,
save_strategy=evaluation_and_save_strategy,
evaluation_strategy=evaluation_and_save_strategy,
save_steps=save_steps,
logging_steps=save_steps,
eval_steps=save_steps,
save_total_limit=1,
load_best_model_at_end=select_best_model,
metric_for_best_model="exact_match",
predict_with_generate=True,
generation_max_length=20,
generation_num_beams=1,
fp16=fp16,
gradient_accumulation_steps=gradient_accumulation_steps,
eval_accumulation_steps=1,
optim="adamw_hf",
lr_scheduler_type="linear",
learning_rate=learning_rate,
warmup_steps=2,
use_mps_device=False,
overwrite_output_dir=True,
seed=seed,
report_to="none",
)
print(f"training_args {training_args}")
trainer = Seq2SeqTrainer(
model=model,
args=training_args,
train_dataset=tokenized_train,
eval_dataset=tokenized_dev,
tokenizer=tokenizer,
data_collator=data_collator,
compute_metrics=get_eval_func(tokenizer, "exact_match"),
callbacks=[EarlyStoppingCallback(early_stopping_patience=2)]
)
trainer.train()
trainer.save_model(out_dir)
trainer.save_state()
tokenizer.save_pretrained(out_dir)
return out_dir
def finetune_entailment_model(base_model, seed, train_df,
dev_df,
learning_rate, batch_size,
hypothesis_template,
out_dir, max_seq_length, num_epochs,
select_best_model,
stop_early,
fp16, gradient_accumulation_steps,
evaluation_and_save_strategy,
save_steps):
train_dataset = Dataset.from_pandas(train_df)
if dev_df is not None:
dev_dataset = Dataset.from_pandas(dev_df)
else:
dev_dataset = None
tokenizer = AutoTokenizer.from_pretrained(base_model, use_fast=True,
_from_pipeline='zero-shot-classification', model_max_length=max_seq_length)
model_for_config = get_model_for_config(base_model)
if model_for_config:
config_for_model = AutoConfig.from_pretrained(model_for_config)
num_labels = config_for_model.num_labels
model = AutoModelForSequenceClassification.from_pretrained(base_model, num_labels=num_labels)
model.config.label2id = config_for_model.label2id
model.config.id2label = config_for_model.id2label
else:
model = AutoModelForSequenceClassification.from_pretrained(base_model)
tokenized_train = preprocess_and_tokenize(base_model, train_dataset, hypothesis_template, tokenizer, model, max_seq_length)
callbacks = []
if stop_early:
callbacks.append(
EarlyStoppingCallback(early_stopping_patience=2,
early_stopping_threshold=1e-3)
)
def compute_metrics(p):
if 'bart' in base_model:
logits = p.predictions[0]
elif 'roberta' in base_model:
logits = p.predictions
elif 'deberta' in base_model:
logits = p.predictions
elif 'DeBERTa' in base_model:
logits = p.predictions
else:
raise Exception(f"unexepected base model {base_model}")
labels = p.label_ids
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)
metric = load_metric("accuracy")
if dev_dataset is not None:
tokenized_dev = preprocess_and_tokenize(base_model, dev_dataset, hypothesis_template, tokenizer,
model, max_seq_length)
else:
tokenized_dev = None
training_args = TrainingArguments(output_dir=out_dir,
overwrite_output_dir=True,
num_train_epochs=num_epochs,
per_device_train_batch_size=batch_size,
per_device_eval_batch_size=batch_size,
learning_rate=learning_rate,
load_best_model_at_end=select_best_model,
save_total_limit=1,
save_strategy=evaluation_and_save_strategy,
evaluation_strategy=evaluation_and_save_strategy if stop_early else "no",
save_steps=save_steps,
metric_for_best_model='accuracy',
report_to="none",
seed=seed,
fp16=fp16,
gradient_accumulation_steps=gradient_accumulation_steps
# half_precision_backend="cuda_amp" #cuda_amp auto or apex
)
print(f"training_args {training_args}")
# model = torch.compile(model)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_train,
eval_dataset=tokenized_dev,
callbacks=callbacks,
compute_metrics=compute_metrics
)
trainer.train()
trainer.save_model(out_dir)
tokenizer.save_pretrained(out_dir)
trainer.evaluate()
return out_dir
parser = argparse.ArgumentParser(description='params for pair-wise training')
#parser.add_argument("--output_dir", required=True)
# TODO add types and actions.
parser.add_argument("--base_model", required=True)
parser.add_argument("--input_dir", required=True)
parser.add_argument("--held_out_input_dir", default=None)
parser.add_argument("--learning_rate", required=True)
parser.add_argument("--train_df_name", required=True)
parser.add_argument("--dev_df_name", required=True)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--batch_size", required=True)
parser.add_argument("--hypothesis_template", required=True, default='This text is about {}')
parser.add_argument("--max_seq_length", required=True)
parser.add_argument("--num_epochs", required=True)
parser.add_argument("--select_best_model", action='store_true')
parser.add_argument("--stop_early", action='store_true')
parser.add_argument("--output_dir", required=True)
parser.add_argument("--use_lora", action='store_true')
parser.add_argument('--training_method', type=str, default='pairwise',
choices=['pairwise', 't5'],
help='What approached to be been used in training')
parser.add_argument("--fp16", action='store_true', help='Should we use fp16 for training?')
parser.add_argument("--gradient_accumulation_steps", default=1)
parser.add_argument("--evaluation_and_save_strategy", default="epoch")
parser.add_argument("--save_steps", type=int, default=500)
parser.add_argument('--version', type=str, required=True, help='version to update on change of code')
def main():
args = parser.parse_args()
run_train(base_model=args.base_model, input_dir=args.input_dir, held_out_input_dir=args.held_out_input_dir,
learning_rate=args.learning_rate, train_df_name=args.train_df_name, dev_df_name=args.dev_df_name,
batch_size=args.batch_size, hypothesis_template=args.hypothesis_template, max_seq_length=args.max_seq_length,
num_epochs=args.num_epochs, select_best_model=args.select_best_model, stop_early=args.stop_early,
output_dir=args.output_dir, use_lora=args.use_lora,
training_method=args.training_method, fp16=args.fp16, gradient_accumulation_steps=args.gradient_accumulation_steps,
evaluation_and_save_strategy=args.evaluation_and_save_strategy, save_steps=args.save_steps,
seed=args.seed)
def run_train(base_model, input_dir, learning_rate, train_df_name, dev_df_name,
batch_size, max_seq_length, num_epochs, output_dir, fp16,
use_lora=False,
select_best_model=False,
stop_early=False,
seed=42,
held_out_input_dir=None,
hypothesis_template="This text is about {}.",
training_method="pairwise",
gradient_accumulation_steps=1,
evaluation_and_save_strategy="epoch",
save_steps=500,
):
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
utils.set_seed(seed)
utils.set_torch_seed(seed)
if training_method == "t5":
config_file = os.path.join(output_dir, 'adapter_config.json')
elif training_method == 'pairwise':
config_file = os.path.join(output_dir, 'config.json')
else:
raise Exception(f"unsupported training method {training_method}")
if config_file and os.path.exists(config_file): # let's use the previous results
return
train_df = pd.read_csv(os.path.join(input_dir ,train_df_name))
if dev_df_name is not None:
if held_out_input_dir is not None:
dev_df = pd.read_csv(os.path.join(held_out_input_dir, dev_df_name))
else:
dev_df = pd.read_csv(os.path.join(input_dir, dev_df_name))
else:
dev_df = None
with open(os.path.join(input_dir, "joint_metadata.json")) as f:
joint_metadata = json.load(f)
if held_out_input_dir is not None:
with open(os.path.join(held_out_input_dir, "joint_metadata.json")) as f:
held_out_joint_metadata = json.load(f)
joint_metadata.update(held_out_joint_metadata)
template = hypothesis_template
print('template', template, len(template)) # WORDAROND for arguments with space
if template[0] == "'":
template = template[1:-1]
print('new template', template, len(template))
if training_method == 'pairwise':
finetune_entailment_model(base_model, int(seed), train_df, dev_df,
float(learning_rate), int(batch_size),
template,
output_dir, int(max_seq_length), int(num_epochs),
select_best_model,
stop_early,
fp16, int(gradient_accumulation_steps),
evaluation_and_save_strategy,
save_steps)
elif training_method == "t5":
finetune_t5_model(base_model=base_model, seed=int(seed), train_df=train_df, dev_df=dev_df,
learning_rate=float(learning_rate), batch_size=int(batch_size),
prompt=template,
out_dir=output_dir, max_seq_length=int(max_seq_length), num_epochs=int(num_epochs),
select_best_model=select_best_model,
fp16=fp16, joint_metadata=joint_metadata,
gradient_accumulation_steps=int(gradient_accumulation_steps), use_lora=use_lora,
evaluation_and_save_strategy=evaluation_and_save_strategy,
save_steps=save_steps)
else:
raise Exception(f"Unexpected training method {training_method}")
# remove_checkpoints(output_dir)
__OUTPUT_DIR_ARG__ = "output_dir"
__OUTPUTS__ = []
__ARGPARSER__ = parser
if __name__ == "__main__":
main()
|
const Discord = require('discord.js')
module.exports= {
name: 'embed' ,
run: async(Client, message, args, config) => {
if (!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send('Vous n\'avez pas la permission d\'utiliser cette commande.')
let embedBeforeEdit = new Discord.MessageEmbed()
.setTitle("Titre par défaut")
let msgEmbedForEditing = await message.channel.send(embedBeforeEdit)
const msgwait = await message.channel.send("Veuillez patienter la fin de l'ajout des réactions.")
await Promise.all(['✏️','💬','🕵️','🔻','🔳','🕙','🌐','🔵','↩️','✅', '❌'].map(r => msgwait.react(r)));
await msgwait.edit(`:pencil2: Modifier le titre\n:speech_balloon: Modifier la description\n:detective: Modifier l'auteur\n:small_red_triangle_down: Modifier le footer\n:white_square_button: Modifier le thumbnail\n:clock10: Ajouter un timestamp\n:globe_with_meridians: Modifier l'url\n:blue_circle: Modifier la couleur\n:leftwards_arrow_with_hook: Ajouter un field\n:white_check_mark: Envoyer l'embed\n:x: Supprimer l'embed en cours`)
const filterReaction = (reaction, user) => user.id===message.author.id&&!user.bot;
const filterMessage = (m) => m.author.id===message.author.id&&!m.author.bot;
const collectorReaction = await new Discord.ReactionCollector(msgwait, filterReaction);
collectorReaction.on('collect', async reaction => {
switch(reaction._emoji.name) {
case '✏️':
const msgQuestionTitle = await message.channel.send("Quel est votre titre ?")
const title = (await message.channel.awaitMessages(filterMessage, {max: 1, time: 60000})).first()
title.delete()
msgQuestionTitle.delete()
embedBeforeEdit.setTitle(title.content);
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '💬':
const msgQuestionDescription = await message.channel.send("Quelle est votre description ?")
const description = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
description.delete()
msgQuestionDescription.delete()
embedBeforeEdit.setDescription(description.content)
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '🕵️':
const msgQuestionAuthor = await message.channel.send("Qui est votre auteur ?")
const author = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
author.delete()
msgQuestionAuthor.delete()
embedBeforeEdit.setAuthor(author.content)
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '🔻':
const msgQuestionFooter = await message.channel.send("Quel est votre footer ?")
const footer = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
footer.delete()
msgQuestionFooter.delete()
embedBeforeEdit.setFooter(footer.content)
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '🔳':
const msgQuestionThumbnail = await message.channel.send("Quelle est votre thumbnail ?")
const thumbnail = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
if(!thumbnail.content.includes('http') || !thumbnail.content.includes('https')) return message.channel.send("Thumbnail incorrecte")
msgQuestionThumbnail.delete()
thumbnail.delete()
embedBeforeEdit.setThumbnail(thumbnail.content)
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '🕙':
embedBeforeEdit.setTimestamp();
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '🌐':
const msgQuestionLien = await message.channel.send("Quel est votre lien ?")
const lien = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
if(!lien.content.startsWith('http') || !lien.content.startsWith('https')) return message.channel.send("Votre lien doit commencer par `http` ou `https`.")
msgQuestionLien.delete()
lien.delete()
embedBeforeEdit.setURL(lien.content)
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '🔵':
const msgQuestionColor = await message.channel.send("Quelle est la couleur que vous désirez ?")
const color = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
msgQuestionColor.delete()
color.delete()
embedBeforeEdit.setColor(color.content)
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '↩️':
const msgQuestionField = await message.channel.send("Quel est le titre de votre field ?")
const titlefield = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
msgQuestionField.delete()
titlefield.delete()
const msgQuestionDescField = await message.channel.send("Quel est la description de votre field ?")
const descfield = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
msgQuestionDescField.delete()
descfield.delete()
embedBeforeEdit.addField(titlefield.content, descfield.content)
msgEmbedForEditing.edit(embedBeforeEdit)
break;
case '✅':
const msgQuestionChannel = await message.channel.send("Veuillez indiquer l'identifiant du message où vous souhaiter envoyer l'embed.")
const channel = (await message.channel.awaitMessages(filterMessage, {max : 1, time: 60000})).first()
msgQuestionChannel.delete()
channel.delete()
if(!message.guild.channels.cache.get(channel.content)) return message.channel.send('Salon invalide !')
else {
Client.channels.cache.get(channel.content).send(embedBeforeEdit);
//await embedBeforeEdit.delete()
await msgwait.delete()
message.channel.send(`Voilà le résultat de votre embed qui a été envoyé dans le salon : **${channel.content}**`)
}
break;
case '❌':
msgEmbedForEditing.delete()
msgwait.delete()
message.delete()
break;
}
})
}
}
|
import React, { useState, useEffect } from 'react';
import logoImg from '../../assets/logo.svg';
import { Link, useHistory } from 'react-router-dom';
import { FiPower, FiTrash2, FiEdit2 } from 'react-icons/fi';
import api from '../../services/api';
import './styles.css';
export default function Profile() {
const [incidents, setIncidents] = useState([]);
const [image, setImage] = useState([]);
const history = useHistory();
const ongId = localStorage.getItem('ongId');
const ongName = localStorage.getItem('ongName');
let id;
useEffect(() => {
api.get('/profile', {
headers: {
Authorization: ongId
}
}).then(response => {
setIncidents(response.data);
});
api.get('/posts').then(response => {
setImage(response.data.name);
})
}, [ongId]);
async function handleDeleteIncident(id) {
try {
await api.delete(`incidents/${id}`, {
headers: {
Authorization: ongId
}
});
setIncidents(incidents.filter(incidents => incidents.id !== id));
} catch (error) {
alert('Erro ao apagar caso, tente novamente');
}
}
async function handleIncident(id) {
api.get('/incidentsAll').then((request, response) => {
})
}
function handleGoPageUpdate(id){
history.push(`/incidents/update/${id}`);
}
function handleLogout() {
localStorage.clear();
history.push('/');
}
return (
<div className="profile-container">
<header>
<img src={logoImg} alt="Be the hero"></img>
<span>Bem vinda, {ongName}</span>
<Link className="button" onClick={handleIncident} to="/incidents/new" >Cadastrar novo caso </Link>
<button onClick={handleLogout} type="button">
<FiPower size={18} color="#E02041"></FiPower>
</button>
</header>
<h1>Casos Cadastrados</h1>
<ul>
{incidents.map(incidents => (
<li key={incidents.id}>
<strong>CASO:</strong>
<p>{incidents.title}</p>
<strong>IMAGEM</strong>
<p>{incidents.image}</p>
<strong>DESRIÇÂO</strong>
<p>{incidents.description}</p>
<strong>VALOR:</strong>
<p>{Intl.NumberFormat('pt-BR', {
style: 'currency',
currency: 'BRL'
})
.format(incidents.value)}</p>
<button type="button" onClick={() => handleDeleteIncident(incidents.id)}>
<FiTrash2 size={20} color="#a8a8b3" />
</button>
<button type="button" className="button-update" onClick={() => handleGoPageUpdate(incidents.id)}>
<FiEdit2 size={20} color="#a8a8b3" />
</button>
</li>
))}
</ul>
</div>
);
}
|
import axios from 'axios'
import { useState, useContext } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { AuthContext } from '../../context/AuthContext'
import './login.styles.scss'
function Login() {
const { dispatch, loading, error } = useContext(AuthContext)
const navigate = useNavigate()
const [credentials, setCredentials] = useState({})
console.log(credentials)
const handleChange = (e) => {
const { name, value } = e.target
setCredentials({
...credentials,
[name]: value
})
}
const handleLogin = async (e) => {
e.preventDefault()
dispatch({
type: "LOGIN_START"
})
try {
const res = await axios.post("/auth/login", credentials)
dispatch({ type: "LOGIN_SUCCESS", payload: res.data.details })
navigate('/')
} catch (err) {
dispatch({ type: "LOGIN_FAILURE", payload: err.response.data })
}
}
return (
<div className='login'>
<h2>DealPlate Admin Dashboard</h2>
<p className="login__secondary-title">Login</p>
<div className="formControl">
<input type="text" className="inputField" placeholder="username" name="username" value={credentials.username} onChange={handleChange} autoComplete="off" />
</div>
<div className="formControl">
<input type="password" className="inputField" placeholder="password" name="password" value={credentials.password} onChange={handleChange} />
</div>
<div className="formAction">
<button disabled={loading} onClick={handleLogin} className="loginBtn">Login</button>
{error && <span>{error.message}</span>}
</div>
<p className='login__register-title'>Don't have an account yet? Register <Link to="/register">here</Link></p>
</div>
)
}
export default Login
|
/*
* Copyright 2016 Game Server Services, Inc. or its affiliates. All Rights
* Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Gs2.Core.Model;
using LitJson;
using UnityEngine.Scripting;
namespace Gs2.Gs2Version.Model
{
[Preserve]
public class Namespace
{
/** ネームスペース */
public string namespaceId { set; get; }
/**
* ネームスペースを設定
*
* @param namespaceId ネームスペース
* @return this
*/
public Namespace WithNamespaceId(string namespaceId) {
this.namespaceId = namespaceId;
return this;
}
/** オーナーID */
public string ownerId { set; get; }
/**
* オーナーIDを設定
*
* @param ownerId オーナーID
* @return this
*/
public Namespace WithOwnerId(string ownerId) {
this.ownerId = ownerId;
return this;
}
/** ネームスペース名 */
public string name { set; get; }
/**
* ネームスペース名を設定
*
* @param name ネームスペース名
* @return this
*/
public Namespace WithName(string name) {
this.name = name;
return this;
}
/** 説明文 */
public string description { set; get; }
/**
* 説明文を設定
*
* @param description 説明文
* @return this
*/
public Namespace WithDescription(string description) {
this.description = description;
return this;
}
/** バージョンチェック通過後に改めて発行するプロジェクトトークンの権限判定に使用する ユーザ のGRN */
public string assumeUserId { set; get; }
/**
* バージョンチェック通過後に改めて発行するプロジェクトトークンの権限判定に使用する ユーザ のGRNを設定
*
* @param assumeUserId バージョンチェック通過後に改めて発行するプロジェクトトークンの権限判定に使用する ユーザ のGRN
* @return this
*/
public Namespace WithAssumeUserId(string assumeUserId) {
this.assumeUserId = assumeUserId;
return this;
}
/** バージョンを承認したときに実行するスクリプト */
public ScriptSetting acceptVersionScript { set; get; }
/**
* バージョンを承認したときに実行するスクリプトを設定
*
* @param acceptVersionScript バージョンを承認したときに実行するスクリプト
* @return this
*/
public Namespace WithAcceptVersionScript(ScriptSetting acceptVersionScript) {
this.acceptVersionScript = acceptVersionScript;
return this;
}
/** バージョンチェック時 に実行されるスクリプト のGRN */
public string checkVersionTriggerScriptId { set; get; }
/**
* バージョンチェック時 に実行されるスクリプト のGRNを設定
*
* @param checkVersionTriggerScriptId バージョンチェック時 に実行されるスクリプト のGRN
* @return this
*/
public Namespace WithCheckVersionTriggerScriptId(string checkVersionTriggerScriptId) {
this.checkVersionTriggerScriptId = checkVersionTriggerScriptId;
return this;
}
/** ログの出力設定 */
public LogSetting logSetting { set; get; }
/**
* ログの出力設定を設定
*
* @param logSetting ログの出力設定
* @return this
*/
public Namespace WithLogSetting(LogSetting logSetting) {
this.logSetting = logSetting;
return this;
}
/** 作成日時 */
public long? createdAt { set; get; }
/**
* 作成日時を設定
*
* @param createdAt 作成日時
* @return this
*/
public Namespace WithCreatedAt(long? createdAt) {
this.createdAt = createdAt;
return this;
}
/** 最終更新日時 */
public long? updatedAt { set; get; }
/**
* 最終更新日時を設定
*
* @param updatedAt 最終更新日時
* @return this
*/
public Namespace WithUpdatedAt(long? updatedAt) {
this.updatedAt = updatedAt;
return this;
}
public void WriteJson(JsonWriter writer)
{
writer.WriteObjectStart();
if(this.namespaceId != null)
{
writer.WritePropertyName("namespaceId");
writer.Write(this.namespaceId);
}
if(this.ownerId != null)
{
writer.WritePropertyName("ownerId");
writer.Write(this.ownerId);
}
if(this.name != null)
{
writer.WritePropertyName("name");
writer.Write(this.name);
}
if(this.description != null)
{
writer.WritePropertyName("description");
writer.Write(this.description);
}
if(this.assumeUserId != null)
{
writer.WritePropertyName("assumeUserId");
writer.Write(this.assumeUserId);
}
if(this.acceptVersionScript != null)
{
writer.WritePropertyName("acceptVersionScript");
this.acceptVersionScript.WriteJson(writer);
}
if(this.checkVersionTriggerScriptId != null)
{
writer.WritePropertyName("checkVersionTriggerScriptId");
writer.Write(this.checkVersionTriggerScriptId);
}
if(this.logSetting != null)
{
writer.WritePropertyName("logSetting");
this.logSetting.WriteJson(writer);
}
if(this.createdAt.HasValue)
{
writer.WritePropertyName("createdAt");
writer.Write(this.createdAt.Value);
}
if(this.updatedAt.HasValue)
{
writer.WritePropertyName("updatedAt");
writer.Write(this.updatedAt.Value);
}
writer.WriteObjectEnd();
}
[Preserve]
public static Namespace FromDict(JsonData data)
{
return new Namespace()
.WithNamespaceId(data.Keys.Contains("namespaceId") && data["namespaceId"] != null ? data["namespaceId"].ToString() : null)
.WithOwnerId(data.Keys.Contains("ownerId") && data["ownerId"] != null ? data["ownerId"].ToString() : null)
.WithName(data.Keys.Contains("name") && data["name"] != null ? data["name"].ToString() : null)
.WithDescription(data.Keys.Contains("description") && data["description"] != null ? data["description"].ToString() : null)
.WithAssumeUserId(data.Keys.Contains("assumeUserId") && data["assumeUserId"] != null ? data["assumeUserId"].ToString() : null)
.WithAcceptVersionScript(data.Keys.Contains("acceptVersionScript") && data["acceptVersionScript"] != null ? ScriptSetting.FromDict(data["acceptVersionScript"]) : null)
.WithCheckVersionTriggerScriptId(data.Keys.Contains("checkVersionTriggerScriptId") && data["checkVersionTriggerScriptId"] != null ? data["checkVersionTriggerScriptId"].ToString() : null)
.WithLogSetting(data.Keys.Contains("logSetting") && data["logSetting"] != null ? LogSetting.FromDict(data["logSetting"]) : null)
.WithCreatedAt(data.Keys.Contains("createdAt") && data["createdAt"] != null ? (long?)long.Parse(data["createdAt"].ToString()) : null)
.WithUpdatedAt(data.Keys.Contains("updatedAt") && data["updatedAt"] != null ? (long?)long.Parse(data["updatedAt"].ToString()) : null);
}
}
}
|
package it.eng.catalog.model;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import it.eng.tools.model.DSpaceConstants;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@JsonDeserialize(builder = Resource.Builder.class)
@JsonPropertyOrder(value = {"@context", "@type", "@id"}, alphabetic = true)
public class Resource {
@JsonProperty(DSpaceConstants.DCAT_KEYWORD)
private List<String> keyword;
@JsonProperty(DSpaceConstants.DCAT_THEME)
private List<String> theme;
@JsonProperty(DSpaceConstants.DCT_CONFORMSTO)
private String conformsTo;
@JsonProperty(DSpaceConstants.DCT_CREATOR)
private String creator;
@JsonProperty(DSpaceConstants.DCT_DESCRIPTION)
private List<Multilanguage> description;
@JsonProperty(DSpaceConstants.DCT_IDENTIFIER)
private String identifier;
@JsonProperty(DSpaceConstants.DCT_ISSUED)
private String issued;
@JsonProperty(DSpaceConstants.DCT_MODIFIED)
private String modified;
@JsonProperty(DSpaceConstants.DCT_TITLE)
private String title;
@JsonPOJOBuilder(withPrefix = "")
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Builder {
private final Resource resource;
private Builder() {
resource = new Resource();
}
@JsonCreator
public static Builder newInstance() {
return new Builder();
}
@JsonProperty(DSpaceConstants.DCAT_KEYWORD)
public Builder keyword(List<String> keyword) {
resource.keyword = keyword;
return this;
}
@JsonProperty(DSpaceConstants.DCAT_THEME)
public Builder theme(List<String> theme) {
resource.theme = theme;
return this;
}
@JsonProperty(DSpaceConstants.DCT_CONFORMSTO)
public Builder conformsTo(String conformsTo) {
resource.conformsTo = conformsTo;
return this;
}
@JsonProperty(DSpaceConstants.DCT_CREATOR)
public Builder creator( String creator) {
resource.creator = creator;
return this;
}
@JsonProperty(DSpaceConstants.DCT_DESCRIPTION)
public Builder description(List<Multilanguage> description) {
resource.description = description;
return this;
}
@JsonProperty(DSpaceConstants.DCT_IDENTIFIER)
public Builder identifier(String identifier) {
resource.identifier = identifier;
return this;
}
@JsonProperty(DSpaceConstants.DCT_ISSUED)
public Builder issued(String issued) {
resource.issued = issued;
return this;
}
@JsonProperty(DSpaceConstants.DCT_MODIFIED)
public Builder modified( String modified) {
resource.modified = modified;
return this;
}
@JsonProperty(DSpaceConstants.DCT_TITLE)
public Builder title( String title) {
resource.title = title;
return this;
}
public Resource build() {
return resource;
}
}
}
|
/*
* Copyright 2023 HM Revenue & Customs
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package views.components
import base.unit.UnitViewSpec
import org.scalatest.matchers.must.Matchers
import play.api.mvc.Call
import play.twirl.api.Html
import views.html.components.listMembers
import views.viewmodels.ListMember
class ListMembersSpec extends UnitViewSpec with Matchers {
private val singleMember = Seq(ListMember(name = "Test Member"))
protected val component: listMembers =
new listMembers()
"List Members Component" should {
"render list members" when {
"single member" in {
val view: Html = component(singleMember)(messages)
val items = view.getElementsByClass("hmrc-add-to-a-list__contents")
items.size() mustBe 1
items.get(0).getElementsByClass(
"hmrc-add-to-a-list__identifier"
).text() mustBe "Test Member"
}
"multiple members" in {
val view: Html =
component(Seq(ListMember(name = "Member1"), ListMember(name = "Member2")))(messages)
val items = view.getElementsByClass("hmrc-add-to-a-list__contents")
items.size() mustBe 2
items.get(0).getElementsByClass("hmrc-add-to-a-list__identifier").text() mustBe "Member1"
items.get(1).getElementsByClass("hmrc-add-to-a-list__identifier").text() mustBe "Member2"
}
"has optional sub-heading" in {
val view: Html =
component(Seq(ListMember(name = "MemberName", subHeading = Some("SubHeading"))))(messages)
val items = view.getElementsByClass("hmrc-add-to-a-list__contents")
items.size() mustBe 1
items.get(0).getElementsByClass(
"hmrc-add-to-a-list__identifier"
).text() mustBe "MemberName SubHeading"
}
"has optional change link" in {
val view: Html = component(
Seq(ListMember(name = "Name", change = Some(Call("GET", "/change-url"))))
)(messages)
view.select(
".hmrc-add-to-a-list__contents > .hmrc-add-to-a-list__change > a"
).first() must haveHref("/change-url")
}
"has optional remove link" in {
val view: Html = component(
Seq(ListMember(name = "Name", remove = Some(Call("GET", "/remove-url"))))
)(messages)
view.select(
".hmrc-add-to-a-list__contents > .hmrc-add-to-a-list__remove > a"
).first() must haveHref("/remove-url")
}
"not render links" in {
val view: Html = component(singleMember)(messages)
view.select(
".hmrc-add-to-a-list__contents > .hmrc-add-to-a-list__change > a"
) must haveSize(0)
view.select(
".hmrc-add-to-a-list__contents > .hmrc-add-to-a-list__remove > a"
) must haveSize(0)
}
}
"not render line separator" when {
"remove link is not rendered" in {
val view: Html = component(singleMember)(messages)
view.select(".hmrc-add-to-a-list__contents > .hmrc-add-to-a-list__remove") must haveSize(0)
}
}
"render line separator" when {
"remove link is rendered" in {
val view: Html = component(
Seq(ListMember(name = "any name", remove = Some(Call("GET", "/remove-url"))))
)(messages)
view.select(".hmrc-add-to-a-list__contents > .hmrc-add-to-a-list__remove") must haveSize(1)
}
}
}
override def exerciseGeneratedRenderingMethods(): Unit = {
component.f(singleMember)
component.render(singleMember, messages)
}
}
|
package edu.hdu.variant1.utils;
import org.springframework.boot.system.ApplicationHome;
import java.util.UUID;
/**
* Singleton FilePathUtil
*/
public class FilePathUtil {
private final String sourcePath = "\\src\\main\\resources\\static\\upload\\";
/**
* applicationHome can get the absolute path prefix in the local server.
*/
private final ApplicationHome applicationHome = new ApplicationHome(this.getClass());
private final String absolutePathPrefix = applicationHome.getDir().getParentFile().
getParentFile().getAbsolutePath();
private FilePathUtil() {
}
/**
* This is a clever use of the classloading mechanism in JVM to ensure that the instance
* is initialized with only one thread (thread-safe).
* The static inner class is not initialized immediately when the Singleton class is
* loaded, but when getInstance is used (lazy loading).
*/
private static class SingletonInstance {
private static final FilePathUtil INSTANCE = new FilePathUtil();
}
public static FilePathUtil getInstance() {
return SingletonInstance.INSTANCE;
}
/**
* Get the Absolute saving path of the file.
* @return : the absolute saving path in the project
*/
public String getSavePath() {
return absolutePathPrefix + sourcePath;
}
/**
* Get the Absolute Root path of the local server.
* We can use the method to splice the path and download the file in the server.
* @return : the absolute root path of the local server
*/
public String getAbsPathPrefix() {
return absolutePathPrefix;
}
/**
* Get the Extension name of the file.
* @param fileName : fileName we want to separate
* @return : the extension name(.pdf/ .txt/ .jpg...)
*/
public String getExtName(String fileName) {
return fileName.substring(fileName.lastIndexOf("."));
}
/**
* Get a UUID name of the file, which can avoid duplication.
* @return : a new UUID name of the file
*/
public String setUUIDName() {
return UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
}
/**
* Get the relative path in the project, which can be used for downloading
* @param fileName : the file name with UUID and extension
* @return : the relative path in the project(\\src\\main\\resources\\static\\upload\\)
*/
public String getSourcePath(String fileName) {
return sourcePath + fileName;
}
}
|
import { MailerService } from '@nestjs-modules/mailer';
import { Injectable } from '@nestjs/common';
@Injectable()
export class MailService {
constructor(private mailerService: MailerService) { }
async sendNotification(message: string) {
try {
await this.mailerService.sendMail({
to: process.env.MAIL_RECEIVED_ADDRESS,
// from: '"Support Team" <support@example.com>', // override default from
subject: 'Please check bridge system',
template: './notification', // `.hbs` extension is appended automatically
context: { // ✏️ filling curly brackets with content
name: "Alex",
content: message
},
});
} catch (error) { }
}
async sendResetPassword(email: string, subject: string, resetPwdURL: string) {
try {
await this.mailerService.sendMail({
to: email,
subject: subject,
template: __dirname + '/templates/resetPassword',
context: {
resetPwdURL
},
});
} catch (error) { console.log('error: ', error.message) }
}
async sendMail(email: string, subject: string, fullname: string, message: string) {
try {
await this.mailerService.sendMail({
to: email,
// from: '"Support Team" <support@example.com>', // override default from
subject: subject,
// template: './notification', // `.hbs` extension is appended automatically
template: __dirname + '/templates/notification',
context: { // ✏️ filling curly brackets with content
name: fullname || "You",
content: message
},
});
} catch (error) { console.log('error: ', error.message) }
}
async sendSubscriber(email: string, subject: string, key: string) {
try {
await this.mailerService.sendMail({
to: email,
// from: 'Welcome to Verdant NFT!', // override default from
subject: subject,
// template: './notification', // `.hbs` extension is appended automatically
template: __dirname + '/templates/subscription',
context: { // ✏️ filling curly brackets with content
host: process.env.URL_BACKEND,
email,
key,
},
});
} catch (error) { console.log('error: ', error.message) }
}
async sendBlackLister(email: string, subject: string, name: string) {
try {
await this.mailerService.sendMail({
to: email,
// from: 'Welcome to Verdant NFT!', // override default from
subject: subject,
// template: './notification', // `.hbs` extension is appended automatically
template: __dirname + '/templates/blacklist',
context: { // ✏️ filling curly brackets with content
name
},
});
} catch (error) { console.log('error: ', error.message) }
}
async sendOTPVerification(email: string, subject: string, code: string) {
try {
console.log("email", email);
console.log("subject", subject);
console.log("code", code);
console.log("template", __dirname);
await this.mailerService.sendMail({
to: email,
subject: subject,
template: __dirname + '/templates/otpVerification',
context: {
code
},
});
} catch (error) { console.log('error: ', error.message) }
}
async sendStrangeLogin(email: string, subject: string, data: any) {
try {
await this.mailerService.sendMail({
to: email,
// from: 'Welcome to Verdant NFT!', // override default from
subject: subject,
// template: './notification', // `.hbs` extension is appended automatically
template: __dirname + '/templates/strangeLogin',
context: { // ✏️ filling curly brackets with content
name: data.fullname || "You",
time: data.time,
location: data.location,
url_ok: data.url_ok,
url_reject: data.url_reject
},
});
} catch (error) { console.log('error: ', error.message) }
}
}
|
"""Тесты для проверки api для registration"""
from http import HTTPStatus
import pytest
from src.entity.api_entity.user.api_func import UserApiFunc
from src.entity.api_entity.user.api_func_positive import UserApiFuncPositive
from src.entity.db_entity.user.db_func import UserDBFunc
from tests.config import faker_ru
@pytest.mark.positive
@pytest.mark.user
def test_registration_success(db_client):
"""Успешная регистрация"""
# данные для регистрации
credential_body = {
"email": faker_ru.email(),
"password": faker_ru.password()
}
# регистрируем пользователя
UserApiFuncPositive.register(credential_body)
# TODO подумать что еще можно проверить кроме статус кода
# удаляем созданного пользователя
user_id = UserDBFunc.get_id(db_client, credential_body["email"])
UserDBFunc.delete_by_id(db_client, user_id)
# TODO создать тест который бы проверял граничные значения по длине email и password
@pytest.mark.negative
@pytest.mark.user
def test_already_registered_user(simple_random_user):
"""Попытка регистрации уже существующего пользователя"""
response = UserApiFunc.register(simple_random_user)
assert response.status_code == HTTPStatus.BAD_REQUEST
@pytest.mark.negative
@pytest.mark.user
@pytest.mark.parametrize("email, password", [
pytest.param(1, 'password', id='email is INT'),
pytest.param([1, 2, 3], 'password', id='email is LIST'),
pytest.param("email1@mail.ru", 1, id='password is int'),
# TODO дописать кейсов
])
def test_registraion_with_bad_data_format(email, password):
"""Попытка регистрации с данными не в том формате"""
# данные для регистрации
credential_body = {
"email": email,
"password": password
}
# регистрируем пользователя
response = UserApiFunc.register(credential_body)
assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY
|
#![allow(unused)]
use std::fmt::Display;
fn main() {
println!("Hello, world!");
let f: Thunk = Box::new(|| println!("hi"));
f();
}
type Thunk = Box<dyn Fn() + Send + 'static>; // instead of writing it in every function
type Kilometer = i32;
fn takes_long_type(f: Thunk) {
// --snip--
}
fn returns_long_type() -> Thunk {
// --snip--
todo!()
}
use std::fmt;
use std::io::Error;
type Result<T> = std::result::Result<T, std::io::Error>;
pub trait Write {
fn write(&mut self, buf: &[u8]) -> Result<usize>;
fn flush(&mut self) -> Result<()>;
fn write_all(&mut self, buf: &[u8]) -> Result<()>;
fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>;
}
|
---
title: "Independent Study"
author: Pito Salas
date: 2020-12-14
---
## FAQ
**Context - **Faculty members have different approaches to independent
studies. These are my guidelines for students doing independent studies under
my direction.
**How do I sign up?** There is no set procedure. Generally a student who is
interested in doing an independent study will speak to a faculty member that
they know from a class (and that they like 🙂 and discuss the possibility. It
is best if you come with a project in mind or if you are interested int he
same kind of things that the professor is interested in. The important thing
is that it is all in your hands and you have to take the initiative.
**Appropriate Projects** - An independent study is not just some hacking fest
for credit. You need to demonstrate at the end that you actually studied and
learned something new and that it is interesting and deserving of credit and
that you can present the results. An independent study can be about something
I am passionate about (see below) or something that you are passionate about.
There is a lot of flexibility.
**Proposal - **Before the term begins you need to develop a proposal, which
would be 1-2 pages max. It should include:
1. Objective: In a few sentences indicate the goal or overall objective of the project.
2. Readings: This is the "independent study" part. Books, papers, chapters, etc are all appropriate.
3. Description: What is the study? What will you actually "do"? Be realistic and not overly ambitious.
4. Deliverables: one ore more demonstration, paper, report, video. All delivery should be collected in a single GitHub repository which normally will be public.
5. Schedule with at least two milestones: midterm (week 7) and final (week 13). For each milestone indicate what you expect to have done.
6. Software and/or hardware required. This is especially relevant for Robotics projects but may apply elsewhere.
7. You and why you think you can do this: Something about your own background, skills, courses, and experiences which you bring to the Independent Study and will serve to give credibility to your proposal
8. Discussion: Additional discussion of the project, including, for example, relevant investigation needed ahead of time, papers or literature, tools required, need for funds if any, etc.
**Types** - There are several course numbers corresponding to independent
studies. As of now, CS98a is an undergraduate independent study. CS99a is the
first semester of a Senior Honors Thesis. Cosi210a is for graduate students.
Depending on your status you will pick a different course.
**One or multiple students - **Generally independent studies are done by a
single student but multiple students are possible when the scope of the
project requires it.
**Meetings - **We will have weekly meetings during the semester. Once you are
well on your way we might move to a meeting every other week.
**Rapid iterations and demos -** It is important to try to get to demonstrable
preliminary results as quickly as possible. I have found that this discipline
helps keep an independent study on track and allows us to detect early that a
pivot is required.
**Deliverables - **At the end of the term there will be a deliverable of some
kind. We will work out the details, but in general I like the deliverables in
the form of a GitHub repository. It could include any models, drawings,
images, documents, code, and any other artifacts. Associated with the
repository is a multi-page report written as showcase of the results of the
project, describe the process, describing future work, including help for
someone who would like to continue the project. I would like the repo to be
public and open source.
**Grading - **We will agree on assessment criteria at the start of the
project. Generally I ask you to propose how you would like to be assessed and
use that as a starting point. There will be a midterm grade which will count
for 1/4 of the final grade, and then a end-term grade which will count for 3/4
of the grade.
|
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { Utils } from "@/utils/response";
import { API_CLASS_ROOM } from "@/services/api";
export const StoreClassRoom = defineStore("StoreClassRoom", () => {
// Các hàm khác
const { onResponse } = Utils();
const API = API_CLASS_ROOM.API_CLASS_ROOM;
// State
const classRooms = ref([]);
const vocabList = ref();
const memberList = ref();
// Getter
const onGetterClassRooms = computed(() => classRooms);
const onGetterVocabList = computed(() => vocabList);
const onGetterMemberList = computed(() => memberList);
// Action
const onActionGetClassRoom = async ({ data, noLoading = false }) => {
const res = await onResponse(API.getClassRoom({ data, noLoading }));
classRooms.value = res.data;
return res;
};
const onActionGetDetailClassRoom = async (id) => {
const res = await onResponse(API.getDetailClassRoom(id));
return res;
};
const onActionSaveClassRoom = async (data) => {
const res = await onResponse(API.saveClassRoom(data), true);
return res;
};
const onActionDeleteClassRoom = async (id) => {
const res = await onResponse(API.deleteClassRoom(id), true);
return res;
};
const onActionJoinClassRoom = async (data) => {
const res = await onResponse(API.joinClassRoom(data), true);
return res;
};
// Check có id phòng và password ko
const onActionIsPassword = async (data) => {
const res = await onResponse(API.isPassword(data));
return res;
};
const onActionGetDetailVocabulary = async (id) => {
const res = await onResponse(API.getDetailVocabulary(id));
return res;
};
const onActionSaveVocabulary = async (args) => {
const res = await onResponse(API.saveVocabulary(args), true);
return res;
};
const onActionUpdateVocabulary = async (args) => {
const res = await onResponse(API.updateVocabulary(args), true);
return res;
};
const onActionGetVocabularyList = async (params) => {
const res = await onResponse(API.getVocabularyList(params));
vocabList.value = res.data;
return res;
};
const onActionDeleteVocabularyItem = async (params) => {
const res = await onResponse(API.deleteVocabularyItem(params));
return res;
};
const onActionGetMemberList = async (params) => {
const res = await onResponse(API.getMemberList(params));
memberList.value = res.data;
return res;
};
const onActionUpdateRoleMember = async (data) => {
const res = await onResponse(API.updateRoleMember(data));
return res;
};
const onActionLeaveMember = async (params, data) => {
const res = await onResponse(API.leaveMember(params, data));
return res;
};
return {
// Getter
onGetterClassRooms,
onGetterVocabList,
onGetterMemberList,
// Action
onActionGetClassRoom,
onActionGetDetailClassRoom,
onActionSaveClassRoom,
onActionDeleteClassRoom,
onActionJoinClassRoom,
onActionIsPassword,
onActionGetDetailVocabulary,
onActionSaveVocabulary,
onActionUpdateVocabulary,
onActionGetVocabularyList,
onActionDeleteVocabularyItem,
onActionGetMemberList,
onActionUpdateRoleMember,
onActionLeaveMember,
};
});
|
//
// FullscreenImageView.swift
// SOZIP
//
// Created by 하창진 on 2021/08/27.
//
import SwiftUI
import SDWebImageSwiftUI
struct FullscreenImageView: View {
@Environment(\.presentationMode) var presentationMode
@Binding var selectedIndex : Int
@State private var offset : CGSize = .zero
@State var lastScaleValue: CGFloat = 1.0
let imgURL : [String?]
var body: some View {
ZStack{
Color.black.edgesIgnoringSafeArea(.all)
VStack{
ZStack(alignment : .topLeading){
ZStack(alignment : .center){
TabView(selection : $selectedIndex){
ForEach(imgURL.indices, id : \.self){index in
WebImage(url: URL(string : imgURL[index]!))
.resizable()
.aspectRatio(contentMode: .fit)
.tag(index)
}
}.tabViewStyle(PageTabViewStyle())
.indexViewStyle(PageIndexViewStyle(backgroundDisplayMode: .always))
HStack{
Button(action : {
selectedIndex -= 1
}){
Image(systemName: "chevron.left.circle")
.resizable()
.frame(width : 30, height : 30)
}.isHidden(self.selectedIndex == 0)
Spacer()
Button(action : {
selectedIndex += 1
}){
Image(systemName: "chevron.right.circle")
.resizable()
.frame(width : 30, height : 30)
.padding(20)
}.isHidden(self.selectedIndex == self.imgURL.count - 1)
}.padding([.horizontal], 20)
}
Button(action : {self.presentationMode.wrappedValue.dismiss()}){
VStack{
Image(systemName: "xmark")
.foregroundColor(.white)
}.padding(10)
.padding([.horizontal], 10)
.background(RoundedRectangle(cornerRadius: 10).shadow(radius: 5).foregroundColor(.gray).opacity(0.5))
}.padding(20)
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.