text
stringlengths 184
4.48M
|
---|
import { Ship } from "./Ship.js";
export class Gameboard {
constructor(boardSize) {
this.missedShots = new Set();
this.hitShots = new Set();
this.boardSize = boardSize;
this.shipsLeft = 0;
this.boardGraph = new Map();
this.buildBoard();
}
buildBoard() {
for (let x = 0; x < this.boardSize; x++) {
for (let y = 0; y < this.boardSize; y++) {
this.boardGraph.set(`${x},${y}`, null);
}
}
}
isValidPosition([x, y]) {
return x >= 0 && x < this.boardSize && y >= 0 && y < this.boardSize;
}
placeShip([x, y], length, direction = "vertical") {
const ship = new Ship(length);
if (
direction === "vertical" &&
this.isValidPosition([x, y]) &&
this.isValidPosition([x + length, y]) &&
this.canPlaceShip([x, y], length, direction)
) {
let index = 0;
let currentX = x;
while (index < length) {
let position = `${currentX},${y}`;
this.boardGraph.set(position, ship);
index++;
currentX++;
}
this.shipsLeft++;
return true;
} else if (
direction === "horizontal" &&
this.isValidPosition([x, y]) &&
this.isValidPosition([x, y + length]) &&
this.canPlaceShip([x, y], length, direction)
) {
let index = 0;
let currentY = y;
while (index < length) {
let position = `${x},${currentY}`;
this.boardGraph.set(position, ship);
index++;
currentY++;
}
this.shipsLeft++;
return true;
}
return false;
}
placeAllShips(amount) {
for (let i = 1; i < amount + 1; i++) {
let isPlace = false;
while (!isPlace) {
const direction = Math.random() < 0.5 ? "horizontal" : "vertical";
if (this.placeShip(getRandomCords(this.boardSize), i, direction)) {
isPlace = true;
}
}
}
}
canPlaceShip([x, y], length, direction) {
const positionsToVisit = [];
if (direction === "vertical")
for (let i = x; i < x + length; i++) {
positionsToVisit.push(`${i},${y}`);
}
else if (direction === "horizontal") {
for (let i = y; i < y + length; i++) {
positionsToVisit.push(`${x},${i}`);
}
}
return positionsToVisit.every(
(position) => this.boardGraph.get(position) === null
);
}
recieveAttack([x, y]) {
if (
this.isValidPosition([x, y]) &&
this.boardGraph.get(`${x},${y}`) !== null
) {
if (!this.hitShots.has(`${x},${y}`)) {
const ship = this.boardGraph.get(`${x},${y}`);
ship.hit();
if (ship.isSunk()) this.shipsLeft--;
this.hitShots.add(`${x},${y}`);
return true;
}
} else if (
this.isValidPosition([x, y]) &&
this.boardGraph.get(`${x},${y}`) === null
) {
console.log("You Missed The Shot!");
this.missedShots.add(`${x},${y}`);
return false;
}
}
clearBoard() {
this.shipsLeft = 0;
this.boardGraph = this.buildBoard();
}
}
function getRandomCords(boardSize) {
return [
Math.floor(Math.random() * boardSize),
Math.floor(Math.random() * boardSize),
];
} |
import { PropsWithChildren, ReactElement } from 'react';
import { render, RenderOptions } from '@testing-library/react';
import { container } from 'tsyringe';
import { AuthProvider } from '@/auth';
import { ConfigProvider } from '@/configuration';
import { DIProvider } from '@/di';
const mockConfig = {
auth: {
signinRoute: '/auth/signin',
authStateName: 'authState',
},
};
function AllTheProviders({ children }: PropsWithChildren) {
return (
<DIProvider container={container}>
<ConfigProvider config={mockConfig}>
<AuthProvider>{children}</AuthProvider>
</ConfigProvider>
</DIProvider>
);
}
const customRender = (ui: ReactElement, options?: Omit<RenderOptions, 'wrapper'>) =>
render(ui, { wrapper: AllTheProviders, ...options });
export * from '@testing-library/react';
export { customRender as render }; |
import subprocess
import docker
import re
from datetime import datetime
from typing import List, Optional, Callable, Tuple
import os
import sys
from dateutil import parser
import runfiles
import platform
import requests
from ci.ray_ci.utils import logger
from ci.ray_ci.builder_container import DEFAULT_ARCHITECTURE, DEFAULT_PYTHON_VERSION
from ci.ray_ci.docker_container import (
GPU_PLATFORM,
PYTHON_VERSIONS_RAY,
PYTHON_VERSIONS_RAY_ML,
PLATFORMS_RAY,
PLATFORMS_RAY_ML,
ARCHITECTURES_RAY,
ARCHITECTURES_RAY_ML,
RayType,
)
bazel_workspace_dir = os.environ.get("BUILD_WORKSPACE_DIRECTORY", "")
SHA_LENGTH = 6
def _check_python_version(python_version: str, ray_type: str) -> None:
if ray_type == RayType.RAY and python_version not in PYTHON_VERSIONS_RAY:
raise ValueError(
f"Python version {python_version} not supported for ray image."
)
if ray_type == RayType.RAY_ML and python_version not in PYTHON_VERSIONS_RAY_ML:
raise ValueError(
f"Python version {python_version} not supported for ray-ml image."
)
def _check_platform(platform: str, ray_type: str) -> None:
if ray_type == RayType.RAY and platform not in PLATFORMS_RAY:
raise ValueError(f"Platform {platform} not supported for ray image.")
if ray_type == RayType.RAY_ML and platform not in PLATFORMS_RAY_ML:
raise ValueError(f"Platform {platform} not supported for ray-ml image.")
def _check_architecture(architecture: str, ray_type: str) -> None:
if ray_type == RayType.RAY and architecture not in ARCHITECTURES_RAY:
raise ValueError(f"Architecture {architecture} not supported for ray image.")
if ray_type == RayType.RAY_ML and architecture not in ARCHITECTURES_RAY_ML:
raise ValueError(f"Architecture {architecture} not supported for ray-ml image.")
def _get_python_version_tag(python_version: str) -> str:
return f"-py{python_version.replace('.', '')}" # 3.x -> py3x
def _get_platform_tag(platform: str) -> str:
if platform == "cpu":
return "-cpu"
versions = platform.split(".")
return f"-{versions[0]}{versions[1]}" # cu11.8.0 -> cu118
def _get_architecture_tag(architecture: str) -> str:
return f"-{architecture}" if architecture != DEFAULT_ARCHITECTURE else ""
def list_image_tag_suffixes(
ray_type: str, python_version: str, platform: str, architecture: str
) -> List[str]:
"""
Get image tags & alias suffixes for the container image.
"""
_check_python_version(python_version, ray_type)
_check_platform(platform, ray_type)
_check_architecture(architecture, ray_type)
python_version_tags = [_get_python_version_tag(python_version)]
platform_tags = [_get_platform_tag(platform)]
architecture_tags = [_get_architecture_tag(architecture)]
if python_version == DEFAULT_PYTHON_VERSION:
python_version_tags.append("")
if platform == "cpu" and ray_type == RayType.RAY:
platform_tags.append("") # no tag is alias to cpu for ray image
if platform == GPU_PLATFORM:
platform_tags.append("-gpu") # gpu is alias for cu11.8.0
if ray_type == RayType.RAY_ML:
platform_tags.append("") # no tag is alias to gpu for ray-ml image
tag_suffixes = []
for platform in platform_tags:
for py_version in python_version_tags:
for architecture in architecture_tags:
tag_suffix = f"{py_version}{platform}{architecture}"
tag_suffixes.append(tag_suffix)
return tag_suffixes
def pull_image(image_name: str) -> None:
logger.info(f"Pulling image {image_name}")
client = docker.from_env()
client.images.pull(image_name)
def remove_image(image_name: str) -> None:
logger.info(f"Removing image {image_name}")
client = docker.from_env()
client.images.remove(image_name)
def get_ray_commit(image_name: str) -> str:
"""
Get the commit hash of Ray in the image.
"""
client = docker.from_env()
# Command to grab commit hash from ray image
command = "python -u -c 'import ray; print(ray.__commit__)'"
container = client.containers.run(
image=image_name, command=command, remove=True, stdout=True, stderr=True
)
output = container.decode("utf-8").strip()
match = re.search(
r"^[a-f0-9]{40}$", output, re.MULTILINE
) # Grab commit hash from output
if not match:
raise Exception(
f"Failed to get commit hash from image {image_name}. Output: {output}"
)
return match.group(0)
def check_image_ray_commit(prefix: str, ray_type: str, expected_commit: str) -> None:
if ray_type == RayType.RAY:
tags = list_image_tags(
prefix, ray_type, PYTHON_VERSIONS_RAY, PLATFORMS_RAY, ARCHITECTURES_RAY
)
elif ray_type == RayType.RAY_ML:
tags = list_image_tags(
prefix,
ray_type,
PYTHON_VERSIONS_RAY_ML,
PLATFORMS_RAY_ML,
ARCHITECTURES_RAY_ML,
)
tags = [f"rayproject/{ray_type}:{tag}" for tag in tags]
for i, tag in enumerate(tags):
logger.info(f"{i+1}/{len(tags)} Checking commit for tag {tag} ....")
pull_image(tag)
commit = get_ray_commit(tag)
if commit != expected_commit:
print(f"Ray commit mismatch for tag {tag}!")
print("Expected:", expected_commit)
print("Actual:", commit)
sys.exit(42) # Not retrying the check on Buildkite jobs
else:
print(f"Commit {commit} match for tag {tag}!")
if i != 0: # Only save first pulled image for caching
remove_image(tag)
def list_image_tags(
prefix: str,
ray_type: str,
python_versions: List[str],
platforms: List[str],
architectures: List[str],
) -> List[str]:
"""
List all tags for a Docker build version.
An image tag is composed by ray version tag, python version and platform.
See https://docs.ray.io/en/latest/ray-overview/installation.html for
more information on the image tags.
Args:
prefix: The build version of the image tag (e.g. nightly, abc123).
ray_type: The type of the ray image. It can be "ray" or "ray-ml".
"""
if ray_type not in RayType.__members__.values():
raise ValueError(f"Ray type {ray_type} not supported.")
tag_suffixes = []
for python_version in python_versions:
for platf in platforms:
for architecture in architectures:
tag_suffixes += list_image_tag_suffixes(
ray_type, python_version, platf, architecture
)
return sorted([f"{prefix}{tag_suffix}" for tag_suffix in tag_suffixes])
class DockerHubRateLimitException(Exception):
"""
Exception for Docker Hub rate limit exceeded.
"""
def __init__(self):
super().__init__("429: Rate limit exceeded for Docker Hub.")
class RetrieveImageConfigException(Exception):
"""
Exception for failing to retrieve image config.
"""
def __init__(self, message: str):
super().__init__(f"Failed to retrieve {message}")
class AuthTokenException(Exception):
"""
Exception for failing to retrieve auth token.
"""
def __init__(self, message: str):
super().__init__(f"Failed to retrieve auth token from {message}.")
def _get_docker_auth_token(namespace: str, repository: str) -> Optional[str]:
service, scope = (
"registry.docker.io",
f"repository:{namespace}/{repository}:pull",
)
auth_url = f"https://auth.docker.io/token?service={service}&scope={scope}"
response = requests.get(auth_url)
if response.status_code != 200:
raise AuthTokenException(f"Docker. Error code: {response.status_code}")
token = response.json().get("token", None)
return token
def _get_docker_hub_auth_token(username: str, password: str) -> Optional[str]:
url = "https://hub.docker.com/v2/users/login"
json_body = {
"username": username,
"password": password,
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, headers=headers, json=json_body)
if response.status_code != 200:
raise AuthTokenException(f"Docker Hub. Error code: {response.status_code}")
return response.json().get("token", None)
def _get_git_log(n_days: int = 30) -> str:
return subprocess.check_output(
[
"git",
"log",
f"--until='{n_days} days ago'",
"--pretty=format:%H",
],
text=True,
)
def _list_recent_commit_short_shas(n_days: int = 30) -> List[str]:
"""
Get list of recent commit SHAs (short version) on ray master branch.
Args:
n_days: Number of days to go back in git log.
Returns:
List of recent commit SHAs (short version).
"""
commit_shas = _get_git_log(n_days=n_days)
short_commit_shas = [
commit_sha[:SHA_LENGTH] for commit_sha in commit_shas.split("\n") if commit_sha
]
return short_commit_shas
def _get_config_docker_oci(tag: str, namespace: str, repository: str):
"""Get Docker image config from tag using OCI API."""
token = _get_docker_auth_token(namespace, repository)
# Pull image manifest to get config digest
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.docker.distribution.manifest.v2+json",
}
image_manifest_url = (
f"https://registry-1.docker.io/v2/{namespace}/{repository}/manifests/{tag}"
)
response = requests.get(image_manifest_url, headers=headers)
if response.status_code != 200:
raise RetrieveImageConfigException("image manifest.")
config_blob_digest = response.json()["config"]["digest"]
# Pull image config
config_blob_url = f"https://registry-1.docker.io/v2/{namespace}/{repository}/blobs/{config_blob_digest}" # noqa E501
config_headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.docker.container.image.v1+json",
}
response = requests.get(config_blob_url, headers=config_headers)
if response.status_code != 200:
raise RetrieveImageConfigException("image config.")
return response.json()
def _get_image_creation_time(tag: str) -> datetime:
namespace, repo_tag = tag.split("/")
repository, tag = repo_tag.split(":")
config = _get_config_docker_oci(tag=tag, namespace=namespace, repository=repository)
if "created" not in config:
raise RetrieveImageConfigException("image creation time.")
return parser.isoparse(config["created"])
def delete_tag(tag: str, docker_hub_token: str) -> bool:
"""Delete tag from Docker Hub repo."""
headers = {
"Authorization": f"Bearer {docker_hub_token}",
}
namespace, repo_tag = tag.split("/")
repository, tag_name = repo_tag.split(":")
url = f"https://hub.docker.com/v2/repositories/{namespace}/{repository}/tags/{tag_name}" # noqa E501
response = requests.delete(url, headers=headers)
if response.status_code == 429:
raise DockerHubRateLimitException()
if response.status_code != 204:
logger.info(f"Failed to delete {tag}, status code: {response.json()}")
return False
logger.info(f"Deleted tag {tag}")
return True
def query_tags_from_docker_hub(
filter_func: Callable[[str], bool],
namespace: str,
repository: str,
docker_hub_token: str,
num_tags: Optional[int] = None,
) -> List[str]:
"""
Query tags from Docker Hub repository with filter.
If Docker Hub API returns an error, the function will:
- Stop querying
- Return the current list of tags.
Args:
filter_func: Function to return whether tag should be included.
namespace: Docker namespace
repository: Docker repository
num_tags: Max number of tags to query
Returns:
Sorted list of tags from Docker Hub repository
with format namespace/repository:tag.
"""
filtered_tags = []
headers = {
"Authorization": f"Bearer {docker_hub_token}",
}
page_count = 1
while page_count:
logger.info(f"Querying page {page_count}")
url = f"https://hub.docker.com/v2/namespaces/{namespace}/repositories/{repository}/tags?page={page_count}&page_size=100" # noqa E501
response = requests.get(url, headers=headers)
response_json = response.json()
# Stop querying if Docker Hub API returns an error
if response.status_code != 200:
logger.info(f"Failed to query tags from Docker Hub: Error: {response_json}")
return sorted([f"{namespace}/{repository}:{t}" for t in filtered_tags])
result = response_json["results"]
tags = [tag["name"] for tag in result]
filtered_tags_page = list(filter(filter_func, tags)) # Filter tags
# Add enough tags to not exceed num_tags if num_tags is specified
if num_tags:
if len(filtered_tags) + len(filtered_tags_page) > num_tags:
filtered_tags.extend(
filtered_tags_page[: num_tags - len(filtered_tags)]
)
break
filtered_tags.extend(filtered_tags_page)
logger.info(f"Tag count: {len(filtered_tags)}")
if not response_json["next"]:
break
page_count += 1
return sorted([f"{namespace}/{repository}:{t}" for t in filtered_tags])
def query_tags_from_docker_with_oci(namespace: str, repository: str) -> List[str]:
"""
Query all repo tags from Docker using OCI API.
Args:
namespace: Docker namespace
repository: Docker repository
Returns:
List of tags from Docker Registry in format namespace/repository:tag.
"""
token = _get_docker_auth_token(namespace, repository)
headers = {
"Authorization": f"Bearer {token}",
}
url = f"https://registry-1.docker.io/v2/{namespace}/{repository}/tags/list"
response = requests.get(url, headers=headers)
if response.status_code != 200:
raise Exception(f"Failed to query tags from Docker: {response.json()}")
return [f"{namespace}/{repository}:{t}" for t in response.json()["tags"]]
def _is_release_tag(
tag: str,
release_versions: Optional[List[str]] = None,
) -> bool:
"""
Check if tag is a release tag & is in the list of release versions.
Tag input format should be just the tag name, without namespace/repository.
Tag input can be in any format queried from Docker Hub: "x.y.z-...", "a1s2d3-..."
Args:
tag: Docker tag name
release_versions: List of release versions.
If None, don't filter by release version.
Returns:
True if tag is a release tag and is in the list of release versions.
False otherwise.
"""
versions = tag.split(".")
if len(versions) != 3 and "post1" not in tag:
return False
# Parse variables into major, minor, patch version
major, minor, patch = versions[0], versions[1], versions[2]
extra = versions[3] if len(versions) > 3 else None
if not major.isnumeric() or not minor.isnumeric():
return False
if not patch.isnumeric() and "rc" not in patch and "-" not in patch:
return False
if "-" in patch:
patch = patch.split("-")[0]
release_version = ".".join([major, minor, patch])
if extra:
release_version += f".{extra}"
if release_versions and release_version not in release_versions:
return False
return True
def _crane_binary():
r = runfiles.Create()
system = platform.system()
if system != "Linux" or platform.processor() != "x86_64":
raise ValueError(f"Unsupported platform: {system}")
return r.Rlocation("crane_linux_x86_64/crane")
def _call_crane_cp(tag: str, source: str, aws_ecr_repo: str) -> Tuple[int, str]:
try:
with subprocess.Popen(
[
_crane_binary(),
"cp",
source,
f"{aws_ecr_repo}:{tag}",
],
stdout=subprocess.PIPE,
text=True,
) as proc:
output = ""
for line in proc.stdout:
logger.info(line + "\n")
output += line
return_code = proc.wait()
if return_code:
raise subprocess.CalledProcessError(return_code, proc.args)
return return_code, output
except subprocess.CalledProcessError as e:
return e.returncode, e.output
def copy_tag_to_aws_ecr(tag: str, aws_ecr_repo: str) -> bool:
"""
Copy tag from Docker Hub to AWS ECR.
Args:
tag: Docker tag name in format "namespace/repository:tag"
Returns:
True if tag was copied successfully, False otherwise.
"""
_, repo_tag = tag.split("/")
tag_name = repo_tag.split(":")[1]
logger.info(f"Copying from {tag} to {aws_ecr_repo}:{tag_name}......")
return_code, output = _call_crane_cp(
tag=tag_name,
source=tag,
aws_ecr_repo=aws_ecr_repo,
)
if return_code:
logger.info(f"Failed to copy {tag} to {aws_ecr_repo}:{tag_name}......")
logger.info(f"Error: {output}")
return False
logger.info(f"Copied {tag} to {aws_ecr_repo}:{tag_name} successfully")
return True
def backup_release_tags(
namespace: str,
repository: str,
aws_ecr_repo: str,
docker_username: str,
docker_password: str,
release_versions: Optional[List[str]] = None,
) -> None:
"""
Backup release tags to AWS ECR.
Args:
release_versions: List of release versions to backup
aws_ecr_repo: AWS ECR repository
"""
docker_hub_token = _get_docker_hub_auth_token(docker_username, docker_password)
docker_hub_tags = query_tags_from_docker_hub(
filter_func=lambda t: _is_release_tag(t, release_versions),
namespace=namespace,
repository=repository,
docker_hub_token=docker_hub_token,
)
_write_to_file("release_tags.txt", docker_hub_tags)
for t in docker_hub_tags:
copy_tag_to_aws_ecr(tag=t, aws_ecr_repo=aws_ecr_repo)
def _write_to_file(file_path: str, content: List[str]) -> None:
file_path = os.path.join(bazel_workspace_dir, file_path)
logger.info(f"Writing to {file_path}......")
with open(file_path, "w") as f:
f.write("\n".join(content)) |
package com.leew.springboot_init.entity;
import jakarta.persistence.Column;
import jakarta.persistence.EntityListeners;
import jakarta.persistence.MappedSuperclass;
import lombok.Getter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.time.LocalDateTime;
// 시간에 대한 객체들은 따로 구분을 하려고 한다.
@MappedSuperclass // Entity 대신 사용
// 각 DB 테이블이 이 하나의 Superclass를 상속하여 기능할 때 이 Superclass에 붙여 준다.
@EntityListeners(AuditingEntityListener.class)
@Getter
public class BaseEntity {
@CreationTimestamp
@Column(updatable = false)
private LocalDateTime createdTime;
@UpdateTimestamp
@Column(insertable = false)
private LocalDateTime updatedTime;
} |
{% extends 'bootstrap/base.html' %}
<!-- Link all style files here -->
{% block head %}
{{ super() }}
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/main.css') }}">
{% endblock %}
<!-- The title of our application is defined here -->
{% block title %}
{% if title %}
{{ title }} - Roles
{% else %}
User Roles
{% endif %}
{% endblock %}
<!-- This is the navbar -->
{% block navbar %}
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href=" {{ url_for('home') }} ">User Roles</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
{% if current_user.is_authenticated %}
<li><a href=" {{ url_for('logout') }} ">Logout</a></li>
{% else %}
<li><a href=" {{ url_for('login') }} ">Login</a></li>
{% endif %}
</ul>
</div>
</div>
</nav>
{% endblock %}
<!-- Contents of all our pages will go here -->
{% block content %}
<div class="container">
{% with messages = get_flashed_messages() %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning" role="alert"> {{ message }} </div>
{% endfor %}
{% endif %}
{% endwith %}
{% block app_content %}{% endblock %}
</div>
{% endblock %}
<!-- All scripts will go here -->
{% block scripts %}
{{ super() }}
{% endblock %} |
import React from "react";
import styles from "./OrderItem.module.css";
import { useCart } from "../context/OrdersContext";
export const OrderItem = ({ event }) => {
const { updateQuantity, removeItem } = useCart();
const incrementQuantity = () => {
updateQuantity(event, 1);
};
const decrementQuantity = () => {
if (event.quantity > 1) {
updateQuantity(event, -1);
} else {
removeItem(event);
}
};
return (
<div className={styles.card}>
<div className={styles.eventContainer}>
<h2 className={styles.eventName}>{event.name}</h2>
<p className={styles.eventDate}>
{" "}
{event.when.date} kl {event.when.from} - {event.when.to}
</p>
</div>
<div className={styles.btnContainer}>
<button className={styles.buttons} onClick={decrementQuantity}>
-
</button>{" "}
<p className={[styles.buttons, styles.itemTotal].join(" ")}>
{event.quantity}
</p>{" "}
<button className={styles.buttons} onClick={incrementQuantity}>
+
</button>
</div>
</div>
);
}; |
<?php
/**
* The template for displaying audio post format content.
*
* @package Tevah Lite
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?> <?php hybrid_attr( 'post' ); ?>>
<?php echo ( $audio = hybrid_media_grabber( array( 'type' => 'audio', 'split_media' => true, 'before' => '<div class="entry-media">', 'after' => '</div>' ) ) ); ?>
<div class="entry-inner">
<header class="entry-header">
<?php get_template_part( 'entry', 'meta' ); // Loads the entry-meta.php template. ?>
<?php
if ( is_single() ) :
the_title( '<h1 class="entry-title" ' . hybrid_get_attr( 'entry-title' ) . '>', '</h1>' );
else :
the_title( sprintf( '<h2 class="entry-title" ' . hybrid_get_attr( 'entry-title' ) . '><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );
endif;
?>
</header><!-- .entry-header -->
<div class="entry-content" <?php hybrid_attr( 'entry-content' ); ?>>
<?php
/* translators: %s: Name of current post */
the_content( sprintf(
__( 'Read more %s', 'tevah' ),
the_title( '<span class="screen-reader-text">', '</span>', false )
) );
wp_link_pages( array(
'before' => '<div class="page-links">' . __( 'Pages:', 'tevah' ),
'after' => '</div>',
'pagelink' => '<span class="screen-reader-text">' . __( 'Page', 'tevah' ) . ' </span>%',
'separator' => '<span class="screen-reader-text">,</span> ',
) );
?>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php toivo_lite_post_terms( array( 'taxonomy' => 'category', 'text' => __( 'Posted in %s', 'tevah' ) ) ); ?>
<?php toivo_lite_post_terms( array( 'taxonomy' => 'post_tag', 'text' => __( 'Tagged %s', 'tevah' ), 'before' => '<br />' ) ); ?>
</footer><!-- .entry-footer -->
</div><!-- .entry-inner -->
</article><!-- #post-## --> |
package com.hitwh.haoqitms.service.executor;
import com.hitwh.haoqitms.entity.Student;
import org.springframework.web.multipart.MultipartFile;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
public interface ExecutorStudentService {
/**
* 获取所有学生的邮箱
*
* @return 所有学生的邮箱表格流
*/
InputStream getAllStudentEmail();
/**
* 导入学生信息
*
* @param file 学生信息表格
* @return 是否导入成功
*/
Boolean importStudent(MultipartFile file);
/**
* 创建学员
* @param student
* @return
*/
Boolean createStudent(Student student);
/**
* 查询学员
* @return student info
*/
public List<Student> getAllStudents();
/**
* 更新学员信息学员
* @return student info
*/
public Boolean updateStudent(Student student);
/**
* 删除学生信息
* @param studentId
* */
public Boolean deleteStudent(Integer studentId);
/**
* 导出学生信息
* @return 学生信息的excel文件
*/
InputStream exportStudent();
/**
* 获取学生信息模板
* @return 学生信息模板
*/
InputStream getTemplate() throws FileNotFoundException;
} |
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
import QtQuick 2.15
import QtQuick.Layouts 1.15
import HelperWidgets 2.0
import StudioControls 1.0 as StudioControls
import StudioTheme 1.0 as StudioTheme
Section {
id: root
anchors.left: parent.left
anchors.right: parent.right
caption: qsTr("Font Extras")
property string fontName: "font"
property bool showStyle: false
function getBackendValue(name) {
return backendValues[root.fontName + "_" + name]
}
function isBackendValueAvailable(name) {
if (backendValues[name] !== undefined)
return backendValues[name].isAvailable
return false
}
SectionLayout {
PropertyLabel {
text: qsTr("Capitalization")
tooltip: qsTr("Sets capitalization rules for the text.")
blockedByTemplate: !getBackendValue("capitalization").isAvailable
}
SecondColumnLayout {
ComboBox {
implicitWidth: StudioTheme.Values.singleControlColumnWidth
+ StudioTheme.Values.actionIndicatorWidth
width: implicitWidth
backendValue: getBackendValue("capitalization")
scope: "Font"
model: ["MixedCase", "AllUppercase", "AllLowercase", "SmallCaps", "Capitalize"]
enabled: backendValue.isAvailable
}
ExpandingSpacer {}
}
PropertyLabel {
visible: root.showStyle
text: qsTr("Style")
tooltip: qsTr("Sets the font style.")
blockedByTemplate: !styleComboBox.enabled
}
SecondColumnLayout {
visible: root.showStyle
ComboBox {
id: styleComboBox
implicitWidth: StudioTheme.Values.singleControlColumnWidth
+ StudioTheme.Values.actionIndicatorWidth
width: implicitWidth
backendValue: (backendValues.style === undefined) ? dummyBackendValue
: backendValues.style
scope: "Text"
model: ["Normal", "Outline", "Raised", "Sunken"]
enabled: backendValue.isAvailable
}
ExpandingSpacer {}
}
PropertyLabel {
text: qsTr("Style color")
tooltip: qsTr("Sets the color for the font style.")
visible: root.isBackendValueAvailable("styleColor")
}
ColorEditor {
visible: root.isBackendValueAvailable("styleColor")
backendValue: backendValues.styleColor
supportGradient: false
}
PropertyLabel {
text: qsTr("Hinting")
tooltip: qsTr("Sets how to interpolate the text to render it more clearly when scaled.")
blockedByTemplate: !getBackendValue("hintingPreference").isAvailable
}
SecondColumnLayout {
ComboBox {
implicitWidth: StudioTheme.Values.singleControlColumnWidth
+ StudioTheme.Values.actionIndicatorWidth
width: implicitWidth
backendValue: getBackendValue("hintingPreference")
scope: "Font"
model: ["PreferDefaultHinting", "PreferNoHinting", "PreferVerticalHinting", "PreferFullHinting"]
enabled: backendValue.isAvailable
}
ExpandingSpacer {}
}
PropertyLabel {
text: qsTr("Auto kerning")
tooltip: qsTr("Resolves the gap between texts if turned true.")
blockedByTemplate: !getBackendValue("kerning").isAvailable
}
SecondColumnLayout {
CheckBox {
text: backendValue.valueToString
implicitWidth: StudioTheme.Values.twoControlColumnWidth
+ StudioTheme.Values.actionIndicatorWidth
backendValue: getBackendValue("kerning")
enabled: backendValue.isAvailable
}
ExpandingSpacer {}
}
PropertyLabel {
text: qsTr("Prefer shaping")
tooltip: qsTr("Toggles the font-specific special features.")
blockedByTemplate: !getBackendValue("preferShaping").isAvailable
}
SecondColumnLayout {
CheckBox {
text: backendValue.valueToString
implicitWidth: StudioTheme.Values.twoControlColumnWidth
+ StudioTheme.Values.actionIndicatorWidth
backendValue: getBackendValue("preferShaping")
enabled: backendValue.isAvailable
}
ExpandingSpacer {}
}
}
} |
# Ionic Recipe App - Waañ wi 🥞
A recipe application for Senegalese dishes, desserts and snacks.

## About 🎯
*"Waan wi"* is a mobile application that allows you to discover and prepare a variety of tasty dishes, desserts and snacks.
Explore **a diverse collection of Senegalese recipes and get inspired to cook delicious dishes at home!** 🥗
## Demo 📹
https://github.com/metzoo10/Waan-wi/assets/129201720/7458c4da-bf4c-4c92-ba15-2d79be88426e
## Features 📝
The recipes are divided into three categories: *dishes*, *desserts* and *snacks*. Each category contains delicious food recipes 🤤
The application retrieves the data for the different recipes from a **JSON file** which is then linked to an Ionic service.
Thus, with a single service, we can communicate the data required for each recipe 🥘
An **About** page where we can find a description of the app and the author (and contacts too 👀) and a **Settings** page for configuration and FAQ 🤓
## Installation ⬇️
To run this application, follow these steps :
### Prerequisites 📏
Make sure you have **Node.js** and **Ionic** installed on your machine before you begin.
1. Node.js :
- If Node.js is not installed, *download and install the latest version from [the official Node.js website.](https://nodejs.org/)*
2. Ionic CLI :
- Install **Ionic CLI** using the following command :
```bash
npm install -g @ionic/cli
```
### Project Cloning 🧬
- Clone the repository from GitHub to your local machine :
```bash
git clone https://github.com/metzoo10/Waan-wi.git
cd nom-du-dossier
```
### Dependencies Installation 🔽
1. Installation of Project Dependencies :
```bash
npm install
```
2. Installation and Launching of the JSON Server :
- To install JSON Server in your application, navigate to your project directory in your terminal or command prompt and type in this command :
```bash
npm install -g json-server
```
- To launch it, go in a separate terminal and *start JSON Server to simulate a REST API from the JSON file containing recipe data* with this command :
```bash
json-server src/assets/recettes.json
```
### Starting the Application ▶️
- Launch the **Ionic app** locally using the following command :
```bash
ionic serve
```
### Tip 💡
Don't forget to view the app with an emulated device by clicking **F12**. And also to refresh your browser so the app will appear normally.
And there you go ! You've installed successfully the app.
## Technologies 🚀







 |
namespace MergeStringsAlternately
{
public class Solution
{
/*
Initialize an empty string to store the merged result.
Traverse both input strings together, picking each character alternately from both strings and appending it to the merged result string.
Continue the traversal until the end of the longer string is reached.
Return the merged result string.
Time O(N)
Space O(N)
*/
public string MergeAlternately(string word1, string word2)
{
int i = 0;
string res = "";
while (i < word1.Length || i < word2.Length)
{
if(i < word1.Length)
{
res += word1[i];
}
if(i < word2.Length)
{
res += word2[i];
}
i++;
}
return res;
}
}
internal class Program
{
static void Main(string[] args)
{
Solution solution = new Solution();
string word1 = "ab";
string word2 = "pqrs";
var res = solution.MergeAlternately(word1, word2);
Console.WriteLine(res);
Console.ReadLine();
}
}
} |
import { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } from 'utils/@reduxjs/toolkit';
import { useInjectReducer, useInjectSaga } from 'utils/redux-injectors';
import { welcomeDialogueSaga } from './saga';
import { WelcomeDialogueState } from './types';
export const initialState: WelcomeDialogueState = {};
const slice = createSlice({
name: 'welcomeDialogue',
initialState,
reducers: {
someAction(state, action: PayloadAction<any>) {},
},
});
export const { actions: welcomeDialogueActions } = slice;
export const useWelcomeDialogueSlice = () => {
useInjectReducer({ key: slice.name, reducer: slice.reducer });
useInjectSaga({ key: slice.name, saga: welcomeDialogueSaga });
return { actions: slice.actions };
};
/**
* Example Usage:
*
* export function MyComponentNeedingThisSlice() {
* const { actions } = useWelcomeDialogueSlice();
*
* const onButtonClick = (evt) => {
* dispatch(actions.someAction());
* };
* }
*/ |
(* ::Package:: *)
(* :Title: Trigonometria *)
(* :Context: Trigonometria *)
(* :Author: Gianluca Lutero, Filippo Soncini, Adele Valerii, Sara Gattari *)
(* :Summary: Insieme di illustrazioni ed esercizzi interattivi sulla trigonometria *)
(* :Package Version: 11.0.1.0 *)
(* :Mathematica Version: 11.0.1.0 *)
BeginPackage["Trigonometria`"]
(* Funzioni *)
angolo::usage = "Calcola i due angoli Subscript[\[Theta], 1], Subscript[\[Theta], 2] necessari\n
per poter disegnare una arco di circonferenza tramite Disk[{x,y},{Subscript[\[Theta], 1],Subscript[\[Theta], 2]}] ";
bottonesen::usage = "Funzione che genera il bottone che richiama la fiunzione grafiseno[]";
bottonecos::usage = "Funzione che genera il bottone che richiama la fiunzione graficocoseno[]";
bottonetan::usage = "Funzione che genera il bottone che richiama la fiunzione graficotangente[]";
bottonepitagora::usage = "Funzione che genera il bottone che richiama la fiunzione bottonepitagora[]";
bottonecalcolatrice::usage = "Funzione che genera il bottone che richiama la fiunzione bottonecalcolatrice[]";
grafiseno::usage = "Illustrazione del seno e della sua funzione";
graficocoseno::usage = "Illustrazione del coseno e della sua funzione";
graficotangente::usage = "Illustrazione della tangente e della sua funzione";
defsencos::usage = "Illustrazione del seno e del coseno sulla circonferenza unitaria";
rapporti::usage = "Illustrazione dei rapporti tra seno e del coseno";
triangolorett::usage = "Illustrazione del un triangolo rettangolo formato da seno e coseno";
tangent::usage = "Illustrazione della tangente sulla circonferenza unitaria";
definizionetangente::usage = "Illustrazione della tangente sulla circonferenza unitaria con rapporti";
angolinoti30::usage = "Illustrazione angoli noti multipli di 30\[Degree]";
angolinoti45::usage = "Illustrazione angoli noti multipli di 45\[Degree]";
teoremacorda::usage = "Illustrazione del teorema della corda";
teoremacorda2::usage = "Illustrazione del teorema della corda interattivo pt.1";
teoremacorda3::usage = "Illustrazione del teorema della corda interattivo pt.2";
teoremaseni::usage = "Illustrazione del teorema dei seni";
teoremacoseno::usage = "Illustrazione del teorema dei coseni pt.1";
teoremacoseno2::usage = "Illustrazione del teorema dei coseni pt.2";
pitagora::usage = "Illustrazione del teorema di pitagora con testo";
EsercizioEsempio::usage = "Stampa un'esercizio d'esempio per calcolare Sen(\[Alpha])";
Esercizio1::usage= "Esercizio su seno coseno tangente";
Esercizio2::usage = "Esercizio a risposta multipla";
Esercizio3::usage = "Esercizio: calcolo lato triangolo - Teorema della corda ";
Esercizio4::usage= "Esercizio: trovare lato di un triangolo a risposta multipla";
Esercizio5::usage = "Esercizio: trovare il lato C usando la relazione \!\(\*FractionBox[\(\(\\\ \)\(A\)\), \(sen \((\[Alpha])\)\)]\) =\!\(\*FractionBox[\(\(\\\ \)\(B\)\), \(sen \((\[Beta])\)\)]\)";
Esercizio6::usage="Esercizio: teorema dei seni risposta multipla";
Esercizio7::usage = "Esercizio: trovare il lato C con il teorema del coseno";
Esercizio8::usage = "Esercizio: trovare cos(\[Gamma]) usando il teorema del coseno";
Esercizio9::usage = "Esercizio: campanile";
Esercizio10::usage = "Esercizio: scivolo";
CheckAnswer::usage = "Modulo che compara i parametri answer_ e correct_ passati in input.\n
Il risultato della valutazione \[EGrave] \[Checkmark] se i parametri sono uguali\n
X altrimenti ";
Calcolatrice::usage = "Calcolatrice semplice per il calcolo di funzioni trigonometriche";
TPitagora::usage = "Suggerimento Teorema di pitagora";
ClearAll["Global`*"]
(* FUNZIONE CALCOLO ANGOLO *)
(* Angolo calcola i due angoli Subscript[\[Theta], 1], Subscript[\[Theta], 2] necessari per poter disegnare una arco di circonferenza tramite Disk[{x,y},{Subscript[\[Theta], 1],Subscript[\[Theta], 2]}] *)
angolo[p1_,p2_,p3_]:=Module[{anga},
anga={If[(p3[[1]]-p1[[1]])!=0, ArcTan[(p3[[2]] -p1[[2]])/(p3[[1]]-p1[[1]])] ,0] ,
If[(p3[[1]]-p2[[1]])!=0, ArcTan[(p3[[2]] -p2[[2]])/(p3[[1]]-p2[[1]])],0] }
];
(* PUNTI GENERICI GLOBALI*)
pa = {Cos[(Pi/2)+0.3], Sin[(Pi/2)+0.3]};
pb = {Cos[-0.2], Sin[-0.2]};
pc = {Cos[Pi +0.5], Sin[Pi +0.5]};
pa2 = {Cos[Pi/2], Sin[(Pi/2)]}
pb2 = {Cos[-0.2], Sin[-0.2]}
pc2 = {Cos[3Pi/2], Sin[3Pi/2]}
(* GENERA BOTTONE *)
(* Funzione che genera il bottone che richiama la fiunzione grafiseno[] *)
bottonesen[]:=
Button["Funzione Seno",MessageDialog[ graficoseno[] ,WindowSize->All,Editable->False]]
(* GENERA BOTTONE *)
(* Funzione che genera il bottone che richiama la fiunzione graficocoseno[] *)
bottonecos[]:=
Button["Funzione Coseno",MessageDialog[ graficocoseno[] ,WindowSize->All,Editable->False]]
(* GENERA BOTTONE *)
(* Funzione che genera il bottone che richiama la fiunzione graficotangente[] *)
bottonetan[]:=
Button["Funzione Tangente",MessageDialog[ graficotangente[] ,WindowSize->All,Editable->False]]
(* GENERA BOTTONE *)
(* Funzione che genera il bottone che richiama la fiunzione pitagora[] *)
bottonepitagora[]:=
Button["Teorema di Pitagora",MessageDialog[ pitagora[] ,WindowSize->All,Editable->False]]
(* GENERA BOTTONE *)
(* Funzione che genera il bottone che richiama la fiunzione Calcolatrice[] *)
bottonecalcolatrice[]:=
Button["Calcolatrice",MessageDialog[ Calcolatrice[] ,WindowSize->All,Editable->False]]
(* Grafico Seno *)
graficoseno[] :=
Manipulate[
(* genero disegno *)
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
(* DETTAGLI *)
(* Circonferenza *)
{Lighter[Gray,0.5],Circle[{0,0},1]},
(* Arco di circonferenza *)
{Darker[Green,0.2],Thick,Circle[{0,0},1,{0,th}]},
(* Linee di dettaglio *)
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
{Red,Thick,Line[{{Cos[th],0},{Cos[th],Sin[th]}}]},
(* yp *)
{Black,Disk[{0, Sin[th]},0.02]},
(* sin *)
{Red,Thick,Dashing[Medium],Line[{{0,0},{0,Sin[th]}}]},
(* retta punto *)
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* angolo *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Circle[{0,0},0.3,{0,th}]},
(* linea tratteggiata per cos *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th]-3,Sin[th]},{3,Sin[th]}}]},
(* linea tratteggiata per sin *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th],Sin[th]-3},{Cos[th],3}}]},
(* TESTO *)
Text["Yp",{0.1,Sin[th]+0.1}],
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}],
Rotate[Text[Style["Sin(\[Theta])",Red],{-0.1,Sin[th]/2}],90\[Degree]]
}],
PlotRange->1,ImageSize->400,BaseStyle->{15},Axes->True,PlotRange->{{-1,1},{-1,1}},PlotRangePadding->0.25];
(* genero grafico *)
maingraph[th_]:=Module[{},
(* plot della funzione seno *)
Show[Plot[{Sin[x]},{x,0.0001,th},PlotRange->{{0,2Pi},{-1,1}},ImageSize->650,PlotRangePadding->{0,0.25},ImagePadding->{{30,12},{0,0}},PlotRangeClipping->False,PlotStyle->Darker[Red,0.6],
(* GRIGLIA *)
(* Valori asse x, y *)
Ticks->{Table[{n Pi/4,n Pi/4},{n,0,8}],Table[n,{n,-1,1,1/2}]},
(* Linee sulla griglia*)
GridLines->{Table[{n Pi/4,Lighter[Gray,0.7]},{n,-2,8}],Table[{n,Lighter[Gray,0.7]},{n,-1,1,1/2}]},ImageSize->{Automatic,145}],
(* DETTAGLI *)
Graphics[{
(* Linea di dettaglio asse x *)
{Darker[Green,0.2],Thick,Line[{{0,0},{th,0}}]},
(* Linea di dettaglio asse y *)
{Red,Thick,Line[{{th,0},{th,Sin[th]}}]}
}],
AspectRatio->Automatic,BaseStyle->{12}]];
(* Variabile diamica *)
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]},pt2={ptctrl,0}},
Labeled[
Grid[{
(* INIZIALIZAZIONE LOCATOR *)
(* http://mathworld.wolfram.com/Circle.html *)
{LocatorPane[Dynamic[pt,
{(pt={Cos[pt2[[1]]],Sin[pt2[[1]]]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
(* Disegno circonferenza *)
Dynamic[anglegraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]],
(* INIZIALIZAZIONE LOCATOR *)
LocatorPane[Dynamic[pt2,
{(pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]],0})&,
(pt2={#[[1]],0};pt={Cos[#[[1]]],Sin[#[[1]]]})&,
(pt2={#[[1]],0};ptctrl=#[[1]])&}],
(* Disegno grafico *)
Dynamic[maingraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]]}},Spacings->0]
,{Row[{Style["Funzione ","Label",22,Gray],Text@Style["Seno",Red,22]}], Style["",10,Lighter[Gray,0.7],"Label"]},{{Top,Center},{Bottom,Right}}
]]],
{{ptctrl,Pi/6,"angle"},0,2Pi},TrackedSymbols:>{ptctrl}]
graficotangente[]:=
Manipulate[
(* genero disegno *)
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Darker[Green,0.2],Thick,Circle[{0,0},1,{0,th}]},
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
(* punti *)
{Black,Disk[{1, Tan[th]},0.02]},
{Black,Disk[{Cos[th], Sin[th]},0.02]},
{Black,Disk[{0, Tan[th]},0.02]},
{Black,Disk[{1,0},0.02]},
(* tangente punto *)
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* angolo *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Circle[{0,0},0.3,{0,th}]},
(* linea tratteggiata per Tan *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{1,3},{1,Tan[th]-3}}]},
(* linea tratteggiata per Tan 2*)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{-3,Tan[th]},{3,Tan[th]}}]},
(* TESTO *)
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text["T",{1.1,Tan[th]+0.1}],
Text["Xt",{1.1,0.1}],
Text["Yt",{0.1,Tan[th]+0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}],
Rotate[Text[Style["Tan(\[Theta])",Orange],{1.1,Tan[th]/2}],90\[Degree]],
(* TAN *)
(* tan *) {Orange,Thick,Line[{{1,0},{1,Tan[th]}}]},
{Orange,Thickness[0.008],Dashing[Medium],Line[{{0,0},{0,Tan[th]}}]}
}],
PlotRange->1,ImageSize->400,BaseStyle->{15},Axes->True,PlotRange->{{-1,1},{-1,1}},PlotRangePadding->0.25];
(* genero grafico *)
maingraph[th_]:=Module[{},
Show[Plot[{Tan[x]},{x,0.0001,th},PlotRange->{{0,2Pi},{-2.2,2.2}},ImageSize->650,PlotRangePadding->{0,0},ImagePadding->{{30,12},{0,0}},PlotRangeClipping->False,PlotStyle->Darker[Orange,0.5],
Ticks->{Table[{n Pi/4,n Pi/4},{n,0,8}],Table[n,{n,-2,2,1/2}]},
GridLines->{Table[{n Pi/4,Lighter[Gray,0.7]},{n,-2,8}],Table[{n,Lighter[Gray,0.7]},{n,-2,2,1/2}]},ImageSize->{Automatic,145}],
Graphics[{
{Darker[Green,0.2],Thick,Line[{{0,0},{th,0}}]},
{Orange,Thick,Line[{{th,0},{th,Tan[th]}}]}
}],
AspectRatio->Automatic,BaseStyle->{12}]];
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]},pt2={ptctrl,0}},
Labeled[Grid[{
{LocatorPane[Dynamic[pt,
{(pt={Cos[pt2[[1]]],Sin[pt2[[1]]]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
Dynamic[anglegraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]],
LocatorPane[Dynamic[pt2,
{(pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]],0})&,
(pt2={#[[1]],0};pt={Cos[#[[1]]],Sin[#[[1]]]})&,
(pt2={#[[1]],0};ptctrl=#[[1]])&}],
Dynamic[maingraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]]}},Spacings->0],{Row[{Style["Funzione ","Label",22,Gray],Text@Style["Tangente",Orange,22]}],
Style["",10,Lighter[Gray,0.7],"Label"]},{{Top,Center},{Bottom,Right}}]]
],
{{ptctrl,Pi/6,"angle"},0,2Pi},TrackedSymbols:>{ptctrl}]
(* Grafico Coseno *)
graficocoseno[] :=
Manipulate[
(* genero disegno *)
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Darker[Green,0.2],Thick,Circle[{0,0},1,{0,th}]},
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
{Lighter[Gray,0.5],Line[{{Cos[th],0},{Cos[th],Sin[th]}}]},
(* yp *)
{Black,Disk[{Cos[th], 0},0.02]},
(* cos *)
{Blue,Thick,Dashing[Medium],Line[{{0,Sin[th]},{Cos[th],Sin[th]}}]},
{Blue,Thick,Line[{{0,0},{Cos[th],0}}]},
(* retta punto *)
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* angolo *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Circle[{0,0},0.3,{0,th}]},
(* linea tratteggiata per cos *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th]-3,Sin[th]},{3,Sin[th]}}]},
(* linea tratteggiata per sin *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th],Sin[th]-3},{Cos[th],3}}]},
(* testo *)
Text["Xp",{Cos[th]+0.1,0.1}],
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}],
Text[Style["Cos(\[Theta])",Blue],{Cos[th]/2,-0.1}]
}],
PlotRange->1,ImageSize->400,BaseStyle->{15},Axes->True,PlotRange->{{-1,1},{-1,1}},PlotRangePadding->0.25];
(*genero grafico*)
maingraph[th_]:=Module[{},
Show[
Plot[{Cos[x]},{x,0.0001,th},PlotRange->{{0,2Pi},{-1,1}},ImageSize->650,PlotRangePadding->{0,0.25},ImagePadding->{{30,12},{0,0}},PlotRangeClipping->False,PlotStyle->Darker[Blue,0.9],
Ticks->{Table[{n Pi/4,n Pi/4},{n,0,8}],Table[n,{n,-1,1,1/2}]},
GridLines->{Table[{n Pi/4,Lighter[Gray,0.7]},{n,-2,8}],Table[{n,Lighter[Gray,0.7]},{n,-1,1,1/2}]},ImageSize->{Automatic,145}],
Graphics[{
{Darker[Green,0.2],Thick,Line[{{0,0},{th,0}}]},
{Blue,Thick,Line[{{th,0},{th,Cos[th]}}]}
}],
AspectRatio->Automatic,BaseStyle->{12}]];
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]},pt2={ptctrl,0}},
Labeled[Grid[{
{LocatorPane[Dynamic[pt,
{(pt={Cos[pt2[[1]]],Sin[pt2[[1]]]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
Dynamic[anglegraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]],
LocatorPane[Dynamic[pt2,
{(pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]],0})&,
(pt2={#[[1]],0};pt={Cos[#[[1]]],Sin[#[[1]]]})&,
(pt2={#[[1]],0};ptctrl=#[[1]])&}],
Dynamic[maingraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]]}},Spacings->0],{Row[{Style["Funzione ","Label",22,Gray],Text@Style["Coseno",Blue,22]}],
Style["",10,Lighter[Gray,0.7],"Label"]},{{Top,Center},{Bottom,Right}}]]
],
{{ptctrl,Pi/6,"angle"},0,2Pi},TrackedSymbols:>{ptctrl}]
(* Definizione Seno Coseno *)
defsencos[] :=
Manipulate[
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
(* punti *)
{Black,Disk[{Cos[th], 0},0.02]},
{Black,Disk[{0, Sin[th]},0.02]},
(* tangente punto *)
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* angolo *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Circle[{0,0},0.3,{0,th}]},
(* linea tratteggiata per cos *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th]-3,Sin[th]},{3,Sin[th]}}]},
(* linea tratteggiata per sin *){
Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th],Sin[th]-3},{Cos[th],3}}]},
(* TESTO *)
Text["Xp",{Cos[th]+0.1,0.1}],
Text["Yp",{0.1,Sin[th]+0.1}],
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}],
Text[Style["Cos(\[Theta])",Blue],{Cos[th]/2,-0.1}],
Rotate[Text[Style["Sin(\[Theta])",Red],{-0.1,Sin[th]/2}],90\[Degree]],
(* SEN COS TAN *)
(* sin *)
{Red,Thickness[0.008],Line[{{0,0},{0,Sin[th]}}]},
{Red,,Dashing[Medium],Line[{{Cos[th],0},{Cos[th],Sin[th]}}]},
(* cos *)
{Blue,Thickness[0.008],Line[{{0, 0},{Cos[th],0}}]},
{Blue,Dashing[Medium],Line[{{0,Sin[th]},{Cos[th],Sin[th]}}]}
}],
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->True,Ticks->Automatic,PlotRangePadding->0.25];
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]},pt2={ptctrl,0}},
Grid[{
{LocatorPane[Dynamic[pt,
{(pt={Cos[pt2[[1]]],Sin[pt2[[1]]]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
Dynamic[anglegraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]
],
LineLegend[{Red, Blue,Darker[Green,0.3]},{"Sin","Cos", "\[Theta]"}]
}},Alignment->{Center,Center}]]
],
{{ptctrl,Pi/6,"Angle"},0,2Pi},TrackedSymbols:>{ptctrl}]
(* Definizione rapporti *)
rapporti[] :=
Manipulate[
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
{Black,Disk[{Cos[th], 0},0.02]},
{Black,Disk[{0, 0},0.02]},
(* {Darker[Green,0.2],Thick,Circle[{0,0},1,{0,th}]}, *)
(* tangente punto *)
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* arco *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Thick,Circle[{0,0},0.3,{0,th}]},
(* triangolo sin cos*)
{Opacity[0.2],Cyan,EdgeForm[Directive[Thick,Cyan]], Triangle[{{0,0},{Cos[th],Sin[th]},{Cos[th],0}}]},
(* angolo 90\[Degree]*)
If[th<= Pi/2 ,
{
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{Cos[th]-0.1, 0},{Cos[th]-0.1, 0.1},{Cos[th], 0.1},{Cos[th], 0}}]},
{Darker[Green,0.3],Line[{{Cos[th]-0.1, 0},{Cos[th]-0.1, 0.1},{Cos[th], 0.1}}]}
},
{If[ th <= Pi,
{
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{Cos[th]+0.1, 0},{Cos[th]+0.1, 0.1},{Cos[th], 0.1},{Cos[th], 0}}]},
{Darker[Green,0.3],Line[{{Cos[th]+0.1, 0},{Cos[th]+0.1, 0.1},{Cos[th], 0.1}}]}
},
{If[ th <=(3*Pi)/2,
{
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{Cos[th]+0.1, 0},{Cos[th]+0.1, -0.1},{Cos[th], -0.1},{Cos[th], 0}}]},
{Darker[Green,0.3],Line[{{Cos[th]+0.1, 0},{Cos[th]+0.1, -0.1},{Cos[th], -0.1}}]}
},
{{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{Cos[th]-0.1, 0},{Cos[th]-0.1, -0.1},{Cos[th], -0.1},{Cos[th], 0}}]},
{Darker[Green,0.3],Line[{{Cos[th]-0.1, 0},{Cos[th]-0.1, -0.1},{Cos[th], -0.1}}]}
}]
}]
}],
(* linea tratteggiata per sin *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th],Sin[th]-3},{Cos[th],3}}]},
(* TESTO *)
Text["H",{Cos[th]+0.1,0.1}],
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text["O",{-0.1,0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}]
}],
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->True,Ticks->Automatic,PlotRangePadding->0.25];
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]},pt2={ptctrl,0}},
Grid[{
{LocatorPane[Dynamic[pt,
{(pt={Cos[pt2[[1]]],Sin[pt2[[1]]]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
Dynamic[anglegraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]
],
LineLegend[{Darker[Green,0.3]},{ "\[Theta]"}]
}},Alignment->{Center,Center}]]
],
{{ptctrl,Pi/6,"angle"},0,2Pi},TrackedSymbols:>{ptctrl}]
triangolorett[] :=
Grid[{{
Graphics[{
(* INIZIALIZZAZIONE PUNTI *)
p11 = {-1,0};
p22 = {1,0};
p33 = {Cos[Pi/4],Sin[Pi/4]};
hp33 = {p33[[1]],0};
(* TRIANGOLO *)
{Opacity[0.1],Cyan,EdgeForm[Directive[Thick,Cyan]],Triangle[{p11,hp33, p33}]},
(* ARCO SU C *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p11,0.2, angolo[p33,p22, p11]]},
{Darker[Green,0.2],Thick,Circle[p11,0.2, angolo[p33,p22, p11]]},
(* ANGOLO RETTO *)
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{hp33[[1]]-0.1, 0},{hp33[[1]]-0.1, 0.1},{hp33[[1]], 0.1},hp33}]},
{Darker[Green,0.3],Line[{{hp33[[1]]-0.1, 0},{hp33[[1]]-0.1, 0.1},{hp33[[1]], 0.1}}]},
(* h *)
{Black,Disk[hp33,0.02]},
(* PUNTI *)
(* A *) {Black,Disk[p33,0.02]},
(* C *) {Black,Disk[p11,0.02]},
(* TESTO *)
Text["A",{p33[[1]], p33[[2]]+0.1}],
Text["C",{p11[[1]]-0.1, p11[[2]]}],
Text["B",{hp33[[1]], hp33[[2]]-0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]], {p11[[1]]+0.3, p11[[2]]+0.06}]
},PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->{0.20,0}]
}},Frame->Directive[Lighter[Gray,0.5]]]
tangente[] :=
Manipulate[
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
(* punti *)
{Black,Disk[{1, Tan[th]},0.02]},
{Black,Disk[{0, Tan[th]},0.02]},
{Black,Disk[{1,0},0.02]},
(* tangente punto *)
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* angolo *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Circle[{0,0},0.3,{0,th}]},
(* linea tratteggiata per Tan *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{1,3},{1,Tan[th]-3}}]},
(* linea tratteggiata per Tan 2*)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{-3,Tan[th]},{3,Tan[th]}}]},
(* TESTO *)
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text["T",{1.1,Tan[th]+0.1}],
Text["Xt",{1.1,0.1}],
Text["Yt",{0.1,Tan[th]+0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}],
Rotate[Text[Style["Tan(\[Theta])",Orange],{1.1,Tan[th]/2}],90\[Degree]],
(* TAN *)
(* tan *)
{Orange,Thick,Line[{{1,0},{1,Tan[th]}}]},
{Orange,Thickness[0.008],Dashing[Medium],Line[{{0,0},{0,Tan[th]}}]},
}],
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->True,Ticks->Automatic,PlotRangePadding->0.25];
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]},pt2={ptctrl,0}},
Grid[{
{LocatorPane[Dynamic[pt,
{(pt={1,Tan[ptctrl]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
Dynamic[anglegraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]
],
LineLegend[{Orange},{"Tan"}]
}},Alignment->{Center,Center}]]
],
{{ptctrl,Pi/6,"angle"},0,2Pi},TrackedSymbols:>{showvalue,ptctrl}]
definizionetangente[] :=
Manipulate[
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
(* punti *)
{Black,Disk[{Cos[th], 0},0.02]},
{Black,Disk[{1, Tan[th]},0.02]},
{Black,Disk[{0, 0},0.02]},
{Black,Disk[{1, 0},0.02]},
(* tangente punto *)
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* arco *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Circle[{0,0},0.3,{0,th}]},
(* triangolo sin cos *)
{Opacity[0.2],Cyan,Thick,EdgeForm[Directive[Thick,Cyan]], Triangle[{{0,0},{Cos[th],Sin[th]},{Cos[th],0}}]},
(* triangolo tan *)
{Opacity[0.2],Magenta,Thick,EdgeForm[Directive[Magenta]], Triangle[{{0,0},{1,0},{1,Tan[th]}}]},
(* cos sin angolo 90\[Degree] *)
If[th<= Pi/2 ,
{
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{Cos[th]-0.1, 0},{Cos[th]-0.1, 0.1},{Cos[th], 0.1},{Cos[th], 0}}]},
{Darker[Green,0.3],Line[{{Cos[th]-0.1, 0},{Cos[th]-0.1, 0.1},{Cos[th], 0.1}}]}
},
{If[ th <= Pi,
{
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{Cos[th]+0.1, 0},{Cos[th]+0.1, 0.1},{Cos[th], 0.1},{Cos[th], 0}}]},
{Darker[Green,0.3],Line[{{Cos[th]+0.1, 0},{Cos[th]+0.1, 0.1},{Cos[th], 0.1}}]}
},
{If[ th <=(3*Pi)/2,
{
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{Cos[th]+0.1, 0},{Cos[th]+0.1, -0.1},{Cos[th], -0.1},{Cos[th], 0}}]},
{Darker[Green,0.3],Line[{{Cos[th]+0.1, 0},{Cos[th]+0.1, -0.1},{Cos[th], -0.1}}]}
},
{{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{Cos[th]-0.1, 0},{Cos[th]-0.1, -0.1},{Cos[th], -0.1},{Cos[th], 0}}]},
{Darker[Green,0.3],Line[{{Cos[th]-0.1, 0},{Cos[th]-0.1, -0.1},{Cos[th], -0.1}}]
}
}]
}]
}],
(* tan angolo 90\[Degree] *)
If[th<= Pi/2 || (th > Pi && th <= (3*Pi)/2),
{
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{0.9, 0},{0.9, 0.1},{1, 0.1},{1, 0}}]},
{Darker[Green,0.3],Line[{{0.9, 0},{0.9, 0.1},{1, 0.1}}]}
},
{{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{0.9, 0},{0.9, -0.1},{1, -0.1},{1, 0}}]},
{Darker[Green,0.3],Line[{{0.9, 0},{0.9, -0.1},{1, -0.1}}]}
}],
(* retta tratteggiata passante per P *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th],Sin[th]-3},{Cos[th],3}}]},
(* retta tratteggiata tangente *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{1, -3},{1, 3}}]},
(* TESTO *)
Text["H",{Cos[th]+0.1,0.1}],
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text["O",{-0.1,0.1}],
Text["K",{1.1,0.1}],
Text["T",{1.1,Tan[th]+0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}],
Rotate[Text[Style["Tan(\[Theta])",Orange],{1.1,Tan[th]/2}],90\[Degree]],
(* TAN *)
{Orange,Thick,Line[{{1,0},{1,Tan[th]}}]},
}],
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->True,Ticks->Automatic,PlotRangePadding->0.25];
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]},pt2={ptctrl,0}},
Grid[{
{LocatorPane[Dynamic[pt,
{(pt={Cos[pt2[[1]]],Sin[pt2[[1]]]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
Dynamic[anglegraph[If[pt2=={2Pi,0},2Pi,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]]
],
LineLegend[{Orange,Darker[Green,0.3]},{"Tan", "\[Theta]"}]
}},Alignment->{Center,Center}]]
],
{{ptctrl,Pi/6,"angle"},0,2Pi},TrackedSymbols:>{showvalue,ptctrl}]
angolinoti30[] :=
Manipulate[
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
(* punti *)
{Black,Disk[{Cos[th], 0},0.02]},
{Black,Disk[{0, Sin[th]},0.02]},
(* tangente punto *)
{Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* angolo *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Circle[{0,0},0.3,{0,th}]},
(* linea tratteggiata per cos *)
{Lighter[Gray,0.5],,Dashing[Medium],Line[{{Cos[th]-3,Sin[th]},{3,Sin[th]}}]},
(* linea tratteggiata per sin *)
{Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th],Sin[th]-3},{Cos[th],3}}]},
(* TESTO *)
Text["Xp",{Cos[th]+0.1,0.1}],
Text["Yp",{0.1,Sin[th]+0.1}],
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}],
Text[Style["Cos(\[Theta])",Blue],{Cos[th]/2,-0.1}],
Rotate[Text[Style["Sin(\[Theta])",Red],{-0.1,Sin[th]/2}],90\[Degree]],
(* SEN COS TAN *)
(* sin *)
{Red,Thickness[0.008],Line[{{0,0},{0,Sin[th]}}]},
{Red,,Dashing[Medium],Line[{{Cos[th],0},{Cos[th],Sin[th]}}]},
(* cos *)
{Blue,Thickness[0.008],Line[{{0, 0},{Cos[th],0}}]},
{Blue,Dashing[Medium],Line[{{0,Sin[th]},{Cos[th],Sin[th]}}]},
{
If[th != Pi/2 && th != 3Pi/2,
(* tan *) {
{Orange,Thick,Line[{{1,0},{1,Tan[th]}}]},
{Orange,Thickness[0.008],Dashing[Medium],Line[{{0,0},{0,Tan[th]}}]}
},
{}
]}
}],
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->True,Ticks->Automatic,PlotRangePadding->0.25];
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]}},
Labeled[Grid[{
{LocatorPane[Dynamic[pt,
{(pt=Normalize[#]) &,
(pt=Normalize[#])&,
(pt=Normalize[#];ptctrl=If[#=={2Pi,0},Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]])&}],
Dynamic[anglegraph[Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]],Enabled->False],
LineLegend[{Darker[Green,0.3],Red, Blue,Orange},{Row[{Style["\[Theta]"]}],Row@{"Sin(\[Theta]) = ",pt[[2]]},Row@{"Cos(\[Theta]) = ",pt[[1]]}, Row@{"Tan(\[Theta]) = ",Tan[ptctrl]}},LegendMarkerSize->40, LabelStyle->15]
}},Alignment->{Center,Center}],{Row[{Style["","Label",20,Gray],Text@Style["\[Theta] = ",Darker[Green,0.3],20],Style[(ptctrl*360)/(2*Pi),Darker[Green,0.3],25]}],
Style["",10,Lighter[Gray,0.7],"Label"]},{{Top,Left},{Bottom,Right}}]]
],
{{ptctrl,Pi/6,""},0,2Pi,Pi/6},TrackedSymbols:>{showvalue,ptctrl}]
angolinoti45[]:=
Manipulate[
Module[{anglegraph,maingraph},
anglegraph[th_]:=Show[
Graphics[{
{Lighter[Gray,0.5],Circle[{0,0},1]},
(* {Darker[Green,0.2],Thick,Circle[{0,0},1,{0,th}]}, *)
{Lighter[Gray,0.5],Line[{{0,0},{Cos[th],Sin[th]}}]},
{Black,Disk[{Cos[th], 0},0.02]},
{Black,Disk[{0, Sin[th]},0.02]},
(* tangente punto *) {Lighter[Gray,0.5],Line[{{-6Cos[th],-6Sin[th]},{6Cos[th],6Sin[th]}}]},
(* angolo *) {Opacity[0.2],Darker[Green,0.3],Thick,Disk[{0,0},0.3,{0,th}]},
{Darker[Green,0.3],Circle[{0,0},0.3,{0,th}]},
(* linea tratteggiata per cos *){Lighter[Gray,0.5],,Dashing[Medium],Line[{{Cos[th]-3,Sin[th]},{3,Sin[th]}}]},
(* linea tratteggiata per sin *){Lighter[Gray,0.5],Dashing[Medium],Line[{{Cos[th],Sin[th]-3},{Cos[th],3}}]},
(* TESTO *)
Text["Xp",{Cos[th]+0.1,0.1}],
Text["Yp",{0.1,Sin[th]+0.1}],
Text["P",{Cos[th] +0.1,Sin[th]+0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]],{0.2,0.1}],
Text[Style["Cos(\[Theta])",Blue],{Cos[th]/2,-0.1}],
Rotate[Text[Style["Sin(\[Theta])",Red],{-0.1,Sin[th]/2}],90\[Degree]],
(* SEN COS TAN *)
(* sin *) {Red,Thickness[0.008],Line[{{0,0},{0,Sin[th]}}]},
{Red,,Dashing[Medium],Line[{{Cos[th],0},{Cos[th],Sin[th]}}]},
(* cos *) {Blue,Thickness[0.008],Line[{{0, 0},{Cos[th],0}}]},
{Blue,Dashing[Medium],Line[{{0,Sin[th]},{Cos[th],Sin[th]}}]},
{
If[th != Pi/2 && th != 3Pi/2,
(* tan *) {
{Orange,Thick,Line[{{1,0},{1,Tan[th]}}]},
{Orange,Thickness[0.008],Dashing[Medium],Line[{{0,0},{0,Tan[th]}}]}
},{}
]}
}],
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->True,Ticks->Automatic,PlotRangePadding->0.25];
DynamicModule[{pt={Cos[ptctrl],Sin[ptctrl]}},
Labeled[Grid[{
{LocatorPane[Dynamic[pt,
{(pt=Normalize[#]) &,
(pt=Normalize[#])&,
(pt=Normalize[#];ptctrl=If[#=={2Pi,0},Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]])&}],
Dynamic[anglegraph[Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]],Enabled->False],
LineLegend[{Darker[Green,0.3],Red, Blue,Orange},{Row[{Style["\[Theta]"]}],Row@{"Sin(\[Theta]) = ",pt[[2]]},Row@{"Cos(\[Theta]) = ",pt[[1]]}, Row@{"Tan(\[Theta]) = ",Tan[ptctrl]}},LegendMarkerSize->40, LabelStyle->15]
}},Alignment->{Center,Center}],
{Row[{Style["","Label",20,Gray],Text@Style["\[Theta] = ",Darker[Green,0.3],20],Style[(ptctrl*360)/(2*Pi),Darker[Green,0.3],25]}],
Style["",10,Lighter[Gray,0.7],"Label"]},{{Top,Left},{Bottom,Right}}]]
],
{{ptctrl,Pi/4,""},0,2Pi,Pi/4},TrackedSymbols:>{ptctrl}]
teoremacorda[] :=
Grid[{{
Graphics[{
(* CIRCONFERENZA *)
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[pc,0.2, angolo[pa,pb, pc]]},
{Darker[Green,0.2],Thick,Circle[pc,0.2, angolo[pa,pb, pc]]},
(* TRIANGOLO *)
{Opacity[0],Black ,EdgeForm[Black], Triangle[{pa,pb,pc}]},
(* RAGGIO *)
{Black,Dashing[Medium],Line[{{0,0},pb}]},
(* CORDA *)
{Red,Thick,Line[{pa,pb}]},
{Black,Disk[{0, 0},0.02]},
(* PUNTI *)
(* A *)
{Black,Disk[pa,0.02]},
(* B *)
{Black,Disk[{Cos[0-0.2], Sin[0-0.2]},0.02]},
(* C *)
{Black,Disk[pc,0.02]},
(* TESTO *)
Text[" A",{pa[[1]],pa[[2]]+0.1}],
Text[" B",{Cos[0], Sin[-0.3]}],
Text[" C", {pc[[1]]-0.15, pc[[2]]}],
Text["r",{0.4,-0.15}],
Text[Style["\[Theta]",Darker[Green,0.3]], {pc[[1]]+0.1, pc[[2]]+0.1}]
},PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->0.25]
, LineLegend[{Darker[Green,0.3],Red},{"\[Theta]","Corda"},LegendMarkerSize->40, LabelStyle->15]
}},Frame->Directive[Lighter[Gray,0.5]]]
teoremacorda2[]:=
Manipulate[
Module[{anglegraph},
anglegraph[a_,b_,th_]:=Module[{anga},
anga={ArcTan[(Sin[th] -a[[2]])/(Cos[th]-a[[1]])] ,ArcTan[(Sin[th] -b[[2]])/(Cos[th]-b[[1]])] };
Show[
Graphics[{
(* CIRCONFERENZA *)
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Purple,Thick,Circle[{0, 0},1, {Pi/2-a[[1]], 2Pi+b[[2]]}]},
{If[ Cos[th] >b[[1]] && Cos[th] > a[[1]],
{
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{Cos[th], Sin[th]},0.2,{anga[[1]]+Pi,anga[[2]]+Pi } ]},
Darker[Green,0.2],Thick,Circle[{Cos[th], Sin[th]},0.2,{anga[[1]]+Pi,anga[[2]]+Pi } ]
},
{If[ Cos[th] <b[[1]] && Cos[th] < a[[1]],
{
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{Cos[th], Sin[th]},0.2,{anga[[1]],anga[[2]] } ]},
Darker[Green,0.2],Thick,Circle[{Cos[th], Sin[th]},0.2,{anga[[1]],anga[[2]]} ]
},
{If[ Sin[th] <b[[2]] && Cos[th] > a[[1]] && Cos[th]< b[[1]],
{
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{Cos[th], Sin[th]},0.2,{anga[[1]]+Pi,anga[[2]] } ]},
Darker[Green,0.2],Thick,Circle[{Cos[th], Sin[th]},0.2,{anga[[1]] +Pi,anga[[2]]} ]
},
{If[ Sin[th] >b[[2]] && Cos[th] > a[[1]] && Cos[th]< b[[1]],
{
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{Cos[th], Sin[th]},0.2,{anga[[1]]-Pi,anga[[2]] } ]},
Darker[Green,0.2],Thick,Circle[{Cos[th], Sin[th]},0.2,{anga[[1]]-Pi,anga[[2]]} ]
},{}
]}
]}
]}
]},
(* TRIANGOLO *)
{Opacity[0],Black ,EdgeForm[Black], Triangle[{a,b,{Cos[th], Sin[th]}}]},
(* RAGGIO *)
{Black,Dashing[Medium],Line[{{0,0},b}]},
(* CORDA *)
{Red,Thick,Line[{a,b}]},
(* PUNTO *)
{Black,Disk[{0, 0},0.02]},
(* PUNTI *)
(* A *)
{Black,Disk[a,0.02]},
(* B *)
{Black,Disk[{Cos[0-0.2], Sin[0-0.2]},0.02]},
(* C *)
{Black,Disk[{Cos[th], Sin[th]},0.02]},
(* TESTO *)
Text[" A",{a[[1]],a[[2]]+0.1}],
Text[" B",{Cos[0], Sin[-0.3]}],
Text[" C", {Cos[th]-0.15, Sin[th]}],
Text["r",{0.4,-0.15}],
Text[Style["\[Theta]",Darker[Green,0.3]], {Cos[th]+0.1, Sin[th]+0.1}]
}],PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->0.25]];
DynamicModule[{pt={Cos[ptctrl], Sin[ptctrl]},pt2={ptctrl,0}},
Grid[{
{LocatorPane[Dynamic[pt,
{(pt={Cos[pt2[[1]]],Sin[pt2[[1]]]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
Dynamic[anglegraph[pa,pb,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]],
pcc ={Sin[ ptctrl], Cos[ptctrl]};
LineLegend[{Darker[Green,0.3],Red,},{"\[Theta]","Corda"},LegendMarkerSize->40, LabelStyle->15]
}},Spacings->0]]
],
{{ptctrl,Pi +0.5,"angle"},0,2Pi},TrackedSymbols:>{ptctrl}]
teoremacorda3[]:=
Manipulate[
Module[{anglegraph},
anglegraph[a_,b_,c_,th_]:=Module[{anga},
anga={ArcTan[(Sin[th] -a[[2]])/(Cos[th]-a[[1]])] ,ArcTan[(Sin[th] -b[[2]])/(Cos[th]-b[[1]])] };
Show[
Graphics[{
(* CIRCONFERENZA *)
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Lighter[Magenta,0.5],Thick,Circle[{0, 0},1, {Pi/2, b[[2]]}]},
{If[ Cos[th] >b[[1]] && Cos[th] > a[[1]],
{
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{Cos[th], Sin[th]},0.2,{anga[[1]]+Pi,anga[[2]]+Pi } ]},
Darker[Green,0.2],Thick,Circle[{Cos[th], Sin[th]},0.2,{anga[[1]]+Pi,anga[[2]]+Pi } ]
},
{If[ Cos[th] <b[[1]] && Cos[th] < a[[1]],
{
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{Cos[th], Sin[th]},0.2,{anga[[1]],anga[[2]] } ]},
Darker[Green,0.2],Thick,Circle[{Cos[th], Sin[th]},0.2,{anga[[1]],anga[[2]]} ]
},
{{If[ Sin[th] <b[[2]] && Cos[th] > a[[1]] && Cos[th]< b[[1]],
{
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{Cos[th], Sin[th]},0.2,{anga[[1]]+Pi,anga[[2]] } ]},
Darker[Green,0.2],Thick,Circle[{Cos[th], Sin[th]},0.2,{anga[[1]] +Pi,anga[[2]]} ]
},
{If[ Sin[th] >b[[2]] && Cos[th] > a[[1]] && Cos[th]< b[[1]],
{
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{Cos[th], Sin[th]},0.2,{anga[[1]]-Pi,anga[[2]] } ]},
Darker[Green,0.2],Thick,Circle[{Cos[th], Sin[th]},0.2,{anga[[1]]-Pi,anga[[2]]} ]
},{}
]}
]}}
]}
]},
(* ANGOLO C*)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[c,0.2,{Pi/2, ArcTan[(c[[2]] -b[[2]])/(c[[1]]-b[[1]])]} ]},
{Darker[Green,0.2],Thick,Circle[c,0.2,{Pi/2, ArcTan[(c[[2]] -b[[2]])/(c[[1]]-b[[1]])]} ]},
(* TRIANGOLO *)
{Opacity[0],Black ,EdgeForm[Black], Triangle[{a,b,c}]},
{Opacity[0],Black ,EdgeForm[Black], Triangle[{a,b,{Cos[th], Sin[th]}}]},
(* ANGOLO RETTO *)
{Rotate[
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{b[[1]]-0.1,b[[2]]},{b[[1]]-0.1,b[[2]]+0.1},{b[[1]],b[[2]]+0.1},b}]},ArcTan[(b[[2]] -c[[2]])/(b[[1]]-c[[1]])],b
]},
{Rotate[
{Darker[Green,0.3],Line[{{b[[1]]-0.1,b[[2]]},{b[[1]]-0.1,b[[2]]+0.1},{b[[1]],b[[2]]+0.1}}]}, ArcTan[(b[[2]] -c[[2]])/(b[[1]]-c[[1]])],b
]},
(* RAGGIO *)
{Black,Dashing[Medium],Line[{{0,0},b}]},
(* CORDA *)
{Red,Thick,Line[{a,b}]},
(* PUNTO *)
{Black,Disk[{0, 0},0.02]},
(* PUNTI *)
(* A *) {Black,Disk[a,0.02]},
(* B *) {Black,Disk[b,0.02]},
(* C *) {Black,Disk[c,0.02]},
(* TESTO *)
Text[" A",{ a[[1]],a[[2]]+0.1}],
Text[" B",{ b[[1]]+0.1,b[[2]]}],
Text[" C",{ c[[1]],c[[2]]-0.1}],
Text[" D", {Cos[th]+ 0.1, Sin[th]}],
Text[Style["\[Delta]",Darker[Green,0.3]], {Cos[th]-0.1, Sin[th]-0.1}],
Text[Style["\[Theta]",Darker[Green,0.3]], c+0.1],
Text["r",{0.4,-0.15}]
}],PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->0.25]];
DynamicModule[{pt={Cos[ptctrl], Sin[ptctrl]},pt2={ptctrl,0}},
Grid[{
{LocatorPane[Dynamic[pt,
{(pt={Cos[pt2[[1]]],Sin[pt2[[1]]]})&,
(pt=Normalize[#];pt2={If[pt2=={2Pi,0},2Pi,Mod[ArcTan[#[[1]],#[[2]]],2 Pi]],0})&,
(pt=Normalize[#];ptctrl=pt2[[1]])&}],
Dynamic[anglegraph[pa2,pb2,pc2,Mod[ArcTan[pt[[1]],pt[[2]]],2 Pi]]]],
pcc ={Sin[ ptctrl], Cos[ptctrl]};
LineLegend[{Darker[Green,0.3],Red},{Row@{"\[Delta]"},"Coda"},LegendMarkerSize->40]
}},Alignment->{Center,Center}]]
],{{ptctrl,0.4,"angle"},0,2Pi},TrackedSymbols:>{ptctrl}]
teoremaseni[] :=
Grid[{{
Graphics[{
(* CIRCONFERENZA *)
{Lighter[Gray,0.5],Circle[{0,0},1]},
(* ARCO SU C *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[pc,0.2, angolo[pa,pb, pc]]},
{Darker[Green,0.2],Thick,Circle[pc,0.2, angolo[pa,pb, pc]]},
(* ARCO SU B *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[pb,0.2, angolo[pa,pc, pb]+Pi]},
{Darker[Green,0.2],Thick,Circle[pb,0.2, angolo[pa,pc, pb]+Pi]},
(* ARCO SU A *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[pa,0.2, {angolo[pc,pb, pa][[1]]-Pi,angolo[pc,pb, pa][[2]]}]},
{Darker[Green,0.2],Thick,Circle[pa,0.2,{angolo[pc,pb, pa][[1]]-Pi,angolo[pc,pb, pa][[2]]}]},
(* TRIANGOLO *)
{Opacity[0.1],Cyan,EdgeForm[Directive[Thick,Cyan]], Triangle[{pa,pb,pc}]},
(* RAGGIO *)
{Black,Dashing[Medium],Line[{{0,0},pb}]},
(* PUNTI *)
(* CENTRO *){Black,Disk[{0, 0},0.02]},
(* A *) {Black,Disk[pa,0.02]},
(* B *) {Black,Disk[{Cos[0-0.2], Sin[0-0.2]},0.02]},
(* C *) {Black,Disk[pc,0.02]},
(* TESTO *)
Text["A",{pa[[1]],pa[[2]]+0.1}],
Text["B",{pb[[1]]+0.1, pb[[2]]}],
Text["C", {pc[[1]]-0.1, pc[[2]]}],
Text["r",{0.4,-0.15}],
Text[Style["\[Theta]",Darker[Green,0.3]], {pc[[1]]+0.1, pc[[2]]+0.1}],
Text[Style["\[Beta]",Darker[Green,0.3]], {pb[[1]]-0.1, pb[[2]]+0.1}],
Text[Style["\[Alpha]",Darker[Green,0.3]], {pa[[1]]+0.05, pa[[2]]-0.1}]
},
(* MISURE PLOT *)
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->0.25]
}},Frame->Directive[Lighter[Gray,0.5]]]
teoremacoseno[]:=
Grid[{{
Graphics[{
(* INIZIALIZZAZIONE PUNTI *)
p11 = {-1,0};
p22 = {1,0};
p33 = {Cos[Pi/4],Sin[Pi/4]};
(* TRIANGOLO *)
{Opacity[0.1],Cyan,EdgeForm[Directive[Thick,Cyan]],Triangle[{p11,p22, p33}]},
(* ARCO SU A *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p33,0.2, angolo[p11,p22, p33]-Pi/2]},
{Darker[Green,0.2],Thick,Circle[p33,0.2, angolo[p11,p22, p33]-Pi/2]},
(* ARCO SU B *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p22,0.2, angolo[p11,p33, p22]+Pi]},
{Darker[Green,0.2],Thick,Circle[p22,0.2, angolo[p11,p33, p22]+Pi]},
(* ARCO SU C *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p11,0.2, angolo[p33,p22, p11]]},
{Darker[Green,0.2],Thick,Circle[p11,0.2, angolo[p33,p22, p11]]},
(* PUNTI *)
(* A *) {Black,Disk[p33,0.02]},
(* B *) {Black,Disk[p22,0.02]},
(* C *) {Black,Disk[p11,0.02]},
(* TESTO *)
Text["A",{p33[[1]], p33[[2]]+0.1}],
Text["B",{p22[[1]]+0.1, p22[[2]]}],
Text["C",{p11[[1]]-0.1, p11[[2]]}],
Text[Style["\[Alpha]",Darker[Green,0.3]], {p33[[1]]-0.05, p33[[2]]-0.1}],
Text[Style["\[Beta]",Darker[Green,0.3]], {p22[[1]]-0.1, p22[[2]]+0.1}],
Text[Style["\[Gamma]",Darker[Green,0.3]], {p11[[1]]+0.3, p11[[2]]+0.06}]
},
(* MISURE PLOT *)
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->{0.20,0}]
}},Frame->Directive[Lighter[Gray,0.5]]]
teoremacoseno2[]:=
Grid[{{
Graphics[{
(* INIZIALIZZAZIONE PUNTI *)
p11 = {-1,0};
p22 = {1,0};
p33 = {Cos[Pi/4],Sin[Pi/4]};
hp33 = {p33[[1]],0};
(* TRIANGOLO *)
{Opacity[0.1],Cyan,EdgeForm[Directive[Thick,Cyan]],Triangle[{p11,p22, p33}]},
(* ARCO SU A *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p33,0.2, angolo[p11,p22, p33]-Pi/2]},
{Darker[Green,0.2],Thick,Circle[p33,0.2, angolo[p11,p22, p33]-Pi/2]},
(* ARCO SU B *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p22,0.2, angolo[p11,p33, p22]+Pi]},
{Darker[Green,0.2],Thick,Circle[p22,0.2, angolo[p11,p33, p22]+Pi]},
(* ARCO SU C *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p11,0.2, angolo[p33,p22, p11]]},
{Darker[Green,0.2],Thick,Circle[p11,0.2, angolo[p33,p22, p11]]},
(* ANGOLO RETTO *)
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{hp33[[1]]-0.1, 0},{hp33[[1]]-0.1, 0.1},{hp33[[1]], 0.1},hp33}]},
{Darker[Green,0.3],Line[{{hp33[[1]]-0.1, 0},{hp33[[1]]-0.1, 0.1},{hp33[[1]], 0.1}}]},
(* PUNTI *)
(* h *) {Black,Dashing[Medium],Line[{hp33,p33}]},
(* Ph *) {Black,,Disk[hp33,0.02]},
(* A *) {Black,Disk[p33,0.02]},
(* B *) {Black,Disk[p22,0.02]},
(* C *) {Black,Disk[p11,0.02]},
(* TESTO *)
Text["A",{p33[[1]], p33[[2]]+0.1}],
Text["B",{p22[[1]]+0.1, p22[[2]]}],
Text["C",{p11[[1]]-0.1, p11[[2]]}],
Text["D",{hp33[[1]], hp33[[2]]-0.1}],
Text["h",{hp33[[1]]-0.05, p33[[2]]/2}],
Text[Style["\[Alpha]",Darker[Green,0.3]], {p33[[1]]-0.05, p33[[2]]-0.1}],
Text[Style["\[Beta]",Darker[Green,0.3]], {p22[[1]]-0.1, p22[[2]]+0.1}],
Text[Style["\[Gamma]",Darker[Green,0.3]], {p11[[1]]+0.3, p11[[2]]+0.06}]
},
(* MISURE PLOT *)
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->{0.20,0}]
}},Frame->Directive[Lighter[Gray,0.5]]]
pitagora[]:=
Grid[{{
Graphics[{
(* INIZIALIZZAZIONE PUNTI *)
p11 = {-1,0};
p22 = {1,0};
p33 = {Cos[Pi/4],Sin[Pi/4]};
hp33 = {p33[[1]],0};
(* TRIANGOLO *)
{Opacity[0.1],Cyan,EdgeForm[Directive[Thick,Cyan]],Triangle[{p11,hp33, p33}]},
(* ARCO SU A *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p33,0.2, {angolo[p11,hp33, p33][[1]]+Pi,3Pi/2}]},
{Darker[Green,0.2],Thick,Circle[p33,0.2, {angolo[p11,hp33, p33][[1]]+Pi,3Pi/2}]},
(* ARCO SU C *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[p11,0.2, angolo[p33,hp33, p11]]},
{Darker[Green,0.2],Thick,Circle[p11,0.2, angolo[p33,hp33, p11]]},
(* ANGOLO RETTO *)
{Opacity[0.2],Darker[Green,0.3],Thick,Polygon[{{hp33[[1]]-0.1, 0},{hp33[[1]]-0.1, 0.1},{hp33[[1]], 0.1},hp33}]},
{Darker[Green,0.3],Line[{{hp33[[1]]-0.1, 0},{hp33[[1]]-0.1, 0.1},{hp33[[1]], 0.1}}]},
(* PUNTI *)
(* h *) {Black,Disk[hp33,0.02]},
(* A *) {Black,Disk[p33,0.02]},
(* C *) {Black,Disk[p11,0.02]},
(* TESTO *)
Text["A",{p33[[1]], p33[[2]]+0.1}],
Text["C",{p11[[1]]-0.1, p11[[2]]}],
Text["B",{hp33[[1]], hp33[[2]]-0.1}],
Text[Style["\[Alpha]",Darker[Green,0.3]], {p33[[1]]-0.05, p33[[2]]-0.1}],
Text[Style["\[Beta]",Darker[Green,0.3]], {hp33[[1]]-0.15, hp33[[2]]+0.15}],
Text[Style["\[Gamma]",Darker[Green,0.3]], {p11[[1]]+0.3, p11[[2]]+0.06}]
},
(* MISURE PLOT*)
PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->{0.20,0}]
}, { Row[{" Se l'angolo \[EGrave] retto il coseno ha valore = 1, \nquindi otteniamo il teorema di pitagora: \!\(\*SuperscriptBox[\(AB\), \(2\)]\) + \!\(\*SuperscriptBox[\(BC\), \(2\)]\) = \!\(\*SuperscriptBox[\(AC\), \(2\)]\)"}]}},Frame->Directive[Lighter[Gray,0.5]]]
(*######################### ESERCIZI ##############################*)
EsercizioEsempio[]:=
Module[{},
datiEsempio = StringJoin[Style["A = 25 \nC = 50",FontFamily-> "OpenDyslexic",Bold],Style["\nTrovare sen(\[Alpha])",FontColor->Red,FontFamily-> "OpenDyslexic",Bold]];
risoluzioneEsempio =Panel[Style[" Sin(\[Alpha]) = \!\(\*FractionBox[\(A\), \(C\)]\) = \!\(\*FractionBox[\(\(\\\ \\\ \)\(25\)\(\\\ \)\), \(\(\\\ \)\(50\)\)]\) = \!\(\*FractionBox[\(\(\\\ \)\(1\)\(\\\ \)\), \(2\)]\)",FontFamily-> "OpenDyslexic"]];
Grid[{{Text[Style["Esempio 1:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(*Disegno del triangolo*)
{Magnify[Graphics[{
(* triangle
Line[{{0, 0}, {0,1}, {2, 0}, {0, 0}}],
right angle symbol
Line[{{0, 0.1}, {0.1, 0.1}, {0.1, 0}}],
angle symbol
Circle[{2, 0}, 0.2, {145.5 Degree, 182.5 Degree}],
Circle[{0,1},0.2,{260 Degree,340 Degree}],*)
(* ANGOLO RETTANGOLO *)
{Opacity[0.2],Darker[Green,0.3],Polygon[{{0, 0.1}, {0.1, 0.1}, {0.1, 0},{0, 0}}]},
{Darker[Green,0.3],Line[{{0, 0.1}, {0.1, 0.1}, {0.1, 0}}]},
(* ANGOLO IN (2,0) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{2, 0}, 0.2, angolo[{0, 0}, {0, 1}, {2, 0}]+Pi]},
{Darker[Green,0.2], Circle[{2, 0}, 0.2, angolo[{0, 0}, {0,1}, {2, 0}]+Pi]},
(* ANGOLO IN (0,1) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{0, 1}, 0.2, {angolo[{2, 0}, {0, 0}, {0, 1}][[1]]+2Pi,3Pi/2}]},
{Darker[Green,0.2], Circle[{0, 1}, 0.2, {angolo[{2, 0}, {0, 0}, {0, 1}][[1]]+2Pi,3Pi/2}]},
(* triangle *)
{Opacity[0],EdgeForm[Directive[Black]],Triangle[{{0, 0}, {0,1}, {2, 0}}]},
(* labels *)
Rotate[
Text[Style["A", 15,FontFamily-> "OpenDyslexic"],{-0.1, 0.5}], 0 Degree],
Text[Style["B", 15,FontFamily-> "OpenDyslexic"],{0.7, -0.1}],
Text[Style["C", 15,FontFamily-> "OpenDyslexic"],{1, 0.6}, {-1, 0}],
Text[Style["\[Alpha]", 10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"], {1.7, 0.08}],
Text[Style["\[Theta]",10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.085,0.75}],
Text[Style["90\[Degree]",10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.2,0.2}]
}],2],
(*Vengono stampati i dati del problema*)
Magnify[Apply[StringJoin,ToString[#,StandardForm]&/@datiEsempio],1],Text[""]},
(*Viene stampata la risoluzione dell'esempio*)
{Text[Style["Procedimento:",17,FontColor -> Red,FontFamily-> "OpenDyslexic"]]},{Text[" "],Magnify[risoluzioneEsempio,2]}}
,Alignment-> {Left,Center},Spacings -> {5,5},Dividers->{{},{3 -> Red}}]
]
(*Modulo che controlla la correttezza di una risposta data dall'utente*)
CheckAnswer[answer_,correct_]:=
DynamicModule[{},
If[answer == "",
Text[""], (*Se la risposta \[EGrave] vuota stampo nulla *)
If[answer == correct,
(*Se la risposta \[EGrave] corretta stampa un segno di spunta verde verde*)
Style["\[Checkmark]",FontColor->Green],
(*Se la risposta \[EGrave] sbagliata stampa una X rossa*)
Style["X",FontColor->Red,Bold],
Text[""]],
Text[""]]
(*If[answer == correct,Style["\[Checkmark]",FontColor->Green],Style["X",FontColor->Red,Bold],Text[""]]*)
]
(*Esercizio1 *)
Esercizio1[]:=
Module[{},
datiEsercizioGuidato = StringJoin[Style["A = 40 \nB = 110",FontFamily-> "OpenDyslexic",Bold],
Style["\nTrovare sen(\[Alpha]),cos(\[Alpha]),tan(\[Alpha]) e l'angolo \[Alpha]",FontColor->Red,FontFamily-> "OpenDyslexic",Bold,FontSize->14]];
risoluzioneEsercizioGuidatoPasso1 = Row[{TPitagora[],
(*Style[
"\n",
"Applico il teorema \[LongRightArrow] \!\(\*SuperscriptBox[\(A\), \(2\)]\) + ",FontFamily-> "OpenDyslexic"],
Dynamic[InputField[Dynamic[catetoNome],String,FieldSize-> 1]],
"\!\(\*SuperscriptBox[\(\\\ \), \(2\)]\) ",
Dynamic[CheckAnswer[catetoNome,"B"]],
" = ",
InputField[Dynamic[ipotenusaNome],String,FieldSize-> 1] ,
"\!\(\*SuperscriptBox[\(\\\ \), \(\(2\)\(\\\ \\\ \\\ \)\)]\)",
Dynamic[CheckAnswer[ipotenusaNome,"C"]],
Style["\n \n",FontFamily-> "OpenDyslexic"],*)
"\n",
Style["Applico il teorema \[LongRightArrow] \!\(\*SuperscriptBox[\(A\), \(2\)]\) + ",FontFamily->"OpenDyslexic"],
Dynamic[InputField[Dynamic[catetoNome],String,FieldSize-> 1]],
"\!\(\*SuperscriptBox[\(\\\ \), \(2\)]\) ",
Dynamic[CheckAnswer[catetoNome,"B"]],
" = ",
InputField[Dynamic[ipotenusaNome],String,FieldSize-> 1] ,
"\!\(\*SuperscriptBox[\(\\\ \), \(\(2\)\(\\\ \\\ \\\ \)\)]\)",
Dynamic[CheckAnswer[ipotenusaNome,"C"]],
"\n \n",
Style["Sostituisco i valori \[LongRightArrow] \!\(\*SuperscriptBox[\(40\), \(2\)]\) + ",FontFamily-> "OpenDyslexic"],
InputField[Dynamic[catetoValore],String,FieldSize-> 3],
"\!\(\*SuperscriptBox[\(\\\ \), \(2\)]\) ",
Dynamic[CheckAnswer[catetoValore,"110"]],
" = \!\(\*SuperscriptBox[\(C\), \(2\)]\)\n",
"\n",
Style["Ricavo C \[LongRightArrow] C = ",FontFamily-> "OpenDyslexic"],
SqrtBox[Row[{"\!\(\*SuperscriptBox[\(A\), \(2\)]\) + ",
InputField[Dynamic[catetoBNome],String,FieldSize-> 1],
"\!\(\*SuperscriptBox[\(\\\ \), \(\(2\)\(\\\ \\\ \\\ \\\ \)\)]\)"}]] // DisplayForm,
Dynamic[CheckAnswer[catetoBNome,"B"]],"\n \n",
Style["Approssima il risultato per difetto!\n\n",FontFamily-> "OpenDyslexic"],
Style["Calcolo C \[LongRightArrow] C = ",FontFamily-> "OpenDyslexic"],
SqrtBox[Row[{InputField[Dynamic[catetoAValore],String,FieldSize-> 2],
"\!\(\*SuperscriptBox[\(\\\ \), \(\(2\)\(\\\ \\\ \\\ \\\ \)\)]\)",
Dynamic[CheckAnswer[catetoAValore,"40"]],
" + ",
InputField[Dynamic[catetoBValore],String,FieldSize-> 3],
"\!\(\*SuperscriptBox[\(\\\ \), \(\(2\)\(\\\ \\\ \)\)]\)",
Dynamic[CheckAnswer[catetoBValore,"110"]]}]] // DisplayForm,
" = ",
InputField[Dynamic[ipotenusaValore],String,FieldSize->3],
Dynamic[CheckAnswer[ipotenusaValore,"117"]]
}];
risoluzioneEsercizioGuidatoPasso2 = Row[{Style["sen(\[Alpha]) = ",FontFamily-> "OpenDyslexic"],
(Style["A",FontFamily-> "OpenDyslexic"])/InputField[Dynamic[ipotenusaSenCNome],String,FieldSize->2],
Dynamic[CheckAnswer[ipotenusaSenCNome,"C"]],
" = ",
(Style["40",FontFamily-> "OpenDyslexic"])/InputField[Dynamic[ipotenusaSenValore],String,FieldSize->3],
Dynamic[CheckAnswer[ipotenusaSenValore,"117"]]}];
risoluzioneEsercizioGuidatoPasso3 = Row[{Style["cos(\[Alpha]) = ",FontFamily-> "OpenDyslexic"],
(Style["B",FontFamily-> "OpenDyslexic"])/InputField[Dynamic[ipotenusaCosCNome],String,FieldSize->2],
Dynamic[CheckAnswer[ipotenusaCosCNome,"C"]],
" = ",
(Style["110",FontFamily-> "OpenDyslexic"])/InputField[Dynamic[ipotenusaCosValore],String,FieldSize->3],
Dynamic[CheckAnswer[ipotenusaCosValore,"117"]]}];
risoluzioneEsercizioGuidatoPasso4 = Row[{Style["tan(\[Alpha]) = ",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[senNome],String,FieldSize->3],Style["(\[Alpha])",FontFamily-> "OpenDyslexic"]}]/(Style["cos(\[Alpha])",FontFamily-> "OpenDyslexic"]),
Dynamic[CheckAnswer[senNome,"sen"]],
"\n",
Style["Sostituisco i valori di seno e coseno trovati ai passi 2 e 3: ",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[senValoreNum],String,FieldSize->3],Dynamic[CheckAnswer[senValoreNum,"40"]]}]/Row[ {InputField[Dynamic[senValoreDen],String,FieldSize->3],Dynamic[CheckAnswer[senValoreDen,"117"]]}],
"/",
Row[{InputField[Dynamic[cosValoreNum],String,FieldSize->3],Dynamic[CheckAnswer[cosValoreNum,"110"]]}]/Row[{InputField[Dynamic[cosValoreDen],String,FieldSize->3],Dynamic[CheckAnswer[cosValoreDen,"117"]]}],
"\n",
Style["Ricorda! La divisione tra due frazioni\ndiventa la prima frazione moltiplicata per l'inversa della seconda:",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[senValoreNum2],String,FieldSize->3],Dynamic[CheckAnswer[senValoreNum2,"40"]]}]/Row[ {InputField[Dynamic[senValoreDen2],String,FieldSize->3],Dynamic[CheckAnswer[senValoreDen2,"117"]]}],
"\[CenterDot]",
Row[{InputField[Dynamic[cosValoreNum2],String,FieldSize->3],Dynamic[CheckAnswer[cosValoreNum2,"117"]]}]/Row[{InputField[Dynamic[cosValoreDen2],String,FieldSize->3],Dynamic[CheckAnswer[cosValoreDen2,"110"]]}],
"\n",
Style["Dopo aver eseguito la moltiplicazione tra le due frazioni ottengo:",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[resNum],String,FieldSize->3],Dynamic[CheckAnswer[resNum,"40"]]}]/Row[{InputField[Dynamic[resDen],String,FieldSize->3],Dynamic[CheckAnswer[resDen,"110"]]}],
"\n",
Style["Semplifico ai minimi termini la frazione e ottengo:",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[resNum2],String,FieldSize->3],Dynamic[CheckAnswer[resNum2,"4"]]}]/Row[{InputField[Dynamic[resDen2],String,FieldSize->3],Dynamic[CheckAnswer[resDen2,"11"]]}]
}];
risoluzioneEsercizioGuidatoPasso5 =Row[{Style["\[Alpha] = \!\(\*SuperscriptBox[\(sen\), \(-1\)]\)(",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[senValoreNum3],String,FieldSize->3],Dynamic[CheckAnswer[senValoreNum3,"40"]]}]/Row[{InputField[Dynamic[senValoreDen3],String,FieldSize->3],Dynamic[CheckAnswer[senValoreDen3,"117"]]}],")"}];
Grid[{{Text[Style["Esercizio Guidato:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(*Disegno del triangolo *)
{Magnify[Graphics[{
(* ANGOLO RETTANGOLO *)
{Opacity[0.2],Darker[Green,0.3],Polygon[{{0, 0.1}, {0.1, 0.1}, {0.1, 0},{0, 0}}]},
{Darker[Green,0.3],Line[{{0, 0.1}, {0.1, 0.1}, {0.1, 0}}]},
(* ANGOLO IN (2,0) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{2, 0}, 0.2, angolo[{0, 0}, {0, 1}, {2, 0}]+Pi]},
{Darker[Green,0.2], Circle[{2, 0}, 0.2, angolo[{0, 0}, {0,1}, {2, 0}]+Pi]},
(* ANGOLO IN (0,1) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{0, 1}, 0.2, {angolo[{2, 0}, {0, 0}, {0, 1}][[1]]+2Pi,3Pi/2}]},
{Darker[Green,0.2], Circle[{0, 1}, 0.2, {angolo[{2, 0}, {0, 0}, {0, 1}][[1]]+2Pi,3Pi/2}]},
(* triangle *)
{Opacity[0],EdgeForm[Directive[Black]],Triangle[{{0, 0}, {0,1}, {2, 0}}]},
(* labels *)
Rotate[
Text[Style["A", 15,FontFamily-> "OpenDyslexic"],
{-0.1, 0.5}], 0 Degree],
Text[Style["B", 15,FontFamily-> "OpenDyslexic"],
{0.7, -0.1}],
Text[Style["C", 15,FontFamily-> "OpenDyslexic"],
{1, 0.6}, {-1, 0}],
Text[Style["\[Alpha]", 10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"], {1.7, 0.08}],
Text[Style["\[Beta]",10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.085,0.75}],
Text[Style["90\[Degree]",10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.2,0.2}]
}],2]
(*Vengono stampati i dati dell'esercizio*)
,Magnify[Apply[StringJoin,ToString[#,StandardForm]&/@datiEsercizioGuidato],1],Text[""]},
{Text[Style["Procedimento:",17,FontColor -> Red,FontFamily-> "OpenDyslexic"]]},
(*Viene stampato il passo 1 dell'esercizio*)
{Text[Style["Passo 1: Cerchiamo l'ipotenusa C.\n Applico il Teorema di Pitagora:",Bold,15,FontFamily-> "OpenDyslexic"]]},
{Text[""],Panel[Magnify[risoluzioneEsercizioGuidatoPasso1,2]]},
(*Viene stampato il passo 2 dell'esercizio*)
{Text[Style["Passo 2: Cerchiamo sen(\[Alpha]).\nAttenzione: nei passaggi,\nprima sostituisci le lettere,\npoi i valori corrispondenti.",Bold,15,FontFamily-> "OpenDyslexic"]]},
{Text[""],Panel[Magnify[risoluzioneEsercizioGuidatoPasso2,2]]},
(*Viene stampato il passo 3 dell'esercizio*)
{Text[Style["Passo 3: Cerchiamo cos(\[Alpha]).",Bold,15,FontFamily-> "OpenDyslexic"]]},
{Text[""],Panel[Magnify[risoluzioneEsercizioGuidatoPasso3,2]]},
(*Viene stampato il passo 4 dell'esercizio*)
{Text[Style["Passo 4: Cerchiamo tan(\[Alpha]).",Bold,15,FontFamily-> "OpenDyslexic"]]},
{Text[""],Panel[Magnify[risoluzioneEsercizioGuidatoPasso4,2]]},
(*Viene stampato il passo 5 dell'esercizio*)
{Text[Style["Passo 5: Cerchiamo \[Alpha].",Bold,15,FontFamily-> "OpenDyslexic"]]},
{Text[""],Panel[Magnify[risoluzioneEsercizioGuidatoPasso5,2]]}
},Alignment-> {Left,Center},Spacings -> {1,1}]
]
Esercizio2[]:=
Module[{catAd = "",catOp = "",catOp2= "",A= ""},
datiEsercizio2 = StringJoin[Style["B = 30 \ntan(\[Beta]) = \!\(\*FractionBox[\(3\), \(5\)]\)",FontFamily-> "OpenDyslexic",Bold],Style["\nTrovare A",FontColor->Red,FontFamily-> "OpenDyslexic",Bold]];
Grid[{{Text[Style["Esercizio 2:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(* Disegno il triangolo *)
{Magnify[Graphics[{
(* ANGOLO RETTANGOLO *)
{Opacity[0.2],Darker[Green,0.3],Polygon[{{0, 0.1}, {0.1, 0.1}, {0.1, 0},{0, 0}}]},
{Darker[Green,0.3],Line[{{0, 0.1}, {0.1, 0.1}, {0.1, 0}}]},
(* ANGOLO IN (0.7,0) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{0.7, 0}, 0.2, angolo[{0, 0}, {0,1.3}, {0.7, 0}]+Pi]},
{Darker[Green,0.2], Circle[{0.7, 0}, 0.2, angolo[{0, 0}, {0,1.3}, {0.7, 0}]+Pi]},
(* ANGOLO IN (0,1.3) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{0, 1.3}, 0.2, {angolo[{0.7, 0}, {0, 0}, {0, 1.3}][[1]]+2Pi,3Pi/2}]},
{Darker[Green,0.2], Circle[{0, 1.3}, 0.2, {angolo[{0.7, 0}, {0, 0}, {0, 1.3}][[1]]+2Pi,3Pi/2}]},
(* triangle *)
{Opacity[0],EdgeForm[Directive[Black]],Triangle[{{0, 0}, {0,1.3}, {0.7, 0}}]},
(* labels *)
Rotate[
Text[Style["A", 15,FontFamily-> "OpenDyslexic"],
{-0.1, 0.5}], 0 Degree],
Text[Style["B", 15,FontFamily-> "OpenDyslexic"],
{0.3, -0.1}],
Text[Style["C", 15,FontFamily-> "OpenDyslexic"],
{0.5, 0.6}, {-1, 0}],
Text[Style["\[Beta]",10, Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.085,1.0}],
Text[Style["\[Alpha]", 10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"], {0.6, 0.08}],
Text[Style["90\[Degree]",10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.15,0.15}]
}],2],
Magnify[Apply[StringJoin,ToString[#,StandardForm]&/@datiEsercizio2],1]},
{Text[Style["Procedimento:",17,FontColor -> Red,FontFamily-> "OpenDyslexic"]]},
(* Viene stampato il suggerimento *)
{Text[Style["Ricorda! tan\[Beta] =\!\(\*FractionBox[\(\(\\\ \)\(cateto\\\ opposto\)\), \(cateto\\\ adiacente\)]\)",Bold,20,FontFamily-> "OpenDyslexic"]]},
(* Prima domanda *)
{Text[Style["Qual \[EGrave] il cateto adiacente?",Bold,20,FontFamily-> "OpenDyslexic"]],
Magnify[RadioButtonBar[Dynamic[catAd],{"A","B","C"}],1.5],
Magnify[Dynamic[CheckAnswer[catAd,"A"]],3]},
(* Seconda domanda *)
{Text[Style["Qual \[EGrave] il cateto opposto?",Bold,20,FontFamily-> "OpenDyslexic"]],
Magnify[RadioButtonBar[Dynamic[catOp],{"A","B","C"}],1.5],
Magnify[Dynamic[CheckAnswer[catOp,"B"]],3]},
(* Terza domanda *)
{Style["Completa i passaggi\ned osserva i suggerimenti proposti: ",FontFamily->"OpenDyslexic",Bold,FontSize->20]},
{Magnify[Row[{Text[Style["tan\[Beta] = ",FontFamily-> "OpenDyslexic"]],
Row[{InputField[Dynamic[catOp2],String,FieldSize->1],Dynamic[CheckAnswer[catOp2,"B"]]}]/Row[{InputField[Dynamic[catAd2],String,FieldSize->1],Dynamic[CheckAnswer[catAd2,"A"]]}],
Text[Style[" \[LongRightArrow] A\[CenterDot]tan(\[Beta]) = B \[LongRightArrow] A = \!\(\*FractionBox[\(\(\\\ \)\(B\)\), \(tan \((\[Beta])\)\)]\)",FontFamily-> "OpenDyslexic"]]}],1.5],SpanFromLeft},
(* Quarta domanda *)
{Text[Style["Quanto vale A?",Bold,20,FontFamily-> "OpenDyslexic"]],
Magnify[RadioButtonBar[Dynamic[A],{"50","18","2"}],1.5],
Magnify[Dynamic[CheckAnswer[A,"50"]],3]}
},Alignment-> {Left,Center},Spacings -> {10,1}]
]
Esercizio3[]:=
Module[{},
Grid[{{Text[Style["Esercizio 3:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(* Disegno del triangolo inscritto nella circonferenza*)
{Graphics[{
(* CIRCONFERENZA *)
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[pc,0.2, angolo[pa,pb, pc]]},
{Darker[Green,0.2],Thick,Circle[pc,0.2, angolo[pa,pb, pc]]},
(* TRIANGOLO *)
{Opacity[0],Black ,EdgeForm[Black], Triangle[{{Cos[(Pi/2)+0.3], Sin[(Pi/2)+0.3]},{Cos[0-0.2], Sin[0-0.2]},{Cos[Pi+0.5], Sin[Pi+0.5]}}]},
(* RAGGIO *)
{Black,Dashing[Medium],Line[{{0,0},pb}]},
(* CORDA *)
{Red,Thick,Line[{{Cos[(Pi/2)+0.3], Sin[(Pi/2)+0.3]},{Cos[0-0.2], Sin[0-0.2]}}]},
{Black,Disk[{0, 0},0.02]},
(* PUNTI *)
(* A *)
{Black,Disk[{Cos[(Pi/2)+0.3], Sin[(Pi/2)+0.3]},0.02]},
(* B *)
{Black,Disk[{Cos[0-0.2], Sin[0-0.2]},0.02]},
(* C *)
{Black,Disk[{Cos[Pi+0.5], Sin[Pi+0.5]},0.02]},
(* TESTO *)
Text[Style[" A",FontFamily-> "OpenDyslexic"],{Cos[(Pi/2)+0.4], Sin[(Pi/2)]}],
Text[Style[" B",FontFamily-> "OpenDyslexic"],{Cos[0], Sin[0-0.3]}],
Text[Style[" C",FontFamily-> "OpenDyslexic"],{Cos[Pi+0.2], Sin[Pi+0.6]}],
Text[Style["\[Theta]",Darker[Green,0.2],FontFamily-> "OpenDyslexic"],{Cos[Pi+0.9],Sin[11/6 Pi+0.2]}],
Text[Style["r",FontFamily-> "OpenDyslexic"],{0.4,-0.15}]
},PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->0.25]
(* Vengono stampati i dati dell'esercizio *)
,Magnify[Row[{Style["r = 2\n\[Theta] = \!\(\*SuperscriptBox[\(60\), \(o\)]\)\n",FontFamily->"OpenDyslexic",Bold],Style["Trovare \!\(\*OverscriptBox[\(AB\), \(_\)]\)",FontColor->Red,FontFamily -> "OpenDyslexic",Bold]}],1.5]},
{Text[Style["Procedimento:",17,FontColor -> Red,FontFamily-> "OpenDyslexic"]]},
(* Risoluzione dell'esercizio *)
{Magnify[ Panel[
Row[{Text[Style["\!\(\*OverscriptBox[\(AB\), \(_\)]\) = 2\[CenterDot] ",FontFamily-> "OpenDyslexic"]],
Row[{InputField[Dynamic[raggio],String,FieldSize->1],Dynamic[CheckAnswer[raggio,"2"]]}],
Style[" \[CenterDot] sen(",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[angolo],String,FieldSize->1.8],"\!\(\*SuperscriptBox[\(\\\ \), \(o\)]\)",Dynamic[CheckAnswer[angolo,"60"]]}],
") = ",
Row[{InputField[Dynamic[AB],String,FieldSize->1],Dynamic[CheckAnswer[AB,"4"]]}],
"\[CenterDot]",
Row[{SqrtBox[InputField[Dynamic[num],String,FieldSize->1]]// DisplayForm,Dynamic[CheckAnswer[num,"3"]]}] /Row[{InputField[Dynamic[den],String,FieldSize->1],Dynamic[CheckAnswer[den,"2"]]}],
" = ",
Row[{InputField[Dynamic[coef],String,FieldSize->1],Dynamic[CheckAnswer[coef,"2"]]}],
" \[CenterDot]",
Row[{SqrtBox[InputField[Dynamic[coef2],String,FieldSize->1]]// DisplayForm,Dynamic[CheckAnswer[coef2,"3"]]}]
}]],2]}
},Alignment-> {Left,Center},Spacings -> {10,5}]
]
Esercizio4[]:=
Module[{AB2=""},
Grid[{{Text[Style["Esercizio 4:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(*Disegno del triangolo inscritto nella circonferenza *)
{Graphics[{
(* CIRCONFERENZA *)
{Lighter[Gray,0.5],Circle[{0,0},1]},
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[pc,0.2, angolo[pa,pb, pc]]},
{Darker[Green,0.2],Thick,Circle[pc,0.2, angolo[pa,pb, pc]]},
(* TRIANGOLO *)
{Opacity[0],Black ,EdgeForm[Black], Triangle[{{Cos[(Pi/2)+0.3], Sin[(Pi/2)+0.3]},{Cos[0-0.2], Sin[0-0.2]},{Cos[Pi+0.5], Sin[Pi+0.5]}}]},
(* RAGGIO *)
{Black,Dashing[Medium],Line[{{0,0},pb}]},
(* CORDA *)
{Red,Thick,Line[{{Cos[(Pi/2)+0.3], Sin[(Pi/2)+0.3]},{Cos[0-0.2], Sin[0-0.2]}}]},
{Black,Disk[{0, 0},0.02]},
(* PUNTI *)
(* A *)
{Black,Disk[{Cos[(Pi/2)+0.3], Sin[(Pi/2)+0.3]},0.02]},
(* B *)
{Black,Disk[{Cos[0-0.2], Sin[0-0.2]},0.02]},
(* C *)
{Black,Disk[{Cos[Pi+0.5], Sin[Pi+0.5]},0.02]},
(* TESTO *)
Text[Style[" A",FontFamily-> "OpenDyslexic"],{Cos[(Pi/2)+0.4], Sin[(Pi/2)]}],
Text[Style[" B",FontFamily-> "OpenDyslexic"],{Cos[0], Sin[0-0.3]}],
Text[Style[" C",FontFamily-> "OpenDyslexic"],{Cos[Pi+0.2], Sin[Pi+0.6]}],
Text[Style["\[Theta]",Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{Cos[Pi+0.9],Sin[11/6 Pi+0.2]}],
Text[Style["r",FontFamily-> "OpenDyslexic"],{0.4,-0.15}]
},PlotRange->1,ImageSize-> 400,BaseStyle->{15},Axes->False,PlotRangePadding->0.25]
(* Dati del problema*)
,Magnify[Row[{Style["r = 5\n\[Theta] = \!\(\*SuperscriptBox[\(60\), \(o\)]\)\n",FontFamily -> "OpenDyslexic",Bold],
Style["Trovare \!\(\*OverscriptBox[\(AB\), \(_\)]\)",FontColor->Red,FontFamily -> "OpenDyslexic",Bold]}]
,1],
Text[""]},
(* Domanda a risposta multipla *)
{Text[Style["Quindi il lato \!\(\*OverscriptBox[\(AB\), \(_\)]\) misura:",20,FontFamily-> "OpenDyslexic",Bold]],
Magnify[RadioButtonBar[Dynamic[AB2],{"\!\(\*FractionBox[\(5\), \(2\)]\)","\!\(\*FractionBox[\(5\), \(2\)]\)\!\(\*SqrtBox[\(3\)]\)","5\*SqrtBox[\(3\)]","30"}],1.5],
Magnify[Dynamic[CheckAnswer[AB2,"5\*SqrtBox[\(3\)]"]],3]}
},Alignment-> {Left,Center},Spacings -> {1,5}]
]
Esercizio8[]:=
Module[{res5 ="",val13="",val14=""},
datiEsercizio8 = StringJoin[Style["A = 24 \nC = 12\!\(\*SqrtBox[\(3\)]\)\nB = 12",FontFamily -> "OpenDyslexic",Bold],Style["\nTrovare cos(\[Gamma])",FontColor -> Red,FontFamily -> "OpenDyslexic",Bold]];
Grid[{{Text[Style["Esercizio 8:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(* Disegno del triangolo *)
{Magnify[Graphics[{
(* ARCO SU (1,0) *)
{Opacity[0.2],Darker[Green,0.3],Thick,Disk[{1, 0}, 0.15, angolo[{-0.2, 0}, {-0.5, 1}, {1, 0}]+Pi]},
{Darker[Green,0.2],Circle[{1, 0}, 0.15, angolo[{-0.2, 0}, {-0.5, 1}, {1, 0}]+Pi]},
(* triangle *)
{Opacity[0],EdgeForm[Directive[Black]], Triangle[{{-0.2, 0}, {-0.5, 1}, {1, 0}, {-0.2, 0}}]},
(* labels *)
Rotate[
Text[Style["C", 10,FontFamily-> "OpenDyslexic"],
{-0.4, 0.4}], 0 Degree],
Text[Style["A", 10,FontFamily-> "OpenDyslexic"],
{0.3, -0.1}],
Text[Style["B", 10,FontFamily-> "OpenDyslexic"],
{0.2, 0.6}, {-0.4, 0}],
Text[Style["\[Gamma]",10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.8,0.08}]
}],2]
(* Vengono stampati i dati dell'esercizio *)
,Magnify[Apply[StringJoin,ToString[#,StandardForm]&/@datiEsercizio8],1.2],Text[""]},
{Text[Style["Procedimento:",17,FontColor -> Red,FontFamily-> "OpenDyslexic"]]},
(* Suggerimento del teorema di Carnot *)
{Text[Style["Ricorda! \!\(\*SuperscriptBox[\(C\), \(2\)]\) = \!\(\*SuperscriptBox[\(B\), \(2\)]\) + \!\(\*SuperscriptBox[\(A\), \(2\)]\) - 2A\[CenterDot]B cos(\[Gamma])",Bold,20,FontFamily-> "OpenDyslexic"]]},
(* Primo passaggio dell'esercizio *)
{Magnify[Row[{Style["cos(\[Gamma]) = \!\(\*FractionBox[\(\(\\\ \)\(\*SuperscriptBox[\(B\), \(2\)]\\\ + \\\ \*SuperscriptBox[\(A\), \(2\)]\\\ - \\\ \*SuperscriptBox[\(C\), \(2\)]\)\), \(2 A\[CenterDot]B\)]\) = ",FontFamily-> "OpenDyslexic",Bold],
Row[{InputField[Dynamic[val13],String,FieldSize->2],Dynamic[CheckAnswer[val13,"12"]],Style["\!\(\*SuperscriptBox[\(\\\ \), \(2\)]\) + 576 - 432",FontFamily->"OpenDyslexic",Bold]}]/Row[{Style["2 \[CenterDot]",Bold,FontFamily->"OpenDyslexic"], InputField[Dynamic[val14],String,FieldSize->3],Dynamic[CheckAnswer[val14,"288"]]}]
}],1]},
(* Conclusione delle'esercizio *)
{Style["Quindi cos(\[Gamma]) misura:",17,Bold,FontFamily-> "OpenDyslexic"],
Magnify[Row[{RadioButtonBar[Dynamic[res5],{"\!\(\*FractionBox[\(1\), \(2\)]\)","\!\(\*FractionBox[SqrtBox[\(3\)], \(2\)]\)","-\!\(\*FractionBox[\(1\), \(2\)]\)","-\!\(\*FractionBox[SqrtBox[\(3\)], \(2\)]\)"}]," ",Dynamic[CheckAnswer[res5,"\!\(\*FractionBox[\(1\), \(2\)]\)"]]
}],1]}
},Alignment->{Left,Center},Spacings -> {10,5}]]
Esercizio5[] :=
Module[{esatt3 = ""},
datiEsercizio5 = StringJoin[Style["A = 6 \n\[Alpha] = \!\(\*SuperscriptBox[\(30\), \(o\)]\)\n\[Beta] = \!\(\*SuperscriptBox[\(105\), \(o\)]\)",FontFamily-> "OpenDyslexic",Bold],Style["\nTrovare C",FontColor->Red,FontFamily-> "OpenDyslexic",Bold]];
Grid[{{Text[Style["Esercizio 5:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(* Disegno il triangolo *)
{Magnify[Graphics[{
(* ARCO SU (0,0) *)
{Opacity[0.2],Darker[Green,0.3],Disk[{0, 0}, 0.12, {angolo[{0.7, 0}, {-1,1}, {0, 0}][[2]]+Pi, 0} ]},
{Darker[Green,0.2],Circle[{0, 0} ,0.12, {angolo[{0.7, 0}, {-1,1}, {0, 0}][[2]]+Pi, 0}]},
(* ARCO SU (0.7, 0) *)
{Opacity[0.2],Darker[Green,0.3],Disk[{0.7, 0}, 0.2, angolo[{0, 0}, {-1,1}, {0.7, 0}]+Pi]},
{Darker[Green,0.2],Circle[{0.7, 0}, 0.2, angolo[{0, 0}, {-1,1}, {0.7, 0}]+Pi]},
(* ARCO SU (-1,1) *)
{Opacity[0.2],Darker[Green,0.3],Disk[{-1,1}, 0.2, angolo[{0, 0}, {0.7, 0}, {-1,1}]]},
{Darker[Green,0.2],Circle[{-1,1}, 0.2, angolo[{0, 0}, {0.7, 0}, {-1,1}]]},
(* triangle *)
{Opacity[0],EdgeForm[Directive[Black]], Triangle[{{0, 0}, {-1,1}, {0.7, 0}}]},
(* labels *)
Rotate[
Text[Style["C", 10,FontFamily-> "OpenDyslexic"],
{-0.6, 0.4}], 0 Degree],
Text[Style["A", 10,FontFamily-> "OpenDyslexic"],
{0.3, -0.1}],
Text[Style["B", 10,FontFamily-> "OpenDyslexic"],
{0.1, 0.6}, {-0.5, 0}],
Text[Style["\[Alpha]",10,Darker[Green,0.2],FontFamily-> "OpenDyslexic"],{-0.8,1.0}],
Text[Style["\[Beta]",10,Darker[Green,0.2],FontFamily-> "OpenDyslexic"],{0.1,0.15}],
Text[Style["\[Gamma]",10,Darker[Green,0.2],FontFamily-> "OpenDyslexic"],{0.4,0.1}]
}],2]
(* Stampo i dati dell'esercizio *)
,Magnify[Apply[StringJoin,ToString[#,StandardForm]&/@datiEsercizio5],1],Text[""]},
{Text[Style["Procedimento:",17,FontColor -> Red,FontFamily-> "OpenDyslexic"]]},
(* Primo passo dell'esercizio *)
{Magnify[Row[{Text[Style["Calcolare l'ampiezza dell'angolo \[Gamma]: \!\(\*SuperscriptBox[\(180\), \(o\)]\)-(",FontFamily-> "OpenDyslexic",Bold]],
InputField[Dynamic[ott],String,FieldSize->2],
Style["\!\(\*SuperscriptBox[\(\\\ \), \(o\)]\)",FontFamily-> "OpenDyslexic"],
(* Dynamic[CheckAnswer[ott,"105"]], *)
Dynamic[esatt3],
Style["+",FontFamily-> "OpenDyslexic"],
InputField[Dynamic[al],String,FieldSize->2],
"\!\(\*SuperscriptBox[\(\\\ \), \(o\)]\)",
(* Dynamic[CheckAnswer[al,"30"]], *)
(* Per la propriet\[AGrave] commutativa *)
Dynamic[ If[(ott == "") || (al == ""),
esatt3 = Text[""];
Text[""],
If[(ott == "105" && al == "30") || (ott == "30" && al == "105"),
esatt3 = Style["\[Checkmark]",FontColor->Green];
Style["\[Checkmark]",FontColor->Green],
esatt3 = Style["X",FontColor->Red,Bold];
Style["X",FontColor->Red,Bold],
esatt3 = Text[""];
Text[""]],
esatt3 = Text[""];
Text[""]]
],
Style[") = ",FontFamily-> "OpenDyslexic"],
InputField[Dynamic[res2],String,FieldSize->2],
Dynamic[CheckAnswer[res2,"45"]],
Style["\!\(\*SuperscriptBox[\(\\\ \), \(o\)]\)",FontFamily-> "OpenDyslexic"]}],
1],SpanFromLeft},
(* Suggerimento *)
{Magnify[Text[Style["Utilizzare la relazione \!\(\*FractionBox[\(\(A\)\(\\\ \)\), \(sen \((\[Alpha])\)\)]\) =\!\(\*FractionBox[\(\(\\\ \)\(C\)\), \(sen \((\[Gamma])\)\)]\)",FontFamily-> "OpenDyslexic",Bold]],1]},
(* Secondo passo dell'esercizio *)
{Text[""],
Magnify[ Panel[
Row[{Style["6",FontFamily-> "OpenDyslexic"]/Row[{Style["sen(",FontFamily-> "OpenDyslexic"],InputField[Dynamic[al2],String,FieldSize->2],"\!\(\*SuperscriptBox[\(\\\ \), \(o\)]\))",Dynamic[CheckAnswer[al2,"30"]]}],
Style[" = ",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[c],String,FieldSize->2],Dynamic[CheckAnswer[c,"C"]]}]/(Style["sen(\!\(\*SuperscriptBox[\(45\), \(o\)]\))",FontFamily-> "OpenDyslexic"]),Style[" \[LongRightArrow] ",FontFamily-> "OpenDyslexic"], Style[" 6 / ",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[num3],String,FieldSize->1],Dynamic[CheckAnswer[num3,"1"]]}]/Row[{InputField[Dynamic[den3],String,FieldSize->1],Dynamic[CheckAnswer[den3,"2"]]}],
Style[" = ",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[num4],String,FieldSize->1],Dynamic[CheckAnswer[num4,"C"]]}],
Style[" /\!\(\*FractionBox[\(\(\\\ \)\*SqrtBox[\(2\)]\), \(2\)]\)",FontFamily-> "OpenDyslexic"]}]],
2]},
(* Terzo passo dell'esercizio *)
{Magnify[Text[Style["Ricavare:",FontFamily-> "OpenDyslexic",Bold]],1]},
{Text[""],
Magnify[ Panel[
Row[{Style["C = 6",FontFamily-> "OpenDyslexic"],
Row[{SqrtBox[InputField[Dynamic[num5],String,FieldSize->1]]//DisplayForm,Dynamic[CheckAnswer[num5,"2"]]}]/Row[{InputField[Dynamic[den5],String,FieldSize->1],Dynamic[CheckAnswer[den5,"2"]]}],
" / ",
Row[{InputField[Dynamic[num6],String,FieldSize->1],Dynamic[CheckAnswer[num6,"1"]]}]/Row[{InputField[Dynamic[den6],String,FieldSize->1],Dynamic[CheckAnswer[den6,"2"]]}],
" = ",
InputField[Dynamic[res3],String,FieldSize->1],
Dynamic[CheckAnswer[res3,"6"]],
SqrtBox[Row[{InputField[Dynamic[res41],String,FieldSize->1],
Dynamic[CheckAnswer[res41,"2"]]}]] // DisplayForm }]],2
]}
},Alignment->{Left,Center},Spacings -> {1,5}]
]
(*Esercizio 6*)
Esercizio6[]:=
Module[{res4=""},
datiEsercizio6 = StringJoin[Style["A = 12 \nB = 9\n\[Beta] = \!\(\*SuperscriptBox[\(30\), \(o\)]\)",FontFamily-> "OpenDyslexic",Bold],Style["\nTrovare sen(\[Alpha])",FontColor->Red,FontFamily-> "OpenDyslexic",Bold]];
Grid[{{Text[Style["Esercizio 6:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(* Disegno del triangolo *)
{Magnify[Graphics[{
(* ANGOLO IN (0,0) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{0, 0}, 0.2, angolo[{2, 0}, {1.3, 1}, {0, 0}]]},
{Darker[Green,0.2], Circle[{0, 0}, 0.2, angolo[{2, 0}, {1.3, 1}, {0, 0}]]},
(* ANGOLO IN (2,0) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{2, 0}, 0.2, angolo[{0, 0}, {1.3, 1}, {2, 0}]+Pi]},
{Darker[Green,0.2], Circle[{2, 0}, 0.2, angolo[{0, 0}, {1.3,1}, {2, 0}]+Pi]},
(* ANGOLO IN (1.3,1) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{1.3, 1}, 0.2, {angolo[{2, 0}, {0, 0}, {1.3, 1}][[1]], angolo[{2, 0}, {0, 0}, {1.3, 1}][[2]]-Pi}]},
{Darker[Green,0.2], Circle[{1.3, 1}, 0.2, {angolo[{2, 0}, {0, 0}, {1.3, 1}][[1]], angolo[{2, 0}, {0, 0}, {1.3, 1}][[2]]-Pi}]},
(* triangle *)
{Opacity[0],EdgeForm[Directive[Black]], Triangle[{{0, 0}, {1.3,1}, {2, 0}}]},
(* labels *)
Rotate[
Text[Style["B", 10,FontFamily-> "OpenDyslexic"],
{0.6, 0.6}], 0 Degree],
Text[Style["C", 10,FontFamily-> "OpenDyslexic"],
{1, -0.1}],
Text[Style["A", 10,FontFamily-> "OpenDyslexic"],
{1.65, 0.6}, {-1, 0}],
Text[Style["\[Beta]", 10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"], {1.7, 0.1}],
Text[Style["\[Gamma]",10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{1.3,0.75}],
Text[Style["\[Alpha]",10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.3, 0.1}]
}],2]
(* Stampo i dati dell'esercizio *)
,Magnify[Apply[StringJoin,ToString[#,StandardForm]&/@datiEsercizio6],1.4],Text[""]},
{Text[Style["Procedimento:",17,FontColor -> Red,FontFamily-> "OpenDyslexic"]]},
(* Suggerimento *)
{Text[Style["Ricorda! \!\(\*FractionBox[\(A\), \(sen \((\[Alpha])\)\)]\) =\!\(\*FractionBox[\(\(B\)\(\\\ \)\), \(sen \((\[Beta])\)\)]\) =\!\(\*FractionBox[\(\(\\\ \)\(C\)\), \(sen \((\[Gamma])\)\)]\)",FontSize->20,Bold,FontFamily-> "OpenDyslexic"]]},
(* Domanda a risposta multipla*)
{Text[Style["Quanto misura sen(\[Alpha])?",Bold,20,FontFamily-> "OpenDyslexic"]],
Magnify[RadioButtonBar[Dynamic[res4],{"\!\(\*FractionBox[\(3\), \(2\)]\)","\!\(\*FractionBox[\(2\), \(3\)]\)","\!\(\*FractionBox[\(2\), \(3\)]\)\!\(\*SqrtBox[\(3\)]\)","\!\(\*FractionBox[\(3\), \(2\)]\)\!\(\*SqrtBox[\(3\)]\)"}],2],
Magnify[Dynamic[CheckAnswer[res4,"\!\(\*FractionBox[\(2\), \(3\)]\)"]],3]}
},Alignment->{Left,Center},Spacings -> {10,5}]
]
(*Esercizio 9*)
Esercizio9[]:=
Module[{},
Grid[{{Text[Style["Esercizio 9:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(* Stampo foto esercizio *)
{Magnify[Sharpen[Import["campanile.jpeg"]],4],
Magnify[
Row[{Style["Trovare H,\ndove H \[EGrave] l'altezza\ndel campanile\n",FontFamily-> "OpenDyslexic",FontColor->Red,FontFamily-> "OpenDyslexic"],
Style["Approssimare il risultato per difetto\n",FontFamily -> "OpenDyslexic",FontColor-> Red,8],
Style["tan(",FontFamily-> "OpenDyslexic"],InputField[Dynamic[tang],String,FieldSize-> 2],
Dynamic[CheckAnswer[tang,"42"]],"\!\(\*SuperscriptBox[\(\\\ \), \(\[Degree]\)]\)) = ",
Row[{InputField[Dynamic[altezza],String,FieldSize->2],Dynamic[CheckAnswer[altezza,"H"]]}]/Row[{InputField[Dynamic[base],String,FieldSize-> 2],Dynamic[CheckAnswer[base,"80"]]}],
Style[" \nH = ",FontFamily-> "OpenDyslexic"],Row[{InputField[Dynamic[base2],String,FieldSize-> 2],Dynamic[CheckAnswer[base2,"80"]]}],
Style[" \[CenterDot] tan(",FontFamily-> "OpenDyslexic"],
Row[{InputField[Dynamic[altezza2],String,FieldSize-> 2],Dynamic[CheckAnswer[altezza2,"42"]]}],
"\!\(\*SuperscriptBox[\(\\\ \), \(\[Degree]\)]\)) = ",
Row[{InputField[Dynamic[altezza3],String,FieldSize-> 2],Dynamic[CheckAnswer[altezza3,"72"]]}]}],
1.5]}
},Alignment->{Left,Center},Spacings -> {10,5}]
]
(*Esercizio 7*)
Esercizio7[] :=
Module[{G7="",esatt = "",esatt2 = ""},
datiEsercizio7 = StringJoin[Style["A = 2 \nB = 3\n\[Gamma] = \!\(\*SuperscriptBox[\(60\), \(o\)]\)",FontFamily -> "OpenDyslexic",Bold],Style["\nTrovare C",FontColor->Red,FontFamily -> "OpenDyslexic",Bold]];
Grid[{{Text[Style["Esercizio 7:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
{Magnify[Graphics[{
(* ANGOLO IN (0,0) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{0, 0}, 0.2, angolo[{1.8, 0}, {0.8, 1}, {0, 0}]]},
{Darker[Green,0.2], Circle[{0, 0}, 0.2, angolo[{1.8, 0}, {0.8, 1}, {0, 0}]]},
(* ANGOLO IN (1.8,0) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{1.8, 0}, 0.2, angolo[{0, 0}, {0.8, 1}, {1.8, 0}]+Pi]},
{Darker[Green,0.2], Circle[{1.8, 0}, 0.2, angolo[{0, 0}, {0.8,1}, {1.8, 0}]+Pi]},
(* ANGOLO IN (0.8,1) *)
{Opacity[0.2], Darker[Green,0.3], Disk[{0.8, 1}, 0.2, {angolo[{1.8, 0}, {0, 0}, {0.8, 1}][[1]], angolo[{1.8, 0}, {0, 0}, {0.8, 1}][[2]]-Pi}]},
{Darker[Green,0.2], Circle[{0.8, 1}, 0.2, {angolo[{1.8, 0}, {0, 0}, {0.8, 1}][[1]], angolo[{1.8, 0}, {0, 0}, {0.8, 1}][[2]]-Pi}]},
(* triangle *)
{Opacity[0],EdgeForm[Directive[Black]], Triangle[{{0, 0}, {0.8,1}, {1.8, 0}}]},
(* labels *)
Rotate[
Text[Style["B", 10,FontFamily-> "OpenDyslexic"],
{0.3, 0.6}], 0 Degree],
Text[Style["C", 10,FontFamily-> "OpenDyslexic"],
{0.7, -0.1}],
Text[Style["A", 10,FontFamily-> "OpenDyslexic"],
{1.4, 0.6}, {-1, 0}],
Text[Style["\[Beta]", 10, 10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"], {1.5, 0.1}],
Text[Style["\[Gamma]",10, 10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.8,0.75}],
Text[Style["\[Alpha]",10, 10,Darker[Green,0.3],FontFamily-> "OpenDyslexic"],{0.3,0.1}]
}],2]
(* Stampo i dati dell'esercizio *)
,Magnify[Apply[StringJoin,ToString[#,StandardForm]&/@datiEsercizio7],1.4],Text[""]},
{Text[Style["Procedimento:",17,FontColor -> Red,FontFamily-> "OpenDyslexic"]]},
(* Primo passo dell'esercizio *)
{Text[Style["Applicare il teorema del coseno:",Bold,20,FontFamily-> "OpenDyslexic"]],
Magnify[Row[{"\!\(\*SuperscriptBox[\(C\), \(2\)]\) = ",
InputField[Dynamic[A7],String,FieldSize-> 1],
"\!\(\*SuperscriptBox[\(\\\ \), \(2\)]\)",
(* Dynamic[CheckAnswer[A7,"A"]], *)
Dynamic[esatt],
" + ",
InputField[Dynamic[B7],String,FieldSize-> 1],
"\!\(\*SuperscriptBox[\(\\\ \), \(2\)]\)",
(* Dynamic[CheckAnswer[B7,"B"]], *)
(* Per la propriet\[AGrave] commutativa *)
Dynamic[ If[(A7 == "") || (B7 == ""),
esatt = Text[""];
Text[""],
If[(A7 == "A" && B7 == "B") || (A7 == "B" && B7 == "A"),
esatt = Style["\[Checkmark]",FontColor->Green];
Style["\[Checkmark]",FontColor->Green],
esatt = Style["X",FontColor->Red,Bold];
Style["X",FontColor->Red,Bold],
esatt = Text[""];
Text[""]],
esatt = Text[""];
Text[""]]
],
" - 2 \[CenterDot] A \[CenterDot] " ,
InputField[Dynamic[B8],String,FieldSize->1],
Dynamic[CheckAnswer[B8,"B"]],
" \[CenterDot] cos(",
PopupMenu[Dynamic[G7],{"\[Alpha]","\[Beta]","\[Gamma]"}],Dynamic[CheckAnswer[G7,"\[Gamma]"]],")" }]]},
(* Secondo passo dell'esercizio *)
{Text[Style["Quindi, sostituendo i valori numerici:",Bold,20,FontFamily-> "OpenDyslexic"]],
Magnify[Row[{Style["\!\(\*SuperscriptBox[\(C\), \(2\)]\) = ",FontFamily -> "OpenDyslexic"],
InputField[Dynamic[Val7],String,FieldSize->1],
"\!\(\*SuperscriptBox[\(\\\ \), \(2\)]\)",
(* Dynamic[CheckAnswer[Val7,"2"]], *)
Dynamic[esatt2],
" + ",
InputField[Dynamic[Val8],String,FieldSize->1],
"\!\(\*SuperscriptBox[\(\\\ \), \(2\)]\)",
(* Dynamic[CheckAnswer[Val8,"3"]], *)
Dynamic[ If[(Val7 == "") || (Val8 == ""),
esatt2 = Text[""];
Text[""],
If[(Val7 == "2" && Val8 == "3") || (Val7 == "3" && Val8 == "2"),
esatt2 = Style["\[Checkmark]",FontColor->Green];
Style["\[Checkmark]",FontColor->Green],
esatt2 = Style["X",FontColor->Red,Bold];
Style["X",FontColor->Red,Bold],
esatt2 = Text[""];
Text[""]],
esatt2 = Text[""];
Text[""]]
],
" - 12 \[CenterDot] " ,
Row[{InputField[Dynamic[Val9],String,FieldSize->1],Dynamic[CheckAnswer[Val9,"1"]]}]/Row[{InputField[Dynamic[Val11],String,FieldSize->1],Dynamic[CheckAnswer[Val11,"2"]]}],
" = ",
InputField[Dynamic[Val10],String,FieldSize->1],
Dynamic[CheckAnswer[Val10,"7"]] }]]},
(* Terzo passo dell'esercizio *)
{Text[Style["Da cui: ",Bold,20,FontFamily-> "OpenDyslexic"]],Magnify[Row[{"C = ",SqrtBox[Row[{InputField[Dynamic[Val12],String,FieldSize->1],Dynamic[CheckAnswer[Val12,"7"]]}]]}] // DisplayForm,2]}
},Alignment->{Left,Center},Spacings -> {1,5}]
]
(*Calcolatrice*)
Calcolatrice[]:=
Module[{},
espressione = "";
CreateDialog[{Magnify[InputField[Dynamic[espressione],String,Alignment->Right,FieldSize-> 17],2],
Grid[{{
Column[{
Row[ {Button[" 1 ", espressione = StringJoin[espressione ,"1"],FrameMargins->7]," ",
Button[" 2 ",espressione = StringJoin[espressione ,"2"],FrameMargins->7]," ",
Button[" 3 ",espressione = StringJoin[espressione ,"3"],FrameMargins->7]}],
Row[ {Button[" 4 ",espressione = StringJoin[espressione ,"4"],FrameMargins->7]," ",
Button[" 5 ",espressione = StringJoin[espressione ,"5"],FrameMargins->7]," ",
Button[" 6 ",espressione = StringJoin[espressione ,"6"],FrameMargins->7]}],
Row[ {Button[" 7 ",espressione = StringJoin[espressione ,"7"],FrameMargins->7]," ",
Button[" 8 ",espressione = StringJoin[espressione ,"8"],FrameMargins->7]," ",
Button[" 9 ",espressione = StringJoin[espressione ,"9"],FrameMargins->7]}],
Row[ {Button[" C ",If[StringLength[espressione]>0,espressione =StringDrop[espressione,-1],espressione = ""],FrameMargins->7]," ",
Button[" 0 ",espressione = StringJoin[espressione ,"0"],FrameMargins->7]," ",
Button[" = ",If[StringLength[espressione]>0,{tmp =StandardForm[ ToExpression[espressione]],espressione = ToString[tmp]}],FrameMargins->7]}]}
]," ",
Column[{
Button[" + ", espressione = StringJoin[espressione ,"+"],FrameMargins->7],
Button[" - ",espressione = StringJoin[espressione ,"-"],FrameMargins->7],
Button[" * ",espressione = StringJoin[espressione ,"*"],FrameMargins->7],
Button[" / ",espressione = StringJoin[espressione ,"/"],FrameMargins->7]
},Spacings->0.5],
Column[{
,
Button[" sen ",espressione = StringJoin["Sin[",espressione ," Degree]"],FrameMargins->7],
Button[" cos ",espressione = StringJoin["Cos[",espressione ," Degree]"],FrameMargins->7],
Button[" tan ",espressione = StringJoin["Tan[",espressione ," Degree]"],FrameMargins->7],
Button[" \!\(\*SuperscriptBox[\(x\), \(2\)]\) ",espressione = StringJoin[espressione ,"^2"],FrameMargins->7]
},Spacings-> 0.5],
Column[{
,
Button[" \!\(\*SuperscriptBox[\(sen\), \(-1\)]\) ",espressione = StringJoin["ArcSin[",espressione ,"]"],FrameMargins->7],
Button[" \!\(\*SuperscriptBox[\(cos\), \(-1\)]\) ",espressione = StringJoin["ArcCos[",espressione ,"]"],FrameMargins->7],
Button[" \!\(\*SuperscriptBox[\(tan\), \(-1\)]\) ",espressione = StringJoin["ArcTan[",espressione ,"]"],FrameMargins->7],
Button["\!\(\*SqrtBox[\(\(x\)\(\\\ \)\)]\) ",espressione = StringJoin["Sqrt[",espressione ,"]"],FrameMargins->7]
},Spacings-> 0.5]
},
{Button["Clear",espressione = "",FrameMargins -> 7],SpanFromLeft}
}]
}]
]
(*Teorema di pitagora*)
TPitagora[]:=Button[Style["Teorema di Pitagora",FontFamily->"OpenDyslexic"],
Module[{},
CreateDialog[{Style["Teorema di Pitagora",FontSize->14,Bold,FontFamily->"OpenDyslexic"],
Graphics[{
(*Triangolo*)
Line[{{0,0},{0,1},{1.5,0},{0,0}}],
(*Quadrato Cateto 1*)
{Lighter[Green,0.5],Rectangle[{0,0},{1.5,-1.5}]},
{Darker[Green,0.5],Line[{{0,0},{1.5,0},{1.5,-1.5},{0,-1.5},{0,0}}]},
Text[Style["\!\(\*SuperscriptBox[\(A\), \(2\)]\)",Bold,20,FontFamily-> "OpenDyslexic"],{0.8,-0.7}],
(*Quadrato Cateto 2*)
{Lighter[Red,0.5],Rectangle[{0,0},{-1,1}]},
{Red,Line[{{0,0},{-1,0},{-1,1},{0,1},{0,0}}]},
Text[Style["\!\(\*SuperscriptBox[\(B\), \(2\)]\)",Bold,20,FontFamily-> "OpenDyslexic"],{-0.5,0.5}],
(*Quadrato ipotenusa*)
{Lighter[Blue,0.5],Rotate[Rectangle[{0,1},{1.8,-0.8}],Pi/3 -0.06,{0,1}]},
{Blue,Line[{{0,1},{1.5,0},{2.5,1.5},{1,2.5},{0,1}}]},
Text[Style["\!\(\*SuperscriptBox[\(C\), \(2\)]\)",Bold,20,FontFamily-> "OpenDyslexic"],{1.3,1.3}]
}]
}]
]
]
(*Esercizio 10*)
Esercizio10[]:=
Module[{},
esercizio10testo = Text[Style["",Bold,20,FontFamily-> "OpenDyslexic"]];
Grid[{{Text[Style["Esercizio 10:",20,FontColor-> Red,FontFamily-> "OpenDyslexic"]]},
(*{esercizio10testo},*)
(* Stampo foto scivolo *)
{ Magnify[Sharpen[Import["scivolo.jpeg"]],5],
(* Svolgimento esercizio *)
Magnify[
Row[{Style["Trovare \[Alpha]\n",FontColor -> Red,FontFamily -> "OpenDyslexic"],Style["Approssima il risultato per\ndifetto alla prima cifra decimale\n\n",FontColor -> Red,8,FontFamily -> "OpenDyslexic"],
Style[""],
Row[{InputField[Dynamic[alpha2],String,FieldSize-> 2],Dynamic[CheckAnswer[alpha2,"2.5"]]}]/(Style["sen(\[Alpha])",Bold,FontFamily -> "OpenDyslexic"]),
" = ",
Row[{InputField[Dynamic[gamma3],String,FieldSize->2],Dynamic[CheckAnswer[gamma3,"3" ]]}]/Row[{Style["sen(",Bold,FontFamily -> "OpenDyslexic"],InputField[Dynamic[gamma2],String,FieldSize->2],
Style["\[Degree])",Bold,FontFamily-> "OpenDyslexic"],
Dynamic[CheckAnswer[gamma2,"60"]]}],
" \[LongRightArrow] ",
Style["sen(\[Alpha]) = ",Bold,FontFamily->"OpenDyslexic"],
Row[{InputField[Dynamic[latob],String,FieldSize -> 2],Dynamic[CheckAnswer[latob,"2.5"]]}]/Row[{InputField[Dynamic[latoc],String,FieldSize->2],Dynamic[CheckAnswer[latoc,"3"]]}],
" \[CenterDot] ",
Row[{SqrtBox[InputField[Dynamic[num10],String,FieldSize->2]]//DisplayForm,Dynamic[CheckAnswer[num10,"3"]] }] /Row[{InputField[Dynamic[den10],String,FieldSize->2],Dynamic[CheckAnswer[den10,"2"]]}],
" = ",
Row[{InputField[Dynamic[res10],String,FieldSize-> 2],Dynamic[CheckAnswer[res10,"0.7"]]}]
}],1.5]}
},Alignment->{Left,Center},Spacings -> {1,5}]
]
EndPackage[] |
###################################################################################
################## Workflow Part 1: Collect initial metrics #################
###################################################################################
suppressMessages(suppressPackageStartupMessages(library(BiocManager)))
suppressMessages(suppressPackageStartupMessages(BiocManager::install("bamsignals")))
suppressMessages(suppressPackageStartupMessages(BiocManager::install("GenomicAlignments")))
suppressMessages(suppressPackageStartupMessages(library(IRanges)))
suppressMessages(suppressPackageStartupMessages(library(bamsignals)))
suppressMessages(suppressPackageStartupMessages(library(GenomeInfoDb)))
suppressMessages(suppressPackageStartupMessages(library(GenomicRanges)))
suppressMessages(suppressPackageStartupMessages(library(GenomicAlignments)))
suppressMessages(suppressPackageStartupMessages(library(Rsamtools)))
qc.spikiness <- function(counts) {
if (is.null(counts)) {
return(NA)
}
counts <- as.vector(counts)
sum.counts <- sum(counts)
spikiness <- sum(abs(diff(counts))) / sum.counts
return(spikiness)
}
bamToGRanges <- function(bamfile, bamindex=bamfile,chromosomes=NULL,pairedEndReads=FALSE,remove.duplicate.reads=FALSE,min.mapq=10,max.fragment.width=1000,blacklist=NULL,what='mapq') {
## Input checks
if (!is.null(blacklist)) {
if ( !(is.character(blacklist) | class(blacklist)=='GRanges') ) {
stop("'blacklist' has to be either a bed(.gz) file or a GRanges object")
}
}
## Check if bamindex exists
bamindex.raw <- sub('\\.bai$', '', bamindex)
bamindex <- paste0(bamindex.raw,'.bai')
if (!file.exists(bamindex)) {
ptm <- startTimedMessage("Making bam-index file ...")
bamindex.own <- Rsamtools::indexBam(bamfile)
warning("Couldn't find BAM index-file ",bamindex,". Creating our own file ",bamindex.own," instead.")
bamindex <- bamindex.own
stopTimedMessage(ptm)
}
chrom.lengths <- GenomeInfoDb::seqlengths(Rsamtools::BamFile(bamfile))
chroms.in.data <- names(chrom.lengths)
if (is.null(chromosomes)) {
chromosomes <- chroms.in.data
}
chroms2use <- intersect(chromosomes, chroms.in.data)
## Stop if non of the specified chromosomes exist
if (length(chroms2use)==0) {
chrstring <- paste0(chromosomes, collapse=', ')
stop('The specified chromosomes ', chrstring, ' do not exist in the data. Pay attention to the naming convention in your data, e.g. "chr1" or "1".')
}
## Issue warning for non-existent chromosomes
diff <- setdiff(chromosomes, chroms.in.data)
if (length(diff)>0) {
diffs <- paste0(diff, collapse=', ')
warning(paste0('Not using chromosomes ', diffs, ' because they are not in the data.'))
}
## Import the file into GRanges
ptm <- startTimedMessage("Reading file ",basename(bamfile)," ...")
gr <- GenomicRanges::GRanges(seqnames=chroms2use, ranges=IRanges(start=rep(1, length(chroms2use)), end=chrom.lengths[chroms2use]))
if (!remove.duplicate.reads) {
if (pairedEndReads) {
data.raw <- GenomicAlignments::readGAlignmentPairs(bamfile, index=bamindex, param=Rsamtools::ScanBamParam(which=range(gr), what=what, mapqFilter = min.mapq))
} else {
data.raw <- GenomicAlignments::readGAlignments(bamfile, index=bamindex, param=Rsamtools::ScanBamParam(which=range(gr), what=what, mapqFilter = min.mapq))
}
} else {
if (pairedEndReads) {
data.raw <- GenomicAlignments::readGAlignmentPairs(bamfile, index=bamindex, param=Rsamtools::ScanBamParam(which=range(gr), what=what, mapqFilter = min.mapq, flag=scanBamFlag(isDuplicate=FALSE)))
} else {
data.raw <- GenomicAlignments::readGAlignments(bamfile, index=bamindex, param=Rsamtools::ScanBamParam(which=range(gr), what=what, mapqFilter = min.mapq, flag=scanBamFlag(isDuplicate=FALSE)))
}
}
stopTimedMessage(ptm)
if (length(data.raw) == 0) {
if (pairedEndReads) {
stop(paste0("No reads imported. Does your file really contain paired end reads? Try with 'pairedEndReads=FALSE'"))
}
stop(paste0('No reads imported! Check your BAM-file ', bamfile))
}
## Convert to GRanges and filter
if (pairedEndReads) {
ptm <- startTimedMessage("Converting to GRanges ...")
data <- GenomicAlignments::granges(data.raw, use.mcols = TRUE, on.discordant.seqnames='drop') # treat as one fragment
stopTimedMessage(ptm)
ptm <- startTimedMessage("Filtering reads ...")
# if (!is.na(min.mapq)) {
# mapq.first <- mcols(GenomicAlignments::first(data.raw))$mapq
# mapq.last <- mcols(GenomicAlignments::last(data.raw))$mapq
# mapq.mask <- mapq.first >= min.mapq & mapq.last >= min.mapq
# if (any(is.na(mapq.mask))) {
# warning(paste0(bamfile,": Reads with mapping quality NA (=255 in BAM file) found and removed. Set 'min.mapq=NA' to keep all reads."))
# }
# data <- data[which(mapq.mask)]
# }
# Filter out too long fragments
data <- data[width(data)<=max.fragment.width]
stopTimedMessage(ptm)
} else {
ptm <- startTimedMessage("Converting to GRanges ...")
data <- GenomicAlignments::granges(data.raw, use.mcols = TRUE) # treat as one fragment
stopTimedMessage(ptm)
ptm <- startTimedMessage("Filtering reads ...")
# if (!is.na(min.mapq)) {
# if (any(is.na(mcols(data)$mapq))) {
# warning(paste0(bamfile,": Reads with mapping quality NA (=255 in BAM file) found and removed. Set 'min.mapq=NA' to keep all reads."))
# mcols(data)$mapq[is.na(mcols(data)$mapq)] <- -1
# }
# data <- data[mcols(data)$mapq >= min.mapq]
# }
# Filter out too long fragments
data <- data[width(data)<=max.fragment.width]
stopTimedMessage(ptm)
}
## Exclude reads falling into blacklisted regions
if (!is.null(blacklist)) {
ptm <- startTimedMessage("Filtering blacklisted regions ...")
if (is.character(blacklist)) {
if (grepl('^chr', seqlevels(data)[1])) {
chromosome.format <- 'UCSC'
} else {
chromosome.format <- 'NCBI'
}
black <- importBed(blacklist, skip=0, chromosome.format=chromosome.format)
} else if (class(blacklist)=='GRanges') {
black <- blacklist
} else {
stop("'blacklist' has to be either a bed(.gz) file or a GRanges object")
}
overlaps <- findOverlaps(data, black)
idx <- setdiff(1:length(data), S4Vectors::queryHits(overlaps))
data <- data[idx]
stopTimedMessage(ptm)
}
return(data)
}
fixedWidthBins <- function(bamfile=NULL, assembly=NULL, chrom.lengths=NULL, chromosome.format, binsizes=1e6, stepsizes=NULL, chromosomes=NULL) {
### Check user input ###
if (length(binsizes) == 0) {
return(list())
}
if (is.null(bamfile) & is.null(assembly) & is.null(chrom.lengths)) {
stop("Please specify either a 'bamfile', 'assembly' or 'chrom.lengths'")
}
if (is.null(bamfile) & is.null(chrom.lengths)) {
trigger.error <- chromosome.format
}
if (!is.null(stepsizes)) {
if (length(stepsizes) != length(binsizes)) {
stop("Need one element in 'stepsizes' for each element in 'binsizes'.")
}
if (any(binsizes < stepsizes)) {
stop("'stepsizes' must be smaller/equal than 'binsizes'")
}
}
### Get chromosome lengths ###
if (!is.null(bamfile)) {
ptm <- startTimedMessage(paste0("Reading header from ", bamfile, " ..."))
chrom.lengths <- GenomeInfoDb::seqlengths(Rsamtools::BamFile(bamfile))
stopTimedMessage(ptm)
} else if (!is.null(assembly)) {
if (is.character(assembly)) {
ptm <- startTimedMessage("Fetching chromosome lengths from UCSC ...")
df <- GenomeInfoDb::getChromInfoFromUCSC(assembly)
stopTimedMessage(ptm)
} else if (is.data.frame(assembly)) {
df <- assembly
} else {
stop("Unknown assembly")
}
chrom.lengths <- df$size
if (chromosome.format=='UCSC') {
} else if (chromosome.format=='NCBI') {
df$chrom = sub('^chr', '', df$chrom)
}
names(chrom.lengths) <- df$chrom
chrom.lengths <- chrom.lengths[!is.na(names(chrom.lengths))]
chrom.lengths <- chrom.lengths[!is.na(chrom.lengths)]
} else if (!is.null(chrom.lengths)) {
chrom.lengths <- chrom.lengths[!is.na(names(chrom.lengths))]
chrom.lengths <- chrom.lengths[!is.na(chrom.lengths)]
}
chroms.in.data <- names(chrom.lengths)
if (is.null(chromosomes)) {
chromosomes <- chroms.in.data
}
chroms2use <- intersect(chromosomes, chroms.in.data)
## Stop if none of the specified chromosomes exist
if (length(chroms2use)==0) {
chrstring <- paste0(chromosomes, collapse=', ')
stop('Could not find length information for any of the specified chromosomes: ', chrstring, '. Pay attention to the naming convention in your data, e.g. "chr1" or "1".')
}
## Issue warning for non-existent chromosomes
diff <- setdiff(chromosomes, chroms.in.data)
if (length(diff)>0) {
diffs <- paste0(diff, collapse=', ')
warning('Could not find length information for the following chromosomes: ', diffs)
}
### Making fixed-width bins ###
bins.list <- list()
for (ibinsize in 1:length(binsizes)) {
binsize <- binsizes[ibinsize]
ptm <- startTimedMessage("Making fixed-width bins for bin size ", binsize, " ...")
chrom.lengths.floor <- floor(chrom.lengths / binsize) * binsize
bins <- unlist(GenomicRanges::tileGenome(chrom.lengths.floor[chroms2use], tilewidth=binsize), use.names=FALSE)
bins <- bins[end(bins) > 0] # no chromosomes that are smaller than binsize
if (any(width(bins)!=binsize)) {
stop("tileGenome failed")
}
# seqlengths(bins) <- as.integer(chrom.lengths[names(seqlengths(bins))])
seqlengths(bins) <- chrom.lengths[chroms2use]
if (!is.null(stepsizes)) {
shift.bp <- 0
stepsize <- stepsizes[ibinsize]
bins.list.step <- GRangesList()
while (shift.bp < binsize) {
bins.list.step[[as.character(shift.bp)]] <- suppressWarnings( trim(shift(bins, shift.bp)) )
shift.bp <- stepsize + shift.bp
}
bins.list[[paste0('binsize_', format(binsize, scientific=TRUE, trim=TRUE), '_stepsize_', format(stepsize, scientific=TRUE, trim=TRUE))]] <- bins.list.step
} else {
bins.list[[paste0('binsize_', format(binsize, scientific=TRUE, trim=TRUE))]] <- bins
}
skipped.chroms <- setdiff(seqlevels(bins), as.character(unique(seqnames(bins))))
if (length(skipped.chroms)>0) {
warning("The following chromosomes were skipped because they are smaller than binsize ", binsize, ": ", paste0(skipped.chroms, collapse=', '))
}
stopTimedMessage(ptm)
}
return(bins.list)
}
startTimedMessage <- function(...) {
x <- paste0(..., collapse='')
message(x, appendLF=FALSE)
ptm <- proc.time()
return(ptm)
}
stopTimedMessage <- function(ptm) {
time <- proc.time() - ptm
message(" ", round(time[3],2), "s")
}
transCoord <- function(gr) {
cum.seqlengths <- cumsum(as.numeric(seqlengths(gr)))
cum.seqlengths.0 <- c(0,cum.seqlengths[-length(cum.seqlengths)])
names(cum.seqlengths.0) <- GenomeInfoDb::seqlevels(gr)
gr$start.genome <- start(gr) + cum.seqlengths.0[as.character(seqnames(gr))]
gr$end.genome <- end(gr) + cum.seqlengths.0[as.character(seqnames(gr))]
return(gr)
}
collectLibraryStats <- function(folder){
met=data.frame(file=c(),coverage=c(),spikiness=c(),evenness.mean=c(),evenness.med=c())
#file=list.files(folder,full.names = T,pattern="\\.bam$")[1]
for (file in list.files(folder,full.names = T,pattern="\\.bam$")){
bamindex=file
bamindex.raw <- sub('\\.bai$', '', bamindex)
bamindex <- paste0(bamindex.raw,'.bai')
if (!file.exists(bamindex)) {
ptm <- startTimedMessage("Making bam-index file ...")
bamindex.own <- Rsamtools::indexBam(file)
warning("Couldn't find BAM index-file ",bamindex,". Creating our own file ",bamindex.own," instead.")
bamindex <- bamindex.own
stopTimedMessage(ptm)
}
chrom.lengths <- GenomeInfoDb::seqlengths(Rsamtools::BamFile(file))
chrom.lengths.df <- data.frame(chromosome=names(chrom.lengths), length=chrom.lengths)
bins <- fixedWidthBins(chrom.lengths=chrom.lengths, binsizes=1e+06, stepsizes=1e+06)
counts.ss <- bamsignals::bamCount(file, bins[[1]][[1]], mapqual=10, paired.end="ignore", tlenFilter=c(0,1000), verbose=FALSE, ss=TRUE, filteredFlag=1024)
pcounts <- counts.ss[1,]
mcounts <- counts.ss[2,]
counts <- pcounts + mcounts
readsperbin <- round(sum(as.numeric(counts)) / length(counts), 2)
countmatrix <- matrix(c(counts,mcounts,pcounts), ncol=3)
colnames(countmatrix) <- c('counts','mcounts','pcounts')
mcols(bins[[1]][[1]]) <- as(countmatrix, 'DataFrame')
data=bamToGRanges(file)
genome.length <- sum(as.numeric(seqlengths(data)))
data.strand <- data
strand(data.strand) <- '*'
coverage <- sum(as.numeric(width(data.strand))) / genome.length
#genome.covered <- sum(as.numeric(width(reduce(data.strand)))) / genome.length
binned.reads = bins[[1]][[1]]
med.reads.per.mb=median(binned.reads$counts)
mean.reads.per.mb=mean(binned.reads$counts)
binned.reads$var.med = (abs(binned.reads$counts - med.reads.per.mb)) /
sd(binned.reads$counts)
binned.reads$var.mean = (abs(binned.reads$counts - mean.reads.per.mb)) /
sd(binned.reads$counts)
evenness.med = sum(binned.reads$var.med) / (3* length(binned.reads))
evenness.mean = sum(binned.reads$var.mean) / (3* length(binned.reads))
spikiness=qc.spikiness(bins[[1]][[1]]$counts)
print(paste0("Coverage:",coverage))
#print(paste0("Genome.covered:",genome.covered))
print(paste0("Spikiness",spikiness))
print(paste0("Evenness.med",evenness.med))
print(paste0("Evenness.mean",evenness.mean))
row=data.frame(file=basename(file),coverage=coverage,spikiness=spikiness,evenness.mean=evenness.mean,evenness.med=evenness.med)
met=rbind(met,row)
}
write.table(met,"thesis.bam.metrics_se.txt",sep="\t",quote=F,row.names = F,col.names = T)
}
collectLibraryStats("THESIS_SE/") |
/*
* Copyright (c) 2021, Jaiden di Lanzo
*
* 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.
*/
/**
* The \p isEmpty function determines whether the value supplied by the \p field
* parameter is empty. The function returns \p true if the field is empty, and
* \p false otherwise.
* @param field - The text field to check for emptiness.
* @return True if the field is empty, false otherwise.
*/
function isEmpty(field) {
if (field.value == "" || field.value == null) {
return true;
}
return false;
}
/**
* The \p isValidName function determines whether the value supplied by the
* \p name parameter is valid. A valid name must contain at least one character.
* The function returns \p true if the name is valid, and \p false otherwise.
* @param name - The name value to check for validity.
* @return True if the name is valid, false otherwise.
*/
function isValidName(name) {
if (!isEmpty(name)) {
if (/[\W\w]+/.test(name.value)) {
document.getElementById('errorName').innerText = "";
return true;
}
}
document.getElementById('errorName').innerText = "Not a valid name!";
return false;
}
/**
* The \p isValidPhoneNumber function determines whether the value supplied by
* the \p number parameter is valid. A valid phone number must contain at least
* one digit, and may contain the \p + special prefix. The function returns \p
* true if the phone number is valid, and \p false otherwise.
* @param number - The phone number value to check for validity.
* @return True if the phone number is valid, false otherwise.
*/
function isValidPhoneNumber(number) {
if (!isEmpty(number)) {
if (/[\d]+/.test(number.value)) {
document.getElementById('errorNumber').innerText = "";
return true;
}
}
document.getElementById('errorNumber').innerText = "Not a valid number!";
return false;
}
/**
* The \p isValidDay function determines whether the value supplied by the \p
* day parameter is valid. A valid day lies within the range [1, 31]. This
* function does not validate days of a particular month (see the \p isValidDate
* function). The function returns \p true if the day is valid,
* and \p false otherwise.
* @param day - The day value to check for validity.
* @return True if the day is valid, false otherwise.
*/
function isValidDay(day) {
if (!isEmpty(day)) {
if (0 < day.value && day.value < 32) {
document.getElementById('errorDate').innerText = "";
return true;
}
}
document.getElementById('errorDate').innerText = "Not a valid day!";
return false;
}
/**
* The \p isValidMonth function determines whether the value supplied by the \p
* month parameter is valid. A valid month lies within the range [1, 12]. The
* function returns \p true if the day is valid, and \p false otherwise.
* @param month - The month value to check for validity.
* @return True if the month is valid, false otherwise.
*/
function isValidMonth(month) {
if (!isEmpty(month)) {
if (0 < month.value && month.value < 13) {
document.getElementById('errorDate').innerText = "";
return true;
}
}
document.getElementById('errorDate').innerText = "Not a valid month!";
return false;
}
/**
* The \p isValidYear function determines whether the value supplied by the \p
* year parameter is valid. A valid year is any non-negative year value
* (including zero). The upper limit is unbounded. The function returns \p true
* if the year is valid, and \p false otherwise.
* @param year - The year value to check for validity.
* @return True if the year is valid, false otherwise.
*/
function isValidYear(year) {
if (!isEmpty(year)) {
if (year.value > -1) {
document.getElementById('errorDate').innerText = "";
return true;
}
}
document.getElementById('errorDate').innerText = "Not a valid year!";
return false
}
/**
* The \p isValidDate function determines whether a whole date is valid based on
* the supplued \p day, \p month, and\p year parameters. This function validates
* particular days of the month, and accounts for leap years. The function
* returns \p true if the date is valid, and \p false otherwise.
* @param day - The day part of the whole date.
* @param month - The month part of the whole date.
* @param year - The year part of the whole date.
* @return True if the date is valid, false otherwise.
*/
function isValidDate(day, month, year) {
if (month.value == 1 || // Months with 31 days.
month.value == 3 || month.value == 5 || month.value == 7 || month.value ==
8 || month.value == 10 || month.value == 12) {
if (0 < day.value && day.value < 32) {
document.getElementById('errorDate').innerText = "";
return true;
}
} else if (month.value == 4 || // Months with 30 days.
month.value == 6 || month.value == 9 || month.value == 11) {
if (0 < day.value && day.value < 31) {
document.getElementById('errorDate').innerText = "";
return true;
}
} else if (month.value == 2) { // February, the special case.
if ((year.value % 4) != 0) {
if (0 < day.value && day.value < 29) {
document.getElementById('errorDate').innerText = "";
return true;
}
} else if ((year.value % 100) != 0) {
if (0 < day.value && day.value < 30) {
document.getElementById('errorDate').innerText = "";
return true;
}
} else if ((year.value % 400) != 0) {
if (0 < day.value && day.value < 29) {
document.getElementById('errorDate').innerText = "";
return true;
}
} else {
if (0 < day.value && day.value < 30) {
document.getElementById('errorDate').innerText = "";
return true;
}
}
}
document.getElementById('errorDate').innerText = "Not a valid date!";
return false;
}
/**
* The \p isValidPastime function determines whether the value supplied by the
* \p pastime parameter is valid. A valid pastime is one of the following:
* - Surfing the Web
* - Playing Sport
* - Listening to Music
* - Watching TV
* - Playing Games
* - Community Service
* - Daydreaming
* - Reading
* - Meditation
* The function returns \p true if the day is valid, and \p false otherwise.
* @param pastime - The pastime value to check for validity.
* @return True if the pastime is valid, false otherwise.
*/
function isValidPastime(pastime) {
if (!isEmpty(pastime)) {
if (pastime.value == "Surfing the Web" || pastime.value ==
"Playing Sport" || pastime.value == "Listening to Music" ||
pastime.value == "Watching TV" || pastime.value == "Playing Games" ||
pastime.value == "Community Service" || pastime.value ==
"Daydreaming" || pastime.value == "Reading" || pastime.value ==
"Meditation") {
document.getElementById('errorPastime').innerText = "";
return true;
}
}
document.getElementById('errorPastime').innerText = "Not a valid pastime!";
return false;
}
/**
* The \p isValidForm function determines whether the entire form, as supplied
* by the \p form parameter, is valid. This function performs individual
* validation checks for each form element. A valid form is one which has each
* field filled and validated correctly. The function returns \p true if the
* whole form is valid, and \p false otherwise.
* @param form - The form to check for validity.
* @return True if the form is valid, false otherwise.
*/
function isValidForm(form) {
if (isValidName(form.name) && isValidPhoneNumber(form.number) &&
isValidDay(form.day) && isValidMonth(form.month) &&
isValidYear(form.year) && isValidDate(form.day, form.month, form.year) &&
isValidPastime(form.pastime)) {
document.getElementById('errorForm').innerText = "";
return true;
}
document.getElementById('errorForm').innerText =
"Form is invalid or incomplete!";
return false;
} |
package com.udacity.shoestore.shoelist
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.udacity.shoestore.models.Shoe
import timber.log.Timber
class ShoedetailViewModel():ViewModel() {
var _shoeName= MutableLiveData<String>()
val shoeName: LiveData<String> get() = _shoeName
var _companyName= MutableLiveData<String>()
val companyName: LiveData<String> get() = _companyName
var _description= MutableLiveData<String>()
val description: LiveData<String> get() = _description
var _shoeSize= MutableLiveData<String>()
val shoeSize: LiveData<String> get() = _shoeSize
init {
Timber.tag("ShoedetailViewModel").i("ShoedetailViewModel created!")
}
fun retrieveNewShoe(): Shoe {
if ((_shoeName.value == null) or (_companyName.value == null) or (_description.value == null) or (_shoeSize.value == null)){
Timber.tag("ShoedetailViewModel").i("No shoe details entered!")
return Shoe("", 0.0, "", "", mutableListOf(""))
}
return Shoe(_shoeName.value.toString(), _shoeSize.value.toString().toDouble(), _companyName.value.toString(), _description.value.toString(), mutableListOf(""))
}
} |
import { useState } from "react";
import { nanoid } from "nanoid";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
/* ------- SCHEMA ------- */
import { productDataValidation } from "./validation/productValidation";
/* ------- MOCK ------- */
import { PRODUCTS } from "./lists/products";
/* ------- COMPONENT ------- */
import ProductCard from "./components/ProductCard";
import Modal from "./shared/Modal/Modal";
import HeroSection from "./components/HeroSection";
import { categories } from "./lists/categories";
import BuildProductModal from "./shared/Modal/BuildProductModal";
const App = () => {
/* ------- STATE ------- */
const [isBuildModalOpen, setIsBuildModalOpen] = useState(false);
const [modalIsOpen, setModalIsOpen] = useState(false);
const [productList, setProductList] = useState(PRODUCTS);
const [product, setProduct] = useState({
title: "",
description: "",
image: "",
price: "",
colors: [],
category: {},
// sizes: [],
});
const [tempColors, setTempColors] = useState([]);
const [temProductIdx, setTemProductIdx] = useState(null);
const [selectedCategory, setSelectedCategory] = useState(categories[6]);
const [errors, setErrors] = useState({ ...product });
const [isError, setIsError] = useState(false);
/* ------- HANDLER ------- */
const changeHandler = e => {
const {
target: { value, name },
} = e;
setProduct({ ...product, [name]: value });
setErrors({ ...errors, [name]: "" });
};
const openModal = () => {
setModalIsOpen(true);
};
const openBuildProductModal = () => {
setIsBuildModalOpen(true);
};
const closeBuildProductModal = () => {
setIsBuildModalOpen(false);
};
const closeModal = () => {
setModalIsOpen(false);
setTemProductIdx(null);
};
const onDestroyProduct = id => {
const filteredArr = productList.filter(item => item.id !== id);
setProductList(filteredArr);
};
const onSubmitHandler = e => {
e.preventDefault();
setErrors(productDataValidation(product));
if (Object.keys(productDataValidation(product)).length) {
setIsError(true);
return;
}
setProductList([
{ ...product, id: nanoid(), colors: tempColors, category: selectedCategory },
...productList,
]);
setProduct({
title: "",
description: "",
image: "",
price: "",
brand: "",
colors: [],
});
setTempColors([]);
setIsError(false);
setIsBuildModalOpen(false);
toast.success("Product has been added successfully", {
position: "bottom-center",
autoClose: 1000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "dark",
});
};
/* ------- RENDER ------- */
const renderProductList = productList.map((product, idx) => (
<ProductCard
key={product.id}
{...product}
productList={productList}
setProductList={setProductList}
openModal={openModal}
idx={idx}
setTemProductIdx={setTemProductIdx}
/>
));
return (
<>
<ToastContainer />
<HeroSection onClickHandler={openBuildProductModal} />
<div className="container">
<div className="flex items-center justify-between mb-10">
<h2 className="text-center text-4xl font-bold tracking-tight text-gray-900 sm:text-6xl">
Latest <span className="text-indigo-600">Products</span>
</h2>
<div
className="rounded-md bg-indigo-600 px-3.5 py-1.5 text-base font-semibold leading-7 text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 cursor-pointer w-fit"
onClick={openBuildProductModal}
>
Build now
</div>
</div>
<div className="grid grid-cols-products-grid gap-3">{renderProductList}</div>
<BuildProductModal
modalIsOpen={isBuildModalOpen}
closeModal={closeBuildProductModal}
product={product}
tempColors={tempColors}
setTempColors={setTempColors}
errors={errors}
selectedCategory={selectedCategory}
setSelectedCategory={setSelectedCategory}
isError={isError}
changeHandler={changeHandler}
onSubmitHandler={onSubmitHandler}
/>
<Modal
modalIsOpen={modalIsOpen}
closeModal={closeModal}
data={productList[temProductIdx]}
onClickAction={onDestroyProduct}
/>
</div>
</>
);
};
export default App; |
import Document, { Html, Head, Main, NextScript } from 'next/document'
import { ServerStyleSheet } from 'styled-components'
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />)
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
)
}
} finally {
sheet.seal()
}
}
render() {
return (
<Html>
<Head>
<title>Pailang Museum</title>
<link
rel="preload"
href="/fonts/OggBold.ttf"
as="font"
type="font/ttf"
crossOrigin="anonymous"
/>
<link
rel="preload"
href="/fonts/OggRegular.ttf"
as="font"
type="font/ttf"
crossOrigin="anonymous"
/>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin />
<link
href="https://fonts.googleapis.com/css2?family=Baskervville&family=IBM+Plex+Sans:ital,wght@0,200;0,600;1,200;1,400;1,500;1,600&family=Noto+Sans+TC:wght@100;300&family=Noto+Serif+TC:wght@200;400;600&display=swap"
rel="stylesheet"
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
} |
// ignore_for_file: file_names
import 'package:estudyingv1/Controller/CourseController.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../Widget/AppBar.dart';
import '../../Widget/CourseCard.dart';
class CourseCategory extends StatelessWidget {
const CourseCategory(
{Key? key, required this.parameters, required this.title})
: super(key: key);
final String parameters;
final String title;
@override
Widget build(BuildContext context) {
return GetBuilder<CourseController>(
init: CourseController(category: parameters),
builder: (c) => Scaffold(
appBar: appBar(value: title, context: context),
body: c.loadingProduct.value
? Center(
child: CircularProgressIndicator(
color: Theme.of(context).primaryColor,
))
: Column(
children: [
Expanded(
child: ListView.builder(
controller: c.scrollController,
padding: const EdgeInsets.only(top: 12, bottom: 35),
itemBuilder: (context, index) {
return CourseCard(
data: c.data[index],
index: index,
fromList: true,
fromdl: false,
fromheart: false,
);
},
itemCount: c.data.length,
),
),
c.loadingPag.value
? Center(
child: CircularProgressIndicator(
color: Theme.of(context).primaryColor,
))
: Container()
],
)));
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="/js/index.js"></script>
</head>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
}
form {
display: flex;
flex-direction: column;
width: 300px;
padding: 20px;
border-radius: 5px;
box-shadow: 0px 3px 15px rgba(0,0,0,0.1);
background-color: #ffffff;
}
label {
margin-bottom: 10px;
font-weight: bold;
}
input, select {
margin-bottom: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 10px;
color: #ffffff;
background-color: #007bff;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.links {
display: flex;
justify-content: space-around;
font-size: 0.8em;
margin-top: 12px;
}
a {
text-decoration: none;
color: #007bff;
}
a:hover {
text-decoration: underline;
}
.address-select {
display: flex;
gap: 10px;
}
</style>
<body>
<form action="" method="post" id="signUpForm">
<label for="">이름</label>
<input type="text" name="name" placeholder="ex-홍길동" required>
<label for="">나이</label>
<input type="text" name="age" placeholder="ex-20" required>
<label for="">아이디</label>
<input type="text" name="user_id" placeholder="ex-god1234" required>
<label for="">패스워드</label>
<input type="password" name="user_pw" id="user_pw" placeholder="비밀번호는 8자 이상이며, 대문자, 소문자, 숫자, 그리고 특수문자(!@#$%^&*)를 포함해야 합니다." required>
<span id="passwordError" style="color: red;"></span>
<label for="">닉네임</label>
<input type="text" name="nickname" placeholder="ex-gildong" required>
<div>
<label for="gender">성별 : </label>
<input type="radio" id="male" name="gender" value="male" required>
<label for="male">남자</label>
<input type="radio" id="female" name="gender" value="female" required>
<label for="female">여자</label>
</div>
<label for="">주소</label>
<input type="text" name="address" id="address" placeholder="아래 도시 선택" required>
<div class="address-select">
<select id="citySelect" onchange="updateGus(); updateAddress();">
</select>
<select id="guSelect" onchange="updateDongs(); updateAddress();">
</select>
<select id="dongSelect" onchange="updateAddress();">
</select>
</div>
<button id="singupBtn">회원가입</button>
</form>
</body>
<script>
// // 비밀번호 정규식 추가
var passwordInput = document.getElementById('user_pw');
var passwordError = document.getElementById('passwordError');
var passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*[!@#$%^&*]).{8,}$/;
// // 에러 메세지 초기화
// passwordError.textContent = '';
passwordInput.addEventListener('input', function(){
if(!passwordRegex.test(passwordInput.value)) {
passwordError.textContent = "비밀번호는 8자 이상이며, 대문자, 소문자, 숫자, 그리고 특수문자(!@#$%^&*)를 포함해야 합니다.";
}else{
passwordError.textContent = '';
}
})
document.getElementById('signUpForm').addEventListener('submit', function(event) {
if (!passwordRegex.test(passwordInput.value)) {
event.preventDefault();
}
});
signUpForm.action = `${serverUrl}/signUp`;
window.onload = function() {
const citySelect = document.getElementById("citySelect");
const defaultOption = document.createElement("option");
defaultOption.text = "-";
defaultOption.value = "";
citySelect.add(defaultOption);
for (const city in regionData) {
const option = document.createElement("option");
option.text = city;
option.value = city
citySelect.add(option);
}
updateGus();
}
function updateGus() {
const citySelect = document.getElementById("citySelect");
const guSelect = document.getElementById("guSelect");
const dongSelect = document.getElementById("dongSelect");
const selectedCity = citySelect.value;
guSelect.innerHTML = "";
dongSelect.innerHTML = "";
const gus = regionData[selectedCity] || {};
for (const gu in gus) {
const option = document.createElement("option");
option.text = gu;
guSelect.add(option);
}
updateDongs();
}
function updateDongs() {
const citySelect = document.getElementById("citySelect");
const guSelect = document.getElementById("guSelect");
const dongSelect = document.getElementById("dongSelect");
const selectedCity = citySelect.value;
const selectedGu = guSelect.value;
dongSelect.innerHTML = "";
const dongs = (regionData[selectedCity] && regionData[selectedCity][selectedGu]) || [];
for (const dong of dongs) {
const option = document.createElement("option");
option.text = dong;
dongSelect.add(option);
}
}
function updateAddress() {
const citySelect = document.getElementById("citySelect");
const guSelect = document.getElementById("guSelect");
const dongSelect = document.getElementById("dongSelect");
const addressInput = document.getElementById("address");
const selectedCity = citySelect.value;
const selectedGu = guSelect.value;
const selectedDong = dongSelect.value;
addressInput.value = `${selectedCity} ${selectedGu} ${selectedDong}`;
}
// singupBtn.onclick() = () => {
// location.href = `./${mainUrl}`;
// }
</script>
</html> |
import React from 'react';
import {
Chart,
Settings,
Axis,
BarSeries,
ScaleType,
timeFormatter,
} from '@elastic/charts';
export interface DataSchema {
time: number;
value: number;
}
interface PropSchema {
itemName: string;
width?: number;
height?: number;
data: DataSchema[];
timeFormat: string;
}
export function SingleItemTimeBarChart(props: PropSchema) {
return (
<Chart size={{
width: props.width,
height: props.height,
}}>
<Settings
showLegend={true}
legendPosition="right"/>
<BarSeries
id="status"
name={props.itemName}
data={props.data}
xAccessor={'time'}
yAccessors={['value']}
xScaleType={ScaleType.Time} />
<Axis
id="bottom-axis"
position="bottom"
tickFormat={timeFormatter(props.timeFormat)}
showGridLines />
<Axis
id="left-axis"
position="left"
showGridLines />
</Chart>
);
}
export default SingleItemTimeBarChart; |
# Using Transformations to "Normalize" Distributions
- When we are confronted with a variable that is not Normally distributed but that we wish was Normally distributed, it is sometimes useful to consider whether working with a transformation of the data will yield a more helpful result.
- Many statistical methods, including t tests and analyses of variance, assume Normal distributions.
- We'll discuss using R to assess a range of what are called Box-Cox power transformations, via plots, mainly.
## The Ladder of Power Transformations
The key notion in re-expression of a single variable to obtain a distribution better approximated by the Normal or re-expression of an outcome in a simple regression model is that of a **ladder of power transformations**, which applies to any unimodal data.
Power | Transformation
:-----: | :----------:
3 | x^3^
2 | x^2^
1 | x (unchanged)
0.5 | x^0.5^ = $\sqrt{x}$
0 | ln x
-0.5 | x^-0.5^ = 1/$\sqrt{x}$
-1 | x^-1^ = 1/x
-2 | x^-2^ = 1/x^2^
## Using the Ladder
As we move further away from the *identity* function (power = 1) we change the shape more and more in the same general direction.
- For instance, if we try a logarithm, and this seems like too much of a change, we might try a square root instead.
- Note that this ladder (which like many other things is due to John Tukey) uses the logarithm for the "power zero" transformation rather than the constant, which is what x^0^ actually is.
- If the variable x can take on negative values, we might take a different approach. If x is a count of something that could be zero, we often simply add 1 to x before transformation.
The ladder of power transformations is particularly helpful when we are confronted with data that shows skew.
- To handle right skew (where the mean exceeds the median) we usually apply powers below 1.
- To handle left skew (where the median exceeds the mean) we usually apply powers greater than 1.
The most common transformations are the square (power 2), the square root (power 1/2), the logarithm (power 0) and the inverse (power -1), and I usually restrict myself to those options in practical work.
## Protein Consumption in the NNYFS data
Here are the protein consumption (in grams) results from the NNYFS data.
```{r}
mosaic::favstats(~ protein, data = nnyfs)
```
```{r}
p1 <- ggplot(nnyfs, aes(x = "Protein", y = protein)) +
geom_violin() +
geom_boxplot(width = 0.2, fill = "salmon",
outlier.color = "red") +
theme_light() +
labs(title = "NNYFS Protein consumption",
x = "", y = "Protein Consumption (g)")
p2 <- ggplot(nnyfs, aes(sample = protein)) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "NNYFS Protein Consumption",
y = "Protein Consumption (g)")
gridExtra::grid.arrange(p1, p2, nrow = 1)
```
The key point here is that we see several signs of meaningful right skew, and we'll want to consider a transformation that might make a Normal model more plausible.
### Using `cowplot::plot_grid()` to compose plots
In addition to the `grid.arrange` function in `gridExtra`, we could also use `plot_grid()` in the `cowplot` package to put our plots together.
```{r}
p1 <- ggplot(nnyfs, aes(x = "Protein", y = protein)) +
geom_violin() +
geom_boxplot(width = 0.2, fill = "salmon",
outlier.color = "red") +
theme_light() +
labs(title = "NNYFS Protein consumption",
x = "", y = "Protein Consumption (g)")
p2 <- ggplot(nnyfs, aes(sample = protein)) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "NNYFS Protein Consumption",
y = "Protein Consumption (g)")
cowplot::plot_grid(p1, p2, nrow = 1)
```
`plot_grid()` has some functionality that's easier to work with than `grid.arrange` for some people, so you might want to learn more about it. Check out its web site at https://wilkelab.org/cowplot/.
### Using `patchwork` to compose plots
For me, the slickest approach to composing how a series of plots are placed together is available in the `patchwork` package, which must be installed via Github using `devtools` at this writing.
```{r}
## must install patchwork from Github using devtools
## with devtools::install_github("thomasp85/patchwork")
library(patchwork)
res <- mosaic::favstats(~ protein, data = nnyfs)
bin_w <- 5 # specify binwidth
p1 <- ggplot(nnyfs, aes(x = protein)) +
geom_histogram(binwidth = bin_w,
fill = "salmon",
col = "white") +
theme_light() +
stat_function(
fun = function(x) dnorm(x, mean = res$mean,
sd = res$sd) *
res$n * bin_w,
col = "darkred", size = 2) +
labs(title = "Histogram with Normal fit",
x = "Protein Consumption (g)", y = "# of subjects")
p2 <- ggplot(nnyfs, aes(sample = protein)) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Normal Q-Q plot",
y = "Protein Consumption (g)")
p3 <- ggplot(nnyfs, aes(x = "", y = protein)) +
geom_violin() +
geom_boxplot(width = 0.2, fill = "salmon",
outlier.color = "red") +
theme_light() +
coord_flip() +
labs(title = "Boxplot with Violin",
x = "", y = "Protein Consumption (g)")
p1 + p2 - p3 + plot_layout(ncol = 1, height = c(3, 1)) +
plot_annotation(title = "NNYFS Protein Consumption")
```
For more on the `patchwork` package, check out its repository at https://github.com/thomasp85/patchwork.
## Can we transform the `protein` data?
As we've seen, the `protein` data are right skewed, and all of the values are strictly positive. If we want to use the tools of the Normal distribution to describe these data, we might try taking a step "down" our ladder from power 1 (raw data) to lower powers.
### The Square Root
Would a square root applied to the protein data help alleviate that right skew?
```{r}
## must install patchwork from Github using devtools
## with devtools::install_github("thomasp85/patchwork")
## library(patchwork)
res <- mosaic::favstats(~ sqrt(protein), data = nnyfs)
bin_w <- 1 # specify binwidth
p1 <- ggplot(nnyfs, aes(x = sqrt(protein))) +
geom_histogram(binwidth = bin_w,
fill = "salmon",
col = "white") +
theme_light() +
stat_function(
fun = function(x) dnorm(x, mean = res$mean,
sd = res$sd) *
res$n * bin_w,
col = "darkred", size = 2) +
labs(title = "Histogram with Normal fit",
x = "Square Root of Protein Consumption (g)", y = "# of subjects")
p2 <- ggplot(nnyfs, aes(sample = sqrt(protein))) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Normal Q-Q plot",
y = "Square Root of Protein Consumption (g)")
p3 <- ggplot(nnyfs, aes(x = "", y = sqrt(protein))) +
geom_violin() +
geom_boxplot(width = 0.2, fill = "salmon",
outlier.color = "red") +
theme_light() +
coord_flip() +
labs(title = "Boxplot with Violin",
x = "", y = "Square Root of Protein Consumption (g)")
p1 + p2 - p3 + plot_layout(ncol = 1, height = c(3, 1)) +
plot_annotation(title = "Square Root of NNYFS Protein Consumption")
```
That looks like a more symmetric distribution, certainly, although we still have some outliers on the right side of the distribution. Should we take another step down the ladder?
### The Logarithm
We might also try a logarithm of the energy circumference data. We can use either the natural logarithm (log, in R) or the base-10 logarithm (log10, in R) - either will have the same impact on skew.
```{r}
## must install patchwork from Github using devtools
## with devtools::install_github("thomasp85/patchwork")
## library(patchwork)
res <- mosaic::favstats(~ log(protein), data = nnyfs)
bin_w <- 0.5 # specify binwidth
p1 <- ggplot(nnyfs, aes(x = log(protein))) +
geom_histogram(binwidth = bin_w,
fill = "salmon",
col = "white") +
theme_light() +
stat_function(
fun = function(x) dnorm(x, mean = res$mean,
sd = res$sd) *
res$n * bin_w,
col = "darkred", size = 2) +
labs(title = "Histogram with Normal fit",
x = "Log of Protein Consumption (g)", y = "# of subjects")
p2 <- ggplot(nnyfs, aes(sample = log(protein))) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Normal Q-Q plot",
y = "Log of Protein Consumption (g)")
p3 <- ggplot(nnyfs, aes(x = "", y = log(protein))) +
geom_violin() +
geom_boxplot(width = 0.2, fill = "salmon",
outlier.color = "red") +
theme_light() +
coord_flip() +
labs(title = "Boxplot with Violin",
x = "", y = "Log of Protein Consumption (g)")
p1 + p2 - p3 + plot_layout(ncol = 1, height = c(3, 1)) +
plot_annotation(title = "Logarithm of NNYFS Protein Consumption")
```
Now, it looks like we may have gone too far in the other direction. It looks like the square root is a sensible choice to try to improve the fit of a Normal model to the protein consumption data.
### This course uses Natural Logarithms, unless otherwise specified
In this course, we will assume the use of natural logarithms unless we specify otherwise. Following R's convention, we will use `log` for natural logarithms.
## What if we considered all 9 available transformations?
```{r, fig.height = 7}
## must install patchwork from Github using devtools
## with devtools::install_github("thomasp85/patchwork")
## library(patchwork)
p1 <- ggplot(nnyfs, aes(sample = protein^3)) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Cube (power 3)",
y = "Protein, Cubed")
p2 <- ggplot(nnyfs, aes(sample = protein^2)) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Square (power 2)",
y = "Protein, Squared")
p3 <- ggplot(nnyfs, aes(sample = protein)) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Original Data",
y = "Protein (g)")
p4 <- ggplot(nnyfs, aes(sample = sqrt(protein))) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "sqrt (power 0.5)",
y = "Square Root of Protein")
p5 <- ggplot(nnyfs, aes(sample = log(protein))) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "log (power 0)",
y = "Natural Log of Protein")
p6 <- ggplot(nnyfs, aes(sample = protein^(-0.5))) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "1/sqrt (power -0.5)",
y = "1/Square Root(Protein)")
p7 <- ggplot(nnyfs, aes(sample = 1/protein)) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Inverse (power -1)",
y = "1/Protein")
p8 <- ggplot(nnyfs, aes(sample = 1/(protein^2))) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "1/Square (power -2)",
y = "1 /(Protein squared)")
p9 <- ggplot(nnyfs, aes(sample = 1/(protein^3))) +
geom_qq(col = "salmon") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "1/Cube (power -3)",
y = "1/(Protein cubed)")
p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 +
plot_layout(nrow = 3) +
plot_annotation(title = "Transformations of NNYFS Protein Consumption")
```
The square root still appears to be the best choice of transformation here, even after we consider all 8 transformation of the raw data.
## A Simulated Data Set
```{r}
set.seed(431);
data2 <- data.frame(sample2 = 100*rbeta(n = 125, shape1 = 5, shape2 = 2))
```
If we'd like to transform these data so as to better approximate a Normal distribution, where should we start? What transformation do you suggest?
```{r}
## must install patchwork from Github using devtools
## with devtools::install_github("thomasp85/patchwork")
## library(patchwork)
res <- mosaic::favstats(~ sample2, data = data2)
bin_w <- 4 # specify binwidth
p1 <- ggplot(data2, aes(x = sample2)) +
geom_histogram(binwidth = bin_w,
fill = "royalblue",
col = "white") +
theme_light() +
stat_function(
fun = function(x) dnorm(x, mean = res$mean,
sd = res$sd) *
res$n * bin_w,
col = "darkred", size = 2) +
labs(title = "Histogram with Normal fit",
x = "Simulated Data", y = "# of subjects")
p2 <- ggplot(data2, aes(sample = sample2)) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Normal Q-Q plot",
y = "Simulated Data")
p3 <- ggplot(data2, aes(x = "", y = sample2)) +
geom_violin() +
geom_boxplot(width = 0.3, fill = "royalblue",
outlier.color = "royalblue") +
theme_light() +
coord_flip() +
labs(title = "Boxplot with Violin",
x = "", y = "Simulated Data")
p1 + p2 - p3 + plot_layout(ncol = 1, height = c(3, 1)) +
plot_annotation(title = "Simulated Data")
```
Given the left skew in the data, it looks like a step up in the ladder is warranted, perhaps by looking at the square of the data?
```{r}
## must install patchwork from Github using devtools
## with devtools::install_github("thomasp85/patchwork")
## library(patchwork)
res <- mosaic::favstats(~ sample2^2, data = data2)
bin_w <- 600 # specify binwidth
p1 <- ggplot(data2, aes(x = sample2^2)) +
geom_histogram(binwidth = bin_w,
fill = "royalblue",
col = "white") +
theme_light() +
stat_function(
fun = function(x) dnorm(x, mean = res$mean,
sd = res$sd) *
res$n * bin_w,
col = "darkred", size = 2) +
labs(title = "Histogram with Normal fit",
x = "Squared Simulated Data", y = "# of subjects")
p2 <- ggplot(data2, aes(sample = sample2^2)) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Normal Q-Q plot",
y = "Squared Simulated Data")
p3 <- ggplot(data2, aes(x = "", y = sample2^2)) +
geom_violin() +
geom_boxplot(width = 0.3, fill = "royalblue",
outlier.color = "royalblue") +
theme_light() +
coord_flip() +
labs(title = "Boxplot with Violin",
x = "", y = "Squared Simulated Data")
p1 + p2 - p3 + plot_layout(ncol = 1, height = c(3, 1)) +
plot_annotation(title = "Squared Simulated Data")
```
Looks like at best a modest improvement. How about cubing the data, instead?
```{r}
## must install patchwork from Github using devtools
## with devtools::install_github("thomasp85/patchwork")
## library(patchwork)
res <- mosaic::favstats(~ sample2^3, data = data2)
bin_w <- 100000 # specify binwidth
p1 <- ggplot(data2, aes(x = sample2^3)) +
geom_histogram(binwidth = bin_w,
fill = "royalblue",
col = "white") +
theme_light() +
stat_function(
fun = function(x) dnorm(x, mean = res$mean,
sd = res$sd) *
res$n * bin_w,
col = "darkred", size = 2) +
labs(title = "Histogram with Normal fit",
x = "Cubed Simulated Data", y = "# of subjects")
p2 <- ggplot(data2, aes(sample = sample2^3)) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Normal Q-Q plot",
y = "Cubed Simulated Data")
p3 <- ggplot(data2, aes(x = "", y = sample2^3)) +
geom_violin() +
geom_boxplot(width = 0.3, fill = "royalblue",
outlier.color = "royalblue") +
theme_light() +
coord_flip() +
labs(title = "Boxplot with Violin",
x = "", y = "Cubed Simulated Data")
p1 + p2 - p3 + plot_layout(ncol = 1, height = c(3, 1)) +
plot_annotation(title = "Cubed Simulated Data")
```
The newly transformed (cube of the) data appears more symmetric, although somewhat light-tailed. Perhaps a Normal model would be more appropriate now, although the standard deviation is likely to overstate the variation we see in the data due to the light tails. Again, I wouldn't be thrilled using a cube in practical work, as it is so hard to interpret, but it does look like a reasonable choice here.
## What if we considered all 9 available transformations?
```{r, fig.height = 7}
## must install patchwork from Github using devtools
## with devtools::install_github("thomasp85/patchwork")
## library(patchwork)
p1 <- ggplot(data2, aes(sample = sample2^3)) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Cube (power 3)")
p2 <- ggplot(data2, aes(sample = sample2^2)) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Square (power 2)")
p3 <- ggplot(data2, aes(sample = sample2)) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Original Data")
p4 <- ggplot(data2, aes(sample = sqrt(sample2))) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "sqrt (power 0.5)")
p5 <- ggplot(data2, aes(sample = log(sample2))) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "log (power 0)")
p6 <- ggplot(data2, aes(sample = sample2^(0.5))) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "1/sqrt (power -0.5)")
p7 <- ggplot(data2, aes(sample = 1/sample2)) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "Inverse (power -1)")
p8 <- ggplot(data2, aes(sample = 1/(sample2^2))) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "1/Square (power -2)")
p9 <- ggplot(data2, aes(sample = 1/(sample2^3))) +
geom_qq(col = "royalblue") +
geom_qq_line(col = "black") +
theme_light() +
labs(title = "1/Cube (power -3)")
p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 +
plot_layout(nrow = 3) +
plot_annotation(title = "Transformations of Simulated Sample")
```
Again, either the cube or the square looks like best choice here, in terms of creating a more symmetric (albeit light-tailed) distribution.
```{r}
rm(p1, p2, p3, p4, p5, p6, p7, p8, p9, res, bin_w, data2)
``` |
/*
* uart
*
* Wrapper for all UART related modules.
*/
module uart
#(
parameter real CLK_FREQ = 100_000_000, // 100 Mhz, 10 ns
BAUDRATE = 115_200,
parameter DATA_BIT = 8,
STOP_BIT = 1,
FIFO_WIDTH = 4 // 2^4 or 16 bytes
)
(
input logic clk,
input logic reset_n,
input logic wr,
input logic [DATA_BIT-1:0] w_data,
output logic tx
);
/* ~~ Create uart_baudrate_gen unit ~~ */
logic s_tick;
uart_baudrate_gen #(.CLK_FREQ(CLK_FREQ), .BAUDRATE(BAUDRATE)) uart_baudrate_gen_unit(
.clk(clk),
.reset_n(reset_n),
// Outputs
.s_tick(s_tick)
);
/* ~~ Create uart_tx unit ~~ */
logic uart_tx_done_tick;
uart_tx #(.DATA_BIT(DATA_BIT), .STOP_BIT(STOP_BIT)) uart_tx_unit(
.clk(clk),
.reset_n(reset_n),
.s_tick(s_tick),
.tx_start(fifo_tx_not_empty), // Start sending as soon as fifo is not empty.
.tx_data(fifo_tx_out),
// Outputs
.tx_done_tick(uart_tx_done_tick),
.tx(tx)
);
/* ~~ Create fifo_tx unit ~~ */
logic fifo_tx_empty, fifo_tx_not_empty, fifo_tx_full;
logic [DATA_BIT-1:0] fifo_tx_out;
fifo #(.DATA_WIDTH(DATA_BIT), .ADDR_WIDTH(FIFO_WIDTH)) fifo_tx_unit(
.clk(clk),
.reset_n(reset_n),
.rd(uart_tx_done_tick), // Read the next byte after the previous byte is tranmitted.
.wr(wr),
.w_data(w_data),
// Outputs
.empty(fifo_tx_empty),
.full(fifo_tx_full),
.r_data(fifo_tx_out)
);
assign fifo_tx_not_empty = ~fifo_tx_empty;
endmodule |
from pydantic import Field, SecretStr
from dispatch.config import BaseConfigurationModel
class OpenAIConfiguration(BaseConfigurationModel):
"""OpenAI configuration description."""
api_key: SecretStr = Field(title="API Key", description="Your secret OpenAI API key.")
model: str = Field(
"gpt-3.5-turbo",
title="Model",
description="Available models can be found at https://platform.openai.com/docs/models",
)
system_message: str = Field(
"You are a helpful assistant.",
title="System Message",
description="The system message to help set the behavior of the assistant.",
) |
import React, { Component } from "react";
import styled from "styled-components";
import Task from "./task";
import { Droppable, Draggable } from "react-beautiful-dnd";
const Container = styled.div`
margin: 8px;
border: 1px solid lightgrey;
border-radius: 2px;
width: 220px;
background-color: white;
display: flex;
flex-direction: column;
`;
const Title = styled.h3`
padding: 8px;
`;
const TaskList = styled.div`
padding: 8px;
transition: background-color 0.2s ease;
background-color: ${props => (props.isDraggingOver ? "skyblue" : "inherit")};
flex-grow: 1;
min-height: 100px;
`;
class InnerList extends React.Component {
shouldComponentUpdate(nextProps) {
if (nextProps.tasks === this.props.tasks) {
return false;
}
return true;
}
render() {
return this.props.tasks.map((task, index) => (
<Task key={task.id} task={task} index={index} />
))
}
}
class Column extends Component {
render() {
const { column } = this.props;
return (
<Draggable draggableId={column.id} index={this.props.index}>
{provided => (
<Container {...provided.draggableProps} ref={provided.innerRef}>
<Title {...provided.dragHandleProps}>{column.title}</Title>
<Droppable
droppableId={column.id}
type="task"
>
{(provided, snapshot) => (
<TaskList
{...provided.droppableProps}
ref={provided.innerRef}
isDraggingOver={snapshot.isDraggingOver}
>
<InnerList tasks={this.props.tasks} />
{provided.placeholder}
</TaskList>
)}
</Droppable>
</Container>
)}
</Draggable>
);
}
}
export default Column; |
import React, { FC } from "react";
import Button from "react-bootstrap/Button";
import ButtonGroup from "react-bootstrap/ButtonGroup";
import { IButton } from "../models/types";
interface ButtonsBlockProps {
buttons: IButton[];
}
const ButtonsBlock: FC<ButtonsBlockProps> = ({ buttons }) => {
return (
<ButtonGroup aria-label="Basic example">
{buttons.map((button) => (
<Button key={button.id} onClick={button.handle} variant={button.variant} active={button.active}>
{button.title}
</Button>
))}
</ButtonGroup>
);
};
export default ButtonsBlock; |
import { useState, useEffect, useContext } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import axios from "axios";
import AuthContext from "../context/AuthProvider";
const useAuth = (currentRoles) => {
const [auth, setAuth] = useState(null);
const navigate = useNavigate();
const context = useContext(AuthContext);
let location = useLocation();
useEffect(() => {
if (context.persist && location.pathname === "/") {
navigate("/Home");
}
if (context.persist === false && location.pathname === "/") {
navigate("/Login");
}
const authenticateUser = async () => {
try {
const token = await axios.get(
`${process.env.REACT_APP_API_URL}/token/refresh`,
{
withCredentials: true,
}
);
const response = await axios.get(
`${process.env.REACT_APP_API_URL}/getUser`,
{
headers: { Authorization: `Bearer ${token.data.token}` },
}
);
// Guard if user is not authorized
if (
context.persist === true &&
currentRoles !== undefined &&
currentRoles.length > 0 &&
!currentRoles?.includes(response?.data?.roleNames[0].toString())
) {
navigate("/unauthorized");
}
setAuth((prev) => {
return {
...prev,
roles: response.data.roleNames,
accessToken: response.data.credentials,
idUser: response.data.user.id,
user: response.data.user,
};
});
} catch (error) {
setAuth(null);
}
};
authenticateUser();
}, [context.persist, currentRoles, location.pathname, navigate]);
return { auth, setAuth };
};
export default useAuth; |
using Godot;
using System;
using System.Data.Odbc;
public class Gem : Node2D
{
[Export] public Color ColorType { get; set; }
[Export] public bool IsInteractable { get; set; } = true;
[Export] public bool Regeneratable { get; set; }
private Timer RegenerationTimer;
private Interactable Interactable;
private Sprite GemSprite;
private ShaderMaterial ShaderMaterial = GD.Load<ShaderMaterial>("res://Scripts/Shared/OutlineShader.tres");
public override void _Ready()
{
this.GemSprite = base.GetNode<Sprite>("Sprite");
this.Interactable = this.GetNode<Interactable>("Interactable");
// Give the player gem when the player interacts with it
this.Interactable.Interacted += () =>
{
if (!this.Visible)
return;
GameState.AddGem(ColorType);
if (Regeneratable)
{
this.Visible = false;
/* if (this.ColorType == Color.Red)
GameState.RedGemQueue.Enqueue(this); */
}
else
{
this.QueueFree();
}
};
if (Regeneratable)
{
this.RegenerationTimer = base.GetNode<Timer>("RegenerationTimer");
this.RegenerationTimer.Connect("timeout", this, nameof(RegenerateGem));
}
// Load Texture based on color
switch (ColorType)
{
case Color.Blue:
this.GetNode<Sprite>("Sprite").Texture = GD.Load<Texture>("res://Assets/LevelSprites/Blue_Gem.png");
break;
case Color.Yellow:
this.GetNode<Sprite>("Sprite").Texture = GD.Load<Texture>("res://Assets/LevelSprites/Yellow_Gem.png");
break;
case Color.Red:
this.GetNode<Sprite>("Sprite").Texture = GD.Load<Texture>("res://Assets/LevelSprites/Red_Gem.png");
break;
case Color.Purple:
this.GetNode<Sprite>("Sprite").Texture = GD.Load<Texture>("res://Assets/LevelSprites/Purple_Gem.png");
break;
}
this.Interactable.PlayerEntered += OnPlayerEntered;
this.Interactable.PlayerExited += OnPlayerExited;
}
private void RegenerateGem()
{
/* if (GameState.RedGemQueue.Contains(this))
{
return;
} */
this.Visible = true;
}
private void OnPlayerEntered()
{
if (IsInteractable)
{
this.GemSprite.Material = ShaderMaterial;
}
}
private void OnPlayerExited()
{
this.GemSprite.Material = null;
}
public enum Color
{
Blue, Yellow, Red, Purple
}
} |
import React, { useState } from "react";
import AlertSuccess from "../../components/Alert/AlertSuccess";
import AlertInfo from "../../components/Alert/AlertInfo";
import "./Contributing.css";
const Contributing = () => {
const [activity, setActivity] = useState("");
const [type, setType] = useState("recreational");
const [participants, setParticipants] = useState("");
const [isAlert, setIsAlert] = useState(false);
const [isHideAlert, setIsHideAlert] = useState(true);
const [message, setMessage] = useState("");
const types = [
"education",
"recreational",
"social",
"diy",
"charity",
"cooking",
"relaxation",
"music",
"busywork",
];
const contribute = (e) => {
e.preventDefault();
const data = {
activity: activity,
type: type,
participants: participants,
};
fetch("https://www.boredapi.com/api/suggestion", {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify(data),
})
.then((response) => {
if (!response.ok) {
setIsAlert(true);
} else {
setIsAlert(false);
}
return response.json();
})
.then((data) => {
if (data.error) {
setIsAlert(true);
} else {
setMessage(data.message);
}
setIsHideAlert(false);
setTimeout(() => {
setIsHideAlert(true);
}, 4000);
})
.catch((error) => console.error(error));
};
return (
<main className="contributing main">
<header className="main__header">
<h2 className="main__title contributing__title">
Help other people to motivate with your ideas.
</h2>
<p className="main__subtitle"></p>
<p>Listed here are some guidelines to help with your submission: </p>
<ul className="guidelines">
<li className="guideline">
Activities should start with a verb in the form of a command (ex.
"Research ...", "Invite ...", "Create ...").
</li>
<li className="guideline">
Try to keep the activities general and without references to
companies or name brand products.
</li>
</ul>
</header>
<form className="form">
<fieldset className="form__fieldset">
<legend className="form__legend">Contributing Form</legend>
<div className="input-group">
<label htmlFor="activity">*Activity: </label>
<br />
<input
type="text"
id="activity"
placeholder="Watch a classic movie"
value={activity}
onChange={(e) => {
setActivity(e.target.value);
}}
className="input-group__input"
minLength="3"
maxLength="64"
required
/>
{/* <span className="input-group__help"></span> */}
</div>
<div className="form__select">
<label htmlFor="select">*Type: </label>
<br />
<select
name="type"
id="select"
className="form__select"
value={type}
onChange={(e) => {
setType(e.currentTarget.value);
}}
required
>
{types.map((type) => {
return (
<option key={type} value={type}>
{type}
</option>
);
})}
</select>
</div>
<div className="input-group">
<label htmlFor="participants">*Participants: </label>
<br />
<input
type="number"
id="participants"
defaultValue={participants}
onChange={(e) => {
setParticipants(e.target.value);
}}
placeholder="2"
min="1"
max="1000"
className="input-group__input"
required
/>
{/* <span className="input-group__help"></span> */}
</div>
<div className="form__actions">
<button type="submit" className="form__btn" onClick={contribute}>
Send
</button>
</div>
</fieldset>
<div className="form__row">
<details className="form__details">
<summary className="form__summary">(*) Required Field</summary>
<p>Fields with the star symbol are required.</p>
</details>
</div>
</form>
{(() => {
if (!isAlert && !isHideAlert) {
return <AlertSuccess message={message} />;
}
if (isAlert && !isHideAlert) {
return <AlertInfo />;
}
})()}
</main>
);
};
export default Contributing; |
'use client';
import { useChat, Message } from 'ai/react';
import { useEffect, useState, useRef } from 'react';
import { Analytics } from "@vercel/analytics/react"
import logo from './logo.jpg';
import Image from 'next/image';
export default function Chat() {
const [inputValue, setInputValue] = useState('');
const [submitted, setSubmitted] = useState(false);
const timerRef = useRef<NodeJS.Timer | null | number>(null);
const [initialMessages, setInitialMessages] = useState<Message[]>();
const { messages, handleInputChange, handleSubmit, append } = useChat({ initialMessages });
const getOldMessages = async () => {
const response = await fetch('/api/messages', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
const jsonResponse = (await response.json()) as Message[];
setInitialMessages(jsonResponse);
}
useEffect(() => {
getOldMessages();
}, [])
useEffect(() => {
if (!submitted && initialMessages?.length === 0) {
const lastMessage = "Hi, how are you?";
setInputValue(lastMessage);
handleInputChange({ target: { value: lastMessage } } as React.ChangeEvent<HTMLInputElement>);
let test: Message = {
id: "initial",
content: lastMessage,
role: "user"
}
append(test);
setSubmitted(true);
}
const interval = setInterval(() => {
console.log("Running check to send automessage")
if (messages.length > 0 && !submitted) {
console.log("Running message check");
const lastMessage = messages[messages.length - 1].content;
console.log("Last message was");
setInputValue(lastMessage);
handleInputChange({ target: { value: lastMessage } } as React.ChangeEvent<HTMLInputElement>);
let test: Message = {
id: "auto" + Math.random(),
content: lastMessage,
role: "user"
}
append(test);
setSubmitted(true);
}
}, 60 * 1000); // 60 seconds
return () => {
console.log("Reset automessage interval");
clearInterval(interval);
};
}, [messages, submitted, initialMessages])
return (
<div>
<div className="mx-auto w-full px-24 py-12 flex"><Image alt="Logo" className='w-20 h-20 mr-4' src={logo}/>This is a proof of concept of AI's talking to each other, hopefully engaging in playful conversation. Messages below have been generated across different user sessions.</div>
<div className="mx-auto w-full max-w-md py-24 flex flex-col stretch">
{messages.length > 0
? messages.map(m => (
<div key={m.id} className="whitespace-pre-wrap">
{m.role === 'user' ? 'AI 2: ' : 'AI 1: '}
{m.content}
</div>
))
: null}
<div className="fixed w-full max-w-md bottom-20 border border-gray-300 rounded mb-8 shadow-xl p-2">In order to keep things fair, AI is only going to talk to itself once a minute to preserve tokens for others.</div>
<form onSubmit={handleSubmit}>
<input
className="fixed w-full max-w-md bottom-0 border border-gray-300 rounded mb-8 shadow-xl p-2"
value={inputValue}
placeholder="Say something..."
onChange={handleInputChange}
disabled
/>
</form>
</div>
</div>
);
} |
import { getAllRoleList, isAccountExist } from '/@/api/demo/system';
import { BasicColumn, FormSchema } from '/@/components/Table';
export const columns: BasicColumn[] = [
{
title: '姓名',
dataIndex: 'name',
width: 120,
},
{
title: '性别',
dataIndex: 'gender',
width: 120,
},
{
title: '部门',
dataIndex: 'department',
width: 120,
},
{
title: '邮箱',
dataIndex: 'email',
width: 120,
},
{
title: '联系电话',
dataIndex: 'phone',
width: 120,
},
{
title: '角色',
dataIndex: 'role',
width: 120,
},
];
export const searchFormSchema: FormSchema[] = [
{
field: 'name',
label: '姓名',
component: 'Input',
colProps: { span: 8 },
},
{
field: 'email',
label: '邮箱',
component: 'Input',
colProps: { span: 8 },
},
];
export const accountFormSchema: FormSchema[] = [
{
field: 'name',
label: '姓名',
component: 'Input',
helpMessage: ['本字段演示异步验证', '不能输入带有admin的用户名'],
rules: [
{
required: true,
message: '请输入用户名',
},
{
validator(_, value) {
return new Promise((resolve, reject) => {
isAccountExist(value)
.then(() => resolve())
.catch((err) => {
reject(err.message || '验证失败');
});
});
},
},
],
},
{
field: 'pwd',
label: '密码',
component: 'InputPassword',
required: true,
ifShow: false,
},
{
label: '角色',
field: 'role',
component: 'ApiSelect',
componentProps: {
api: getAllRoleList,
labelField: 'roleName',
valueField: 'roleValue',
},
required: true,
},
{
field: 'dept',
label: '所属部门',
component: 'TreeSelect',
componentProps: {
fieldNames: {
label: 'deptName',
key: 'id',
value: 'id',
},
getPopupContainer: () => document.body,
},
required: true,
},
{
label: '邮箱',
field: 'email',
component: 'Input',
required: true,
},
{
label: '备注',
field: 'remark',
component: 'InputTextArea',
},
]; |
/*
* Copyright [2021] [wisemapping]
*
* Licensed under WiseMapping Public License, Version 1.0 (the "License").
* It is basically the Apache License, Version 2.0 (the "License") plus the
* "powered by wisemapping" text requirement on every single page;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the license at
*
* http://www.wisemapping.org/license
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React, { ReactElement, useEffect } from 'react';
import Popover from '@mui/material/Popover';
import { Vortex } from 'react-loader-spinner';
import { FormattedMessage, IntlProvider } from 'react-intl';
import { Designer, DesignerKeyboard } from '@edifice-wisemapping/mindplot';
import I18nMsg from '../classes/i18n-msg';
// eslint-disable-next-line no-restricted-imports
import { Theme } from '@mui/material/styles';
import { Notifier } from './warning-dialog/styled';
import WarningDialog from './warning-dialog';
import AppBar from './app-bar';
import { ToolbarActionType } from './toolbar/ToolbarActionType';
import EditorToolbar from './editor-toolbar';
import ZoomPanel from './zoom-panel';
import IconButton from '@mui/material/IconButton';
import Box from '@mui/material/Box';
import CloseIcon from '@mui/icons-material/Close';
import { SpinnerCentered } from './style';
import Typography from '@mui/material/Typography';
import { useWidgetManager } from '../hooks/useWidgetManager';
import { EditorConfiguration } from '../hooks/useEditor';
type EditorProps = {
theme?: Theme;
onAction: (action: ToolbarActionType) => void;
onLoad: (designer: Designer) => void;
editor: EditorConfiguration;
accountConfiguration?: React.ReactElement;
};
const Editor = ({ editor, onAction, accountConfiguration }: EditorProps): ReactElement => {
// We can access editor instance and other configuration from editor props
const { model, mindplotRef, mapInfo, capability, options } = editor;
const { popoverOpen, setPopoverOpen, popoverTarget, widgetManager } = useWidgetManager();
useEffect(() => {
if (options.enableKeyboardEvents) {
DesignerKeyboard.resume();
} else {
DesignerKeyboard.pause();
}
}, [options.enableKeyboardEvents]);
// Initialize locale ...
const locale = options.locale;
const msg = I18nMsg.loadLocaleData(locale);
return (
<IntlProvider locale={locale} messages={msg}>
{options.enableAppBar ? (
<AppBar
model={model}
mapInfo={mapInfo}
capability={capability}
onAction={onAction}
accountConfig={accountConfiguration}
/>
) : null}
<Popover
id="popover"
open={popoverOpen}
anchorEl={popoverTarget}
onClose={widgetManager.handleClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
>
<Box textAlign={'right'} ml={1}>
<Typography variant="body1" style={{ paddingTop: '10px', float: 'left' }}>
<FormattedMessage
id={widgetManager.getEditorTile()}
defaultMessage=""
></FormattedMessage>
</Typography>
<IconButton onClick={() => setPopoverOpen(false)} aria-label={'Close'}>
<CloseIcon />
</IconButton>
</Box>
{widgetManager.getEditorContent()}
</Popover>
<div className="no-print">
<EditorToolbar model={model} capability={capability} />
<ZoomPanel model={model} capability={capability} />
</div>
<mindplot-component
ref={mindplotRef}
id="mindmap-comp"
mode={options.mode}
locale={locale}
zoom={options.zoom}
/>
<Notifier id="headerNotifier" />
<WarningDialog
capability={capability}
message={mapInfo.isLocked() ? mapInfo.getLockedMessage() : ''}
/>
{!model?.isMapLoadded() && (
<div className="no-print">
<SpinnerCentered>
<Vortex
visible={true}
height="160"
width="160"
ariaLabel="vortex-loading"
colors={['#ffde1a', '#ffce00', '#ffa700', '#ff8d00', '#ff7400', '#ffde1a']}
/>
</SpinnerCentered>
</div>
)}
</IntlProvider>
);
};
export default Editor; |
/*
* Copyright (c) 2021-2021 Huawei Device Co., Ltd.
* 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.
*/
#include "plugin_meta.h"
#include <cinttypes>
#include <cstring>
#include <memory>
#include <vector>
#include "plugin/common/plugin_audio_tags.h"
namespace OHOS {
namespace Media {
namespace Plugin {
using PointerPair = std::pair<std::shared_ptr<uint8_t>, size_t>;
Meta::~Meta()
{
Clear();
}
bool Meta::Empty() const
{
return items_.empty();
}
bool Meta::SetString(Plugin::MetaID id, const std::string& value)
{
return SetData<std::string>(id, value);
}
bool Meta::SetInt32(Plugin::MetaID id, int32_t value)
{
return SetData<int32_t>(id, value);
}
bool Meta::SetUint32(Plugin::MetaID id, uint32_t value)
{
return SetData<uint32_t>(id, value);
}
bool Meta::SetInt64(Plugin::MetaID id, int64_t value)
{
return SetData<int64_t>(id, value);
}
bool Meta::SetUint64(Plugin::MetaID id, uint64_t value)
{
return SetData<uint64_t>(id, value);
}
bool Meta::SetFloat(Plugin::MetaID id, float value)
{
return SetData<float>(id, value);
}
bool Meta::GetString(Plugin::MetaID id, std::string& value) const
{
auto ite = items_.find(id);
if (ite == items_.end()) {
return false;
}
if (ite->second.SameTypeWith(typeid(const char*))) {
value = Plugin::AnyCast<const char*>(ite->second);
} else if (ite->second.SameTypeWith(typeid(std::string))) {
value = Plugin::AnyCast<std::string>(ite->second);
} else if (ite->second.SameTypeWith(typeid(char*))) {
value = Plugin::AnyCast<char*>(ite->second);
} else {
return false;
}
return true;
}
bool Meta::GetInt32(Plugin::MetaID id, int32_t& value) const
{
return GetData<int32_t>(id, value);
}
bool Meta::GetUint32(Plugin::MetaID id, uint32_t& value) const
{
return GetData<uint32_t>(id, value);
}
bool Meta::GetInt64(Plugin::MetaID id, int64_t& value) const
{
return GetData<int64_t>(id, value);
}
bool Meta::GetUint64(Plugin::MetaID id, uint64_t& value) const
{
return GetData<uint64_t>(id, value);
}
bool Meta::GetFloat(Plugin::MetaID id, float& value) const
{
return GetData<float>(id, value);
}
void Meta::Clear()
{
items_.clear();
}
bool Meta::Remove(Plugin::MetaID id)
{
auto ite = items_.find(id);
if (ite == items_.end()) {
return false;
}
items_.erase(ite);
return true;
}
void Meta::Update(const Meta& meta)
{
for (auto& ptr : meta.items_) {
// we need to copy memory for pointers
if (ptr.second.SameTypeWith(typeid(PointerPair))) {
auto pointerPair = Plugin::AnyCast<PointerPair>(ptr.second);
SetPointer(ptr.first, pointerPair.first.get(), pointerPair.second);
} else {
items_[ptr.first] = ptr.second;
}
}
}
bool Meta::SetPointer(Plugin::MetaID id, const void* ptr, size_t size) // NOLINT:void*
{
if (size == 0) {
return false;
}
auto tmp = new (std::nothrow) uint8_t[size];
if (tmp == nullptr) {
return false;
}
std::shared_ptr<uint8_t> savePtr(tmp, std::default_delete<uint8_t[]>());
if (memcpy_s(savePtr.get(), size, ptr, size) != EOK) {
delete[] tmp;
return false;
}
return SetData<std::pair<std::shared_ptr<uint8_t>, size_t>>(id, std::make_pair(savePtr, size));
}
bool Meta::GetPointer(Plugin::MetaID id, void** ptr, size_t& size) const // NOLINT: void*
{
std::pair<std::shared_ptr<uint8_t>, size_t> item;
if (GetData<std::pair<std::shared_ptr<uint8_t>, size_t>>(id, item)) {
size = item.second;
if (size == 0) {
return false;
}
auto tmp = new (std::nothrow) uint8_t[size];
if (tmp == nullptr) {
return false;
}
if (memcpy_s(tmp, size, item.first.get(), size) != EOK) {
delete[] tmp;
return false;
}
*ptr = tmp;
return true;
} else {
return false;
}
}
std::vector<MetaID> Meta::GetMetaIDs() const
{
std::vector<MetaID> ret (items_.size());
int cnt = 0;
for (const auto& tmp : items_) {
ret[cnt++] = tmp.first;
}
return ret;
}
} // namespace Plugin
} // namespace Media
} // namespace OHOS |
"""A child is playing with a ball on the nth floor of a tall building. The height of this floor above ground level, h, is known.
He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).
His mother looks out of a window 1.5 meters from the ground.
How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing)?
Three conditions must be met for a valid experiment:
Float parameter "h" in meters must be greater than 0
Float parameter "bounce" must be greater than 0 and less than 1
Float parameter "window" must be less than h.
If all three conditions above are fulfilled, return a positive integer, otherwise return -1.
Note:
The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.
"""
def bouncing_ball(h, bounce, window):
if h > 0 and window < h and bounce > 0 and bounce < 1:
sighting = 1
while h > window:
if h * bounce > window:
sighting += 2
h = h * bounce
return sighting
return -1
def fixed_tests():
def testing(h, bounce, window, exp):
actual = bouncing_ball(h, bounce, window)
print(f"actual: {actual}, exp: {exp}")
assert actual == exp
def tests():
testing(2, 0.5, 1, 1)
testing(3, 0.66, 1.5, 3)
testing(30, 0.66, 1.5, 15)
testing(30, 0.75, 1.5, 21)
tests()
fixed_tests() |
const { MessageEmbed } = require("discord.js");
const {
database: { upgrade },
Enum: { Player },
functions: { errorEmbed, getUpgNeed, log }
} = require("./../../lib/index.js");
const setting = require("./../../config/setting.json");
// 升級的面板
module.exports = {
num: 5,
name: ["升級", "upgrade", "upg"],
type: "rpg",
expectedArgs: "",
description: "查看升級所需的晶玉和材料",
minArgs: 0,
maxArgs: 0,
level: 1,
cooldown: 10,
requireItems: [],
requireBotPermissions: [],
async execute(msg, args, client, user) {
try {
await msg.react("✅");
if (!user) {
msg.reply({
content: `您還沒有帳戶喔`,
allowedMentions: setting.allowedMentions
});
return;
}
const { author, channel } = msg;
const createEmbed = (title, content = null, field = null, footer = null) => {
let embed = new MessageEmbed()
.setTitle(title)
.setColor(setting.embedColor.normal)
.setTimestamp();
if (content) embed.setDescription(content);
if (footer) embed.setFooter({ text: footer });
if (field) {
for (let i in field) {
embed.addField(field[i].name, field[i].value);
}
}
return embed;
}
let content = "";
let n = Math.floor(user.level / 10) + 1;
let bigUpgrade = true;
let userClasses = Player.classes.list[n];
let needs = "\n";
let coinNeed = getUpgNeed(user.level);
if (!user.level.toString().endsWith("9")) {
bigUpgrade = false;
content = `\n\n**Lv. ${user.level}** ➠ **Lv. ${user.level + 1}**\n所需:${coinNeed} 晶玉`;
}
for (let i in Player.classes.need[userClasses]) {
needs += `${i} * ${Player.classes.need[userClasses][i].amount}\n\n`
}
msg.reply({
embeds: [
createEmbed("升級面板", content, [{
name: `${userClasses} 所需素材`,
value: needs
}], "🔥 升級|💥升階")
],
allowedMentions: setting.allowedMentions
}).then(async m => {
if (!bigUpgrade) {
await m.react("🔥");
}
await m.react("💥");
const filter = (reaction, mUser) => {
if (mUser.id === msg.author.id) {
// 處理消耗
if (reaction.emoji.name == "🔥" && !bigUpgrade) {
if (user.coin >= coinNeed) {
user.coin -= coinNeed;
upgrade(user);
createEmbed(
"++ level up ++",
`${user.level - 1} to ${user.level}`,
null,
author.tag)
return true;
} else {
errorEmbed(channel, author, null, `您沒有那麼多${setting.coinName}喔`);
}
}
if (reaction.emoji.name == "💥") {
if (user.coin >= coinNeed) {
user.coin -= coinNeed;
upgrade(user);
return true;
} else {
errorEmbed(channel, author, null, `您沒有那麼多${setting.coinName}喔`);
}
}
}
return false;
}
await m.awaitReactions({
filter: filter,
max: 1,
time: 120000,
errors: ["time"]
}).catch(err => { });
user.save();
})
} catch (err) {
console.log(err);
log(client, err.toString());
}
}
} |
import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import HomeScreen from '../screens/HomeScreen';
import WelcomeScreen from '../screens/WelcomeScreen';
import LoginScreen from '../screens/LoginScreen';
import SignUpScreen from '../screens/SignUpScreen';
import useAuth from '../hooks/useAuth';
const Stack = createNativeStackNavigator();
const AppNavigation = () => {
const {user} = useAuth();
if (user) {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen
name="Home"
options={{headerShown: false}}
component={HomeScreen}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Welcome">
<Stack.Screen
name="Welcome"
options={{headerShown: false}}
component={WelcomeScreen}
/>
<Stack.Screen
name="Login"
options={{headerShown: false}}
component={LoginScreen}
/>
<Stack.Screen
name="SignUp"
options={{headerShown: false}}
component={SignUpScreen}
/>
</Stack.Navigator>
</NavigationContainer>
);
};
export default AppNavigation; |
from framework.exceptions.nulls import ArgumentNullException
from framework.mongo.mongo_repository import MongoRepositoryAsync
from motor.motor_asyncio import AsyncIOMotorClient
from domain.mongo import MongoCollection, MongoDatabase
class ChatGptRepository(MongoRepositoryAsync):
def __init__(
self,
client: AsyncIOMotorClient
):
super().__init__(
client=client,
database=MongoDatabase.ChatGPT,
collection=MongoCollection.History)
async def get_history(
self,
start_timestamp,
end_timestamp,
endpoint: str = None
):
ArgumentNullException.if_none(start_timestamp, 'start_timestamp')
ArgumentNullException.if_none(end_timestamp, 'end_timestamp')
query_filter = {
'created_date': {
'$gte': start_timestamp,
'$lt': end_timestamp
}
}
if endpoint is not None:
query_filter['endpoint'] = endpoint
results = self.collection.find(
filter=query_filter)
return await results.to_list(
length=None) |
#ifndef UNIFIERTABLE_H
#define UNIFIERTABLE_H
#include "constants.hh"
#include <iostream>
#include <vector>
#include <algorithm>
#include "unifier.hh"
using namespace std;
typedef vector<Unifier *> unifierTable;
typedef unifierTable::const_iterator unifiercit;
typedef unifierTable::iterator unifierit;
class UnifierTable
{
protected:
unifierTable utable; /**< @brief Vector de Substitutions*/
public:
/**
* @brief Constructor por defecto.
*/
UnifierTable();
/**
* @brief Constructor de copia.
*/
UnifierTable(const UnifierTable * o);
/**
@brief Destructor
*/
~UnifierTable();
/**
@brief Anade una Unifier al unificador
@param uni: Unifier que anadiremos al unificador
*/
inline void addUnifier(Unifier * uni) {utable.push_back(uni);};
/**
@brief iterador al primer elemento para recorrer la estructura.
*/
inline unifierit getUnifierBegin(void) {return utable.begin();};
/**
@brief iterador al elemento uno pasado al �ltimo para recorrer la estructura.
*/
inline unifierit getUnifierEnd(void) {return utable.end();};
inline Unifier * getback(void) {Unifier * u = utable.back(); utable.pop_back(); return u;};
/**
* Borra el unificador en la posici�n pos.
* /param pos la posici�n a borrar
*/
void erase(int pos) {unifierit i = utable.begin() + pos; Unifier * u = (*i); utable.erase(i); delete u;};
/**
* Borra todos los unificadores
*/
void eraseAll(void);
Unifier * getUnifierAt(int pos) {unifierit i = utable.begin() + pos; return (*i);};
/**
@brief Dado un iterador menor que el getUnifierEnd() devuelve su objeto asociado
*/
inline const Unifier * getUnifier(unifierit i) {return (*i);};
/**
@brief a�ade los unificadores de ut a this. Ut se queda vac�a de unificadores en el proceso.
*/
void addUnifiers(UnifierTable * t);
/**
@brief Funci�n de uso interno, no llamar directamente
*/
inline void clearUnifiers(void) {utable.clear();};
inline bool isEmpty(void) {return utable.empty();};
void print(ostream * os) const;
inline int countUnifiers(void) {return utable.size();};
// Elimina todos los elementos de la tabla de unificaciones excepto el primero
void cut(void);
};
#endif |
export const frontMatter = {
name: 'Slider',
menu: 'Inputs',
route: '/documentation/inputs/Slider',
};
import { Slider } from '@re-flex/ui';
import SingleSliderExample from './Examples/JS/Single';
import MultipleSliderExample from './Examples/JS/Multiple';
import VerticalSliderExample from './Examples/JS/Vertical';
import MultipleVerticalSliderExample from './Examples/JS/MultipleVertical';
## Single Slider
<Playground
description="inputs.sliders.descriptions.singleBasic"
jsFile={import('./Examples/JS/Single.jsx?raw')}
tsFile={import('./Examples/TS/Single.tsx?raw')}
>
<SingleSliderExample />
</Playground>
## Multiple Slider
<Playground
description="inputs.sliders.descriptions.multipleBasic"
jsFile={import('./Examples/JS/Multiple.jsx?raw')}
tsFile={import('./Examples/TS/Multiple.tsx?raw')}
>
<MultipleSliderExample />
</Playground>
## Vertical Slider
<Playground
description="inputs.sliders.descriptions.verticalSingle"
jsFile={import('./Examples/JS/Vertical.jsx?raw')}
tsFile={import('./Examples/TS/Vertical.tsx?raw')}
>
<VerticalSliderExample />
</Playground>
## Nultiple Vertical Slider
<Playground
description="inputs.sliders.descriptions.multipleVertical"
jsFile={import('./Examples/JS/MultipleVertical.jsx?raw')}
tsFile={import('./Examples/TS/MultipleVertical.tsx?raw')}
>
<MultipleVerticalSliderExample />
</Playground>
## Properties
<Props of={Slider} /> |
import { Injectable } from "@angular/core";
import { CartService } from "../carts/cart.service";
import { Book } from "./book.directive";
@Injectable()
export class BooksService {
books: Book[] = [
{
name: "Clean Code",
image: "https://m.media-amazon.com/images/I/41SH-SvWPxL._SX260_.jpg",
author: "Robbert C. Martins",
amount: 700
},
{
name: "The Pragmatic Programmer",
image: "https://images-na.ssl-images-amazon.com/images/I/51yaxPX4BFL._SX360_BO1,204,203,200_.jpg",
author: "David Thomas",
amount: 5500
},
{
name: "Test Driven Development for Embedded C",
image: "https://images-na.ssl-images-amazon.com/images/I/51W6W+UOptL._SX415_BO1,204,203,200_.jpg",
author: "James W Grenning",
amount: 8000
},
{
name: "Software Engineering | Tenth Edition",
image: "https://images-na.ssl-images-amazon.com/images/I/511DuL1myZL._SX397_BO1,204,203,200_.jpg",
author: "Ian Sommerville",
amount: 1580
},
]
constructor(){}
getBooks() : Book[]{
return this.books.slice();
}
} |
package bo.edu.ucb.ingsoft.deliverybot.delivery.chat;
import bo.edu.ucb.ingsoft.deliverybot.delivery.util.UserSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.methods.BotApiMethod;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DeliveryLongPollingBot extends TelegramLongPollingBot {
/**
* Atributo que sirve para guardar el proceso actual de los diferentes usuarios.
*/
private Map<Long, AbstractProcess> usersSession;
private boolean test = false;
private List<BotApiMethod> testMessages = new ArrayList<>();
private ApplicationContext context;
public Logger logger = LoggerFactory.getLogger(DeliveryLongPollingBot.class);
public DeliveryLongPollingBot(ApplicationContext context) {
this.context = context;
usersSession = new HashMap<>();
}
public DeliveryLongPollingBot(ApplicationContext context,boolean test) {
this.test = test;
this.context = context;
usersSession = new HashMap<>();
}
@Override
public String getBotUsername() {
return "FoodGoNowBot";
}
@Override
public String getBotToken() {
return "5215231662:AAF1bz21CEH8eS-Yb98BnYr13JDn5LBD5yA";
}
@Override
public void onRegister() {
super.onRegister();
}
public void sendMyMessage(BotApiMethod method) throws TelegramApiException {
logger.info("Enviando mensaje: {}" , method);
if (test) {
// no enviamos
testMessages.add(method);
} else {
this.execute(method);
}
}
@Override
public void onUpdateReceived(Update update) {
// Primero identifico al usuario por chat Id Long
Long chatId = update.getMessage().getChatId();
if( UserSession.get(chatId,"process_status") == null){
UserSession.put(chatId,"process_status", "STARTED");
}
// Busco si ya existe Proceso en el map userSession
AbstractProcess currentProcess = usersSession.get(chatId);
if (currentProcess == null) { // Primera vez que se contacto con nostros.
logger.info("Creando proceso para el chatId: {}" , chatId);
// Debo crear el proceso por defecto
currentProcess = context.getBean(MenuProcessImpl.class);
usersSession.put(chatId, currentProcess);
logger.info("Derivando la conversación al proceso: {}", currentProcess.getName());
AbstractProcess nextProcess = currentProcess.handle(context,update, this);
if (!nextProcess.equals(currentProcess)) { // Si el siguiente proceso es diferente lo iniciamos
logger.info("Iniciando siguiente proceso: {}" , nextProcess.getName());
nextProcess.handle(context,update, this);
} else {
logger.info("No hay cambio de proceso, así que termina conversación");
}
usersSession.put(chatId, nextProcess);
} else { // Ya existe un proceso
logger.info("Continuamos el proceso para el chatId: {}" +
" proceso: {}" , chatId ,currentProcess.getName());
AbstractProcess nextProcess = currentProcess.handle(context,update, this);
if (!nextProcess.equals(currentProcess)) { // Si el siguiente proceso es diferente
logger.info("Iniciando siguiente proceso: {}" , nextProcess.getName());
nextProcess = nextProcess.handle(context,update, this);
} else {
logger.info("No hay cambio de proceso, así que termina conversación");
}
usersSession.put(chatId, nextProcess);
}
}
@Override
public void onUpdatesReceived(List<Update> updates) {
super.onUpdatesReceived(updates);
}
public List<BotApiMethod> getTestMessages() {
return testMessages;
}
} |
<?php
namespace Modules\SMSModule\Http\Controllers\Web\Admin;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;
use Illuminate\Contracts\View\View;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\RedirectResponse;
use Illuminate\Contracts\View\Factory;
use Illuminate\Support\Facades\Validator;
use Modules\PaymentModule\Entities\Setting;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Validation\ValidationException;
use Illuminate\Contracts\Foundation\Application;
use Modules\BusinessSettingsModule\Entities\BusinessSettings;
class SMSConfigController extends Controller
{
private BusinessSettings $business_setting;
private Setting $addon_settings;
public function __construct(BusinessSettings $business_setting, Setting $addon_settings)
{
$this->business_setting = $business_setting;
$this->addon_settings = $addon_settings;
}
/**
* Display a listing of the resource.
* @return Application|Factory|View
*/
public function sms_config_get(): View|Factory|Application
{
$published_status = 0; // Set a default value
$payment_published_status = config('get_payment_publish_status');
if (isset($payment_published_status[0]['is_published'])) {
$published_status = $payment_published_status[0]['is_published'];
}
$routes = config('addon_admin_routes');
$desiredName = 'sms_setup';
$payment_url = '';
foreach ($routes as $routeArray) {
foreach ($routeArray as $route) {
if ($route['name'] === $desiredName) {
$payment_url = $route['url'];
break 2;
}
}
}
$data_values = $this->addon_settings
->whereIn('settings_type', ['sms_config'])
->whereIn('key_name', array_column(SMS_GATEWAY, 'key'))
->get();
return view('smsmodule::admin.sms-config', compact('data_values', 'published_status', 'payment_url'));
}
/**
* Display a listing of the resource.
* @param Request $request
* @return RedirectResponse
*/
public function sms_config_set(Request $request): RedirectResponse
{
$validation = [
'gateway' => 'required|in:releans,twilio,nexmo,2factor,msg91',
'mode' => 'required|in:live,test'
];
$additional_data = [];
if ($request['gateway'] == 'releans') {
$additional_data = [
'status' => 'required|in:1,0',
'api_key' => 'required',
'from' => 'required',
'otp_template' => 'required'
];
} elseif ($request['gateway'] == 'twilio') {
$additional_data = [
'status' => 'required|in:1,0',
'sid' => 'required',
'messaging_service_sid' => 'required',
'token' => 'required',
'from' => 'required',
'otp_template' => 'required'
];
} elseif ($request['gateway'] == 'nexmo') {
$additional_data = [
'status' => 'required|in:1,0',
'api_key' => 'required',
'api_secret' => 'required',
'token' => 'required',
'from' => 'required',
'otp_template' => 'required'
];
} elseif ($request['gateway'] == '2factor') {
$additional_data = [
'status' => 'required|in:1,0',
'api_key' => 'required'
];
} elseif ($request['gateway'] == 'msg91') {
$additional_data = [
'status' => 'required|in:1,0',
'template_id' => 'required',
'auth_key' => 'required',
];
}
$validation = $request->validate(array_merge($validation, $additional_data));
$this->addon_settings->updateOrCreate(['key_name' => $request['gateway'], 'settings_type' => 'sms_config'], [
'key_name' => $request['gateway'],
'live_values' => $validation,
'test_values' => $validation,
'settings_type' => 'sms_config',
'mode' => $request['mode'],
'is_active' => $request['status'],
]);
if ($request['status'] == 1) {
foreach (['releans', 'twilio', 'nexmo', '2factor', 'msg91'] as $gateway) {
if ($request['gateway'] != $gateway) {
$keep = $this->addon_settings->where(['key_name' => $gateway, 'settings_type' => 'sms_config'])->first();
if (isset($keep)) {
$hold = $keep->live_values;
$hold['status'] = 0;
$this->addon_settings->where(['key_name' => $gateway, 'settings_type' => 'sms_config'])->update([
'live_values' => $hold,
'test_values' => $hold,
'is_active' => 0,
]);
}
}
}
}
Toastr::success(DEFAULT_UPDATE_200['message']);
return back();
}
} |
// fetch
// const SearchButton = document.querySelector('.search-button');
// SearchButton.addEventListener('click', function() {
// const inputKeyword = document.querySelector('.input-keyword');
// fetch('http://www.omdbapi.com/?apikey=9e96ad3b&s=' + inputKeyword.value)
// .then(response => response.json())
// .then(response => {
// const movies = response.Search;
// let cards = '';
// movies.forEach(m => cards += showCard(m));
// const moviesContainer = document.querySelector('.movie-container');
// moviesContainer.innerHTML = cards;
// // ketika tombol detail di-klik
// const modalDetailButton = document.querySelectorAll('.modal-detail-button');
// modalDetailButton.forEach(btn => {
// btn.addEventListener('click', function() {
// const imdbid = this.dataset.imdbid;
// fetch('http://www.omdbapi.com/?apikey=9e96ad3b&i='+ imdbid)
// .then(response => response.json())
// .then(m => {
// const movieDetail = showMoviesDetails(m);
// const modalBody = document.querySelector('.modal-body');
// modalBody.innerHTML = movieDetail;
// });
// });
// });
// });
// });
const searchButton = document.querySelector('.search-button');
searchButton.addEventListener('click', async function () {
const inputKeyword = document.querySelector('.input-keyword');
const movies = await getMovies(inputKeyword.value);
updateUI(movies);
});
// event binding
document.addEventListener('click', async function(e) {
if(e.target.classList.contains('modal-detail-button')) {
const imdbid = e.target.dataset.imdbid;
const movieDetail = await getMoviesDetail(imdbid);
updateUIDetail(movieDetail);
}
});
function getMoviesDetail(imdbid) {
return fetch('http://www.omdbapi.com/?apikey=9e96ad3b&i='+ imdbid)
.then(response => response.json())
.then(m => m);
}
function updateUIDetail(m) {
const movieDetail = showMoviesDetails(m);
const modalBody = document.querySelector('.modal-body');
modalBody.innerHTML = movieDetail;
}
function getMovies(keyword) {
return fetch('http://www.omdbapi.com/?apikey=9e96ad3b&s=' + keyword)
.then(response => response.json())
.then(response => response.Search);
}
function updateUI(movies) {
let cards = '';
movies.forEach(m => cards += showCard(m));
const moviesContainer = document.querySelector('.movie-container');
moviesContainer.innerHTML = cards;
}
function showCard(m) {
return ` <div class="col-md-4 my-5">
<div class="card">
<img src="${m.Poster}" class="card-img-top">
<div class="card-body">
<h5 class="card-title">${m.Title}</h5>
<h6 class="card-subtitle mb-2 text-muted">${m.Year}</h6>
<a href="#" class="btn btn-primary modal-detail-button" data-bs-toggle="modal" data-bs-target="#movieDetailModal" data-imdbid="${m.imdbID}">Show Detail</a>
</div>
</div>
</div>`;
}
function showMoviesDetails(m) {
return ` <div class="container-fliud">
<div class="row">
<div class="col-md-3">
<img src="${m.Poster}" class="img-fluid" alt="">
</div>
<div class="col-md">
<ul class="list-group">
<li class="list-group-item"><h4>${m.Title}</h4></li>
<li class="list-group-item"><strong>Director : </strong>${m.Director}</li>
<li class="list-group-item"><strong>Actors : </strong>${m.Actors}</li>
<li class="list-group-item"><strong>Writer : </strong>${m.Writer}</li>
<li class="list-group-item"><strong>Plot : </strong><br>${m.Plot}</li>
</ul>
</div>
</div>
</div>`;
} |
package api
import (
"database/sql"
"errors"
"github.com/gin-gonic/gin"
"github.com/lib/pq"
"net/http"
db "simple-bank/db/sqlc"
"simple-bank/token"
)
type createAccountRequest struct {
Currency string `json:"currency" binding:"required,currency"`
}
func (s *Server) createAccount(c *gin.Context) {
var req createAccountRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, errorResponse(err))
return
}
authPayload := c.MustGet(authorizationPayloadKey).(*token.Payload)
arg := db.CreateAccountParams{
Owner: authPayload.Username,
Balance: 0,
Currency: req.Currency,
}
account, err := s.store.CreateAccount(c, arg)
if err != nil {
var pqErr *pq.Error
if errors.As(err, &pqErr) {
switch pqErr.Code.Name() {
case "foreign_key_violation", "unique_violation":
c.JSON(http.StatusForbidden, errorResponse(err))
return
}
}
c.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
c.JSON(http.StatusOK, account)
}
type getAccountRequest struct {
ID int64 `uri:"id" binding:"required,min=1"`
}
func (s *Server) getAccount(c *gin.Context) {
var req getAccountRequest
if err := c.ShouldBindUri(&req); err != nil {
c.JSON(http.StatusBadRequest, errorResponse(err))
return
}
account, err := s.store.GetAccount(c, req.ID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
c.JSON(http.StatusNotFound, errorResponse(err))
return
}
c.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
authPayload := c.MustGet(authorizationPayloadKey).(*token.Payload)
if account.Owner != authPayload.Username {
err := errors.New("account doesn't belong to authenticated user")
c.JSON(http.StatusUnauthorized, errorResponse(err))
return
}
c.JSON(http.StatusOK, account)
}
type listAccountsRequest struct {
PageID int32 `form:"page_id" binding:"required,min=1"`
PageSize int32 `form:"page_size" binding:"required,min=5,max=10"`
}
func (s *Server) listAccounts(c *gin.Context) {
var req listAccountsRequest
if err := c.ShouldBindQuery(&req); err != nil {
c.JSON(http.StatusBadRequest, errorResponse(err))
return
}
authPayload := c.MustGet(authorizationPayloadKey).(*token.Payload)
arg := db.ListAccountsParams{
Owner: authPayload.Username,
Limit: req.PageSize,
Offset: (req.PageID - 1) * req.PageSize,
}
accounts, err := s.store.ListAccounts(c, arg)
if err != nil {
c.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
c.JSON(http.StatusOK, accounts)
} |
<template>
<div>
<div class="inputBox shadow">
<input type="text" v-model="newTodoItem" @keyup.enter="addTodo">
<span class="addContainer" @click="addTodo">
<i class="fas fa-folder-plus addBtn"></i>
</span>
</div>
<Modal
v-if="showModal"
@close="showModal = false"
>
<h3 slot="header">
<span>헤더 경고!</span>
<i
class="fas fa-times closeModal"
@click="showModal = false"
></i>
</h3>
<div slot="body">
아무것도 입력하지 않으셨습니다!
</div>
</Modal>
</div>
</template>
<script>
import Modal from './common/Modal.vue';
export default {
data() {
return {
newTodoItem: "",
showModal: false
}
},
methods: {
addTodo() {
if(this.newTodoItem !== '') {
this.$store.commit('addOneItem', this.newTodoItem);
this.clearInput();
} else {
this.showModal = !this.showModal;
}
},
clearInput() {
this.newTodoItem = "";
}
},
components: {
Modal
}
}
</script>
<style scoped>
input:focus {
outline: none;
}
.inputBox {
background: white;
height: 50px;
line-height: 50px;
border-radius: 5px;
display: flex;
}
.inputBox input {
width: 100%;
height: 100%;
border-style: none;
font-size: 20px;
padding: 0 0 0 20px;
}
.addContainer {
float: right;
background: linear-gradient(to right, rgb(255, 0, 0), purple);
display: flex;
width: 50px;
border-radius: 0 5px 5px 0;
height: 100%;
justify-content: center;
align-items: center;
}
.addContainer:hover {
cursor: pointer;
}
.addBtn {
font-size: 30px;
color: white;
}
.closeModal {
color: black;
border-radius: 10px;
}
.closeModal:hover {
color: rgb(80, 80, 80);
cursor: pointer;
}
</style> |
package de.intranda.goobi.plugins;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
/**
* This file is part of a plugin for Goobi - a Workflow tool for the support of mass digitization.
*
* Visit the websites for more information.
* - https://goobi.io
* - https://www.intranda.com
* - https://github.com/intranda/goobi
*
* 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.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
import java.util.HashMap;
import java.util.List;
import org.apache.commons.configuration.SubnodeConfiguration;
import org.apache.commons.lang.StringUtils;
import org.goobi.beans.Step;
import org.goobi.production.enums.PluginGuiType;
import org.goobi.production.enums.PluginReturnValue;
import org.goobi.production.enums.PluginType;
import org.goobi.production.enums.StepReturnValue;
import org.goobi.production.plugin.interfaces.IStepPluginVersion2;
import de.sub.goobi.config.ConfigPlugins;
import de.sub.goobi.helper.StorageProvider;
import de.sub.goobi.helper.exceptions.DAOException;
import de.sub.goobi.helper.exceptions.SwapException;
import lombok.Getter;
import lombok.extern.log4j.Log4j2;
import net.xeoh.plugins.base.annotations.PluginImplementation;
@PluginImplementation
@Log4j2
public class DeleteFirstImageStepPlugin implements IStepPluginVersion2 {
@Getter
private String title = "intranda_step_deleteFirstImage";
@Getter
private Step step;
private String namepartSplitter = "_";
private String returnPath;
@Override
public void initialize(Step step, String returnPath) {
this.returnPath = returnPath;
this.step = step;
// read parameters from correct block in configuration file
SubnodeConfiguration myconfig = ConfigPlugins.getProjectAndStepConfig(title, step);
namepartSplitter = myconfig.getString("namepartSplitter", "_");
log.info("DeleteFirstImage step plugin initialized");
}
@Override
public PluginGuiType getPluginGuiType() {
return PluginGuiType.NONE;
}
@Override
public String getPagePath() {
return "/uii/plugin_step_deleteFirstImage.xhtml";
}
@Override
public PluginType getType() {
return PluginType.Step;
}
@Override
public String cancel() {
return "/uii" + returnPath;
}
@Override
public String finish() {
return "/uii" + returnPath;
}
@Override
public int getInterfaceVersion() {
return 0;
}
@Override
public HashMap<String, StepReturnValue> validate() {
return null;
}
@Override
public boolean execute() {
PluginReturnValue ret = run();
return ret != PluginReturnValue.ERROR;
}
@Override
public PluginReturnValue run() {
boolean successfull = true;
try {
Path masterFolderPath = Paths.get(step.getProzess().getImagesOrigDirectory(false));
Path mediaFolderPath = Paths.get(step.getProzess().getImagesTifDirectory(false));
List<Path> imagesInAllFolder = new ArrayList<>();
if (Files.exists(masterFolderPath)) {
imagesInAllFolder.addAll(StorageProvider.getInstance().listFiles(masterFolderPath.toString()));
}
if (Files.exists(mediaFolderPath)) {
imagesInAllFolder.addAll(StorageProvider.getInstance().listFiles(mediaFolderPath.toString()));
}
for (Path imageName : imagesInAllFolder) {
String filenameWithoutExtension = imageName.getFileName().toString();
filenameWithoutExtension = filenameWithoutExtension.substring(0, filenameWithoutExtension.lastIndexOf("."));
String[] nameParts = filenameWithoutExtension.split(namepartSplitter);
// just check the last token
String part = nameParts[nameParts.length -1];
// if all parts should be checked, uncomment this for loop
// for (String part : nameParts) {
if (StringUtils.isNumeric(part) && part.length() > 1 ) {
// check if it is 0, 00, 000, 0000, ....
if (Integer.parseInt(part) == 0) {
// delete image
StorageProvider.getInstance().deleteFile(imageName);
}
}
// }
}
} catch (IOException | SwapException | DAOException e) {
log.error(e);
}
log.info("DeleteFirstImage step plugin executed");
if (!successfull) {
return PluginReturnValue.ERROR;
}
return PluginReturnValue.FINISH;
}
} |
package unit;
import com.company.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
import static org.junit.Assert.*;
public class JsonDataFileTest {
JsonDataFile file = new JsonDataFile();
String path = System.getProperty("user.dir") + "/src/unit/resources/TestJSON";
String testFileName = "/test.json";
Scanner sampleReader;
Scanner reader;
@After
public void tearDown() throws Exception {
File f = new File(path + testFileName);
f.delete();
}
@Test
public void saveToFile() {
Set<Worker> workers = new LinkedHashSet<>();
workers.add(new Worker(1, "Бирюков Дмитрий Михайлович"));
workers.add(new Worker(2, "Рыжов Игорь Дмитриевич"));
workers.add(new Worker(3, "Селяков Николай Викторович"));
try{
file.saveToFile(path + testFileName, workers);
sampleReader = new Scanner(new File(path + "/fileToSave.json"));
reader = new Scanner(new File(path + testFileName));
while(reader.hasNextLine() && sampleReader.hasNextLine()){
assertEquals(sampleReader.nextLine(), reader.nextLine());
}
assertFalse(reader.hasNextLine() || sampleReader.hasNextLine());
} catch (FileNotFoundException | FileSaveException e) {
fail();
} finally {
sampleReader.close();
reader.close();
}
}
@Test
public void loadFormFile() {
Worker[] expectedWorkers = new Worker[]{new Worker(1, "Строеньев Степан Дмитриевич"),
new Worker(2, "Глазов Александр Михайлович"),
new Worker(3, "Озеров Дмитрий Андреевич")};
try {
Set<Worker> workers = file.loadFormFile(path + "/fileToLoad.json");
assertArrayEquals(expectedWorkers, workers.toArray());
} catch (FileException e) {
fail();
}
}
} |
package oldapi;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.mapred.AvroCollector;
import org.apache.avro.mapred.AvroJob;
import org.apache.avro.mapred.AvroMapper;
import org.apache.avro.mapred.AvroReducer;
import org.apache.avro.mapred.AvroUtf8InputFormat;
import org.apache.avro.mapred.Pair;
import org.apache.avro.util.Utf8;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import specific.WeatherRecord;
public class AvroSpecificMaxTemperature extends Configured implements Tool {
public static class MaxTemperatureMapper
extends AvroMapper<Utf8, Pair<Integer, WeatherRecord>> {
private NcdcRecordParser parser = new NcdcRecordParser();
private WeatherRecord record = new WeatherRecord();
@Override
public void map(Utf8 line,
AvroCollector<Pair<Integer, WeatherRecord>> collector,
Reporter reporter) throws IOException {
parser.parse(line.toString());
if (parser.isValidTemperature()) {
record.setYear(parser.getYearInt());
record.setTemperature(parser.getAirTemperature());
record.setStationId(parser.getStationId());
collector.collect(
new Pair<Integer, WeatherRecord>(parser.getYearInt(), record));
}
}
}
public static class MaxTemperatureReducer extends
AvroReducer<Integer, WeatherRecord, WeatherRecord> {
@Override
public void reduce(Integer key, Iterable<WeatherRecord> values,
AvroCollector<WeatherRecord> collector,
Reporter reporter) throws IOException {
WeatherRecord max = null;
for (WeatherRecord value : values) {
if (max == null || value.getTemperature() > max.getTemperature()) {
max = newWeatherRecord(value);
}
}
collector.collect(max);
}
}
public static class MaxTemperatureCombiner extends
AvroReducer<Integer, WeatherRecord, Pair<Integer, WeatherRecord>> {
@Override
public void reduce(Integer key, Iterable<WeatherRecord> values,
AvroCollector<Pair<Integer, WeatherRecord>> collector,
Reporter reporter) throws IOException {
WeatherRecord max = null;
for (WeatherRecord value : values) {
if (max == null || value.getTemperature() > max.getTemperature()) {
max = newWeatherRecord(value);
}
}
collector.collect(new Pair<Integer, WeatherRecord>(key, max));
}
}
private static WeatherRecord newWeatherRecord(WeatherRecord value) {
return new WeatherRecord(value.getYear(), value.getTemperature(), value.getStationId());
}
@Override
public int run(String[] args) throws Exception {
if (args.length != 2) {
System.err.printf("Usage: %s [generic options] <input> <output>\n",
getClass().getSimpleName());
ToolRunner.printGenericCommandUsage(System.err);
return -1;
}
JobConf conf = new JobConf(getConf(), getClass());
conf.setJobName("Max temperature");
FileInputFormat.addInputPath(conf, new Path(args[0]));
FileOutputFormat.setOutputPath(conf, new Path(args[1]));
AvroJob.setInputSchema(conf, Schema.create(Schema.Type.STRING));
AvroJob.setMapOutputSchema(conf, Pair.getPairSchema(
Schema.create(Schema.Type.INT), WeatherRecord.SCHEMA$));
AvroJob.setOutputSchema(conf, WeatherRecord.SCHEMA$);
conf.setInputFormat(AvroUtf8InputFormat.class);
AvroJob.setMapperClass(conf, MaxTemperatureMapper.class);
AvroJob.setCombinerClass(conf, MaxTemperatureCombiner.class);
AvroJob.setReducerClass(conf, MaxTemperatureReducer.class);
JobClient.runJob(conf);
return 0;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new AvroSpecificMaxTemperature(), args);
System.exit(exitCode);
}
} |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AboutComponent } from './about/about.component';
import { AppComponent } from './app.component';
import { AuthGuard } from './auth-guard.service';
import { ContactComponent } from './contact/contact.component';
import { CryptoTradingGameComponent } from './crypto-trading-game/crypto-trading-game.component';
import { GameModeComponent } from './crypto-trading-game/game-mode/game-mode.component';
import { HomeGameComponent } from './crypto-trading-game/home-game/home-game.component';
import { SignUpComponent } from './crypto-trading-game/sign-up/sign-up.component';
import { FriendsListComponent } from './friends-list/friends-list.component';
import { HomepageComponent } from './homepage/homepage.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { ResumeComponent } from './resume/resume.component';
import { AppsListComponent } from './apps-list/apps-list.component';
const routes: Routes = [
{path: '', component: AboutComponent},
{path: 'home', component: HomepageComponent},
{path: 'about', component: AboutComponent},
{path: 'contact', component: ContactComponent},
{path: 'resume', component: ResumeComponent},
{path: 'friends-list', component: FriendsListComponent},
{path: 'game', component: CryptoTradingGameComponent},
{path: 'game/sign-up', component: SignUpComponent},
{path: 'game/home',canActivate:[AuthGuard], component: HomeGameComponent}, //,
{path: 'game/game-mode', component: GameModeComponent},
{path: 'appsList', component: AppsListComponent},
{path: '**', component: PageNotFoundComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } |
import React from 'react'
import Navbar from './components/Navbar'
import "./App.css";
import { Layout, Space, Typography } from 'antd';
import { Link, Route, Routes } from 'react-router-dom';
import HomePage from './components/HomePage';
import Exchanges from './components/Exchanges';
import Cryptocurrencies from './components/Cryptocurrencies';
import News from './components/News';
import CryptoDetails from './components/CryptoDetails';
const App = () => {
return (
<div className='app'>
<div className="navbar">
<Navbar/>
</div>
<div className="main">
<Layout>
<div className="routes">
<Routes>
<Route exact path='/' element={<HomePage/>}/>
<Route exact path='/exchanges' element={<Exchanges/>} />
<Route exact path='/cryptocurrencies' element={<Cryptocurrencies/>} />
<Route exact path='/crypto/:coinId' element={<CryptoDetails/>}/>
<Route exact path='/news' element={<News/>}/>
</Routes>
</div>
</Layout>
<div className="footer">
<Typography.Title level={5} style={{color:"white",textAlign:"center"}}>
Cryptoverse <br/> All rights reserved
</Typography.Title>
<Space>
<Link to="/">Home</Link>
<Link to="/exchanges">Exchanges</Link>
<Link to="/news">News</Link>
</Space>
</div>
</div>
</div>
)
}
export default App |
import chainlit as cl
import re
from typing import List
from agent import agent_factory
from langchain.agents.agent import AgentExecutor
KEY_AGENT = "agent"
KEY_USER_QUESTIONS = "user_questions"
@cl.on_chat_start
async def on_chat_start():
agent = agent_factory()
cl.user_session.set(KEY_AGENT, agent)
cl.user_session.set(KEY_USER_QUESTIONS, [])
await cl.Message(content="OpenSearch Agent started").send()
@cl.on_message
async def on_message(message: cl.Message):
agent: AgentExecutor = cl.user_session.get(KEY_AGENT)
cb = cl.AsyncLangchainCallbackHandler()
user_questions: List = cl.user_session.get(KEY_USER_QUESTIONS)
user_questions = user_questions[-3:]
joined_questions = '\n'.join(user_questions)
memory_questions = f"""
Here are some previous questions that you do not need to answer but consider in relationship to the actual question:
```
{joined_questions}
```
""" if len(joined_questions) else ""
prompt = f"""
Make sure that you query first the indices in the OpenSearch database.
Make sure that after querying the indices you query the field names.
{memory_questions}
Then answer this question:
{message.content}
"""
response = await cl.make_async(agent.run)(input=prompt, callbacks=[cb])
if "graph" in response:
img_path_match = re.search(r"\(sandbox:(.*?)\)", response)
if img_path_match:
img_path = img_path_match.group(1).strip()
image = cl.Image(path=img_path, name="plot_image", display="inline")
response_text = response.split("\n\n")[0]
await cl.Message(content=response_text, elements=[image]).send()
else:
await cl.Message(content=response).send()
user_questions.append(prompt)
cl.user_session.set(KEY_USER_QUESTIONS, user_questions) |
#ifndef DATAINTERREQUEST_H
#define DATAINTERREQUEST_H
#include "DataInterRequest_global.h"
#include "datainterchangeinterface.h"
#include "tcpclinet.h"
class DATAINTERREQUEST_EXPORT DataInterRequest:public DataInterchangeInterface
{
Q_OBJECT
Q_INTERFACES(DataInterchangeInterface)
Q_PLUGIN_METADATA(IID DataInterchangeInterfaceIID)
public:
DataInterRequest(QObject* parent=nullptr);
~DataInterRequest()Q_DECL_OVERRIDE;
///
/// \brief InterfaceType 插件类型,多插件调用统一接口
/// \return
///
QString InterfaceType()Q_DECL_OVERRIDE;
public:
///
/// \brief InitializationParameterSlot 初始化参数
/// \param address 地址
/// \param port 端口
/// \param serviceType 服务类型
/// \param heartBeat 心跳包 状态
/// \param serviceMode 服务模式
/// \param shortLink 短链接状态
/// \param newline 换行符
///
void InitializationParameterSlot(const QString& address, const quint16& port, const int& serviceType,const bool& heartBeat, const int& serviceMode,const int& shortLink,const int& newline)Q_DECL_OVERRIDE;
///
/// \brief toSendDataSlot 发送数据
/// \param data 数据体
///
void toSendDataSlot(int channel_number,const QString& data)Q_DECL_OVERRIDE;
///
/// \brief releaseResourcesSlot 释放动资源
///
void releaseResourcesSlot()Q_DECL_OVERRIDE;
///
/// \brief setImagePathSlot 设置图片路径,用于上传图片
/// \param imgPath
///
void setImagePathSlot(const QString &imgPath,int ImageFormat,int ImageNamingRules,int channel_id_placeholder,int camera_id_placeholder)Q_DECL_OVERRIDE;
private:
/*****************************
* @brief:上传数据
******************************/
QNetworkAccessManager* pManager;
QNetworkRequest request;
/*****************************
* @brief:上传图片
******************************/
QNetworkRequest requestImg;
QNetworkAccessManager* pManagerImg;
QUrl url;
QVector<QFile*> qFiles;
///
/// \brief channel_number 通道编号
///
int channel_number;
QString address;
///
/// \brief tmpData 临时数据
///
QString tmpData;
TcpClient* pTcpClient;
///
/// \brief imgPath 图片路径
///
QString imgPath;
///
/// \brief ImageFormat 图片格式
///
int ImageFormat;
///
/// \brief ImageNamingRules 图片命名方式
///
int ImageNamingRules;
///
/// \brief channel_id_placeholder 通道命名方式
///
int channel_id_placeholder;
///
/// \brief camera_id_placeholder 相机命名方式
///
int camera_id_placeholder;
private slots:
///
/// \brief replyFinishedSlot 上传完成
///
void replyFinishedSlot(QNetworkReply* reply);
///
/// \brief slot_SslErrors SSL/TLS会话在设置过程中遇到错误,包括证书验证错误
///
void slot_SslErrors(QList<QSslError> sslErr);
///
/// \brief slot_Error 应答在处理过程中检测到错误
///
void slot_Error(QNetworkReply::NetworkError err);
///
/// \brief slot_finished 应答完成
///
void slot_finished();
///
/// \brief slot_upLoadImg 上传图片,本地使用
/// \param msgMap
///
void slot_upLoadImg(QMap<QString,QString> msgMap);
///
/// \brief requestImgFinished 上传图片
///
void requestImgFinished(QNetworkReply* reply);
signals:
///
/// \brief signalSendData 发送识别结果
/// \param channel 通道号
/// \param result 识别结果
///
void signalSendData(int channel_number,const QString& result);
///
/// \brief signal_upLoadImg 上传图片,本地使用
/// \param msgMap
///
void signal_upLoadImg(QMap<QString,QString> msgMap);
};
#endif // DATAINTERREQUEST_H |
---
title: Building Subgraphs on Base
---
This guide will quickly take you through how to initialize, create, and deploy your subgraph on Base testnet.
What you'll need:
- A Base testnet contract address
- A crypto wallet (e.g. MetaMask or Coinbase Wallet)
## Subgraph Studio
### 1. Install the Graph CLI
The Graph CLI (>=v0.41.0) is written in JavaScript and you will need to have either `npm` or `yarn` installed to use it.
```sh
# NPM
npm install -g @graphprotocol/graph-cli
# Yarn
yarn global add @graphprotocol/graph-cli
```
### 2. Create your subgraph in the Subgraph Studio
Go to the [Subgraph Studio](https://thegraph.com/studio/) and connect your crypto wallet.
Once connected, click "Create a Subgraph" and enter a name for your subgraph.
Select "Base (testnet)" as the indexed blockchain and click Create Subgraph.
### 3. Initialize your Subgraph
> You can find specific commands for your subgraph in the Subgraph Studio.
Make sure that the graph-cli is updated to latest (above 0.41.0)
```sh
graph --version
```
Initialize your subgraph from an existing contract.
```sh
graph init --studio <SUBGRAPH_SLUG>
```
Your subgraph slug is an identifier for your subgraph. The CLI tool will walk you through the steps for creating a subgraph, including:
- Protocol: ethereum
- Subgraph slug: `<SUBGRAPH_SLUG>`
- Directory to create the subgraph in: `<SUBGRAPH_SLUG>`
- Ethereum network: base-testnet \_ Contract address: `<CONTRACT_ADDRESS>`
- Start block (optional)
- Contract name: `<CONTRACT_NAME>`
- Yes/no to indexing events (yes means your subgraph will be bootstrapped with entities in the schema and simple mappings for emitted events)
### 3. Write your Subgraph
> If emitted events are the only thing you want to index, then no additional work is required, and you can skip to the next step.
The previous command creates a scaffold subgraph that you can use as a starting point for building your subgraph. When making changes to the subgraph, you will mainly work with three files:
- Manifest (subgraph.yaml) - The manifest defines what datasources your subgraphs will index. Make sure to add `base-testnet` as the network name in manifest file to deploy your subgraph on Base testnet.
- Schema (schema.graphql) - The GraphQL schema defines what data you wish to retreive from the subgraph.
- AssemblyScript Mappings (mapping.ts) - This is the code that translates data from your datasources to the entities defined in the schema.
If you want to index additional data, you will need extend the manifest, schema and mappings.
For more information on how to write your subgraph, see [Creating a Subgraph](/developing/creating-a-subgraph).
### 4. Deploy to the Subgraph Studio
Before you can deploy your subgraph, you will need to authenticate with the Subgraph Studio. You can do this by running the following command:
Authenticate the subgraph on studio
```
graph auth --studio <DEPLOY_KEY>
```
Next, enter your subgraph's directory.
```
cd <SUBGRAPH_DIRECTORY>
```
Build your subgraph with the following command:
````
```
graph codegen && graph build
```
````
Finally, you can deploy your subgraph using this command:
````
```
graph deploy --studio <SUBGRAPH_SLUG>
```
````
### 5. Query your subgraph
Once your subgraph is deployed, you can query it from your dapp using the `Development Query URL` in the Subgraph Studio.
Note - Studio API is rate-limited. Hence should preferably be used for development and testing.
To learn more about querying data from your subgraph, see the [Querying a Subgraph](/querying/querying-the-graph) page. |
import React, { HTMLProps } from 'react';
import { joinClassName } from '@/helpers';
import BaseIcon from '@/components/widgets/BaseIcon';
/**
* Props
*/
interface Props extends HTMLProps<HTMLDivElement>, Partial<IDrawerLink> {
header?: boolean;
}
export interface IDrawerLink {
label?: string;
icon?: string;
items?: IDrawerLink[];
}
/**
* DrawerItem
* @returns
*/
function DrawerItem({ className, icon, label, header }: Props) {
if (header) {
return (
<div className={joinClassName([className, 'text-center p-2'])}>
{label}
</div>
);
}
return (
<li className={joinClassName([className, 'hover:bg-slate-50'])}>
<div>
{icon ? (
<>
<span>
<BaseIcon path={icon} size="1rem" />
</span>
<span className="pl-1">{label}</span>
</>
) : (
<span className="pl-8">{label}</span>
)}
</div>
</li>
);
}
export default DrawerItem; |
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from bs4 import BeautifulSoup
class Shifaam(CrawlSpider):
allowed_domain = ['shifaam.com']
start_urls = ['https://www.shifaam.com/doctors/pakistan/']
le_doctors = LinkExtractor(restrict_xpaths="//div[@class = 'doc-name']//a")
doctors_rule = Rule(le_doctors, callback='parse_item', follow=True)
le_pagination = LinkExtractor(restrict_xpaths="//ul[@class = 'pagination justify-content-center']/li[last()]/a")
pagination_rule = Rule(le_pagination, follow=True)
rules = [doctors_rule, pagination_rule]
name = 'shifaam'
def parse_item(self, response):
id = response.url.split('-')[-1]
name = response.xpath("//div[@class = 'doc-name']/h4/text()").get()
xp = response.xpath("//p[@class='xp-level']/text()").get()[12:]
xp = "".join(xp).strip()
try:
pmc = response.xpath("//span[@class='pmc-verified']/span/text()").get()
if pmc is not None:
pmc = 'Yes'
else:
pmc = 'No'
except:
pass
try:
img = response.url + response.xpath("//div[@class='doctor-card-large']//div[@class = 'img-cont']/img/@src").get()
except:
img = ''
try:
typee = response.xpath("//p[@class='doc-desc']/text()").get().strip()
except:
typee = ''
try:
about = response.xpath("//div[@class='shifaam-card']/div[@class='card-body']/p/text()").get().strip()
except:
about = ''
try:
services = response.xpath("//div[@class='services-tags']//a/text()").getall()
services = "\n".join(services)
except:
pass
try:
education = response.xpath("//div[@class='education']/ul/following-sibling::h6[contains(text(), 'Specializations')]/preceding-sibling::ul//text()").getall()
education = "\n".join(education)
except:
education = ''
try:
specialization = response.xpath("//div[@class='education']/h6[contains(text(), 'Specializations')]/following-sibling::ul[1]//text()").getall()
specialization = "\n".join(specialization)
except:
specialization = ''
try:
langs = response.xpath("//div[@class='education']/h6[contains(text(), 'Languages')]/following-sibling::ul[1]//text()").getall()
langs = "\n".join(langs)
except:
langs = ''
try:
exp = response.xpath("//div[@class='education']/h6[contains(text(), 'Experience')]/following-sibling::ul[1]//text()").getall()
exp = "\n".join(exp)
except:
exp = ''
#Clinic
try:
clinicName = response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Clinic')]/text()").get().strip()
clinicAddress = response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Clinic')]/../../following-sibling::div/div/span[@class='pd-18-38']/text()").get().strip()
clinicCharge = response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Clinic')]/../../following-sibling::div/div/span[@class='dark ml-auto']/text()").extract_first().strip()
clinicSchedule = "\n".join(response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Clinic')]/../../following-sibling::div//div[@class='doc-info available-today doc-details-hide']/div/span//text()").extract()).strip()
except:
clinicName = ''
clinicAddress = ''
clinicCharge = ''
clinicSchedule = ''
#Online Consultation
try:
onlineName = response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Online')]/text()").get().strip()
onlineFees = response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Online')]/../../following-sibling::div/div/span[@class='dark ml-auto']/text()").extract_first().strip()
onlineSchedule = "\n".join(response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Online')]/../../following-sibling::div//div[@class='doc-info available-today doc-details-hide']/div/span//text()").extract()).strip()
except:
onlineName = ''
onlineFees = ''
onlineSchedule = ''
#Medical Center
try:
medicalName = response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Medical')]/text()").get().strip()
medicalAddrs = response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Medical')]/../../following-sibling::div/div/span[@class='pd-18-38']/text()").get().strip()
medicalCharge = response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Medical')]/../../following-sibling::div/div/span[@class='dark ml-auto']/text()").extract_first().strip()
medicalSchedule = "\n".join(response.xpath("//div[@class='shifaam-card']//h2[contains(text(), 'Medical')]/../../following-sibling::div//div[@class='doc-info available-today doc-details-hide']/div/span//text()").extract()).strip()
except:
medicalName = ''
medicalAddrs = ''
medicalCharge = ''
medicalSchedule = ''
yield{
'Doctor ID': id,
'Doctor Name': name,
'Years of Experience': xp,
'PMC Verified': pmc,
'Doctor Image': img,
'Type' : typee,
'About' : about,
'Services': services,
'Education and Certification' : education,
'Specialization': specialization,
'Languages': langs,
'Experience': exp,
'Clinic Name': clinicName,
'Clinic Address': clinicAddress,
'Clinic Fees': clinicCharge,
'Clinic Schedule': clinicSchedule,
'Consultation' : onlineName,
'Consultation Fees': onlineFees,
'Consultation Schedule': onlineSchedule,
'Medical Center': medicalName,
'Center Address': medicalAddrs,
'Center Fees': medicalCharge,
'Center Schedule': medicalSchedule,
'Page Url': response.url
} |
---
title: "E1 Data analysis"
author: "Matt Crump"
date: "10/5/2021"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
warning = FALSE,
message = FALSE)
```
Data collected 2/10/22
# Load libraries
```{r}
library(pacman)
library(dplyr)
library(tidyverse)
library(jsonlite)
library(xtable)
```
## Import Data
```{r}
# Read the text file from JATOS ...
read_file('data/E1/jatos_results_20220330235250.txt') %>%
# ... split it into lines ...
str_split('\n') %>% first() %>%
# ... filter empty rows ...
discard(function(x) x == '') %>%
# ... parse JSON into a data.frame
map_dfr(fromJSON, flatten=T) -> all_data
```
## Pre-processing
We are interested in including participants who attempted to perform the task to the best of their ability. We adopted the following exclusion criteria.
1. Lower than 75% correct during the encoding task. This means that participants failed to correctly press the F or R keys on each trial.
```{r}
# select data from the study phase
study_accuracy <- all_data %>%
filter(experiment_phase == "study",
is.na(correct) == FALSE) %>%
group_by(ID)%>%
summarize(mean_correct = mean(correct))
study_excluded_subjects <- study_accuracy %>%
filter(mean_correct < .75) %>%
pull(ID)
ggplot(study_accuracy, aes(x=mean_correct))+
coord_cartesian(xlim=c(0,1))+
geom_vline(xintercept=.75)+
geom_histogram()+
ggtitle("Histogram of mean correct responses \n for each subject during study phase")
```
2. More than 25% Null responses (120*.25 = 30) during test. NULL responses mean that the participant did not respond on a test trial after 10 seconds.
```{r}
# select data from the study phase
test_null <- all_data %>%
filter(experiment_phase == "test",
response =="NULL") %>%
group_by(ID) %>%
count()
test_null_excluded <- test_null %>%
filter(n > (120*.25)) %>%
pull(ID)
ggplot(test_null, aes(x=n))+
geom_vline(xintercept=30)+
geom_histogram()+
ggtitle("Histogram of count of null responses \n for each subject during test")
```
3. Higher than 75% response bias in the recognition task. This suggests that participants were simply pressing the same button on most trials.
```{r}
test_response_bias <- all_data %>%
filter(experiment_phase == "test",
response !="NULL") %>%
mutate(response = as.numeric(response)) %>%
group_by(ID, response) %>%
count() %>%
pivot_wider(names_from = response,
values_from = n,
values_fill = 0) %>%
mutate(bias = abs(`0` - `1`)/120)
test_response_bias_excluded <- test_response_bias %>%
filter(bias > .75) %>%
pull(ID)
ggplot(test_response_bias, aes(x=bias))+
geom_vline(xintercept=.75)+
geom_histogram()+
ggtitle("Histogram of response bias \n for each subject during test phase")
```
4. Making responses too fast during the recognition memory test, indicating that they weren't performing the task. We excluded participants whose mean RT was less than 300 ms.
```{r}
test_mean_rt <- all_data %>%
filter(experiment_phase == "test",
response !="NULL",
rt != "NULL") %>%
mutate(rt = as.numeric(rt)) %>%
group_by(ID) %>%
summarize(mean_RT = mean(rt))
test_mean_rt_excluded <- test_mean_rt %>%
filter(mean_RT < 300) %>%
pull(ID)
ggplot(test_mean_rt, aes(x=mean_RT))+
geom_vline(xintercept=300)+
geom_histogram()+
ggtitle("Histogram of response bias \n for each subject during test phase")
```
5.
```{r}
test_mean_novel_accuracy <- all_data %>%
filter(experiment_phase == "test",
test_condition == "novel") %>%
mutate(correct = as.logical(correct)) %>%
group_by(ID) %>%
summarize(mean_correct = mean(correct))
test_mean_novel_accuracy_excluded <- test_mean_novel_accuracy %>%
filter(mean_correct < .55) %>%
pull(ID)
ggplot(test_mean_novel_accuracy, aes(x=mean_correct))+
geom_vline(xintercept=.55)+
geom_histogram()+
ggtitle("Histogram of mean accuracy for novel lures \n for each subject during test phase")
```
## all exclusions
```{r}
all_excluded <- unique(c(study_excluded_subjects,
test_null_excluded,
test_response_bias_excluded,
test_mean_rt_excluded,
test_mean_novel_accuracy_excluded))
length(all_excluded)
```
# Accuracy analysis
## Get subject means in each condition
```{r, eval= FALSE}
# attempt general solution
## Declare helper functions
################
# get_mean_sem
# data = a data frame
# grouping_vars = a character vector of factors for analysis contained in data
# dv = a string indicated the dependent variable colunmn name in data
# returns data frame with grouping variables, and mean_{dv}, sem_{dv}
# note: dv in mean_{dv} and sem_{dv} is renamed to the string in dv
get_mean_sem <- function(data, grouping_vars, dv){
a <- data %>%
group_by_at(grouping_vars) %>%
summarize("mean_{ dv }" := mean(.data[[dv]]),
"sem_{ dv }" := sd(.data[[dv]])/sqrt(length(.data[[dv]])),
.groups="drop")
return(a)
}
################
# get_effect_names
# grouping_vars = a character vector of factors for analysis
# returns a named list
# list contains all main effects and interaction terms
# useful for iterating the computation means across design effects and interactions
get_effect_names <- function(grouping_vars){
effect_names <- grouping_vars
if( length(grouping_vars > 1) ){
for( i in 2:length(grouping_vars) ){
effect_names <- c(effect_names,apply(combn(grouping_vars,i),2,paste0,collapse=":"))
}
}
effects <- strsplit(effect_names, split=":")
names(effects) <- effect_names
return(effects)
}
################
# get_effect_names
##################
# Begin analysis
# create list to hold results
Accuracy <- list()
# Pre-process data for analysis
# assign to "filtered_data" object
Accuracy$filtered_data <- all_data %>%
filter(experiment_phase == "test",
ID %in% all_excluded == FALSE)
# declare factors, IVS, subject variable, and DV
Accuracy$factors$IVs <- c("encoding_stimulus_time",
"encoding_instruction",
"test_condition")
Accuracy$factors$subject <- "ID"
Accuracy$factors$DV <- "correct"
## Subject-level means used for ANOVA
# get individual subject means for each condition
Accuracy$subject_means <- get_mean_sem(data=Accuracy$filtered_data,
grouping_vars = c(Accuracy$factors$subject,
Accuracy$factors$IVs),
dv = Accuracy$factors$DV)
## Condition-level means
# get all possible main effects and interactions
Accuracy$effects <- get_effect_names(Accuracy$factors$IVs)
Accuracy$means <- lapply(Accuracy$effects, FUN = function(x) {
get_mean_sem(data=Accuracy$filtered_data,
grouping_vars = x,
dv = Accuracy$factors$DV)
})
## ANOVA
# ensure factors are factor class
Accuracy$subject_means <- Accuracy$subject_means %>%
mutate_at(Accuracy$factors$IVs,factor) %>%
mutate_at(Accuracy$factors$subject,factor)
# run ANOVA
Accuracy$aov.out <- aov(mean_correct ~ encoding_stimulus_time*encoding_instruction*test_condition + Error(ID/(encoding_stimulus_time*encoding_instruction*test_condition)), Accuracy$subject_means)
# save printable summaries
Accuracy$apa_print <- papaja::apa_print(Accuracy$aov.out)
```
## Print Means
```{r}
lapply(Accuracy$means,knitr::kable)
```
## Print ANOVA
```{r}
knitr::kable(xtable(summary(Accuracy$aov.out)))
```
```{r}
Accuracy <- list()
# select data from test phase
Accuracy$filtered_data <- all_data %>%
filter(experiment_phase == "test",
ID %in% all_excluded == FALSE)
# get mean accuracy in each condition for each subject
Accuracy$subject_means <- Accuracy$filtered_data %>%
group_by(ID,
encoding_stimulus_time,
encoding_instruction,
test_condition)%>%
summarize(mean_correct = mean(correct))
# get mean accuracy in each condition across subjects
Accuracy$condition_means <- Accuracy$subject_means %>%
group_by(encoding_stimulus_time,
encoding_instruction,
test_condition)%>%
summarize(grp_mean_correct = mean(mean_correct),
sem = sd(mean_correct)/sqrt(length(mean_correct)))
# print table
knitr::kable(Accuracy$condition_means)
e1_figure1 <- ggplot(Accuracy$condition_means, aes(x=test_condition,
y=grp_mean_correct,
group=encoding_instruction,
fill=encoding_instruction))+
geom_bar(stat="identity", position="dodge")+
geom_errorbar(aes(ymin = grp_mean_correct-sem,
ymax = grp_mean_correct+sem),
width=.9, position=position_dodge2(width = 0.2, padding = 0.8))+
facet_wrap(~encoding_stimulus_time)+
coord_cartesian(ylim=c(.4,1))+
geom_hline(yintercept=.5)+
scale_y_continuous(breaks = seq(0.4,1,.1))+
theme_classic(base_size=12)+
ylab("Proportion Correct")+
xlab("Lure Type")+
scale_fill_discrete(name = " Encoding \n Instruction") +
ggtitle("1A: Proportion Correct by Stimulus Encoding Duration, \n Encoding Instruction, and Lure Type")
e1_figure1
```
## Encoding_instruction x encoding_stimulus_time
```{r}
instruction_time <- Accuracy$subject_means %>%
mutate(encoding_stimulus_time = as.factor(encoding_stimulus_time)) %>%
group_by(encoding_stimulus_time,encoding_instruction)%>%
summarize(grp_mean_correct = mean(mean_correct),
sem = sd(mean_correct)/sqrt(length(mean_correct)))
ggplot(instruction_time, aes(x=encoding_stimulus_time,
y=grp_mean_correct,
group=encoding_instruction,
fill=encoding_instruction))+
geom_bar(stat="identity", position="dodge")+
geom_errorbar(aes(ymin = grp_mean_correct-sem,
ymax = grp_mean_correct+sem),
width=.9, position=position_dodge2(width = 0.5, padding = 0.5))+
coord_cartesian(ylim=c(.4,1))+
geom_hline(yintercept=.5)+
scale_y_continuous(breaks = seq(0.4,1,.1))+
theme_classic(base_size=12)+
ylab("Proportion Correct")+
xlab("Stimulus Encoding Duration")+
scale_fill_discrete(name = " Encoding \n Instruction") +
ggtitle("1A: Proportion Correct by Stimulus Encoding Duration \n and Encoding Instruction")
```
## ANOVA
```{r}
# ensure factor class
Accuracy$subject_means <- Accuracy$subject_means %>%
mutate(ID = as.factor(ID),
encoding_stimulus_time = as.factor(encoding_stimulus_time),
encoding_instruction = as.factor(encoding_instruction),
test_condition = as.factor(test_condition))
# run ANOVA
aov.out <- aov(mean_correct ~ encoding_stimulus_time*encoding_instruction*test_condition + Error(ID/(encoding_stimulus_time*encoding_instruction*test_condition)), Accuracy$subject_means)
```
## Write-up
```{r}
library(papaja)
E1_ANOVA <- papaja::apa_print(aov.out)
E1_ANOVA$full_result$encoding_stimulus_time
E1_ANOVA$full_result$test_condition
E1_ANOVA$full_result$encoding_instruction
E1_ANOVA$full_result$encoding_stimulus_time_encoding_instruction
## simple effects
IT500 <- subject_means %>%
filter(encoding_stimulus_time == "500") %>%
group_by(ID,encoding_instruction) %>%
summarize(grp_mean_correct = mean(mean_correct))
IT500_report <- apa_print(t.test(IT500[IT500$encoding_instruction == "R",]$grp_mean_correct - IT500[IT500$encoding_instruction == "F",]$grp_mean_correct ))
IT500_report$full_result
IT1000 <- subject_means %>%
filter(encoding_stimulus_time == "1000") %>%
group_by(ID,encoding_instruction) %>%
summarize(grp_mean_correct = mean(mean_correct))
IT1000_report <- apa_print(t.test(IT1000[IT1000$encoding_instruction == "R",]$grp_mean_correct - IT1000[IT1000$encoding_instruction == "F",]$grp_mean_correct))
IT1000_report$full_result
IT2000 <- subject_means %>%
filter(encoding_stimulus_time == "2000") %>%
group_by(ID,encoding_instruction) %>%
summarize(grp_mean_correct = mean(mean_correct))
IT2000_report <- apa_print(t.test(IT2000[IT2000$encoding_instruction == "R",]$grp_mean_correct - IT2000[IT2000$encoding_instruction == "F",]$grp_mean_correct))
IT2000_report$full_result
```
Proportion correct for each subject in each condition was submitted to a 3 (Encoding Time: 500ms, 1000ms, 2000ms) x 2 (Encoding Instruction: Forget vs. Remember) x 2 (Lure type: Novel vs. Exemplar) fully repeated measures ANOVA. For completeness, each main effect and higher-order interaction is described in turn.
The main effect of encoding time was, `r E1_ANOVA$full_result$encoding_stimulus_time`. Proportion correct was `r round(duration_means[duration_means$encoding_stimulus_time == "500",]$grp_mean_correct, digits=3)` (`r round(duration_means[duration_means$encoding_stimulus_time == "500",]$sem,digits=3)`), `r round(duration_means[duration_means$encoding_stimulus_time == "1000",]$grp_mean_correct, digits=3)` (`r round(duration_means[duration_means$encoding_stimulus_time == "1000",]$sem,digits=3)`), and `r round(duration_means[duration_means$encoding_stimulus_time == "2000",]$grp_mean_correct, digits=3)` (`r round(duration_means[duration_means$encoding_stimulus_time == "2000",]$sem,digits=3)`) for the 500ms, 1000ms, and 2000ms intervals, respectively.
The main effect of test lure was significant, `r E1_ANOVA$full_result$test_condition`. Proportion correct was higher for novel lures (`r round(test_means[test_means$test_condition == "novel",]$grp_mean_correct, digits=3)`, SEM = `r round(test_means[test_means$test_condition == "novel",]$sem, digits=3)`), compared to exemplar lures (`r round(test_means[test_means$test_condition == "exemplar",]$grp_mean_correct, digits=3)`, SEM = `r round(test_means[test_means$test_condition == "exemplar",]$sem, digits=3)`).
The main effect of encoding instruction was, `r E1_ANOVA$full_result$encoding_instruction`. Proportion correct was similar for forget cued (`r round(instruction_means[instruction_means$encoding_instruction == "F",]$grp_mean_correct, digits=3)`, SEM = `r round(instruction_means[instruction_means$encoding_instruction == "F",]$sem, digits=3)`) and remember cued (`r round(instruction_means[instruction_means$encoding_instruction == "R",]$grp_mean_correct, digits=3)`, SEM = `r round(instruction_means[instruction_means$encoding_instruction == "R",]$sem, digits=3)`) items
The interaction between encoding instruction and encoding time was significant, `r E1_ANOVA$full_result$encoding_stimulus_time_encoding_instruction`. To further interpret this interaction, paired sample t-tests were used to assess the directed forgetting effect at each encoding time duration. The directed forgetting effect is taken as the difference between proportion correct for remember minus forget items. At 500 ms, the directed forgetting effect was not detected, `r IT500_report$full_result`. At 1000ms, the directed forgetting effect was reversed, `r IT1000_report$full_result`. And, at 2000 ms, the directed forgetting effect was again not detected, `r IT2000_report$full_result`. The remaining interactions were not significant.
# RT analysis
## Get means across Conditions
```{r}
# select data from test phase
filtered_data_rt <- all_data %>%
filter(experiment_phase == "test",
correct == TRUE)
# get mean accuracy in each condition for each subject
subject_means_rt <- filtered_data_rt %>%
group_by(ID,
encoding_stimulus_time,
encoding_instruction,
test_condition)%>%
summarize(mean_RT = mean(rt))
# get mean accuracy in each condition across subjects
condition_means_rt <- subject_means_rt %>%
group_by(encoding_stimulus_time,
encoding_instruction,
test_condition)%>%
summarize(grp_mean_RT = mean(mean_RT),
sem = sd(mean_RT)/sqrt(length(mean_RT)))
# print table
knitr::kable(condition_means_rt)
e1_figure1_rt <- ggplot(condition_means_rt, aes(x=test_condition,
y=grp_mean_RT,
group=encoding_instruction,
fill=encoding_instruction))+
geom_bar(stat="identity", position="dodge")+
geom_errorbar(aes(ymin = grp_mean_RT-sem,
ymax = grp_mean_RT+sem),
width=.9, position=position_dodge2(width = 0.5, padding = 0.5))+
facet_wrap(~encoding_stimulus_time)+
coord_cartesian(ylim=c(1000,2000))+
theme_classic(base_size=12)+
ylab("Mean RT (ms)")+
xlab("Lure Type")+
scale_fill_discrete(name = " Encoding \n Instruction") +
ggtitle("1A: Proportion Correct by Stimulus Encoding Duration, \n Encoding Instruction, and Lure Type")
e1_figure1_rt
```
## ANOVA
```{r}
subject_means_rt$ID <- as.factor(subject_means_rt$ID)
subject_means_rt$encoding_stimulus_time <- as.factor(subject_means_rt$encoding_stimulus_time)
subject_means_rt$encoding_instruction <- as.factor(subject_means_rt$encoding_instruction)
subject_means_rt$test_condition <- as.factor(subject_means_rt$test_condition)
aov.out_rt <- aov(mean_RT ~ encoding_stimulus_time*encoding_instruction*test_condition + Error(ID/(encoding_stimulus_time*encoding_instruction*test_condition)), subject_means_rt)
summary(aov.out_rt)
```
## Write-up
```{r}
library(papaja)
E1_ANOVA_RT <- papaja::apa_print(aov.out_rt)
E1_ANOVA_RT$full_result$encoding_stimulus_time
E1_ANOVA_RT$full_result$test_condition
E1_ANOVA_RT$full_result$encoding_instruction
E1_ANOVA_RT$full_result$encoding_stimulus_time_encoding_instruction
## simple effects
IT500 <- subject_means_rt %>%
filter(encoding_stimulus_time == "500") %>%
group_by(ID,encoding_instruction) %>%
summarize(grp_mean_RT = mean(mean_RT))
IT500_report <- apa_print(t.test(IT500[IT500$encoding_instruction == "R",]$grp_mean_RT - IT500[IT500$encoding_instruction == "F",]$grp_mean_RT ))
IT500_report$full_result
IT1000 <- subject_means %>%
filter(encoding_stimulus_time == "1000") %>%
group_by(ID,encoding_instruction) %>%
summarize(grp_mean_RT = mean(mean_RT))
IT1000_report <- apa_print(t.test(IT1000[IT1000$encoding_instruction == "R",]$grp_mean_RT - IT1000[IT1000$encoding_instruction == "F",]$grp_mean_RT))
IT1000_report$full_result
IT2000 <- subject_means %>%
filter(encoding_stimulus_time == "2000") %>%
group_by(ID,encoding_instruction) %>%
summarize(grp_mean_RT = mean(mean_RT))
IT2000_report <- apa_print(t.test(IT2000[IT2000$encoding_instruction == "R",]$grp_mean_RT - IT2000[IT2000$encoding_instruction == "F",]$grp_mean_RT))
IT2000_report$full_result
```
Mean reaction times for each subject in each condition was submitted to a 3 (Encoding Time: 500ms, 1000ms, 2000ms) x 2 (Encoding Instruction: Forget vs. Remember) x 2 (Lure type: Novel vs. Exemplar) fully repeated measures ANOVA. For completeness, each main effect and higher-order interaction is described in turn.
The main effect of encoding time was, `r E1_ANOVA$full_result$encoding_stimulus_time`. Proportion correct was `r round(duration_means[duration_means$encoding_stimulus_time == "500",]$grp_mean_correct, digits=3)` (`r round(duration_means[duration_means$encoding_stimulus_time == "500",]$sem,digits=3)`), `r round(duration_means[duration_means$encoding_stimulus_time == "1000",]$grp_mean_correct, digits=3)` (`r round(duration_means[duration_means$encoding_stimulus_time == "1000",]$sem,digits=3)`), and `r round(duration_means[duration_means$encoding_stimulus_time == "2000",]$grp_mean_correct, digits=3)` (`r round(duration_means[duration_means$encoding_stimulus_time == "2000",]$sem,digits=3)`) for the 500ms, 1000ms, and 2000ms intervals, respectively.
The main effect of test lure was significant, `r E1_ANOVA$full_result$test_condition`. Proportion correct was higher for novel lures (`r round(test_means[test_means$test_condition == "novel",]$grp_mean_correct, digits=3)`, SEM = `r round(test_means[test_means$test_condition == "novel",]$sem, digits=3)`), compared to exemplar lures (`r round(test_means[test_means$test_condition == "exemplar",]$grp_mean_correct, digits=3)`, SEM = `r round(test_means[test_means$test_condition == "exemplar",]$sem, digits=3)`).
The main effect of encoding instruction was, `r E1_ANOVA$full_result$encoding_instruction`. Proportion correct was similar for forget cued (`r round(instruction_means[instruction_means$encoding_instruction == "F",]$grp_mean_correct, digits=3)`, SEM = `r round(instruction_means[instruction_means$encoding_instruction == "F",]$sem, digits=3)`) and remember cued (`r round(instruction_means[instruction_means$encoding_instruction == "R",]$grp_mean_correct, digits=3)`, SEM = `r round(instruction_means[instruction_means$encoding_instruction == "R",]$sem, digits=3)`) items
The interaction between encoding instruction and encoding time was significant, `r E1_ANOVA$full_result$encoding_stimulus_time_encoding_instruction`. To further interpret this interaction, paired sample t-tests were used to assess the directed forgetting effect at each encoding time duration. The directed forgetting effect is taken as the difference between proportion correct for remember minus forget items. At 500 ms, the directed forgetting effect was not detected, `r IT500_report$full_result`. At 1000ms, the directed forgetting effect was reversed, `r IT1000_report$full_result`. And, at 2000 ms, the directed forgetting effect was again not detected, `r IT2000_report$full_result`. The remaining interactions were not significant.
## Attention check
Did individual participants successfully press the F or R keys during encoding?
```{r}
# select data from test phase
filtered_data <- all_data %>%
filter(experiment_phase == "study",
is.na(correct) == FALSE)
# get mean accuracy in each condition for each subject
subject_means <- filtered_data %>%
group_by(ID)%>%
summarize(mean_correct = mean(correct))
knitr::kable(subject_means)
```
## Design
```{r}
sub_1 <- all_data %>%
filter(ID =="j1s5gca39ee2lkr9",
item_type == "study",
experiment_phase == "study") %>%
group_by(category_type,category,encoding_instruction,stimulus_time) %>%
count()
```
## Demographics
```{r}
library(tidyr)
demographics <- all_data %>%
filter(trial_type == "survey-html-form") %>%
select(ID,response) %>%
unnest_wider(response) %>%
mutate(age = as.numeric(age))
age_demographics <- demographics %>%
summarize(mean_age = mean(age),
sd_age = sd(age),
min_age = min(age),
max_age = max(age))
factor_demographics <- apply(demographics[-1], 2, table)
```
A total of `r dim(demographics)[1]` participants were recruited from Amazon's Mechanical Turk. Mean age was `r round(age_demographics$mean_age, digits=1)` (range = `r age_demographics$min_age` to `r age_demographics$max_age` ). There were `r as.numeric(factor_demographics$sex["female"])` females, and `r as.numeric(factor_demographics$sex["male"])` males. There were `r as.numeric(factor_demographics$hand["Right"])` right-handed participants, and `r as.numeric(factor_demographics$hand["Both"])+as.numeric(factor_demographics$hand["Left"])` left or both handed participants. `r as.numeric(factor_demographics$vision["Normal"])` participants reported normal vision, and `r as.numeric(factor_demographics$vision["Corrected"])` participants reported corrected-to-normal vision. `r as.numeric(factor_demographics$english["First"])` participants reported english as a first language, and `r as.numeric(factor_demographics$english["Second"])` participants reported english as a second language.
## save environment
```{r}
save.image("data/E1/E1_data.RData")
``` |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
</head>
<body style="background-color: #eeeeee">
<nav class="navbar navbar-expand-lg navbar-dark bg-success">
<div class="container-fluid">
<a class="navbar-brand" href="#">Register</a>
<button class="navbar-toggler" type="button"
data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
</div>
</div>
</nav>
<div th:if="${param.error}" class="alert alert-error justify-content-center container">
<div class="col-sm text-align-center" style="text-align: center">Email is used.</div>
</div>
<div class="container justify-content-center">
<form method="post" th:action="@{/register/success}" th:object="${userForm}">
<div class="row justify-content-center" style="height: 50px">
<div class="col-sm-1"><label for="email">Email:</label></div>
<div class="col-sm-1"><input type="email" id="email" name="email" th:value="*{email}" required/></div>
</div>
<div class="row justify-content-center" style="height: 50px">
<div class="col-md-1"><label for="firstName">First Name:</label></div>
<div class="col-md-1"><input type="text" id="firstName" name="firstName" th:value="*{firstName}" required/></div>
</div>
<div class="row justify-content-center" style="height: 50px">
<div class="col-md-1"><label for="lastName">Last Name:</label></div>
<div class="col-md-1"><input type="text" id="lastName" name="lastName" th:value="*{lastName}" required/></div>
</div>
<div class="row justify-content-center" style="height: 50px">
<div class="col-md-1"><label for="password">Password:</label></div>
<div class="col-md-1"><input type="password" id="password" name="password" th:value="*{password}" required/></div>>
</div>
<div class="row justify-content-center" style="height: 50px">
<div class="col-md-1"><label for="role">Role:</label></div>
<div class="col-md-1">
<select name="role" required>
<option th:each="role : ${T(com.seminar.WebApp.entities.Role).values()}"
th:value="${role}" th:text="${role}"></option>
</select></div>
</div>
<div class="row justify-content-center" style="height: 50px">
<div class="col-md-1"><input type="Submit" class="btn btn-primary" name="Submit">
</form>
</div>
<div class="row justify-content-center mt-2" style="height: 50px">
<div class="col-sm-1"><a href="/login" class="btn btn-primary">Login</a></div>
</div>
<div class="row justify-content-center" style="height: 50px">
<div class="col-sm-1"><a href="/" class="btn btn-secondary">Index</a></div>
</div>
</div>
</div>
</body>
</html> |
<template>
<div class="app-container">
<h2>Belajar Matematika</h2>
<el-row :gutter="20">
<el-col :span="20">
<div
v-for="section in list.section"
:key="section.uuid"
class="section"
>
<b> {{ section.section_of }} - {{ section.name }}</b>
<el-row :gutter="20" class="section-row">
<div v-if="section.chapter[0] === undefined">
<button>Add</button>
</div>
<el-col v-else>
<el-col
v-for="(chapter, index) in section.chapter"
:key="index"
:span="8"
style="margin-bottom:10px"
>
<el-card class="box-card">
<img src="../.../../../assets/icon/book.png" class="image" >
<div>
<h4 style="margin-bottom:5px">
{{ index + 1 }}. {{ chapter.name }}
</h4>
</div>
</el-card>
</el-col>
<el-col :span="8">
<el-card class="box-card">
<div>
<el-button
type="primary"
style="margin-top:19px"
@click="handleDialog(section.uuid)"
>Add Chapter <i
class="el-icon-plus el-icon-plus"
/></el-button>
</div>
</el-card>
</el-col>
</el-col>
</el-row>
</div>
</el-col>
<el-col :span="4">
<h1>Hello</h1>
</el-col>
</el-row>
<el-dialog :visible.sync="dialog" title="Add Chapter" width="30%" center>
<el-row class="button-raw">
<el-col :span="24">
<router-link
:to="'/elearning/lesson/add/' + subject_uuid"
class="link-type"
>
<el-button size="medium"><b>Add Lesson</b></el-button>
</router-link>
</el-col>
<el-col :span="24">
<el-button size="medium"><b>Add Exercise</b></el-button>
</el-col>
<el-col :span="24">
<el-button size="medium"><b>Add Exam</b></el-button>
</el-col>
</el-row>
<span slot="footer" class="dialog-footer">
<el-button @click="dialog = false">Cancel</el-button>
<el-button type="primary" @click="dialog = false">Confirm</el-button>
</span>
</el-dialog>
</div>
</template>
<style scoped>
.image {
width: 20%;
display: block;
/* height: 200px; */
text-align: center;
}
.section {
margin-block: 30px;
}
.section-row {
margin-top: 30px;
}
.button-raw div {
margin-bottom: 20px;
}
.button-raw button {
width: 100%;
}
</style>
<script>
import Subject from '@/service/Subject'
export default {
data() {
return {
currentDate: new Date(),
params: '',
list: [],
dialog: false,
subject_uuid: ''
}
},
created() {
this.params = this.$route.params.id
this.getList(this.params)
},
methods: {
async getList(uuid) {
await Subject.getSubject(uuid)
.then(({ data }) => {
this.list = data.data
console.log(this.list)
})
.catch(err => {
console.log(err)
})
},
addChapter() {
console.log('Section')
},
handleDialog(uuid) {
this.dialog = true
this.subject_uuid = uuid
}
}
}
</script> |
<!DOCTYPE HTML>
<!--
Solid State by HTML5 UP
html5up.net | @ajlkn
Free for personal and commercial use under the CCA 3.0 license (html5up.net/license)
-->
<html>
<head>
<title>OpenGL Graphics Project</title>
<link rel="icon" type="image/x-icon" href="images/logo.png">
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="stylesheet" href="assets/css/main.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Page Wrapper -->
<div id="page-wrapper">
<!-- Header -->
<header id="header" class="alt">
<h1><a href="index.html">OpenGL Graphics Project</a></h1>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<nav id="menu">
<div class="inner">
<h2>Menu</h2>
<ul class="links">
<li><a href="index.html">Home</a></li>
<li><a href="projectOne.html">OpenGL Graphics Project</a></li>
<li><a href="projectTwo.html">Mario</a></li>
<li><a href="projectThree.html">S2D Graphics Project</a></li>
<li><a href="projectFour.html">2D Platformer in Unity</a></li>
</ul>
<a href="#" class="close">Close</a>
</div>
</nav>
<!-- Banner -->
<section id="banner">
<div class="inner">
<h2>OpenGL Graphics Project</h2>
<p></p>
</div>
</section>
<!-- Wrapper -->
<section id="wrapper">
<!-- One -->
<section id="one" class="wrapper spotlight style1">
<div class="inner">
<a href="images/FOGGSSemTwo/FOGGSSemTwoGif.gif" target="_blank" class="image"><img src="images/FOGGSSemTwo/FOGGSSemTwoGif.gif" alt="Gif of Final Graphics Project" /></a>
<div class="content">
<h2 class="major">Overview</h2>
<p>During my work at Staffordshire University, I was tasked with understanding the fundamentals of the fixed graphical pipeline using OpenGL to prepare for the programmable
pipeline in Year Two. Throughout this project I learnt many techniques, Object Oriented Programming is an important concept to understand for this
project to keep code manageable and readable, researching skills and problem-solving also helped when an issue was encountered, and good coding practice such as comments and naming standards
allowed me to navigate and understand my code base quickly and efficiently.
<br><br>This GIF shows the final piece I produced which is a complex 3D scene that can load .obj files and render them using lighting, materials, and textures, in the scene that they are rendered
Text is also displayed and a depth buffer is used, and to ensure smooth animations double buffering has been implemented. The player can move around the scene using their keyboard to control the camera or turn the lighting off and on.</p>
</div>
</div>
</section>
<section id="two" class="wrapper alt spotlight style2">
<div class="inner">
<a href="images/FOGGSSemTwo/WhiteRect.png" target="_blank" class="image"><img src="images/FOGGSSemTwo/WhiteRect.png" alt="White REctangle in OpenGL" /></a>
<div class="content">
<h2 class="major">Getting Started</h2>
<p>My experience in the OpenGL library was also my first implementation of a state machine, by defining a current state that is then kept until changed,
this meant that if a colour was defined then everything would be that colour until redefined. These screenshots demonstrate the colour blending that happens when drawing a simple shape using the RGB colour model.
<br><br>
My first step was to create a shape in 2D space to understand the coordinate system, OpenGL sets the origin of the world (0,0) in the centre of the screen, this was a crucial first step as previous frameworks use the origin
at the top left-hand corner of the screen.</p>
</div>
</div>
</section>
<section id="three" class="wrapper spotlight style3">
<div class="inner">
<a href="images/FOGGSSemTwo/firstRotation.gif" target="_blank" class="image"><img src="images/FOGGSSemTwo/firstRotation.gif" alt="First Rotation of Objects in OpenGL" /></a>
<div class="content">
<h2 class="major">Moving Forward</h2>
<p>Using the skills learnt from the previous session to add new features to the program, this included creating a game loop allowing animations to be played, simulations to be run and players to interact with the program moving away from a static image on the screen. <br><br> Once the game loop was established rotation was added to one of
the shapes created previously this led to multiple shapes rotating at the same time as shown in the gif.</p>
</div>
</div>
</section>
<section id="two" class="wrapper alt spotlight style2">
<div class="inner">
<a href="images/FOGGSSemTwo/wireframeCube.gif" target="_blank" class="image"><img src="images/FOGGSSemTwo/wireframeCube.gif" alt="Wireframe Cube" /></a>
<div class="content">
<h2 class="major">Adventures in 3D</h2>
<p>After creating my first animation I noticed that the object movement was jittery and lacked the smoothness expected, to fix this I created a double buffer smoothing the frames.<br>
<br> However if the update gets increasingly complex then the program may face FPS problems due to the time it takes to run the update loop and then fire the next frame. To fix this elapsed
time was used to ensure that the frames, whether late or early, fired in the same 16ms that the others have smoothing them out to the expected 60fps and adding a dynamically altering frame rate to the program. <br>
</p>
</div>
</div>
</section>
<section id="three" class="wrapper spotlight style3">
<div class="inner">
<a href="images/FOGGSSemTwo/colouredCube.gif" target="_blank" class="image"><img src="images/FOGGSSemTwo/colouredCube.gif" alt="Solid Rainbow Cube in OpenGL" /></a>
<div class="content">
<h2 class="major">Adventures in 3D Continued</h2>
<p>I also explored multiple ways of creating a 3D cube, initially using a prebuilt wireframe version, then moving on to create my own using a few different methods starting with the basic plot of every vertex in
3D space for each triangle. However, this meant that there was some overlap and the vertices were plotted on top of each other taking up memory and causing potential issues later. To fix this rather than replotting vertices I reused them,
along with the back face culling, resulting in the cube presented in the GIF.
<br><br>
To take this even further and more akin to the industry standard OOP practices using the file provided for us to practice with pulling the cube data in from a file and drawing the object that way.</p>
</div>
</div>
</section>
<section id="two" class="wrapper alt spotlight style2">
<div class="inner">
<a href="images/FOGGSSemTwo/untexturedCubeField.gif" target="_blank" class="image"><img src="images/FOGGSSemTwo/untexturedCubeField.gif" alt="Cube Field" /></a>
<div class="content">
<h2 class="major">Travering the Cube Field</h2>
<p>Creating a single object that spins in space was a fun way to further my understanding of 3D Space but I wanted to take it further this led me to create an array of cubes that will be rendered in space using random positions,
as seen in the gif. This was created to expand this to create multiple different objects in 3D space.
</p>
</div>
</div>
</section>
<section id="three" class="wrapper spotlight style3">
<div class="inner">
<a href="images/FOGGSSemTwo/cubeField.gif" target="_blank" class="image"><img src="images/FOGGSSemTwo/cubeField.gif" alt="Textured Cube Field" /></a>
<div class="content">
<h2 class="major">Texturing</h2>
<p>After creating a cube field I wanted to add more more depth to my objects by adding textures. Up until this point I had just been using solid colours or interpolated colours to give life to my cubes, however, in games textures
are used to breathe life into boring objects. To add textures I created a class to read in values from a txt file to create a more modular program. Once the file was read in the values were assigned to the UV coordinates
and imprinted on the cubes. </p>
</div>
</div>
</section>
<section id="two" class="wrapper alt spotlight style2">
<div class="inner">
<a href="images/FOGGSSemTwo/shadowedCubeField.gif" target="_blank" class="image"><img src="images/FOGGSSemTwo/shadowedCubeField.gif" alt="Cube Field" /></a>
<div class="content">
<h2 class="major">Lighting and Materials</h2>
<p>Now that my objects had depth and textures I wanted to highlight both of these and make it easier for a user to see the different objects using lighting. However I did not stop there I wanted to give the user a way to turn the lights on or off, I did this using a simple method that checks if
the light is on when the 'l' key is pushed and if so turns them off and vice versa.
<br><br>
To keep with the OOP standards I created a material library in its class that would be called by the object, I also wanted to implement a call that would change the material when the user pressed a key. This is where a major problem arose,
while creating materials I accidentally put the material new call in the cube update loop, this meant that I was creating a new material to assign to every one of the cubes every frame but also creating it on the heap so it never went out of
scope creating a major memory leak. After a few days of searching for this memory leak I turned to Google for help, this led me to tools that could help me and found that VS has a built-in way of seeing how many new objects are created, so after
finding out that I had created a ridiculous number of materials this narrowed down the search enough for me to find the problem and solve it.
</p>
</div>
</div>
</section>
<section id="three" class="wrapper alt spotlight style3">
<div class="inner">
<a href="images/FOGGSSemTwo/FOGGSSemTwoGif.gif" target="_blank" class="image"><img src="images/FOGGSSemTwo/FOGGSSemTwoGif.gif" alt="Final Product" /></a>
<div class="content">
<h2 class="major">Final Product</h2>
<p>Finally, I created a scene graph to demonstrate an understanding of matrices I used this inherited relationship to rotate objects around another object. so rather than using a rotation and the object rotation around the object and then translating them into another area of space I translated the object first and then rotated around the object's origin point this allowed objects to orbit other objects. Once I was happy with this I downloaded some free-use textures and obj files to create an array of different objects to show my program is modular.
<br><br>
I am very proud of how this project turned out, as I was very overwhelmed when beginning but kept working at it and very happily walked away with a first.
</p>
</div>
</div>
</section>
<!--<section id="three" class="wrapper spotlight style3">
<div class="inner">
<div class="content">
<h2 class="major">Materials Library</h2>
<a href="images/FOGGSSemTwo/blueCubeField.gif" target="_blank"><p><span class="image left"><img src="images/FOGGSSemTwo/blueCubeField.gif" alt="Blue Cube Field" /></span></p></a>
<a href="images/FOGGSSemTwo/redCubeField.gif" target="_blank"><p><span class="image right"><img src="images/FOGGSSemTwo/redCubeField.gif" alt="Red Cube Field" /></span></p></a>
</div>
</div>
</section>-->
</section>
<!-- Footer -->
<section id="footer">
<div class="inner">
<h2 class="major">Get in touch</h2>
<ul class="icons">
<li><a href="https://www.linkedin.com/in/harryawatts/" target="_blank"><img src="images/linkedinIcon.png" alt="Linkedin Logo" width="200"></a></li>
<li><a href="https://github.com/HarryMadn3ss" target="_blank"><img src="images/githubIcon.png" alt="Github Logo" width="200"></a></li>
</ul>
<ul class="copyright">
<li>© Harry Watts. All rights reserved.</li><li>Design: <a href="http://html5up.net">HTML5 UP</a></li>
</ul>
</div>
</section>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html> |
const Blog = require('../models/blog.model');
const User = require('../models/user.model');
const jwt = require('jsonwebtoken');
const blogsRouter = require('express').Router();
const { userExtractor } = require('../utils/middleware');
blogsRouter.get('/', async (request, response) => {
const blogs = await Blog.find({}).populate('user', {
username: 1,
name: 1,
_id: 1,
});
response.json(blogs);
});
blogsRouter.post('/', userExtractor, async (request, response) => {
const user = request.user;
const blog = new Blog(request.body);
if (!blog.likes) blog.likes = 0;
blog.user = user._id;
const savedBlog = await blog.save();
user.blogs = user.blogs.concat(savedBlog);
await user.save();
await savedBlog.populate('user', { username: 1, name: 1, _id: 1 });
response.status(201).json(savedBlog);
});
blogsRouter.delete('/:id', userExtractor, async (request, response) => {
const user = request.user;
const blog = await Blog.findById(request.params.id);
if (user.id !== blog.user.toString()) {
return response.status(401).json({ error: 'invalid user' });
}
await Blog.findByIdAndDelete(request.params.id);
user.blogs = user.blogs.filter((blog) => blog !== request.params.id);
await user.save();
response.status(204).end();
});
blogsRouter.put('/:id', async (request, response) => {
const body = request.body;
const blog = {
title: body.title,
author: body.author,
url: body.url,
likes: body.likes,
};
const updatedBlog = await Blog.findByIdAndUpdate(request.params.id, blog, {
new: true,
}).populate('user', { username: 1, name: 1, _id: 1 });
response.json(updatedBlog);
});
blogsRouter.post('/:id/comments', async (request, response) => {
const newComment = request.body.comment;
const blogToComment = await Blog.findById(request.params.id);
blogToComment.comments
? blogToComment.comments.push(newComment)
: blogToComment.comments = [newComment];
await blogToComment.save();
await blogToComment.populate('user', { username: 1, name: 1, _id: 1 });
response.json(blogToComment);
});
module.exports = blogsRouter; |
---
description: "Simple Way to Prepare Quick Our Family Recipe for Fluffy and Creamy Okonomiyaki"
title: "Simple Way to Prepare Quick Our Family Recipe for Fluffy and Creamy Okonomiyaki"
slug: 3669-simple-way-to-prepare-quick-our-family-recipe-for-fluffy-and-creamy-okonomiyaki
date: 2020-10-17T06:17:36.544Z
image: https://img-global.cpcdn.com/recipes/5487442716000256/751x532cq70/our-family-recipe-for-fluffy-and-creamy-okonomiyaki-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5487442716000256/751x532cq70/our-family-recipe-for-fluffy-and-creamy-okonomiyaki-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5487442716000256/751x532cq70/our-family-recipe-for-fluffy-and-creamy-okonomiyaki-recipe-main-photo.jpg
author: Jorge Jefferson
ratingvalue: 3.2
reviewcount: 8
recipeingredient:
- "300 grams Okonomiyaki flour"
- "2 large Eggs"
- "360 grams Milk"
- "240 grams Grated nagaimo"
- "1 Onion 1 cm dice"
- "1 bunch Green onions"
- "300 grams Cabbage 1 cm squares"
- "1 handful per pancake Melting cheese"
- "1 egg per pancake Egg"
- "1 Pork belly shrimp squid beni shouga picked red ginger chikuwa tempura batter crumbs aonori bonito flakes etc"
- "1 Okonomiyaki sauce mustard mayonnaise"
recipeinstructions:
- "Make the batter. Mix the okonomiyaki flour, eggs, and milk well in a bowl to remove clumps. Add grated yam."
- "Add onions, leeks, cabbage, and your favorite additional ingredients into the bowl."
- "We like to add a pack of peeled shrimp (approximately 150 g), deep fried as tempura, into the okonomiyaki batter."
- "How to cook the okonomiyaki: Pour a ladle full of batter mixture into a non-stick frying pan or onto an electric griddle. Make a well in the middle."
- "Crack an egg into the well."
- "Pour more batter on top."
- "Add the pork slices, tempura batter crumbs and cheese on top. Put a lid on top of the pan (or on top of the pancake on the griddle (and cook slowly over low heat (about 140°C) until browned."
- "Flip over once, put the lid back on and wait until the cheese has turned golden brown."
- "The cheese should be golden brown when you flip the okonomiyaki over. (Be careful not to let it burn!). The okonomiyaki should have puffed up quite a bit at this stage."
- "Now for the finish! Spread mustard and okonomiyaki sauce to taste on top."
- "Add more okonomiyaki sauce, mayonnaise, aonori seaweed powder and bonito flakes. Enjoy while it's piping hot."
- "Also delicious with chopped tomatoes."
categories:
- Recipe
tags:
- our
- family
- recipe
katakunci: our family recipe
nutrition: 194 calories
recipecuisine: American
preptime: "PT38M"
cooktime: "PT31M"
recipeyield: "4"
recipecategory: Lunch
---

Hello everybody, I hope you are having an amazing day today. Today, we're going to make a special dish, our family recipe for fluffy and creamy okonomiyaki. One of my favorites. This time, I will make it a little bit tasty. This is gonna smell and look delicious.
Our Family Recipe for Fluffy and Creamy Okonomiyaki is one of the most well liked of current trending meals on earth. It's appreciated by millions every day. It's easy, it is fast, it tastes yummy. Our Family Recipe for Fluffy and Creamy Okonomiyaki is something which I've loved my whole life. They are fine and they look wonderful.
I am thrilled to share this recipe for "okonomiyaki" aka cabbage pancake. You don't need to go to Japan or fancy Japanese. Best Okonomiyaki Recipe: Okonomiyak is easy to make!
To begin with this recipe, we have to first prepare a few ingredients. You can have our family recipe for fluffy and creamy okonomiyaki using 11 ingredients and 12 steps. Here is how you cook it.
<!--inarticleads1-->
##### The ingredients needed to make Our Family Recipe for Fluffy and Creamy Okonomiyaki:
1. Take 300 grams Okonomiyaki flour
1. Make ready 2 large Eggs
1. Get 360 grams Milk
1. Get 240 grams Grated nagaimo
1. Get 1 Onion (1 cm dice)
1. Make ready 1 bunch Green onions
1. Prepare 300 grams Cabbage (1 cm squares)
1. Make ready 1 handful per pancake Melting cheese
1. Get 1 egg per pancake Egg
1. Get 1 Pork belly, shrimp, squid, beni shouga (picked red ginger), chikuwa, tempura batter crumbs, aonori, bonito flakes, etc
1. Take 1 Okonomiyaki sauce, mustard, mayonnaise
I have seen other okonomiyaki recipes using dashi and yakisoba. Okonomiyaki are Japanese savoury pancakes packed with flavour and SO easy to make! It's also a popular meal Japanese families will cook at home, usually tweaking the recipe to suit their We first tried okonomiyaki with our Osaka-mum Rieko and her friend Noriko. They took us to their favourite.
<!--inarticleads2-->
##### Steps to make Our Family Recipe for Fluffy and Creamy Okonomiyaki:
1. Make the batter. Mix the okonomiyaki flour, eggs, and milk well in a bowl to remove clumps. Add grated yam.
1. Add onions, leeks, cabbage, and your favorite additional ingredients into the bowl.
1. We like to add a pack of peeled shrimp (approximately 150 g), deep fried as tempura, into the okonomiyaki batter.
1. How to cook the okonomiyaki: Pour a ladle full of batter mixture into a non-stick frying pan or onto an electric griddle. Make a well in the middle.
1. Crack an egg into the well.
1. Pour more batter on top.
1. Add the pork slices, tempura batter crumbs and cheese on top. Put a lid on top of the pan (or on top of the pancake on the griddle (and cook slowly over low heat (about 140°C) until browned.
1. Flip over once, put the lid back on and wait until the cheese has turned golden brown.
1. The cheese should be golden brown when you flip the okonomiyaki over. (Be careful not to let it burn!). The okonomiyaki should have puffed up quite a bit at this stage.
1. Now for the finish! Spread mustard and okonomiyaki sauce to taste on top.
1. Add more okonomiyaki sauce, mayonnaise, aonori seaweed powder and bonito flakes. Enjoy while it's piping hot.
1. Also delicious with chopped tomatoes.
Vegan Okonomiyaki Recipe - Japanese Savory Pancake Check out our delicious Okonomiyaki recipe - easy, vegan + gluten-free! Okonomiyaki - A cheap, easy, tasty family meal. I love okonomiyaki, or Japanese pancakes as they're also known. Learn how to make this simple and delicious Okonomiyaki from a recipe from Chef Jeremy Pang.
So that is going to wrap it up for this exceptional food our family recipe for fluffy and creamy okonomiyaki recipe. Thank you very much for your time. I am confident you can make this at home. There is gonna be more interesting food at home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your loved ones, colleague and friends. Thank you for reading. Go on get cooking! |
package uk.ac.ic.doc.aware
import android.content.BroadcastReceiver
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.text.Html
import android.view.View
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.ContextCompat
import com.google.android.gms.location.LocationServices
import uk.ac.ic.doc.aware.clients.GeofenceClient
import uk.ac.ic.doc.aware.services.GeofenceService
import uk.ac.ic.doc.aware.clients.WebSocketClient
import uk.ac.ic.doc.aware.services.WebSocketService
import uk.ac.ic.doc.aware.databinding.ActivityMainBinding
import uk.ac.ic.doc.aware.models.LoginStatus
import uk.ac.ic.doc.aware.models.RadiusList.radiusList
import java.lang.IllegalArgumentException
import java.lang.NumberFormatException
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var isServiceBound = false
// private val dialogsQueue = ArrayList<AlertDialog.Builder>()
private val serviceConnection = object : ServiceConnection {
override fun onNullBinding(name: ComponentName?) {
super.onNullBinding(name)
println("NO BINDER RECEIVED :(")
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
println("WebSocketService onServiceConnected called")
val binder = service as WebSocketService.LocalBinder
WebSocketClient.webSocketService = binder.getService()
isServiceBound = true
// You can now access the WebSocket service and use its methods or variables.
// For example, you can call webSocketService.sendMessage("Hello") to send a message.
}
override fun onServiceDisconnected(name: ComponentName?) {
isServiceBound = false
}
}
private val serviceConnection2 = object : ServiceConnection {
override fun onNullBinding(name: ComponentName?) {
super.onNullBinding(name)
println("NO BINDER RECEIVED :(")
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
println("GeoFence onServiceConnected called")
val binder = service as GeofenceService.LocalBinder
GeofenceClient.geofenceClient = binder.getService()
GeofenceClient.geofenceClient.geofencingClient =
LocationServices.getGeofencingClient(this@MainActivity)
isServiceBound = true
// You can now access the WebSocket service and use its methods or variables.
// For example, you can call webSocketService.sendMessage("Hello") to send a message.
}
override fun onServiceDisconnected(name: ComponentName?) {
isServiceBound = false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.getBooleanExtra("EXIT", false)) {
val webSocketService = Intent(this, WebSocketService::class.java)
val geofenceService = Intent(this, GeofenceService::class.java)
stopService(webSocketService)
stopService(geofenceService)
println("FINISHING")
finishAffinity();
System.exit(0)
return
}
binding = ActivityMainBinding.inflate(layoutInflater)
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
setContentView(binding.root)
binding.map.setOnClickListener {
val intent = Intent(this, MapActivity::class.java)
startActivity(intent)
// no settings
// binding.settings.visibility = View.GONE
}
binding.login.setOnClickListener {
val intent = Intent(this, LoginActivity::class.java)
startActivity(intent)
// binding.settings.visibility = View.GONE
}
val serviceIntent = Intent(this, WebSocketService::class.java)
ContextCompat.startForegroundService(this, serviceIntent)
applicationContext.bindService(
Intent(this, WebSocketService::class.java),
serviceConnection,
Context.BIND_AUTO_CREATE
)
println("service 1 started")
val serviceIntent2 = Intent(this, GeofenceService::class.java)
ContextCompat.startForegroundService(this, serviceIntent2)
applicationContext.bindService(
Intent(this, GeofenceService::class.java),
serviceConnection2,
Context.BIND_AUTO_CREATE
)
println("service 2 started")
// binding.settings.setOnClickListener {
// val builder = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// val layout = layoutInflater.inflate(R.layout.settings_dialog, null)
// builder.setView(layout)
// builder.setTitle("Settings for Radius")
// builder.setPositiveButton(android.R.string.yes) { _, _ ->
// val theftField = layout.findViewById<EditText>(R.id.theft_radius)
// val antiField = layout.findViewById<EditText>(R.id.anti_radius)
// val roadField = layout.findViewById<EditText>(R.id.road_radius)
// val majorField = layout.findViewById<EditText>(R.id.major_radius)
// val theftRadiusStr = theftField.text.toString()
// val antiRadiusStr = antiField.text.toString()
// val roadRadiusStr = roadField.text.toString()
// val majorRadiusStr = majorField.text.toString()
// if (theftRadiusStr.isNotEmpty()) {
// var theftRadius = 100
// try {
// theftRadius = theftRadiusStr.toInt()
// } catch (nfe: NumberFormatException) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Thieving</b> alerts is too high, a radius of less than <b>2km</b> is recommended."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// }
// if (theftRadius < 100) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Thieving</b> alerts is too low, a radius of at least <b>100m</b> is needed."))
// builder1.setCancelable(false)
// builder1.setNegativeButton(android.R.string.no) { _, _ ->
// }
// dialogsQueue.add(builder1)
// } else if (theftRadius >= 2000) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Thieving</b> alerts is too high, a radius of less than <b>2km</b> is recommended."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// } else {
// radiusList[0] = theftRadius
// }
// } else {
// radiusList[0] = 100
// }
// if (antiRadiusStr.isNotEmpty()) {
// var antiRadius = 200
// try {
// antiRadius = antiRadiusStr.toInt()
// } catch (nfe: NumberFormatException) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Anti Social Behaviour</b> alerts too high, a radius of less than <b>2km</b> is recommended."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// }
// if (antiRadius < 100) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Anti Social Behaviour</b> alerts is too low, a radius of at least <b>100m</b> is needed."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// } else if (antiRadius >= 2000) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Anti Social Behaviour</b> alerts too high, a radius of less than <b>2km</b> is recommended."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// } else {
// radiusList[1] = antiRadius
// }
// } else {
// radiusList[1] = 200
// }
// if (roadRadiusStr.isNotEmpty()) {
// var roadRadius = 300
// try {
// roadRadius = roadRadiusStr.toInt()
// } catch (nfe: NumberFormatException) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Travel Disruption</b> alerts too high, a radius of less than <b>2km</b> is recommended."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// }
// if (roadRadius < 100) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Travel Disruption</b> alerts is too low, a radius of at least <b>100m</b> is needed."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// } else if (roadRadius >= 2000) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Travel Disruption</b> alerts too high, a radius of less than <b>2km</b> is recommended."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// } else {
// radiusList[2] = roadRadius
// }
// } else {
// radiusList[2] = 300
// }
// if (majorRadiusStr.isNotEmpty()) {
// var majorRadius = 400
// try {
// majorRadius = majorRadiusStr.toInt()
// } catch (nfe: NumberFormatException) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Major Disruption</b> alerts is too high, a radius of less than <b>2km</b> is recommended."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// }
// if (majorRadius < 100) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Major Disruption</b> alerts is too low, a radius of at least <b>100m</b> is needed."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// } else if (majorRadius >= 2000) {
// val builder1 = AlertDialog.Builder(this,R.style.CustomAlertDialog)
// builder1.setMessage(Html.fromHtml("Radius setting for <b>Major Disruption</b> alerts is too high, a radius of less than <b>2km</b> is recommended."))
// builder1.setCancelable(false)
// builder1.setNegativeButton("OK") { _, _ ->
// }
// dialogsQueue.add(builder1)
// } else {
// radiusList[3] = majorRadius
// }
// } else {
// radiusList[3] = 400
// }
// val confirmationDialog = AlertDialog.Builder(this,R.style.CustomAlertDialog).setTitle("Confirmation")
// .setMessage(
// "Radius for Thieving Activity: ${radiusList[0]}m\nRadius for Anti Social Behaviour: ${radiusList[1]}m\n" +
// "Radius for Travel Disruptions: ${radiusList[2]}m\nRadius for Major Incidences: ${radiusList[3]}m"
// )
// .setPositiveButton("OK") { _, _ -> }
// confirmationDialog.show()
// for (dialog in dialogsQueue.reversed()) {
// dialog.show()
// }
// dialogsQueue.clear()
// println(radiusList)
// }
// builder.setNegativeButton(android.R.string.no) { _, _ ->
// }
// builder.show()
// }
}
} |
/*
* (C) Copyright IBM Corp. 2023.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.cloud.secrets_manager_sdk.secrets_manager.v2.model;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.cloud.secrets_manager_sdk.secrets_manager.v2.model.KVSecretPrototype;
import com.ibm.cloud.secrets_manager_sdk.secrets_manager.v2.utils.TestUtilities;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
/**
* Unit test class for the KVSecretPrototype model.
*/
public class KVSecretPrototypeTest {
final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
final List<FileWithMetadata> mockListFileWithMetadata = TestUtilities.creatMockListFileWithMetadata();
@Test
public void testKVSecretPrototype() throws Throwable {
KVSecretPrototype kvSecretPrototypeModel = new KVSecretPrototype.Builder()
.secretType("kv")
.name("my-secret-example")
.description("Extended description for this secret.")
.secretGroupId("default")
.labels(java.util.Arrays.asList("my-label"))
.data(java.util.Collections.singletonMap("anyKey", "anyValue"))
.customMetadata(java.util.Collections.singletonMap("anyKey", "anyValue"))
.versionCustomMetadata(java.util.Collections.singletonMap("anyKey", "anyValue"))
.build();
assertEquals(kvSecretPrototypeModel.secretType(), "kv");
assertEquals(kvSecretPrototypeModel.name(), "my-secret-example");
assertEquals(kvSecretPrototypeModel.description(), "Extended description for this secret.");
assertEquals(kvSecretPrototypeModel.secretGroupId(), "default");
assertEquals(kvSecretPrototypeModel.labels(), java.util.Arrays.asList("my-label"));
assertEquals(kvSecretPrototypeModel.data(), java.util.Collections.singletonMap("anyKey", "anyValue"));
assertEquals(kvSecretPrototypeModel.customMetadata(), java.util.Collections.singletonMap("anyKey", "anyValue"));
assertEquals(kvSecretPrototypeModel.versionCustomMetadata(), java.util.Collections.singletonMap("anyKey", "anyValue"));
String json = TestUtilities.serialize(kvSecretPrototypeModel);
KVSecretPrototype kvSecretPrototypeModelNew = TestUtilities.deserialize(json, KVSecretPrototype.class);
assertTrue(kvSecretPrototypeModelNew instanceof KVSecretPrototype);
assertEquals(kvSecretPrototypeModelNew.secretType(), "kv");
assertEquals(kvSecretPrototypeModelNew.name(), "my-secret-example");
assertEquals(kvSecretPrototypeModelNew.description(), "Extended description for this secret.");
assertEquals(kvSecretPrototypeModelNew.secretGroupId(), "default");
assertEquals(kvSecretPrototypeModelNew.data().toString(), java.util.Collections.singletonMap("anyKey", "anyValue").toString());
assertEquals(kvSecretPrototypeModelNew.customMetadata().toString(), java.util.Collections.singletonMap("anyKey", "anyValue").toString());
assertEquals(kvSecretPrototypeModelNew.versionCustomMetadata().toString(), java.util.Collections.singletonMap("anyKey", "anyValue").toString());
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testKVSecretPrototypeError() throws Throwable {
new KVSecretPrototype.Builder().build();
}
} |
# -*- coding: utf-8 -*-
"""
Rotation around the z-axis.
"""
from renom_q.circuit import Gate
from renom_q.circuit import QuantumCircuit
from renom_q.circuit import QuantumRegister
from renom_q.circuit.decorators import _1q_gate
from renom_q.converters.dagcircuit import DAGCircuit
from . import header # pylint: disable=unused-import
from .u1 import U1Gate
class RZGate(Gate):
"""rotation around the z-axis."""
def __init__(self, phi, qubit, circ=None):
"""Create new rz single qubit gate."""
super().__init__("rz", [phi], [qubit], circ)
def _define_decompositions(self):
"""
gate rz(phi) a { u1(phi) a; }
"""
decomposition = DAGCircuit()
q = QuantumRegister(1, "q")
decomposition.add_qreg(q)
decomposition.add_basis_element("u1", 1, 0, 1)
rule = [
U1Gate(self.params[0], q[0])
]
for inst in rule:
decomposition.apply_operation_back(inst)
self._decompositions = [decomposition]
def inverse(self):
"""Invert this gate.
rz(phi)^dagger = rz(-phi)
"""
self.params[0] = -self.params[0]
self._decompositions = None
return self
def reapply(self, circ):
"""Reapply this gate to corresponding qubits in circ."""
self._modifiers(circ.rz(self.params[0], self.qargs[0]))
@_1q_gate
def rz(self, phi, q):
"""Apply Rz to q."""
self._check_qubit(q)
return self._attach(RZGate(phi, q, self))
QuantumCircuit.rz = rz |
const ExplorerController = require("../../lib/controllers/ExplorerController");
describe("Test para ExplorerController", () => {
test("Explorers by mission", () => {
const explorersInNode = ExplorerController.getExplorersByMission("node");
expect(explorersInNode).toStrictEqual([
{
githubUsername: "ajolonauta1",
mission: "node",
name: "Woopa1",
score: 1,
stacks: ["javascript", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta2",
mission: "node",
name: "Woopa2",
score: 2,
stacks: ["javascript", "groovy", "elm"],
},
{
githubUsername: "ajolonauta3",
mission: "node",
name: "Woopa3",
score: 3,
stacks: ["elixir", "groovy", "reasonML"],
},
{
githubUsername: "ajolonauta4",
mission: "node",
name: "Woopa4",
score: 4,
stacks: ["javascript"],
},
{
githubUsername: "ajolonauta5",
mission: "node",
name: "Woopa5",
score: 5,
stacks: ["javascript", "elixir", "elm"],
},
{
githubUsername: "ajolonauta11",
mission: "node",
name: "Woopa11",
score: 11,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta12",
mission: "node",
name: "Woopa12",
score: 12,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta13",
mission: "node",
name: "Woopa13",
score: 13,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta14",
mission: "node",
name: "Woopa14",
score: 14,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta15",
mission: "node",
name: "Woopa15",
score: 15,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
]);
});
test("Amount of explorers by mission", () => {
const amountExplorers =
ExplorerController.getExplorersAmountByMission("node");
expect(amountExplorers).toBe(10);
});
test("Explorer Usernames by mission", () => {
const usernames = ExplorerController.getExplorersUsernamesByMission("node");
expect(usernames).toStrictEqual([
"ajolonauta1",
"ajolonauta2",
"ajolonauta3",
"ajolonauta4",
"ajolonauta5",
"ajolonauta11",
"ajolonauta12",
"ajolonauta13",
"ajolonauta14",
"ajolonauta15",
]);
});
test("explorers by stack", () => {
const amountExplorers =
ExplorerController.getExplorersByStack("javascript");
expect(amountExplorers).toStrictEqual([
{
githubUsername: "ajolonauta1",
mission: "node",
name: "Woopa1",
score: 1,
stacks: ["javascript", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta2",
mission: "node",
name: "Woopa2",
score: 2,
stacks: ["javascript", "groovy", "elm"],
},
{
githubUsername: "ajolonauta4",
mission: "node",
name: "Woopa4",
score: 4,
stacks: ["javascript"],
},
{
githubUsername: "ajolonauta5",
mission: "node",
name: "Woopa5",
score: 5,
stacks: ["javascript", "elixir", "elm"],
},
{
githubUsername: "ajolonauta9",
mission: "java",
name: "Woopa9",
score: 9,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta10",
mission: "java",
name: "Woopa10",
score: 10,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta11",
mission: "node",
name: "Woopa11",
score: 11,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta12",
mission: "node",
name: "Woopa12",
score: 12,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta13",
mission: "node",
name: "Woopa13",
score: 13,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
githubUsername: "ajolonauta14",
mission: "node",
name: "Woopa14",
score: 14,
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
{
name: "Woopa15",
githubUsername: "ajolonauta15",
score: 15,
mission: "node",
stacks: ["javascript", "elixir", "groovy", "reasonML", "elm"],
},
]);
});
}); |
import { browser, element, by } from 'protractor';
import { NavBarPage, SignInPage, AsideBarPage } from '../page-objects/jhi-page-objects';
const expect = chai.expect;
describe('system', () => {
let navBarPage: NavBarPage;
let signInPage: SignInPage;
let asideBarPage: AsideBarPage;
before(async () => {
navBarPage = new NavBarPage(true);
asideBarPage = new AsideBarPage();
signInPage = await navBarPage.getSignInPage();
await signInPage.autoSignInUsing('appadmin', 'password1');
});
it('should load metrics', async () => {
await asideBarPage.clickOnAdminMainMuen();
await asideBarPage.clickOnSystemMainMuen();
await asideBarPage.clickOnMetricsMuen();
const expect1 = 'metrics.title';
const value1 = await element(by.id('metrics-page-heading')).getAttribute('jhiTranslate');
expect(value1).to.eq(expect1);
});
it('should load health', async () => {
await asideBarPage.clickOnHealthMuen();
const expect1 = 'health.title';
const value1 = await element(by.id('health-page-heading')).getAttribute('jhiTranslate');
expect(value1).to.eq(expect1);
});
it('should load logs', async () => {
await asideBarPage.clickOnadminLogsMuen();
const expect1 = 'logs.title';
const value1 = await element(by.id('logs-page-heading')).getAttribute('jhiTranslate');
expect(value1).to.eq(expect1);
});
it('should load configuration', async () => {
await asideBarPage.clickOnadminConfigurationMuen();
await browser.sleep(2000);
const expect1 = 'configuration.title';
const value1 = await element(by.id('configuration-page-heading')).getAttribute('jhiTranslate');
expect(value1).to.eq(expect1);
});
it('should load Swagger UI', async () => {
await asideBarPage.clickOnadminSwaggerMuen();
await browser.sleep(2000);
const expect1 = true;
const value1 = await element(by.tagName('iframe')).isDisplayed();
expect(value1).to.eq(expect1);
});
after(async () => {
await navBarPage.autoSignOut();
});
}); |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.wrapper {
margin: 0 auto;
}
nav {
background: #333;
}
nav ul {
list-style-type: none;
padding: 0;
}
nav a {
text-decoration: none;
text-align: center;
color: white;
display: block;
padding: 10px;
}
nav a:hover {
background-color: #555;
}
/* flex styles */
@media screen and (min-width: 568px) {
nav {
display: flex;
justify-content: space-between;
}
nav ul {
display: flex;
}
nav li {
flex: 1 1 0;
}
.social {
margin: 0!important;
}
}
/* social menu base style */
a.tw {
background: url('./img/tw.png') no-repeat center;
background-size: 80%;
}
a.fb {
background: url('./img/fb.png') no-repeat center;
background-size: 80%;
}
.social a {
text-indent: -10000px;
}
.social {
max-width: 80px;
margin: 0 auto;
}
/* flex styles */
nav ul.social {
display: flex;
flex: 1 1 0;
align-items: center;
}
nav ul.social li {
flex: 1 1 0;
}
</style>
</head>
<body>
<div class="wrapper">
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Store</a></li>
<li><a href="#">Contact</a></li>
</ul>
<ul class="social">
<li><a href="#" class="fb">Facebook</a></li>
<li><a href="#" class="tw">Twitter</a></li>
</ul>
</nav>
</div>
</body>
</html> |
# Xilinx Zynq 7000 系列开发板AX7010
## 开发板介绍
### 开发板简介
此款开发板使用的是Xilinx公司的Zynq7000系列的芯片,型号为XC7Z010-1CLG400I,
400 个引脚的 FBGA 封装。ZYNQ7000 芯片可分成处理器系统部分 Processor System(PS)
和可编程逻辑部分 Programmable Logic(PL)。在 AX7010 开发板上,ZYNQ7000 的 PS
部分和 PL 部分都搭载了丰富的外部接口和设备,方便用户的使用和功能验证。另外开发板上
集成了 Xilinx USB Cable 下载器电路,用户只要用一个 USB 线就可以对开发板进行下载和调
试。
### 关键特性
1. +5V 电源输入,最大 2A 电流保护;
2. Xilinx ARM+FPGA 芯片 Zynq-7000 XC7Z010-1CLG400C
3. 两片大容量的 2Gbit(共 4Gbit)高速 DDR3 SDRAM,可作为 ZYNQ 芯片数据的缓存,也可以作为操作系统运行的内存;
4. 一片 256Mbit 的 QSPI FLASH, 可用作 ZYNQ 芯片的系统文件和用户数据的存储;
5. 一路10/100M/1000M以太网RJ-45接口, 可用于和电脑或其它网络设备进行以太网数据交换;
6. 一路 HDMI 图像视频输入输出接口, 能实现 1080P 的视频图像传输;
7. 一路高速 USB2.0 HOST 接口, 可用于开发板连接鼠标、键盘和 U 盘等 USB 外设;
8. 一路高速 USB2.0 OTG 接口, 用于和 PC 或 USB 设备的 OTG 通信;
9. 一路 USB Uart 接口, 用于和 PC 或外部设备的串口通信;
10. 一片的 RTC 实时时钟,配有电池座,电池的型号为 CR1220。
11. 一片 IIC 接口的 EEPROM 24LC04;
12. 6 个用户发光二极管 LED, 2 个 PS 控制,4 个 PL 控制;
13. 7 个按键,1 个 CPU 复位按键,2 个 PS 控制按键,4 个 PL 控制按键;
14. 板载一个 33.333Mhz 的有源晶振,给 PS 系统提供稳定的时钟源,一个 50MHz 的有源晶振,为 PL 逻辑提供额外的时钟;
15. 2 路 40 针的扩展口(2.54mm 间距),用于扩展 ZYNQ 的 PL 部分的 IO。可以接 7寸 TFT 模块、摄像头模块和 AD/DA 模块等扩展模块;
16. 一个 12 针的扩展口(2.54mm 间距),用于扩展 ZYNQ 的 PS 系统的 MIO;
17. 一路 USB JTAG 口,通过 USB 线及板载的 JTAG 电路对 ZYNQ 系统进行调试和下载。1 路 Micro SD 卡座(开发板背面),用于存储操作系统镜像和文件系统。
# AX7010 文档教程链接
https://ax7010-20231-v101.readthedocs.io/zh-cn/latest/7010_S1_RSTdocument_CN/00_%E5%85%B3%E4%BA%8EALINX_CN.html
注意:文档的末尾页脚处可以切换中英文语言
# AX7010 例程
## 例程描述
此项目为开发板出厂例程,支持板卡上的大部分外设。
## 开发环境及需求
* Vivado 2023.1
* AX7010开发板
## 创建Vivado工程
* 下载最新的ZIP包。
* 创建新的工程文件夹.
* 解压下载的ZIP包到此工程文件夹中。
有两种方法创建Vivado工程,如下所示:
### 利用Vivado tcl console创建Vivado工程
1. 打开Vivado软件并且利用**cd**命令进入"**auto_create_project**"目录,并回车
```
cd \<archive extracted location\>/vivado/auto_create_project
```
2. 输入 **source ./create_project.tcl** 并且回车
```
source ./create_project.tcl
```
### 利用bat创建Vivado工程
1. 在 "**auto_create_project**" 文件夹, 有个 "**create_project.bat**"文件, 右键以编辑模式打开,并且修改vivado路径为本主机vivado安装路径,保存并关闭。
```
CALL E:\XilinxVitis\Vivado\2023.1\bin\vivado.bat -mode batch -source create_project.tcl
PAUSE
```
2. 在Windows下双击bat文件即可。
更多信息, 请访问[ALINX网站](https://www.alinx.com) |
#ifndef BANK_H
#define BANK_H
#include "account.h"
class Bank
{
public:
inline void addAccount(std::shared_ptr<Account> const& ac) { m_bank.append(ac); }
inline void removeAccount(std::shared_ptr<Account> const& ac) { m_bank.removeOne( ac ); }
inline unsigned int accounts() const { return m_bank.size(); }
inline std::shared_ptr<Account> getAccount(unsigned int n) const { return m_bank[n]; }
inline std::shared_ptr<Account> lastAccount() const { return m_bank.last(); }
inline QVector<std::shared_ptr<Account>> allAccounts() const { return m_bank; }
inline void OrderAccounts()
{
for(std::shared_ptr<Account> it: m_bank)
it->OrderTransactions();
std::sort(m_bank.begin(),m_bank.end(),[](std::shared_ptr<Account> a,std::shared_ptr<Account> b) -> bool
{
if(!a->transactions())
return false;
if(!b->transactions())
return true;
return (a->lastTransaction().m_time<b->lastTransaction().m_time);
});
}
friend QDataStream& operator<< (QDataStream& strm,
Bank const& s){
strm<<s.m_bank;
return strm;
}
friend QDataStream& operator>> (QDataStream& strm,
Bank & s){
QVector<std::shared_ptr<Account>> tmp;
strm>>tmp;
s.m_bank = tmp;
return strm;
}
friend QDataStream& operator<< (QDataStream& strm,
std::shared_ptr<Bank> const& s){
strm<<s->m_bank;
return strm;
}
Bank() = default;
private:
QVector<std::shared_ptr<Account>> m_bank;
};
#endif // BANK_H |
# --------------------------------------
# Author: Andreas Alfons
# Erasmus Universiteit Rotterdam
# --------------------------------------
## load required packages
library("car")
library("robmed")
library("sn")
## additional functions
# find shape parameter of skew-normal distribution for given skewness
find_alpha <- function(skewness) {
# check for NA or NaN
if (any(is.na(skewness) | is.nan(skewness))) {
stop("missing skewness values not allowed")
}
# compute sign and absolute value
sign <- sign(skewness)
gamma <- abs(skewness)
# check for invalid skewness values
if (any(gamma > 1)) {
stop("skewness of skew-normal distribution is limited to (-1, 1)")
}
# initialize parameter values
alpha <- sign * Inf
# overwrite values for skewness within (-1, 1)
ok <- gamma != 1
gamma23 <- gamma[ok]^(2/3)
zeta <- gamma23 / (gamma23 + ((4-pi)/2)^(2/3))
delta2 <- zeta * pi / 2
alpha[ok] <- sign[ok] * sqrt(delta2 / (1-delta2))
# return values of shape parameter
alpha
}
# compute mean of skew-t distribution
get_mean <- function(ksi = 0, omega = 1, alpha = 0, nu = Inf) {
if (is.infinite(alpha)) delta <- sign(alpha)
else delta <- alpha / sqrt(1 + alpha^2)
if (is.infinite(nu)) b_nu <- sqrt(2 / pi)
else b_nu <- sqrt(nu) * beta((nu-1)/2, 0.5) / (sqrt(pi) * gamma(0.5))
# compute mean
ksi + omega * delta * b_nu
}
## control parameters for simulation
seed <- 20200309 # seed for the random number generator
sample_sizes <- c(100, 250) # number of observations
K <- 1000 # number of simulation runs
R <- 5000 # number of bootstrap samples
# coefficients in mediation model
effect <- 0.4
a <- rep(effect, 2)
b <- c(effect, 0)
c <- rep(effect, 2)
# error scales in mediation model
sigma_m <- sqrt(1 - a^2)
sigma_y <- sqrt(1 - b^2 - c^2 - 2*a*b*c)
## parameters of the skew-t distribution
alpha <- find_alpha(seq(-1, 1, by = 0.5))
nu <- c(Inf, 5, 2)
parameters <- expand.grid(alpha = alpha, nu = nu)
## control parameters for methods
level <- 0.95 # confidence level
lmrob_control <- reg_control(max_iterations = 5000) # MM-estimator
## run simulation
cat(paste(Sys.time(), ": starting ...\n"))
results_list <- lapply(sample_sizes, function(n) {
## use the same seed for each sample size
## (then simulations can be run separately for different sample sizes)
set.seed(seed)
## print sample size
cat(paste(Sys.time(), sprintf(": n = %d\n", n)))
## perform simulation for current sample size
results_n <- lapply(1:K, function(k) {
## print simulation run
cat(paste(Sys.time(), sprintf(": run = %d\n", k)))
## generate independent variable and error terms such that results are
## comparable across different values of the parameters
x <- rnorm(n)
# First uniformly distributed values are drawn, which are later transformed
# to the given error distribution by applying the inverse CDF.
u_m <- runif(n)
u_y <- runif(n)
## ensure that the same bootstrap samples are used for all parameter
## settings and all bootstrap tests for maximum comparability
indices <- boot_samples(n, R = R)
## loop over different error distributions
results_nk <- mapply(function(alpha, nu) {
## transform errors
if (is.infinite(nu)) {
# normal or skew-normal distribution
if (is.finite(alpha) && alpha == 0) {
# normal errors
e_m <- qnorm(u_m)
e_y <- qnorm(u_y)
} else {
# skew-normal errors
e_m <- qsn(u_m, alpha = alpha)
e_y <- qsn(u_y, alpha = alpha)
}
} else {
# t or skew-t distribution
if (is.finite(alpha) && alpha == 0) {
# t-distributed errors
e_m <- qt(u_m, df = nu)
e_y <- qt(u_y, df = nu)
} else {
# skew-t distributed errors
e_m <- qst(u_m, alpha = alpha, nu = nu)
e_y <- qst(u_y, alpha = alpha, nu = nu)
}
}
## loop over different parameter settings
results_nke <- mapply(function(a, b, c, sigma_m, sigma_y) {
# compute mean of error terms such that it can be subtracted
mu_m <- get_mean(omega = sigma_m, alpha = alpha, nu = nu)
mu_y <- get_mean(omega = sigma_y, alpha = alpha, nu = nu)
# transform error terms (scale and center)
e_m_transformed <- sigma_m * e_m - mu_m
e_y_transformed <- sigma_y * e_y - mu_y
# generate hypothesized mediator and dependent variable
m <- a * x + e_m_transformed
y <- b * m + c * x + e_y_transformed
simulated_data <- data.frame(x, y, m)
# OLS regression
df_ols <- tryCatch({
# fit mediation model
ols_fit <- fit_mediation(simulated_data, "x", "y", "m",
method = "regression", robust = FALSE,
family = "gaussian")
# perform test for indirect effect
ols_boot <- test_mediation(ols_fit, test = "boot", level = level,
indices = indices)
ols_sobel <- test_mediation(ols_fit, test = "sobel")
# extract indirect effect
ab_boot <- c(coef(ols_boot, parm = "ab", type = "boot"),
coef(ols_boot, parm = "ab", type = "data"),
use.names = FALSE)
ab_sobel <- c(NA_real_, coef(ols_sobel, parm = "ab"),
use.names = FALSE)
# check for significant indirect effect
reject_boot <- prod(ols_boot$ci) > 0
reject_sobel <- ols_sobel$p_value < 1 - level
# combine into data frame
data.frame(n = n, Run = k, alpha = alpha, nu = nu, a = a, b = b,
Method = c("ols_boot", "ols_sobel"),
ab_boot = c(ab_boot[1], ab_sobel[1]),
ab_data = c(ab_boot[2], ab_sobel[2]),
reject = c(reject_boot, reject_sobel),
stringsAsFactors = FALSE)
}, error = function(condition) NULL)
# Box-Cox transformations (with negative values allowed) followed by OLS
df_bcn <- tryCatch({
# transform variables
transformed_list <- lapply(simulated_data, function(variable) {
bcn <- powerTransform(variable, family = "bcnPower")
bcnPower(variable, lambda = bcn$lambda, gamma = bcn$gamma)
})
transformed_data <- as.data.frame(transformed_list)
# fit mediation model
bcn_fit <- fit_mediation(transformed_data, "x", "y", "m",
method = "regression", robust = FALSE,
family = "gaussian")
# perform test for indirect effect
bcn_boot <- test_mediation(bcn_fit, test = "boot", level = level,
indices = indices)
bcn_sobel <- test_mediation(bcn_fit, test = "sobel")
# extract indirect effect
ab_boot <- c(coef(bcn_boot, parm = "ab", type = "boot"),
coef(bcn_boot, parm = "ab", type = "data"),
use.names = FALSE)
ab_sobel <- c(NA_real_, coef(bcn_sobel, parm = "ab"),
use.names = FALSE)
# check for significant indirect effect
reject_boot <- prod(bcn_boot$ci) > 0
reject_sobel <- bcn_sobel$p_value < 1 - level
# combine into data frame
data.frame(n = n, Run = k, alpha = alpha, nu = nu, a = a, b = b,
Method = c("bcn_boot", "bcn_sobel"),
ab_boot = c(ab_boot[1], ab_sobel[1]),
ab_data = c(ab_boot[2], ab_sobel[2]),
reject = c(reject_boot, reject_sobel),
stringsAsFactors = FALSE)
}, error = function(condition) NULL)
# Huberized covariance matrix
df_huber <- tryCatch({
# fit mediation model
huber_fit <- fit_mediation(simulated_data, "x", "y", "m",
method = "covariance", robust = TRUE)
# perform test for indirect effect
huber_boot <- test_mediation(huber_fit, test = "boot", level = level,
indices = indices)
huber_sobel <- test_mediation(huber_fit, test = "sobel")
# extract indirect effect
ab_boot <- c(coef(huber_boot, parm = "ab", type = "boot"),
coef(huber_boot, parm = "ab", type = "data"),
use.names = FALSE)
ab_sobel <- c(NA_real_, coef(huber_sobel, parm = "ab"),
use.names = FALSE)
# check for significant indirect effect
reject_boot <- prod(huber_boot$ci) > 0
reject_sobel <- huber_sobel$p_value < 1 - level
# combine into data frame
data.frame(n = n, Run = k, alpha = alpha, nu = nu, a = a, b = b,
Method = c("huber_boot", "huber_sobel"),
ab_boot = c(ab_boot[1], ab_sobel[1]),
ab_data = c(ab_boot[2], ab_sobel[2]),
reject = c(reject_boot, reject_sobel),
stringsAsFactors = FALSE)
}, error = function(condition) NULL)
# median regression
df_median <- tryCatch({
# fit mediation model
median_fit <- fit_mediation(simulated_data, "x", "y", "m",
method = "regression", robust = "median")
# perform test for indirect effect
median_boot <- test_mediation(median_fit, test = "boot", level = level,
indices = indices)
median_sobel <- test_mediation(median_fit, test = "sobel")
# extract indirect effect
ab_boot <- c(coef(median_boot, parm = "ab", type = "boot"),
coef(median_boot, parm = "ab", type = "data"),
use.names = FALSE)
ab_sobel <- c(NA_real_, coef(median_sobel, parm = "ab"),
use.names = FALSE)
# check for significant indirect effect
reject_boot <- prod(median_boot$ci) > 0
reject_sobel <- median_sobel$p_value < 1 - level
# combine into data frame
data.frame(n = n, Run = k, alpha = alpha, nu = nu, a = a, b = b,
Method = c("median_boot", "median_sobel"),
ab_boot = c(ab_boot[1], ab_sobel[1]),
ab_data = c(ab_boot[2], ab_sobel[2]),
reject = c(reject_boot, reject_sobel),
stringsAsFactors = FALSE)
}, error = function(condition) NULL)
# regression with selection of error distribution
df_select <- NULL
# df_select <- tryCatch({
# # fit mediation model
# select_fit <- fit_mediation(simulated_data, "x", "y", "m",
# method = "regression", robust = FALSE,
# family = "select", total_model = FALSE)
# # perform test for indirect effect
# select_boot <- test_mediation(select_fit, test = "boot", level = level,
# indices = indices)
# select_sobel <- test_mediation(select_fit, test = "sobel")
# # extract indirect effect
# ab_boot <- c(coef(select_boot, parm = "ab", type = "boot"),
# coef(select_boot, parm = "ab", type = "data"),
# use.names = FALSE)
# ab_sobel <- c(NA_real_, coef(select_sobel, parm = "ab"),
# use.names = FALSE)
# # check for significant indirect effect
# reject_boot <- prod(select_boot$ci) > 0
# reject_sobel <- select_sobel$p_value < 1 - level
# # combine into data frame
# data.frame(n = n, Run = k, alpha = alpha, nu = nu, a = a, b = b,
# Method = c("select_boot", "select_sobel"),
# ab_boot = c(ab_boot[1], ab_sobel[1]),
# ab_data = c(ab_boot[2], ab_sobel[2]),
# reject = c(reject_boot, reject_sobel),
# stringsAsFactors = FALSE)
# }, error = function(condition) NULL)
# robust regression
df_robust <- tryCatch({
# fit mediation model
robust_fit <- fit_mediation(simulated_data, "x", "y", "m",
method = "regression", robust = "MM",
control = lmrob_control)
# perform test for indirect effect
robust_boot <- test_mediation(robust_fit, test = "boot", level = level,
indices = indices)
robust_sobel <- test_mediation(robust_fit, test = "sobel")
# extract indirect effect
ab_boot <- c(coef(robust_boot, parm = "ab", type = "boot"),
coef(robust_boot, parm = "ab", type = "data"),
use.names = FALSE)
ab_sobel <- c(NA_real_, coef(robust_sobel, parm = "ab"),
use.names = FALSE)
# check for significant indirect effect
reject_boot <- prod(robust_boot$ci) > 0
reject_sobel <- robust_sobel$p_value < 1 - level
# combine into data frame
data.frame(n = n, Run = k, alpha = alpha, nu = nu, a = a, b = b,
Method = c("robust_boot", "robust_sobel"),
ab_boot = c(ab_boot[1], ab_sobel[1]),
ab_data = c(ab_boot[2], ab_sobel[2]),
reject = c(reject_boot, reject_sobel),
stringsAsFactors = FALSE)
}, error = function(condition) NULL)
## results for current parameter settings
rbind(df_ols, df_bcn, df_huber, df_median, df_select, df_robust)
}, a = a, b = b, c = c, sigma_m = sigma_m, sigma_y = sigma_y,
SIMPLIFY = FALSE)
## combine results for current error distribution into data frame
do.call(rbind, results_nke)
}, alpha = parameters$alpha, nu = parameters$nu, SIMPLIFY = FALSE)
## combine results for current simulation run into data frame
do.call(rbind, results_nk)
})
## combine results for current sample size into data frame
do.call(rbind, results_n)
})
## combine results into data frame
results <- do.call(rbind, results_list)
cat(paste(Sys.time(), ": finished.\n"))
## store results
file <- "simulations/results/results_skewt.RData"
save(results, sample_sizes, a, b, c, level, file = file) |
// ignore_for_file: prefer_const_literals_to_create_immutables, use_key_in_widget_constructors
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:midsatech_mobile/pages/main/work/near_miss_form/page/near_miss_form.dart';
import 'package:midsatech_mobile/pages/main/work/near_miss_form/page/near_missing.dart';
class NearMissPage extends StatefulWidget {
const NearMissPage({super.key});
@override
State<NearMissPage> createState() => _NearMissPageState();
}
class _NearMissPageState extends State<NearMissPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color(0xFF021734),
foregroundColor: Colors.white,
title: Text(
'near_miss_actions'.tr,
style: TextStyle(
color: Colors.white,
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => NearMissFormPage()),
);
},
child: const Icon(
Icons.add,
color: Colors.white,
),
backgroundColor: Colors.deepOrange,
),
body: StreamBuilder(
stream: FirebaseFirestore.instance
.collection('near_miss_forms')
.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(
child: CircularProgressIndicator(),
);
} else if (snapshot.hasError) {
return Center(
child: Text('Error: ${snapshot.error}'),
);
} else {
final forms = snapshot.data!.docs;
return ListView.builder(
itemCount: forms.length,
itemBuilder: (context, index) {
final form = forms[index];
final formData = form.data() as Map<String, dynamic>;
final date = (formData['date'] as Timestamp).toDate();
return Card(
child: ListTile(
title: Text(
'${formData['business_name']} - ${DateFormat('yyyy-MM-dd').format(date)}',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
subtitle: Text(
'${formData['adi']} - ${formData['location']}',
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
NearMissDetailPage(formData: formData),
),
);
},
),
);
},
);
}
},
),
);
}
} |
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head th:fragment="head(title)">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.9.1/font/bootstrap-icons.css">
<link rel="stylesheet" th:href="@{/css/style.css}">
<meta charset="UTF-8">
<title th:text="${title}"></title>
</head>
<body>
<nav th:fragment="navigation"
class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand"
th:href="@{/public/posts}"
th:text="${@blog.name}"></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo02"
aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarTogglerDemo02">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li sec:authorize="isAuthenticated()" class="nav-item">
<a class="nav-link"
th:classappend="${#httpServletRequest.requestURI eq '/posts/save' ? 'active' : ''}"
th:href="@{/posts/save}"
th:text="#{lt.codeacademy.blog.menu.post}"></a>
</li>
<li th:replace="this :: languageSelector"></li>
</ul>
</div>
<div>
<a sec:authorize="isAnonymous()"
th:href="@{/login}"
class="text-decoration-none text-light">
<i class="bi bi-person-x-fill fs-3"></i>
</a>
<div sec:authorize="isAuthenticated()"
class="dropdown">
<a class="text-decoration-none text-light"
href="#"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false">
<i class="bi bi-person-circle fs-3"></i>
</a>
<ul class="dropdown-menu dropdown-menu-dark">
<li>
<div class="user-name" sec:authentication="principal.fullName"></div>
</li>
<li><a class="dropdown-item"
th:href="@{/logout}"
th:text="#{lt.codeacademy.blog.menu.logout}"></a>
</li>
</ul>
</div>
</div>
</div>
</nav>
<nav th:fragment="paginator"
aria-label="Page navigation example">
<ul class="pagination justify-content-center"
th:with="pageSort=${postsByPage.sort.toList().get(0)},
sort=${pageSort.property + ',' + pageSort.direction + ',ignorecase'}">
<li class="page-item"
th:classappend="${postsByPage.number eq 0 ? 'disabled' : ''}">
<a class="page-link"
th:href="@{/public/posts(page=${postsByPage.number} - 1, sort=${sort})}"
th:text="#{lt.codeacademy.blog.posts.paginator.previous}">Previous</a>
</li>
<li class="page-item"
th:each="productPage: ${#numbers.sequence(0, postsByPage.totalPages - 1)}"
th:classappend="${productPage eq postsByPage.number ? 'active' : ''}">
<a class="page-link"
th:href="@{/public/posts(page=${productPage}, sort=${sort})}"
th:text="${productPage} + 1"></a>
</li>
<li class="page-item"
th:classappend="${postsByPage.number eq postsByPage.totalPages - 1 ? 'disabled' : ''}">
<a class="page-link"
th:href="@{/public/posts(page=${postsByPage.number} + 1, sort=${sort})}"
th:text="#{lt.codeacademy.blog.posts.paginator.next}"></a>
</li>
</ul>
</nav>
<div th:fragment="notification(shouldShow, class, text)"
th:if="${shouldShow}"
class="alert"
th:classappend="${class}"
role="alert"
th:text="${text}">
</div>
<li th:fragment="languageSelector"
class="nav-item dropdown">
<a class="nav-link dropdown-toggle"
href="#" role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
th:text="#{lt.codeacademy.blog.language.switcher.select}">
</a>
<ul class="dropdown-menu dropdown-menu-dark">
<li><a class="dropdown-item"
th:href="${#httpServletRequest.requestURI + '?lang=EN'}"
th:text="#{lt.codeacademy.blog.language.switcher.en}"></a>
</li>
<li><a class="dropdown-item"
th:href="${#httpServletRequest.requestURI + '?lang=LT'}"
th:text="#{lt.codeacademy.blog.language.switcher.lt}"></a>
</li>
</ul>
</li>
<div th:fragment="inputWithErrorHandler(id, fieldName, isValueValid, text, type,showGlobalErrors)"
class="form-floating mb-3">
<input th:type="${type}"
class="form-control"
th:id="${id}"
th:field="*{__${fieldName}__}"
th:placeholder="${text}"
th:classappend="${#fields.hasErrors(fieldName) || showGlobalErrors && #fields.hasErrors('global')} ? 'is-invalid' : (${isValueValid} ? 'is-valid' : '')">
<label th:for="${id}"
th:text="${text}"></label>
<div class="invalid-feedback">
<div th:if="${#fields.hasErrors(fieldName)}"
th:errors="*{__${fieldName}__}">
</div>
<div th:if="${showGlobalErrors && #fields.hasErrors('global')}"
th:errors="*{global}">
</div>
</div>
</div>
</body>
<footer th:fragment="footer"
class="bg-dark footer py-4">
<div class="container">
<div class="text-light text-center">
<div th:text="${@blog.address}"></div>
<div th:text="${@blog.phone}"></div>
<div th:text="${@blog.email}"></div>
<div>
<span th:text="${@blog.copyRight}"></span>
<span th:if="${myDate}"
th:text="${myDate}"></span>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0-beta1/dist/js/bootstrap.bundle.min.js"
integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2"
crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</footer>
</html> |
using System.Collections;
using UnityEngine;
using Firebase;
using Firebase.Auth;
using Firebase.Database;
using System.Linq;
public class FireBaseManager : MonoBehaviour
{
private GameManager _gameManager;
//Firebase variables
[Header("Firebase")]
public DependencyStatus dependencyStatus;
public FirebaseAuth auth;
public FirebaseUser User;
public DatabaseReference DBreference;
public void Init(GameManager gameManager)
{
_gameManager = gameManager;
//Check that all of the necessary dependencies for Firebase are present on the system
FirebaseApp.CheckAndFixDependenciesAsync().ContinueWith(task =>
{
dependencyStatus = task.Result;
if (dependencyStatus == DependencyStatus.Available)
{
//If they are avalible Initialize Firebase
InitializeFirebase();
}
else
{
Debug.LogError("Could not resolve all Firebase dependencies: " + dependencyStatus);
}
});
}
private void InitializeFirebase()
{
Debug.Log("Setting up Firebase Auth");
//Set the authentication instance object
auth = FirebaseAuth.DefaultInstance;
DBreference = FirebaseDatabase.DefaultInstance.RootReference;
}
public void SignOutButton()
{
auth.SignOut();
_gameManager._uIManager._uILogin.ShowUI();
_gameManager._uIManager._uILogin.ClearLoginFeilds();
_gameManager._uIManager._uIRegister.ClearRegisterFeilds();
}
public void SaveDataButton()
{
StartCoroutine(UpdateUsernameAuth(_gameManager._uIManager._uiUserData._inputUserName.text));
StartCoroutine(UpdateUsernameDatabase(_gameManager._uIManager._uiUserData._inputUserName.text));
StartCoroutine(UpdateXp(int.Parse(_gameManager._uIManager._uiUserData._inputExp.text)));
StartCoroutine(UpdateKills(int.Parse(_gameManager._uIManager._uiUserData._inputKills.text)));
StartCoroutine(UpdateDeaths(int.Parse(_gameManager._uIManager._uiUserData._inputDeaths.text)));
}
//Function for the scoreboard button
public void ScoreboardButton()
{
StartCoroutine(LoadScoreboardData());
}
//Function for the login button
public void LoginButton(string _email, string _pass)
{
//Call the login coroutine passing the email and password
StartCoroutine(Login(_email, _pass));
}
//Function for the register button
public void RegisterButton(string _email, string _pass,string _repass, string _userName)
{
//Call the register coroutine passing the email, password, and username
StartCoroutine(Register(_email, _pass,_repass, _userName));
}
private IEnumerator Login(string _email, string _password)
{
//Call the Firebase auth signin function passing the email and password
var LoginTask = auth.SignInWithEmailAndPasswordAsync(_email, _password);
//Wait until the task completes
yield return new WaitUntil(predicate: () => LoginTask.IsCompleted);
if (LoginTask.Exception != null)
{
//If there are errors handle them
Debug.LogWarning(message: $"Failed to register task with {LoginTask.Exception}");
FirebaseException firebaseEx = LoginTask.Exception.GetBaseException() as FirebaseException;
AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
string message = "Login Failed!";
switch (errorCode)
{
case AuthError.MissingEmail:
message = "Missing Email";
break;
case AuthError.MissingPassword:
message = "Missing Password";
break;
case AuthError.WrongPassword:
message = "Wrong Password";
break;
case AuthError.InvalidEmail:
message = "Invalid Email";
break;
case AuthError.UserNotFound:
message = "Account does not exist";
break;
}
_gameManager._uIManager._uILogin.Notice(message, true);
}
else
{
//User is now logged in
//Now get the result
User = LoginTask.Result.User;
Debug.LogFormat("User signed in successfully: {0} ({1})", User.DisplayName, User.Email);
_gameManager._uIManager._uILogin.Notice("Logged In", false);
StartCoroutine(LoadUserData());
yield return new WaitForSeconds(2);
_gameManager._uIManager._uiUserData._inputUserName.text = User.DisplayName;
_gameManager._uIManager._uiUserData.ShowUI();
_gameManager._uIManager._uILogin.Notice("", false);
_gameManager._uIManager._uILogin.ClearLoginFeilds();
_gameManager._uIManager._uIRegister.ClearRegisterFeilds();
}
}
private IEnumerator Register(string _email, string _password,string _rePassword ,string _username)
{
if (_username == "")
{
//If the username field is blank show a warning
_gameManager._uIManager._uILogin.Notice("Missing Username", true);
}
else if (_password != _rePassword)
{
//If the password does not match show a warning
_gameManager._uIManager._uILogin.Notice("Password Does Not Match!", true);
}
else
{
//Call the Firebase auth signin function passing the email and password
var RegisterTask = auth.CreateUserWithEmailAndPasswordAsync(_email, _password);
//Wait until the task completes
yield return new WaitUntil(predicate: () => RegisterTask.IsCompleted);
if (RegisterTask.Exception != null)
{
//If there are errors handle them
Debug.LogWarning(message: $"Failed to register task with {RegisterTask.Exception}");
FirebaseException firebaseEx = RegisterTask.Exception.GetBaseException() as FirebaseException;
AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
string message = "Register Failed!";
switch (errorCode)
{
case AuthError.MissingEmail:
message = "Missing Email";
break;
case AuthError.MissingPassword:
message = "Missing Password";
break;
case AuthError.WeakPassword:
message = "Weak Password";
break;
case AuthError.EmailAlreadyInUse:
message = "Email Already In Use";
break;
}
_gameManager._uIManager._uILogin.Notice(message, true);
}
else
{
//User has now been created
//Now get the result
User = RegisterTask.Result.User;
if (User != null)
{
//Create a user profile and set the username
UserProfile profile = new UserProfile { DisplayName = _username };
//Call the Firebase auth update user profile function passing the profile with the username
var ProfileTask = User.UpdateUserProfileAsync(profile);
//Wait until the task completes
yield return new WaitUntil(predicate: () => ProfileTask.IsCompleted);
if (ProfileTask.Exception != null)
{
//If there are errors handle them
Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
//FirebaseException firebaseEx = ProfileTask.Exception.GetBaseException() as FirebaseException;
//AuthError errorCode = (AuthError)firebaseEx.ErrorCode;
_gameManager._uIManager._uILogin.Notice("Username Set Failed!", true);
}
else
{
//Username is now set
//Now return to login screen
_gameManager._uIManager._uIRegister.HideUI();
_gameManager._uIManager._uILogin.ShowUI();
_gameManager._uIManager._uILogin.ClearLoginFeilds();
_gameManager._uIManager._uIRegister.ClearRegisterFeilds();
}
}
}
}
}
private IEnumerator UpdateUsernameAuth(string _username)
{
//Create a user profile and set the username
UserProfile profile = new UserProfile { DisplayName = _username };
//Call the Firebase auth update user profile function passing the profile with the username
var ProfileTask = User.UpdateUserProfileAsync(profile);
//Wait until the task completes
yield return new WaitUntil(predicate: () => ProfileTask.IsCompleted);
if (ProfileTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register task with {ProfileTask.Exception}");
}
else
{
//Auth username is now updated
}
}
private IEnumerator UpdateUsernameDatabase(string _username)
{
//Set the currently logged in user username in the database
var DBTask = DBreference.Child("users").Child(User.UserId).Child("username").SetValueAsync(_username);
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
}
else
{
//Database username is now updated
}
}
private IEnumerator UpdateXp(int _xp)
{
//Set the currently logged in user xp
var DBTask = DBreference.Child("users").Child(User.UserId).Child("xp").SetValueAsync(_xp);
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
}
else
{
//Xp is now updated
}
}
private IEnumerator UpdateKills(int _kills)
{
//Set the currently logged in user kills
var DBTask = DBreference.Child("users").Child(User.UserId).Child("kills").SetValueAsync(_kills);
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
}
else
{
//Kills are now updated
}
}
private IEnumerator UpdateDeaths(int _deaths)
{
//Set the currently logged in user deaths
var DBTask = DBreference.Child("users").Child(User.UserId).Child("deaths").SetValueAsync(_deaths);
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
}
else
{
//Deaths are now updated
}
}
private IEnumerator LoadUserData()
{
//Get the currently logged in user data
var DBTask = DBreference.Child("users").Child(User.UserId).GetValueAsync();
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
}
else if (DBTask.Result.Value == null)
{
//No data exists yet
_gameManager._uIManager._uiUserData._inputExp.text = "0";
_gameManager._uIManager._uiUserData._inputKills.text = "0";
_gameManager._uIManager._uiUserData._inputDeaths.text = "0";
}
else
{
//Data has been retrieved
DataSnapshot snapshot = DBTask.Result;
_gameManager._uIManager._uiUserData._inputExp.text = snapshot.Child("xp").Value.ToString();
_gameManager._uIManager._uiUserData._inputKills.text = snapshot.Child("kills").Value.ToString();
_gameManager._uIManager._uiUserData._inputDeaths.text = snapshot.Child("deaths").Value.ToString();
}
}
private IEnumerator LoadScoreboardData()
{
//Get all the users data ordered by kills amount
var DBTask = DBreference.Child("users").OrderByChild("kills").GetValueAsync();
yield return new WaitUntil(predicate: () => DBTask.IsCompleted);
if (DBTask.Exception != null)
{
Debug.LogWarning(message: $"Failed to register task with {DBTask.Exception}");
}
else
{
//Data has been retrieved
DataSnapshot snapshot = DBTask.Result;
//Destroy any existing scoreboard elements
foreach (Transform child in _gameManager._uIManager._uIScore.scoreboardContent.transform)
{
Destroy(child.gameObject);
}
//Loop through every users UID
foreach (DataSnapshot childSnapshot in snapshot.Children.Reverse<DataSnapshot>())
{
string username = childSnapshot.Child("username").Value.ToString();
int kills = int.Parse(childSnapshot.Child("kills").Value.ToString());
int deaths = int.Parse(childSnapshot.Child("deaths").Value.ToString());
int xp = int.Parse(childSnapshot.Child("xp").Value.ToString());
//Instantiate new scoreboard elements
GameObject scoreboardElement = Instantiate(_gameManager._uIManager._uIScore.scoreElement, _gameManager._uIManager._uIScore.scoreboardContent);
scoreboardElement.GetComponent<ScoreBoard>().SetData(username, kills, deaths, xp);
}
//Go to scoareboard screen
_gameManager._uIManager._uIScore.ShowUI();
}
}
} |
import { InvoiceId } from '../store/invoices/models';
import { Lot } from '../store/lots/models';
import { firebase } from '../services/firebase';
import { firebaseFetchTickets } from '../services/firebase/firebaseFetchTickets';
import { firebaseWriteBatch } from '../services/firebase/firebaseWriteBatch';
import { FirebaseFunctionResponse } from '../services/firebase/models';
import { TicketId, Ticket } from '../store/tickets/models';
import { UserId } from '../store/userProfile/models';
import { arrayFromNumber } from '../utils/arrayFromNumber';
import { getTimeAsISOString } from '../utils/getTimeAsISOString';
import { blockCypherGetBlockByHeight } from '../services/blockCypher/blockCypherGetBlockByHeight';
import { firebaseUpdateLot } from '../services/firebase/firebaseUpdateLot';
export const getNotEnoughTicketsAvailableResponseMessage = ({
ticketCount,
totalAvailableTickets,
}: {
ticketCount: number;
totalAvailableTickets: number;
}) =>
totalAvailableTickets === 0
? 'There are no more tickets available for this lot. Please try again tomorrow.'
: `There are only ${totalAvailableTickets} and you are attempting to reserve ${ticketCount} tickets. please try again with ${totalAvailableTickets} tickets.`;
export const getReachedUserTicketLimitResponseMessage = ({
existingUserTicketCount,
perUserTicketLimit,
}: {
existingUserTicketCount: number;
perUserTicketLimit: number;
}) => {
const remainingUserTicketLimit = perUserTicketLimit - existingUserTicketCount;
return remainingUserTicketLimit
? `By reserving these tickets you'll reach the user ticket limit of ${perUserTicketLimit}. please try again using your remaininig ticket limit of ${remainingUserTicketLimit}.`
: "You've reached the maximum number of tickets that you can purchase today.";
};
export const createTickets = async ({
lot,
uid,
ticketCount,
ticketPriceBTC,
invoiceId,
dependencies = {
firebaseFetchTickets,
blockCypherGetBlockByHeight,
firebaseUpdateLot,
firebaseWriteBatch,
},
}: {
lot: Lot;
uid: UserId;
ticketCount: number;
ticketPriceBTC: number;
invoiceId: InvoiceId;
dependencies?: {
firebaseFetchTickets: typeof firebaseFetchTickets;
blockCypherGetBlockByHeight: typeof blockCypherGetBlockByHeight;
firebaseUpdateLot: typeof firebaseUpdateLot;
firebaseWriteBatch: typeof firebaseWriteBatch;
};
}): Promise<FirebaseFunctionResponse<TicketId[]>> => {
// validate against totalAvailableTickets
if (ticketCount > lot.totalAvailableTickets) {
const message = getNotEnoughTicketsAvailableResponseMessage({
ticketCount,
totalAvailableTickets: lot.totalAvailableTickets,
});
console.log(`createTickets: ${message}`);
return {
error: true,
message,
};
}
// validate against perUserTicketLimit
const lotId = lot.id;
const existingUserTicketCount = (
await dependencies.firebaseFetchTickets({ lotId, uid })
).length;
const remainingUserTicketLimit =
lot.perUserTicketLimit - existingUserTicketCount;
if (ticketCount > remainingUserTicketLimit) {
const message = getReachedUserTicketLimitResponseMessage({
existingUserTicketCount,
perUserTicketLimit: lot.perUserTicketLimit,
});
console.log(`createTickets: ${message}`);
return {
error: true,
message,
};
}
// get the n -1 block hash as the ticket id for each ticket
let latestTicketIdBlockHeight = lot.latestTicketIdBlockHeight;
const tickets: Ticket[] = [];
// we iterate in an ordered loop to make sure that the latestTicketIdBlockHeight is updated correctly
for await (const _ of arrayFromNumber(ticketCount)) {
// get the previous block hash using the latestTicketIdBlockHeight
const previousBlockHeight = latestTicketIdBlockHeight - 1;
const previousBlockHash = (
await dependencies.blockCypherGetBlockByHeight(previousBlockHeight)
).hash;
const ticket: Ticket = {
id: previousBlockHash,
lotId,
uid,
priceBTC: ticketPriceBTC,
dateCreated: getTimeAsISOString(),
invoiceId,
};
tickets.push(ticket);
latestTicketIdBlockHeight = previousBlockHeight;
}
const ticketDocs = tickets.map((ticket) => ({
ref: firebase
.firestore()
.collection('lots')
.doc(lotId)
.collection('tickets')
.doc(ticket.id),
data: ticket,
}));
await dependencies.firebaseWriteBatch(ticketDocs);
// save the latestTicketIdBlockHeight to the lot
await dependencies.firebaseUpdateLot(lotId, { latestTicketIdBlockHeight });
return {
error: false,
message: 'great success!',
data: tickets.map((ticket) => ticket.id),
};
}; |
/*
* Copyright 2015 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef RTC_BASE_NETWORK_MONITOR_H_
#define RTC_BASE_NETWORK_MONITOR_H_
#include "rtc_base/network_constants.h"
#include "rtc_base/third_party/sigslot/sigslot.h"
#include "rtc_base/thread.h"
namespace rtc {
class IPAddress;
enum class NetworkBindingResult {
SUCCESS = 0, // No error
FAILURE = -1, // Generic error
NOT_IMPLEMENTED = -2,
ADDRESS_NOT_FOUND = -3,
NETWORK_CHANGED = -4
};
class NetworkBinderInterface {
public:
// Binds a socket to the network that is attached to |address| so that all
// packets on the socket |socket_fd| will be sent via that network.
// This is needed because some operating systems (like Android) require a
// special bind call to put packets on a non-default network interface.
virtual NetworkBindingResult BindSocketToNetwork(
int socket_fd,
const IPAddress& address) = 0;
virtual ~NetworkBinderInterface() {}
};
/*
* Receives network-change events via |OnNetworksChanged| and signals the
* networks changed event.
*
* Threading consideration:
* It is expected that all upstream operations (from native to Java) are
* performed from the worker thread. This includes creating, starting and
* stopping the monitor. This avoids the potential race condition when creating
* the singleton Java NetworkMonitor class. Downstream operations can be from
* any thread, but this class will forward all the downstream operations onto
* the worker thread.
*
* Memory consideration:
* NetworkMonitor is owned by the caller (NetworkManager). The global network
* monitor factory is owned by the factory itself but needs to be released from
* the factory creator.
*/
// Generic network monitor interface. It starts and stops monitoring network
// changes, and fires the SignalNetworksChanged event when networks change.
class NetworkMonitorInterface {
public:
NetworkMonitorInterface();
virtual ~NetworkMonitorInterface();
sigslot::signal0<> SignalNetworksChanged;
virtual void Start() = 0;
virtual void Stop() = 0;
// Implementations should call this method on the base when networks change,
// and the base will fire SignalNetworksChanged on the right thread.
virtual void OnNetworksChanged() = 0;
virtual AdapterType GetAdapterType(const std::string& interface_name) = 0;
virtual AdapterType GetVpnUnderlyingAdapterType(
const std::string& interface_name) = 0;
};
class NetworkMonitorBase : public NetworkMonitorInterface,
public MessageHandler,
public sigslot::has_slots<> {
public:
NetworkMonitorBase();
~NetworkMonitorBase() override;
void OnNetworksChanged() override;
void OnMessage(Message* msg) override;
AdapterType GetVpnUnderlyingAdapterType(
const std::string& interface_name) override;
protected:
Thread* worker_thread() { return worker_thread_; }
private:
Thread* worker_thread_;
};
/*
* NetworkMonitorFactory creates NetworkMonitors.
*/
class NetworkMonitorFactory {
public:
// This is not thread-safe; it should be called once (or once per audio/video
// call) during the call initialization.
static void SetFactory(NetworkMonitorFactory* factory);
static void ReleaseFactory(NetworkMonitorFactory* factory);
static NetworkMonitorFactory* GetFactory();
virtual NetworkMonitorInterface* CreateNetworkMonitor() = 0;
virtual ~NetworkMonitorFactory();
protected:
NetworkMonitorFactory();
};
} // namespace rtc
#endif // RTC_BASE_NETWORK_MONITOR_H_ |
<!--
This file is part of Choir, a colaborative repository for choir lyrics.
Copyright (C) 2023 – Florent Descroix <florentdescroix@posteo.net>
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/>
-->
<template>
<Editor is="editor" class="editor" ref="editor" @click="click" :init="init" v-model="value" />
</template>
<script>
import Editor from '@tinymce/tinymce-vue'
import { genInit } from '@/helpers/TinyMce'
export default {
name: 'LyricsEditor',
components: { Editor },
emits: ["update:modelValue"],
props: {
modelValue: {
type: [Array, String],
default: () => [],
}
},
data() {
return {
value: typeof this.modelValue == 'string' ? this.modelValue : this.toHTML({
div: 'editor',
content: this.modelValue
}).innerHTML,
buttons: {},
init: genInit('#song .body', this.setup)
}
},
computed: {
voices() {
return this.$parent.song.voices
}
},
watch: {
value() {
const div = document.createElement('div')
div.innerHTML = this.value
this.$emit('update:modelValue', this.toJson(div).content)
},
voices: {
deep: true,
handler() {
this.updateVoicesButton()
}
}
},
methods: {
setup(editor, voicesApi) {
this.editor = editor
this.buttons = voicesApi
this.updateVoicesButton()
},
updateVoicesButton() {
for (const name in this.voices) {
this.buttons?.[name]?.setEnabled(this.voices[name]?.note)
}
},
click(e, editor) {
// Two events are triggered : native's and editor's
if (editor) {
const box = e.target.getBoundingClientRect()
if (e.clientX < box.left && e.target?.tagName == 'SECTION') {
editor.formatter.toggle("section", { value: 'chorus' })
} else if (e.clientX < box.left && e.target?.tagName == 'REPEAT') {
editor.formatter.remove("repeat", { value: e.target.className }, e.target)
}
}
},
toJson(node) {
if (node.nodeType == 3) {
return node.textContent
} else {
return {
[node.tagName.toLowerCase()]: node.className,
content: [...node.childNodes].map(this.toJson).filter(part => part.br != undefined || part?.length || part?.content?.length)
}
}
},
toHTML(obj) {
if (typeof obj == 'string') {
return document.createTextNode(obj)
} else {
const tag = Object.keys(obj).find(key => key !== 'content')
const el = document.createElement(tag)
el.className = obj[tag]
const children = obj.content.map(this.toHTML)
el.append(...children)
return el
}
}
}
}
</script>
<style lang="scss">
.tox-pop {
max-width: 500px !important;
}
.editor {
outline: none;
width: max-content;
max-width: 100%;
min-width: 184px;
padding: 4px 8px;
&::before {
cursor: text;
margin-left: 10px;
color: #757575;
}
&:focus-within {
>* {
outline-style: auto;
outline-color: rgb(0, 95, 204);
outline-offset: .25em;
}
section {
position: relative;
&::before {
content: "";
position: absolute;
left: -20px;
top: calc(50% - 6px);
color: grey;
font-size: 14px;
line-height: 14px;
}
&.verse::before {
content: "▶";
cursor: e-resize;
}
&.chorus::before {
content: "◀";
cursor: w-resize;
left: -24px;
}
}
}
repeat {
pointer-events: none;
&::after {
pointer-events: all;
cursor: url('@/assets/icons/cancel.svg') 12 12, auto;
}
}
}
.toggler {
cursor: row-resize;
position: absolute;
left: 0;
width: 100%;
height: .4em;
display: flex;
align-items: center;
z-index: 999;
&::before {
content: "";
display: block;
height: 1px;
width: 50%;
background: rgba(0, 0, 0, 0.25);
}
&.merge {
cursor: ns-resize;
height: 1em;
}
}
trix-editor:not(.hasSelection)+div .floating-toolbar {
display: none;
}
.floating-toolbar {
position: absolute;
margin-top: -5px;
width: max-content;
transform: translate(-50%, -100%);
border-radius: 25px;
box-shadow: 2px 2px 10px -5px black;
z-index: 2;
button {
width: 25px;
height: 25px;
border-width: 1px;
margin: 0;
background: white;
font-weight: inherit;
x2,
x3 {
&::after {
display: none;
}
}
&:first-child {
border-top-left-radius: 25px;
border-bottom-left-radius: 25px;
}
&:last-child {
border-top-right-radius: 25px;
border-bottom-right-radius: 25px;
}
&.trix-active {
background: #CCC;
}
}
}
</style> |
using App.Metrics;
using App.Metrics.Counter;
using Core.Contracts.Controllers.Suppliers;
using Core.Entities;
using Core.Mediator.Commands.Suppliers;
using Infrastructure.Mediator.Handlers.Suppliers;
using Infrastructure.Services.Interfaces;
using Moq;
namespace Infrastructure.Tests.Mediator.Handlers.Suppliers
{
public sealed class CreateSupplierHandlerTests
{
private readonly Mock<ISupplierService> _service;
private readonly Mock<IMetrics> _metrics;
private readonly CreateSupplierHandler _handler;
public CreateSupplierHandlerTests()
{
_service = new();
_metrics = new();
_handler = new(_service.Object, _metrics.Object);
}
[Fact]
public void Handle_WhenCalled_ReturnSupplier()
{
//Arrange
CreateSupplierRequest createSupplier = new("First", "City");
Supplier supplier = new()
{
Name = "First",
City = "City",
};
_service.Setup(s => s.CreateSupplier(It.IsAny<CreateSupplierRequest>()))
.ReturnsAsync(supplier);
var counterMock = new Mock<IMeasureCounterMetrics>();
_metrics.Setup(m => m.Measure.Counter).Returns(counterMock.Object);
//Act
var result = _handler.Handle(new CreateSupplierCommand(createSupplier), CancellationToken.None).Result;
//Assert
result.Should().BeOfType<Supplier>();
result.Should().BeEquivalentTo(supplier);
}
}
} |
import { HttpClient, HttpEvent, HttpHeaders, HttpParams, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import {catchError, map} from 'rxjs/operators';
import { ConfigurationService } from './configuration.service';
@Injectable({
providedIn: 'root'
})
export class ApiService {
baseUrl: string;
constructor(
private http: HttpClient,
configService: ConfigurationService
) {
const settings = configService.getAppSettings();
Object.assign(this, { baseUrl: settings.apiGateway })
}
get headers(): HttpHeaders {
const headersConfig = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
return new HttpHeaders(headersConfig);
}
get<T>(path?: string, params: HttpParams = new HttpParams()): Observable<T> {
return this.http.get<T>(`${this.baseUrl}${path}`, {
headers: this.headers,
params,
}).pipe(catchError(e => throwError(e)));
}
post<T, D>(path: string, data: D, params: HttpParams = new HttpParams()): Observable<T> {
return this.http.post<T>(`${this.baseUrl}${path}`, JSON.stringify(data), { headers: this.headers, params })
.pipe(catchError(e => throwError(e)));
}
put<T, D>(path: string, data: D, params: HttpParams = new HttpParams()): Observable<T> {
return this.http.put<T>(`${this.baseUrl}${path}`, JSON.stringify(data), {
headers: this.headers,
params
})
.pipe(catchError(e => throwError(e)));
}
delete<T>(path?: string): Observable<T> {
return this.http.delete<T>(`${this.baseUrl}${path}`, {
headers: this.headers,
})
.pipe(catchError(e => throwError(e)));
}
deleteWithParams<T>(path: string, params: HttpParams = new HttpParams()): Observable<T>{
return this.http.delete<T>(`${this.baseUrl}${path}`, {
headers: this.headers,
params
})
.pipe(catchError(e => throwError(e)));
}
patch<T>(path: string, data?: any): Observable<T>{
return this.http.patch<T>(`${this.baseUrl}${path}`, JSON.stringify(data),{
headers: this.headers,
})
.pipe(catchError(e => throwError(e)));
}
getImageFile(path: string): Observable<any>{
return this.http.get(`${path}`, {
headers: this.headers,
responseType: 'blob'
}).pipe(catchError(e => throwError(e)));
}
uploadFile(path: string, data: FormData, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.post(`${this.baseUrl}${path}`, data, {
reportProgress: true,
observe: 'events',
params
});
}
getFile(path?: string, params: HttpParams = new HttpParams()): Observable<Blob> {
this.http.get(`${this.baseUrl}${path}`, {
headers: this.headers,
params,
responseType: 'blob',
observe: 'response',
}).subscribe((response: any) => {
const header_content = response?.headers?.get('Content-Disposition');
const filename = header_content?.split('filename=')[1]?.split('.')[0]?.replace(/_/g, '-');
})
return this.http.get(`${this.baseUrl}${path}`, {
headers: this.headers,
params,
responseType: 'blob',
});
}
getFileWithFileName(path?: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${this.baseUrl}${path}`, {
headers: this.headers,
params,
responseType: 'blob',
observe: 'response',
}).pipe(map((value) => {
const header_content = value?.headers?.get('Content-Disposition');
const filename = header_content?.split('filename=')[1]?.split('.')[0];
return {
file: value?.body,
filename: filename
};
}));
}
getFileWithHeader(path?: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${this.baseUrl}${path}`, {
headers: this.headers,
params,
responseType: 'blob',
observe: 'response',
}).pipe(map((value) => {
const header_content = value?.headers?.get('Content-Disposition');
return {
file: value?.body,
header_content,
};
}));
}
getBase64File(path: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${this.baseUrl}${path}`, {
headers: new HttpHeaders({'Content-Type': 'text/plain', Accept: "application/octet-stream"}),
params,
responseType: 'text'
});
}
downloadBase64(path: string, params: HttpParams = new HttpParams()): Observable<HttpEvent<any>> {
return this.http.get(`${this.baseUrl}${path}`, {
headers: new HttpHeaders({'Content-Type': 'text/plain', Accept: "application/octet-stream"}),
params,
responseType: 'text',
reportProgress: true,
observe: 'events'
});
}
/**
* Method used to get value of type (text/plain;charset=ISO-8859-1).
* @param url
* @param path
* @param params
* @returns value of {@link Observable}
*/
getPlainText(path?: string, params: HttpParams = new HttpParams()): Observable<any>{
return this.http.get(`${this.baseUrl}${path}`, {
headers: this.headers,
params,
responseType: 'text'
}
).pipe(catchError(e => throwError(e)));
}
uploadFileWithProgress<T>(path: string, form: FormData, params: HttpParams = new HttpParams()): Observable<HttpEvent<T>> {
const request = new HttpRequest('POST', `${this.baseUrl}${path}`, form, {
reportProgress: true,
responseType: 'json',
params: params
})
return this.http.request<T>(request).pipe(catchError(e => throwError(e)))
}
} |
package com.example.androiddemo.module
import android.content.Context
import com.example.androiddemo.AppSchedulerProvider
import com.example.androiddemo.SchedulerProvider
import com.example.common.network.NetworkManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object ApplicationModule {
@Provides
@Singleton
fun provideNetworkManager(@ApplicationContext context: Context):NetworkManager = NetworkManager(context)
@Provides
@Singleton
fun providesScheduler():SchedulerProvider = AppSchedulerProvider()
@Provides
@Singleton
fun provideApplicationContext(@ApplicationContext context: Context): Context {
return context
}
} |
# Copyright (c) 2022 kamyu. All rights reserved.
#
# Google Code Jam 2022 Virtual World Finals - Problem B. Goose, Goose, Ducks
# https://codingcompetitions.withgoogle.com/codejam/round/000000000087762e/0000000000b9ce14
#
# Time: O(N + M + S * (logM + logS)), TLE in large set for both PyPy3 and Python3
# Space: O(N + S)
#
from bisect import bisect_left
# Template:
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class SortedList(object):
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
# modified Template:
# https://github.com/kamyu104/GoogleCodeJam-2018/blob/master/World%20Finals/swordmaster.py
def min_size_of_leaf_strongly_connected_components(adj): # Time: O(|V| + |E|) = O(N + 2N) = O(N), Space: O(|V|) = O(N)
def iter_strongconnect(v):
stk = [(1, (v,))]
while stk:
step, args = stk.pop()
if step == 1:
v = args[0]
index[v] = index_counter[0]
lowlinks[v] = index_counter[0]
index_counter[0] += 1
stack_set[v] = True
stack.append(v)
stk.append((4, (v,)))
for w in reversed(adj[v]):
stk.append((2, (v, w)))
elif step == 2:
v, w = args
if index[w] == -1:
stk.append((3, (v, w)))
stk.append((1, (w,)))
elif stack_set[w]:
lowlinks[v] = min(lowlinks[v], index[w])
else: # visited child but not in curr stack
is_leaf_found[v] = True
elif step == 3:
v, w = args
if is_leaf_found[w]:
is_leaf_found[v] = True
lowlinks[v] = min(lowlinks[v], lowlinks[w])
elif step == 4:
v = args[0]
if lowlinks[v] != index[v]:
continue
w = None
cnt = 0
while w != v:
w = stack.pop()
stack_set[w] = False
cnt += 1
if not is_leaf_found[v]: # only keep leaf SCCs
is_leaf_found[v] = True
result[0] = min(result[0], cnt)
index_counter, index, lowlinks = [0], [-1]*len(adj), [-1]*len(adj)
stack, stack_set = [], [False]*len(adj)
is_leaf_found = [False]*len(adj)
result = [len(adj)]
for v in range(len(adj)):
if index[v] == -1:
iter_strongconnect(v)
return result[0]
def check(a, b):
return (a[0]-b[0])**2 >= (a[1]-b[1])**2 + (a[2]-b[2])**2
def add_statement(s, sl, is_duck):
sl.add(s)
i = sl.bisect_left(s)
while i-1 >= 0 and not check(sl[i-1][0], s[0]):
is_duck[sl[i-1][1]] = True
del sl[i-1]
i -= 1
while i+1 != len(sl) and not check(sl[i+1][0], s[0]):
is_duck[sl[i+1][1]] = True
del sl[i+1]
def bfs(adj, is_duck):
q = list(u for u in range(len(adj)) if is_duck[u])
while q:
new_q = []
for u in q:
for v in adj[u]:
if is_duck[v]:
continue
is_duck[v] = True
new_q.append(v)
q = new_q
return sum(is_duck)
def goose_goose_ducks():
N, M, S = list(map(int, input().split()))
meetings = []
for _ in range(M):
X, Y, C = list(map(int, input().split()))
meetings.append((C, X, Y))
is_duck = [False]*N
adj = [[] for _ in range(N)]
sls = [SortedList() for _ in range(N)]
for _ in range(S):
A, B, U, V, D = list(map(int, input().split()))
A -= 1
B -= 1
s = ((D, U, V), A)
i = bisect_left(meetings, s[0])
if (i-1 >= 0 and not check(meetings[i-1], s[0])) or (i < M and not check(meetings[i], s[0])):
adj[B].append(A)
add_statement(s, sls[A], is_duck)
add_statement(s, sls[B], is_duck)
if any(is_duck):
return bfs(adj, is_duck)
return min_size_of_leaf_strongly_connected_components(adj)
for case in range(int(input())):
print('Case #%d: %s' % (case+1, goose_goose_ducks())) |
import React from 'react';
import ReactDOM from 'react-dom';
class StopWatch extends React.Component {
constructor(props) {
super(props);
this.state = {
time: 0,
playClick: false,
pauseClick: true
};
this.playHandleClick = this.playHandleClick.bind(this);
this.pauseHandleClick = this.pauseHandleClick.bind(this);
this.clearHandleClick = this.clearHandleClick.bind(this);
}
playHandleClick() {
this.setState({ playClick: true, pauseClick: false });
this.intervalId = setInterval(() => {
this.setState({
time: this.state.time + 1
});
}, 1000);
}
pauseHandleClick() {
clearInterval(this.intervalId);
this.setState({ playClick: false, pauseClick: true });
}
clearHandleClick() {
if (this.state.playClick === false) {
this.setState({ time: 0 });
}
}
render() {
if (this.state.playClick === false) {
return (
<div>
<div className="circle" onClick={this.clearHandleClick}>
<div className="time">
<h1>{this.state.time}</h1>
</div>
</div>
<div className="play-button" onClick={this.playHandleClick}>
<h1>▶</h1>
</div>
</div>
);
} else {
return (
<div>
<div className="circle" onClick={this.clearHandleClick}>
<div className="time">
<h1>{this.state.time}</h1>
</div>
</div>
<div className="pause-button" onClick={this.pauseHandleClick}>
<h1>||</h1>
</div>
</div>
);
}
}
}
ReactDOM.render(
<StopWatch />,
document.querySelector('#root')
);
// ▶ |
import { useEffect, useState } from "react";
import "./trainers.css";
export function Trainers() {
const [trainers, setTrainers] = useState([]);
useEffect(() => {
async function fetchTrainersData() {
try {
var response = await fetch("http://localhost:5000/trainers");
} catch {
return navigate("/404");
}
if (!response.ok) {
const errorData = await response.json();
errorToastMessage(errorData.error);
return navigate('/404');
}
const data = await response.json();
setTrainers(data);
}
fetchTrainersData();
},
[]);
return (
<main className="trainers-main">
{trainers.map((trainer) =>
<div className="trainer-section">
<img src={`data:image/jpeg;base64,${trainer.photo}`} alt=""/>
<h5>Name: {trainer.name}</h5>
<a className="clickable" target="_blank" href={`mailto:${trainer.email}?subject=Subject%20of%20the%20email&body=Body%20of%20the%20email`}>Email: {trainer.email}</a>
<a className="clickable" href={`tel:+${trainer.phoneNumber}`}>Telephone: +{trainer.phoneNumber}</a>
</div>)}
</main>
);
} |
import { useEffect, useReducer, useState } from "react";
import BudgetGroceryPage from "../view/pages/BudgetGroceryPage";
import budgetModel from "../model/BudgetModel";
const BudgetController = () => {
const [exceedError, setExceedError] = useState(false);
const [totalBudget, setTotalBudget] = useState(0);
const [budget, setBudget] = useState(null);
const [listHeader, setListHeader] = useState(false);
const [errorBudget, setErrorBudget] = useState({
errorGeneral: false,
});
const [selectedGrocery, setSelectedGrocery] = useState("");
const [currentGrocery, setCurrentGrocery] = useState([]);
const [form, setForm] = useState({
name: "",
price: "",
quantity: "",
total: "",
});
useEffect(() => {
getBudget().then((grocery) => {
setCurrentGrocery(grocery);
});
}, []);
const getBudget = async () => {
return budgetModel.getBudgetList();
};
const postBudget = async () => {
try {
const newGrocery = await budgetModel.addBudgetList({
...form,
name: form.name,
price: form.price,
quantity: form.quantity,
total: form.price * form.quantity,
});
setCurrentGrocery([...currentGrocery, newGrocery]);
} catch (error) {
throw new Error("Failed to add", error);
}
};
const putBudget = async (id) => {
try {
setSelectedGrocery("");
const data = await budgetModel.updateBudgetList(id, {
...form,
total: form.price * form.quantity,
});
setCurrentGrocery((currentGrocery) =>
currentGrocery.map((grocery) => {
if (data._id === grocery._id) {
return {
...grocery,
name: data.name,
price: data.price,
quantity: data.quantity,
total: data.total,
};
} else {
return grocery;
}
})
);
setForm({ name: "", price: "", quantity: "", total: 0 });
} catch (error) {
console.error("Error fetching grocery item:", error);
}
};
const removeBudget = async (id) => {
const newGrocery = await budgetModel.deleteBudgetList(id);
if (newGrocery) {
setCurrentGrocery(currentGrocery.filter((grocery) => grocery._id !== id));
}
};
const doneBudget = async (id) => {
const data = await budgetModel.completeBudgetList(id);
setCurrentGrocery((currentGrocery) =>
currentGrocery.map((grocery) => {
if (grocery._id === data._id) {
grocery.complete = data.complete;
}
return grocery;
})
);
};
const getUpdateBudget = async (id) => {
const data = await budgetModel.getUpdateBudgetList(id);
setForm({
...form,
name: data.name,
price: data.price,
quantity: data.quantity,
total: data.total,
});
setSelectedGrocery(id);
};
const clearText = () => {
setForm({ name: "", price: "", quantity: "", total: 0 });
};
const handleChange = (event) => {
switch (event.target.id) {
case "name":
return setForm({ ...form, name: event.target.value });
case "price":
return setForm({ ...form, price: event.target.value });
case "quantity":
return setForm({ ...form, quantity: event.target.value });
case "total":
return setForm({ ...form, total: event.target.value });
default:
return form;
}
};
const totalAmount = currentGrocery.reduce((acc, grocery) => {
return acc + parseFloat(grocery.total);
}, 0);
const handleSubmit = (event) => {
event.preventDefault();
if (selectedGrocery) {
putBudget(selectedGrocery);
} else if (form.name && form.price && form.quantity && !selectedGrocery) {
postBudget();
} else {
console.log("No data to update or post. Error");
}
setErrorBudget({
...errorBudget,
errorGeneral: !form.product && !form.price && !form.quantity,
});
setForm({
...form,
product: "",
price: "",
quantity: "",
total: 0,
});
};
useEffect(() => {
if (Object.keys(currentGrocery).length > 0) {
setListHeader(true);
} else {
setListHeader(false);
}
handleError();
}, [totalAmount, currentGrocery, totalBudget]);
const handleError = () => {
if (totalAmount < totalBudget) {
setExceedError(false);
} else if (totalAmount == totalBudget) {
setExceedError(false);
} else {
setExceedError(true);
}
};
const handleBudget = () => {
if (budget > 0) {
setTotalBudget(budget);
setBudget("");
} else {
alert("Add budget a valid budget");
setBudget("");
}
};
return (
<BudgetGroceryPage
exceedError={exceedError}
totalBudget={totalBudget}
budget={budget}
setBudget={setBudget}
listHeader={listHeader}
errorBudget={errorBudget}
handleChange={handleChange}
handleSubmit={handleSubmit}
handleBudget={handleBudget}
form={form}
totalAmount={totalAmount}
removeBudget={removeBudget}
putBudget={putBudget}
selectedGrocery={selectedGrocery}
doneBudget={doneBudget}
clearText={clearText}
getUpdateBudget={getUpdateBudget}
currentGrocery={currentGrocery}
/>
);
};
export default BudgetController; |
import React, { useEffect, useState, useRef } from 'react';
import './Navbar.css';
import logo from './logo2.jpg';
import { useNavigate } from 'react-router-dom';
import { useCart } from '../CartContext/CartContext';
import { ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
const Navbar = () => {
const { cartItems, handleNavigate, isSignedIn, updateSignInStatus, isAdmin, resetSignedUserInfo, searchProductFromDb, fetchCategories, category, setCategory, listOfCategory } = useCart();
const [searchboxitem, setSearchBoxItem] = useState([]);
const searchInputRef = useRef(null);
// calculate the total quantity of items in the cart
const totalQuantity = cartItems.reduce((total, item) => total + item.quantity, 0);
useEffect(() => {
resetSignedUserInfo()
}, [isSignedIn])
useEffect(() => {
searchInputRef.current.focus();
}, []);
const handleClickLogout = (props) => {
if (isSignedIn) {
updateSignInStatus(props);
}
handleNavigate('/login2');
}
const handleNavigateUserByRole = () => {
if (isAdmin === true) {
handleNavigate('/adminPage')
} else {
handleNavigate('/profilePage');
}
}
const handleSearchButtonClick = () => {
if (searchboxitem.length === 0) {
return;
} else {
searchProductFromDb(searchboxitem);
}
}
const handleSubmit = (event) => {
event.preventDefault();
if (searchboxitem.length === 0) {
return;
} else {
searchProductFromDb(searchboxitem);
}
};
const handleKeyDown = (event) => {
if (event.key === "Enter") {
handleSubmit(event);
}
};
const handleFetchCategory = (url) => {
fetchCategories(url, setCategory);
handleNavigate(`/${url}`);
}
return (
<div>
<ToastContainer />
<nav className='navbar'>
<div className='right-side'>
<img src={logo} className='logo' onClick={() => handleNavigate('/')} alt="logo"></img>
<ul className='ul-list'>
<li>
<a className='products-tag' href="#">Categories</a>
<ul className='ul-list2'>
<li><a className='a-tag' href="#" onClick={() => handleFetchCategory('Electronic')}>Electronic</a></li>
<li><a className='a-tag' href="#" onClick={() => handleFetchCategory('Clothes')}>Clothes</a></li>
<li><a className='a-tag' href="#" onClick={() => handleFetchCategory('Shoe')}>Shoe</a></li>
</ul>
</li>
</ul>
</div>
<form onSubmit={handleSubmit}>
<div className='middle search'>
<input
ref={searchInputRef}
className='search-box'
type='search'
placeholder='search'
value={searchboxitem}
onChange={(e) => setSearchBoxItem(e.target.value)}
onKeyDown={handleKeyDown}
/>
<i className="btn bi-search search-icon" onClick={handleSearchButtonClick}></i>
</div>
</form>
<div className='right-side'>
{ /*<i className="btn bi-box-arrow-in-right login-color" onClick={() => handleNavigate('/login')}></i> */}
{/* <button onClick={() => handleNavigate('/gsapCard')}>go to aminate gsap</button> */}
<i className="btn bi-box-arrow-in-right login-color" title='signin/signout' onClick={handleClickLogout}></i>
<i class="btn login-color bi-person-circle" title='profile' onClick={handleNavigateUserByRole}></i>
<i className="btn bi-heart login-color" title='favorites' onClick={() => handleNavigate('/favori')}></i>
<i className="btn bi-cart4 login-color" title='cart' onClick={() => handleNavigate('/shoppingcart')}>
{totalQuantity > 0 && <span className="cart-quantity">{totalQuantity}</span>}
</i>
</div>
</nav>
</div>
);
}
export default Navbar; |
#!/usr/bin/python
import argparse
import file_index
import index_comparator
import logging
import os
import sys
logger = logging.getLogger(__name__)
# Check arguments and try to load indexes first, so errors can fail fast
def compare(args):
from_paths = [args.from_path] + args.extra_from_paths
to_paths = [args.to_path] + args.extra_to_paths
from_index = file_index.FileIndex("from")
to_index = file_index.FileIndex("to")
for path in from_paths:
from_index.add_path(path)
for path in to_paths:
to_index.add_path(path)
comparator = index_comparator.IndexComparator(from_index, to_index, args.exclude)
logger.info("From: {}".format(from_index))
logger.info("To : {}".format(to_index))
comparator.compare()
comparator.print_changes(args.show_changes, args.hide_change_type)
def index(args):
if not os.path.isdir(args.directory):
raise IOError("{} is not a directory".format(args.directory))
if not args.force and os.path.exists(args.index_file):
raise IOError("{} already exists. Add -f to overwrite.".format(args.index_file))
logger.info("Indexing {}".format(args.directory))
index = file_index.FileIndex()
message = " ".join(args.message) if args.message is not None else None
index.scan_dir(args.directory, message)
index.save(args.index_file)
def execute_command_line():
parser = argparse.ArgumentParser(description = "directory diff - compare changes in files between two directories")
base_subparser = argparse.ArgumentParser(add_help = False)
base_subparser.add_argument("--exclude", action = "append", help = "Glob for files to exclude. Can be specified multiple times.")
base_subparser.add_argument("-v", "--verbose", action = "count", help = "Log INFO messages if specified once. Log DEBUG messages if specified twice.")
subparsers = parser.add_subparsers()
parser_compare = subparsers.add_parser("compare", help = "Compare two directories", parents=[base_subparser])
parser_compare.add_argument("from_path", help = "Directory or index to compare changes from")
parser_compare.add_argument("to_path", help = "Directory or index to compare changes to")
parser_compare.add_argument("--extra-from-paths", nargs = "+", default = [], help = "Extra directories or indexes to compare changes from")
parser_compare.add_argument("--extra-to-paths", nargs = "+", default = [], help = "Extra directories or indexes to compare changes to")
parser_compare.add_argument("-n", "--hide-change-type", action = "store_true", help = "Hide change type, only list files")
parser_compare.add_argument("-i", "--show-identical", const = index_comparator.Change.Type.IDENTICAL,
action = "append_const", dest = "show_changes", help = "Show identical files")
parser_compare.add_argument("-m", "--show-moved", const = index_comparator.Change.Type.MOVED,
action = "append_const", dest = "show_changes", help = "Show moved files")
parser_compare.add_argument("-c", "--show-changed", const = index_comparator.Change.Type.CHANGED,
action = "append_const", dest = "show_changes", help = "Show changed files")
parser_compare.add_argument("-d", "--show-deleted", const = index_comparator.Change.Type.DELETED,
action = "append_const", dest = "show_changes", help = "Show deleted files")
parser_compare.add_argument("-a", "--show-added", const = index_comparator.Change.Type.ADDED,
action = "append_const", dest = "show_changes", help = "Show added files")
parser_compare.add_argument("-u", "--show-duplicated", const = index_comparator.Change.Type.DUPLICATED,
action = "append_const", dest = "show_changes", help = "Show duplicated files")
parser_compare.add_argument("-e", "--show-deduplicated", const = index_comparator.Change.Type.DUPLICATED,
action = "append_const", dest = "show_changes", help = "Show deduplicated files")
parser_compare.set_defaults(func = compare)
parser_index = subparsers.add_parser("index", help = "Index directory and save to file", parents=[base_subparser])
parser_index.add_argument("directory", help = "Directory to index")
parser_index.add_argument("index_file", nargs = "?", default = "index.did", help = "File to store index in")
parser_index.add_argument("-f", "--force", action = "store_true", help = "Force overwriting of existing index file")
parser_index.add_argument("-m", "--message", nargs = "+", help = "Message to be stored in index file")
parser_index.set_defaults(func = index)
args = parser.parse_args()
if len(sys.argv) == 1:
parser.print_help()
parser.exit()
if args.verbose is None:
logging.basicConfig(level = logging.WARNING)
elif args.verbose == 1:
logging.basicConfig(level = logging.INFO)
elif args.verbose >= 2:
logging.basicConfig(level = logging.DEBUG)
args.func(args)
if __name__ == '__main__':
execute_command_line() |
import React,{Component} from 'react';
import "./Dashboard.css"
import {BrowserRouter ,Route,Switch,Link} from "react-router-dom";
import{useNavigate} from "react-router-dom";
import Form from './form';
import In01form from './in01form';
import In02table from './in02table';
import Attform from './att_form';
import Sample from './sample';
import Autocomplete from './autocomplete';
import Pass_form from './pass_form';
import Student_Details from './Student_Details';
const autocomplete_options = ["option1","option2","option3"];
function Car(){
return (
<div>
<BrowserRouter>
<Switch>
<React.Fragment>
{/* <!-- Page Wrapper --> */}
<div id="wrapper">
{/* <!-- Sidebar --> */}
<ul className="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar">
{/* <!-- Sidebar - Brand --> */}
<a className="sidebar-brand d-flex align-items-center justify-content-center" href="index.html">
<div className="sidebar-brand-icon rotate-n-15">
<i className="fas fa-laugh-wink"></i>
</div>
<div className="sidebar-brand-text mx-3">SB Admin <sup>2</sup></div>
</a>
{/* <!-- Divider --> */}
<hr className="sidebar-divider my-0"/>
{/* <!-- Nav Item - Dashboard --> */}
<li className="nav-item active">
<a className="nav-link" href="index.html">
<i className="fas fa-fw fa-tachometer-alt"></i>
<span>Dashboard</span></a>
</li>
{/* <!-- Divider --> */}
<hr className="sidebar-divider"/>
{/* <!-- Heading --> */}
<div className="sidebar-heading">
Interface
</div>
{/* <!-- Nav Item - Pages Collapse Menu --> */}
{/* <!-- Nav Item - Utilities Collapse Menu --> */}
<li className="nav-item">
<a className="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseUtilities"
aria-expanded="true" aria-controls="collapseUtilities">
<i className="fas fa-fw fa-wrench"></i>
<span>Utilities</span>
</a>
<div id="collapseUtilities" className="collapse" aria-labelledby="headingUtilities"
data-parent="#accordionSidebar">
<div className="bg-white py-2 collapse-inner rounded">
<h6 className="collapse-header">Custom Utilities:</h6>
<Link className='collapse-item' to="/Form" element={<Form/>}>Form</Link>
<Link className='collapse-item' to="/In01form" element={<In01form/>}>Invoice01 & 02</Link>
{/* <Link className='collapse-item' to="/In02table" element={<In02table/>}>DataTable</Link> */}
<Link className='collapse-item' to="/att_form" element={<Attform/>}>UmarBro Form</Link>
<Link className='collapse-item' to="/Sample" element={<Sample/>}>Sample</Link>
<Link className='collapse-item' to="/Autocomplete" element={<Autocomplete/>}>Autocomplete</Link>
<Link className='collapse-item' to="/Pass_form" element={<Pass_form/>}>Password-Management</Link>
<Link className='collapse-item' to="/Student_Details" element={<Student_Details/>}>Student_Details</Link>
<a className="collapse-item" href="utilities-other.html">Other</a>
</div>
</div>
</li>
{/* <!-- Divider --> */}
<hr className="sidebar-divider"/>
{/* <!-- Heading --> */}
<div className="sidebar-heading">
Addons
</div>
{/* <!-- Nav Item - Pages Collapse Menu --> */}
<li className="nav-item">
<a className="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapsePages"
aria-expanded="true" aria-controls="collapsePages">
<i className="fas fa-fw fa-folder"></i>
<span>Pages</span>
</a>
<div id="collapsePages" className="collapse" aria-labelledby="headingPages" data-parent="#accordionSidebar">
<div className="bg-white py-2 collapse-inner rounded">
<h6 className="collapse-header">Login Screens:</h6>
<a className="collapse-item" href="login.html">Login</a>
<a className="collapse-item" href="register.html">Register</a>
<a className="collapse-item" href="forgot-password.html">Forgot Password</a>
<div className="collapse-divider"></div>
<h6 className="collapse-header">Other Pages:</h6>
<a className="collapse-item" href="404.html">404 Page</a>
<a className="collapse-item" href="blank.html">Blank Page</a>
</div>
</div>
</li>
{/* <!-- Nav Item - Charts --> */}
<li className="nav-item">
<a className="nav-link" href="charts.html">
<i className="fas fa-fw fa-chart-area"></i>
<span>Charts</span></a>
</li>
{/* <!-- Nav Item - Tables --> */}
<li className="nav-item">
<a className="nav-link" href="tables.html">
<i className="fas fa-fw fa-table"></i>
<span>Tables</span></a>
</li>
{/* <!-- Divider --> */}
<hr className="sidebar-divider d-none d-md-block"/>
{/* <!-- Sidebar Toggler (Sidebar) --> */}
<div className="text-center d-none d-md-inline">
<button className="rounded-circle border-0" id="sidebarToggle"></button>
</div>
{/* <!-- Sidebar Message --> */}
<div className="sidebar-card d-none d-lg-flex">
<img className="sidebar-card-illustration mb-2" src="img/undraw_rocket.svg" alt="..."/>
<p className="text-center mb-2"><strong>SB Admin Pro</strong> is packed with premium features, components, and more!</p>
<a className="btn btn-success btn-sm" href="https://startbootstrap.com/theme/sb-admin-pro">Upgrade to Pro!</a>
</div>
</ul>
{/* <!-- End of Sidebar --> */}
<div id="content-wrapper" className="d-flex flex-column">
{/* <!-- Main Content --> */}
{/* <!-- Topbar --> */}
<nav className="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
{/* <!-- Sidebar Toggle (Topbar) --> */}
<button id="sidebarToggleTop" className="btn btn-link d-md-none rounded-circle mr-3">
<i className="fa fa-bars"></i>
</button>
{/* <!-- Topbar Search --> */}
<form
className="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
<div className="input-group">
<input type="text" className="form-control bg-light border-0 small" placeholder="Search for..."
aria-label="Search" id="search" aria-describedby="basic-addon2"/>
<div className="input-group-append">
<button className="btn btn-primary" type="button">
<i className="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
<div class="navbar-nav ml-auto">
<button type="button" class="btn btn-outline-primary px-3 me-2">
Login
</button>
<button type="button" class="btn btn-primary me-3">
Sign up for free
</button>
</div>
{/* <!-- Topbar Navbar --> */}
<ul className="navbar-nav ml-end">
{/* <!-- Nav Item - Search Dropdown (Visible Only XS) --> */}
<li className="nav-item dropdown no-arrow d-sm-none">
<a className="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i className="fas fa-search fa-fw"></i>
</a>
{/* <!-- Dropdown - Messages --> */}
<div className="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in"
aria-labelledby="searchDropdown">
<form className="form-inline mr-auto w-100 navbar-search">
<div className="input-group">
<input type="text" className="form-control bg-light border-0 small"
placeholder="Search for..." aria-label="Search"
aria-describedby="basic-addon2"/>
<div className="input-group-append">
<button className="btn btn-primary" type="button">
<i className="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
</div>
</li>
{/* <!-- Nav Item - Alerts --> */}
<li className="nav-item dropdown no-arrow mx-1">
<a className="nav-link dropdown-toggle" href="#" id="alertsDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i className="fas fa-bell fa-fw"></i>
{/* <!-- Counter - Alerts --> */}
<span className="badge badge-danger badge-counter">3+</span>
</a>
{/* <!-- Dropdown - Alerts --> */}
<div className="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in"
aria-labelledby="alertsDropdown">
<h6 className="dropdown-header">
Alerts Center
</h6>
<a className="dropdown-item d-flex align-items-center" href="#">
<div className="mr-3">
<div className="icon-circle bg-primary">
<i className="fas fa-file-alt text-white"></i>
</div>
</div>
<div>
<div className="small text-gray-500">December 12, 2019</div>
<span className="font-weight-bold">A new monthly report is ready to download!</span>
</div>
</a>
<a className="dropdown-item d-flex align-items-center" href="#">
<div className="mr-3">
<div className="icon-circle bg-success">
<i className="fas fa-donate text-white"></i>
</div>
</div>
<div>
<div className="small text-gray-500">December 7, 2019</div>
$290.29 has been deposited into your account!
</div>
</a>
<a className="dropdown-item d-flex align-items-center" href="#">
<div className="mr-3">
<div className="icon-circle bg-warning">
<i className="fas fa-exclamation-triangle text-white"></i>
</div>
</div>
<div>
<div className="small text-gray-500">December 2, 2019</div>
Spending Alert: We've noticed unusually high spending for your account.
</div>
</a>
<a className="dropdown-item text-center small text-gray-500" href="#">Show All Alerts</a>
</div>
</li>
{/* <!-- Nav Item - Messages --> */}
<li className="nav-item dropdown no-arrow mx-1">
<a className="nav-link dropdown-toggle" href="#" id="messagesDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i className="fas fa-envelope fa-fw"></i>
{/* <!-- Counter - Messages --> */}
<span className="badge badge-danger badge-counter">7</span>
</a>
{/* <!-- Dropdown - Messages --> */}
<div className="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in"
aria-labelledby="messagesDropdown">
<h6 className="dropdown-header">
Message Center
</h6>
<a className="dropdown-item d-flex align-items-center" href="#">
<div className="dropdown-list-image mr-3">
<img className="rounded-circle" src="img/undraw_profile_1.svg"
alt="..."/>
<div className="status-indicator bg-success"></div>
</div>
<div className="font-weight-bold">
<div className="text-truncate">Hi there! I am wondering if you can help me with a
problem I've been having.</div>
<div className="small text-gray-500">Emily Fowler · 58m</div>
</div>
</a>
<a className="dropdown-item d-flex align-items-center" href="#">
<div className="dropdown-list-image mr-3">
<img className="rounded-circle" src="img/undraw_profile_2.svg"
alt="..."/>
<div className="status-indicator"></div>
</div>
<div>
<div className="text-truncate">I have the photos that you ordered last month, how
would you like them sent to you?</div>
<div className="small text-gray-500">Jae Chun · 1d</div>
</div>
</a>
<a className="dropdown-item d-flex align-items-center" href="#">
<div className="dropdown-list-image mr-3">
<img className="rounded-circle" src="img/undraw_profile_3.svg"
alt="..."/>
<div className="status-indicator bg-warning"></div>
</div>
<div>
<div className="text-truncate">Last month's report looks great, I am very happy with
the progress so far, keep up the good work!</div>
<div className="small text-gray-500">Morgan Alvarez · 2d</div>
</div>
</a>
<a className="dropdown-item d-flex align-items-center" href="#">
<div className="dropdown-list-image mr-3">
<img className="rounded-circle" src="https://source.unsplash.com/Mv9hjnEUHR4/60x60"
alt="..."/>
<div className="status-indicator bg-success"></div>
</div>
<div>
<div className="text-truncate">Am I a good boy? The reason I ask is because someone
told me that people say this to all dogs, even if they aren't good...</div>
<div className="small text-gray-500">Chicken the Dog · 2w</div>
</div>
</a>
<a className="dropdown-item text-center small text-gray-500" href="#">Read More Messages</a>
</div>
</li>
<div className="topbar-divider d-none d-sm-block"></div>
{/* <!-- Nav Item - User Information --> */}
<li className="nav-item dropdown no-arrow">
<a className="nav-link dropdown-toggle" href="#" id="userDropdown" role="button"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span className="mr-2 d-none d-lg-inline text-gray-600 small">Douglas McGee</span>
<img className="img-profile rounded-circle"
src="img/undraw_profile.svg"/>
</a>
{/* <!-- Dropdown - User Information --> */}
<div className="dropdown-menu dropdown-menu-right shadow animated--grow-in"
aria-labelledby="userDropdown">
<a className="dropdown-item" href="#">
<i className="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i>
Profile
</a>
<a className="dropdown-item" href="#">
<i className="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i>
Settings
</a>
<a className="dropdown-item" href="#">
<i className="fas fa-list fa-sm fa-fw mr-2 text-gray-400"></i>
Activity Log
</a>
<div className="dropdown-divider"></div>
<a className="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal">
<i className="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i>
Logout
</a>
</div>
</li>
</ul>
</nav>
<div id="content">
<div id="content">
{/* <!-- End of Topbar --> */}
{/* <!-- Begin Page Content --> */}
<div className="container-fluid">
{/* <!-- Page Heading --> */}
<div className="d-sm-flex align-items-center justify-content-between mb-4">
<h1 className="h3 mb-0 text-gray-800">
</h1>
<a href="#" className="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm"><i
className="fas fa-download fa-sm text-white-50"></i> Generate Report</a>
</div>
</div>
{/* <!-- Content Wrapper --> */}
<div id="content-wrapper" className="d-flex flex-column">
{/* <!-- Main Content --> */}
<Route exact path='/Form'>
<Form/>
</Route>
<Route exact path='/In01form'>
<In01form/>
</Route>
<Route exact path='/In02table'>
<In02table/>
</Route>
<Route exact path='/att_form'>
<Attform/>
</Route>
<Route exact path='/Sample'>
<Sample/>
</Route>
<Route exact path='/Autocomplete'>
<Autocomplete/>
</Route>
<Route exact path='/pass_form'>
<Pass_form/>
</Route>
<Route exact path='/Student_Details'>
<Student_Details/>
</Route>
</div>
</div>
</div>
</div></div>
</React.Fragment>
</Switch>
</BrowserRouter>
</div>
)}
export default Car; |
import pandas as pd
from pathlib import Path
import os
from torch.utils.tensorboard import SummaryWriter
import numpy as np
import code.params as cfg
class CrossValidation(object):
def __init__(self, config_name, experiment_name, data_dir, start_id, test_experiment_name):
self.config_name = config_name
self.experiment_name = experiment_name
self.test_experiment_name = test_experiment_name
self.data_dir = data_dir
self.start_id = start_id
def nested_cv_configurations(self):
for outer_fold in range(cfg.outer_k):
yield from self.inner_cv_configurations(outer_fold)
def inner_cv_configurations(self, outer_fold):
for inner_fold in range(cfg.inner_k):
yield from self.single_train_valid_split(outer_fold, inner_fold)
def single_train_valid_split(self, outer_fold, inner_fold):
yield from cfg.config_generator(self, outer_fold, inner_fold)
def save_params_results(self, params, results):
Path(params['valid_results_dir']).mkdir(parents=True, exist_ok=True)
df = pd.DataFrame([list(params.values()) + list(results.values())], columns=list(params.keys()) + list(results.keys()))
df.to_pickle(params['valid_results_file'])
def save_test_results(self, params, results):
Path(params['test_results_dir']).mkdir(parents=True, exist_ok=True)
df = pd.DataFrame([list(params.values()) + list(results.values())], columns=list(params.keys()) + list(results.keys()))
df.to_pickle(params['test_results_file'])
# allele_evaluation_df.to_pickle(params['test_allele_results_file'])
def merge_test_results(self):
config = cfg.get_combined_config(self)
df_list = []
for result_file in os.listdir(config['test_results_dir']):
if 'allele' not in result_file:
df_list.append(pd.read_pickle(config['test_results_dir'] + '/' + result_file))
results_df = pd.concat(df_list)
results_df.to_csv(config['combined_test_results_file'])
return results_df
def read_valid_results(self, config, outer_fold=None):
df_list = []
for result_file in os.listdir(config['valid_results_dir']):
if '.pkl' in result_file:
inner_fold = result_file[-5]
df = pd.read_pickle(config['valid_results_dir'] + '/' + result_file)
df['inner_fold'] = inner_fold
df_list.append(df)
results_df = pd.concat(df_list)
if outer_fold is not None:
results_df = results_df.loc[results_df['outer_fold'] == outer_fold]
return results_df
def get_best_hyperparams(self, selection_criteria, outer_k=cfg.outer_k, multiple_random_seeds=True):
for outer_fold in range(outer_k):
file_paths_config = cfg.get_combined_config(self, outer_fold, test=True)
fold_results_df = self.read_valid_results(file_paths_config, outer_fold)
for key, value in selection_criteria:
fold_results_df = fold_results_df.loc[fold_results_df[key] == value]
# take the mean over all inner folds with the same configuration
selected_metrics = [metric for metric in set(fold_results_df.dropna(axis=1, how='all').columns) if 'Selected metric' in metric]
if len(selected_metrics) != 1:
print('selected metric undefined', outer_fold, selected_metrics)
return False
selected_metric = selected_metrics[0]
param_keys = cfg.get_param_keys(self.config_name)
param_keys.remove('random_seed')
param_keys.remove('batch_size')
if 'eval_interval' in param_keys:
param_keys.remove('eval_interval')
mean_results = fold_results_df[param_keys + ['early_stop_epochs', 'config_id', selected_metric]].groupby(param_keys).mean()
# the index specifies the parameter values of the best configuration
best_index = mean_results.idxmax()[selected_metric]
best_params = dict(zip(param_keys, list(best_index)))
# config_id will only be used for displaying it in tensorboard
config_id = int(mean_results.loc[best_index, 'config_id'])
if multiple_random_seeds:
random_seeds = list(range(1, 11))
else:
random_seeds = [1]
for random_seed in random_seeds:
# add other parameters/file paths that are not considered for finding the best configuration
best_params['random_seed'] = random_seed
config = cfg.get_combined_config(self, outer_fold, test=True, config_id=config_id, params=best_params)
params_combined = {key: best_params[key] if key in best_params else value for key, value in config.items()}
params_combined['early_stop_epochs'] = round(mean_results.loc[best_index, 'early_stop_epochs'])
params_combined['outer_fold'] = outer_fold
if self.experiment_name == 'TransformerMultiSourcePaper':
params_combined['evaluate_pep_sources'] = True
# pandas uses numpy types but pytorch uses python types for parameters
params_casted = {key: value.item() if isinstance(value, np.integer) else value for key, value in params_combined.items()}
yield params_casted
def get_permutation_hyperparams(self):
for outer_fold in range(cfg.outer_k):
random_seeds = list(range(200))
for random_seed in random_seeds:
params = {'random_seed': random_seed, 'dataset_folder': 'nested_cv_thesis'}
config = cfg.get_combined_config(self, outer_fold, test=True, config_id=0, params=params)
config['early_stop_epochs'] = 200
config['random_seed'] = random_seed
# pandas uses numpy types but pytorch uses python types for parameters
config_casted = {key: value.item() if isinstance(value, np.integer) else value for key, value in config.items()}
yield config_casted
def get_hyperparams_without_cv(self):
for outer_fold in range(cfg.outer_k):
random_seeds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for random_seed in random_seeds:
params = {'random_seed': random_seed, 'dataset_folder': 'nested_cv_thesis'}
config = cfg.get_combined_config(self, outer_fold, test=True, config_id=0, params=params)
config['early_stop_epochs'] = 120
config['random_seed'] = random_seed
config['adversary_learning_rate'] = 0.005
config['learning_rate'] = 0.002
config['embedding_dim'] = 32
# pandas uses numpy types but pytorch uses python types for parameters
config_casted = {key: value.item() if isinstance(value, np.integer) else value for key, value in config.items()}
yield config_casted
def inner_cv_to_tensorboard_mean(self, outer_fold):
config = cfg.get_combined_config(self)
fold_results_df = self.read_valid_results(config, outer_fold)
value_counts = fold_results_df.nunique()
variable_params = value_counts.loc[value_counts > 1].index
# fold_results_df = self.add_selection_criterion(fold_results_df)
param_keys = cfg.get_param_keys(self.config_name)
parameter_selection = ''
for param in set(variable_params) & set(param_keys):
param_values = ', '.join(map(str, fold_results_df[param].unique()))
parameter_selection += f'{param}: {param_values}\n\n'
param_keys.remove('random_seed')
param_keys.remove('batch_size')
# take the mean over all inner folds with the same configuration
grouped_results = fold_results_df.fillna(0.3).groupby(param_keys)
config_strings = []
for _, df in grouped_results:
config_strings.append('_'.join(set([str(id) for id in df['config_id'].to_list()])))
mean_results = grouped_results.mean()
mean_results['config_string'] = config_strings
writer = SummaryWriter(config['tensorboard_dir'])
for param_values in mean_results.index:
params = dict(zip(param_keys, list(param_values)))
results = mean_results.loc[param_values].to_dict()
config_id = results["config_string"]
results_selection = {cfg.tensorboard_hparams_metrics[key]: value for key, value in results.items() if key in list(cfg.tensorboard_hparams_metrics.keys())}
params_selection = {key: value for key, value in params.items() if key in variable_params}
# params_selection = {**params_selection, 'random_seed': 'mean', 'inner_fold': 'mean'}
writer.add_hparams(params_selection, results_selection,
run_name=f'{self.experiment_name}/config_{config_id}/cv_{outer_fold}_mean')
self.log_tensorboard_text(parameter_selection, params, outer_fold, config_id, config['tensorboard_dir'])
writer.close()
def log_tensorboard_text(self, params, print_dict, outer_fold, config_id, tensorboard_dir, step=0):
"""
Add the model configuration and results to the TensorBoard "Text" tab.
"""
text_writer = SummaryWriter(f'{tensorboard_dir}/{self.experiment_name}/config_{config_id}/cv_{outer_fold}_mean')
model_description = f'# {self.experiment_name}\n\n{self.config_name}\n\n{params}'
table_head = f'|Parameter|Value|\n| :--- |:---|\n'
table_main = "\n".join(f'|{k}|{v:.4f}|' if isinstance(v, float) else f'|{k}|{v}|' for k, v in print_dict.items())
text_writer.add_text('Parameters', model_description + table_head + table_main, global_step=step)
text_writer.close()
def inner_cv_to_tensorboard(self, outer_fold):
config = cfg.get_combined_config(self)
fold_results_df = self.read_valid_results(config, outer_fold)
value_counts = fold_results_df.nunique()
variable_params = value_counts.loc[value_counts > 1].index
# fold_results_df = self.add_selection_criterion(fold_results_df)
param_keys = cfg.get_param_keys(self.config_name) + ['inner_fold']
param_keys.remove('random_seed')
# not really take the mean because all groups just have one element here
mean_results = fold_results_df.fillna("").groupby(param_keys).mean()
writer = SummaryWriter(config['tensorboard_dir'])
for param_values in mean_results.index:
params = dict(zip(param_keys, list(param_values)))
results = mean_results.loc[param_values].to_dict()
config_id = round(results["config_id"])
inner_fold = params['inner_fold']
results_selection = {cfg.tensorboard_hparams_metrics[key]: value for key, value in results.items() if key in list(cfg.tensorboard_hparams_metrics.keys())}
params_selection = {key: value for key, value in params.items() if key in variable_params}
# writer.add_hparams(params_selection, results_selection,
# run_name=f'{self.experiment_name}/config_{config_id}/cv_{outer_fold}_mean')
writer.add_hparams(params_selection, results_selection,
run_name=f'{self.experiment_name}/config_{config_id}/cv_{outer_fold}_{inner_fold}')
writer.add_text('Experiment name', self.experiment_name, global_step=0)
writer.close() |
import { useEffect, useState } from 'react';
const useAPI = <T>(url: string) => {
const [data, setData] = useState<T | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<unknown>(null);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
const response = await fetch(url);
if (!response.ok) {
setError('No data')
}
const responseData = await response.json() as T;
return responseData
};
fetchData()
.then((response) => {
if (response) {
setData(response)
}
})
.catch((error) => {
setError(error)
})
.finally(() => setIsLoading(false));
}, [url]);
return { data, isLoading, error };
};
export { useAPI }; |
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { NavbarComponent } from './components/NavBarComponent/navbar.component';
import { JumbotronComponent } from './components/JumbotronComponent/jumbotron.component';
import { HomeComponent } from './components/pages/home.component';
import { AboutComponent } from './components/pages/about.component';
import { RouterModule, Routes } from '@angular/router';
const appRoutes: Routes = [
{ path: '', component: HomeComponent},
{ path: 'about', component: AboutComponent}
];
@NgModule({
imports: [ BrowserModule, RouterModule.forRoot(appRoutes) ],
declarations: [ AppComponent, NavbarComponent, JumbotronComponent, HomeComponent, AboutComponent ],
bootstrap: [ AppComponent, NavbarComponent, JumbotronComponent]
})
export class AppModule { } |
# Configuring AMQ DR
* [Prerequisites](#prerequisites)
* [Install Terraform](#install-terraform)
* [Verify Terraform installation](#verify-terraform-installation)
* [Install Ansible](#install-ansible)
* [Verify Ansible installation](#verify-ansible-installation)
* [Install Ansible collections](#install-ansible-collections)
* [Checkout config repo](#checkout-setup-config)
* [Download AMQ archive](#download-rhamq-archive-file)
* [Create API key](#create-api-key-for-ibm-cloud)
* [Create SSH key](#create-ssh-key-to-work-with-vpc)
* [Setup Region 1](#setup-region-1)
* [Prerequisites](#prerequisites---region-1)
* [Setup API key config](#setup-config-for-ibm-api-key)
* [Setup Region 1 infrastructure](#setup-region-1-infrastructure)
* [Setup Region 2](#setup-region-2)
* [Prerequisites](#prerequisites---region-2)
* [Setup Region 2 infrastructure](#setup-region-2-infrastructure)
* [Transit Gateway setup](#global-transit-gateway-setup)
* [Prerequisites](#prerequisites---transit-gateway-setup)
* [Configure Region 1/2 with Ansible](#configure-region-12---ansible)
* [Prerequisites](#prerequisites---ansible-config)
* [Capture public IP](#capture-public-ip---manual-step)
* [Create vault password](#create-vault-password---manual-step)
* [Configure regions](#configure-regions)
* [Run performance tests using JMeter](#run-performance-tests)
* [Prerequisites](#prerequisites---install-jmeter)
* [Run tests](#run-tests)
* [Other Ansible plays](#other-ansible-plays)
* [Prerequisites](#prerequisites---other-ansible-plays)
* [Reset regions](#reset-regions)
* [Stop brokers and routers](#stop-brokersrouters)
* [Run brokers and routers](#run-brokersrouters)
* [Purge queue](#purge-queue)
* [Start/stop instances](#startstop-the-instances)
* [Prerequisites](#prerequisites---startstop-instances)
* [Start stopped instances](#start-instances---region-12)
* [Stop running instances](#stop-instances---region-12)
* [Destroy the resources](#destroy-the-resources)
* [Prerequisites](#prerequisites---destroy-resources)
* [Global Transit Gateway](#destroy-global-transit-gateway)
* [Region 1](#destroy-resources---region-1)
* [Region 2](#destroy-resources---region-2)
* [Instance info](#instance-info)
<details>
<summary>TMP section for setting up cluster 1 in Toronto region</summary>
* [TMP - Setup Region 1](#setup-region-1---tmp)
* [TMP - Prerequisites](#prerequisites---region-1---tmp)
* [TMP - Setup API key config](#setup-config-for-ibm-api-key---tmp)
* [TMP - Setup Region 1 infrastructure](#setup-region-1-infrastructure---tmp)
* [TMP - Configure Region 1 with Ansible](#configure-region-1---ansible---tmp)
* [TMP - Create vault password](#create-vault-password---tmp)
* [TMP - Configure region](#configure-region---tmp)
* [TMP - Destroy the resources](#destroy-the-resources---tmp)
* [TMP - Region 1](#destroy-resources---region-1---tmp)
</details>
* [References](#references)
Configuring AMQ advanced topology for DR, in **IBM Cloud**, following setup was used:
* Region 1 (Toronto)
* Two clusters
* Hub Router
* Routers to connect to live brokers in each clusters
* Hub and other routers are part of hub and spoke topology
* Two sets of Live/Backup brokers running in different availability zones (AZs) in each cluster
* Local Transit Gateway to allow inter-VPC communication
* Region 2 (Dallas)
* Two clusters
* Hub Router
* Routers to connect to live brokers in each clusters
* Hub and other routers are part of hub and spoke topology
* Two sets of Live/Backup brokers running in different availability zones (AZs) in each cluster
* Local Transit Gateway to allow inter-VPC communication
* Global Transit Gateway
* This is to allow the following inter-region communication:
* Between region1.cluster1 and region2.cluster1
* Between region1.cluster2 and region2.cluster2
## Prerequisites
### Install Terraform
Please follow instructions to [install Terraform](https://learn.hashicorp.com/tutorials/terraform/install-cli)
for your platform
### Verify Terraform installation
Run `terraform -help` command to verify that `terraform` is installed correctly
### Install Ansible
Please follow instructions to [install Ansible](https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html)
for your platform
### Verify Ansible installation
Run `ansible --version` command to verify that `ansible` is installed correctly
### Install Ansible collections
Install the following Ansible collections for configuring the instances by running following commands:
```shell
ansible-galaxy collection install ansible.posix community.general
```
* `ansible.posix` is needed for mount/unmount
* `community.general` is needed for subscription
### Checkout Setup config
Clone this repo to setup brokers/routers in IBM Cloud:
* `git clone https://github.com/RHEcosystemAppEng/amq-cob.git`
* Open up a terminal and run following commands
```shell
cd amq-cob
MAIN_CONFIG_DIR=`pwd`
```
### Download RHAMQ archive file
* Download RedHat AMQ by following step at [Download AMQ Broker](https://access.redhat.com/documentation/en-us/red_hat_amq/2021.q3/html/getting_started_with_amq_broker/installing-broker-getting-started#downloading-broker-archive-getting-started)
* Name the downloaded zip file `amq-broker-7.9.0-bin.zip` if it's not already named that
* Copy the downloaded AMQ archive to `$MAIN_CONFIG_DIR/ansible/roles/setup_nfs_server/files` directory
### Create API key for IBM CLoud
* Create a new API key by following instructions at [Create API key](https://cloud.ibm.com/docs/account?topic=account-userapikey&interface=ui)
* Save the API key on your system as you'll need it later on to run Terraform config
* _Please skip these steps if an API key is already created_
### Create SSH key to work with VPC
* Create a new SSH key by following instructions at [Create SSH key](https://cloud.ibm.com/docs/vpc?topic=vpc-ssh-keys)
* _Please skip these steps if a SSH key is already created and added to the account_
<br>
## Setup Region 1
Region 1 is setup in **Toronto** that has two clusters:
* **Cluster1** - consisting of following four brokers:
* `broker01` - live/primary
* `broker02` - backup of broker01
* `broker03` - live/primary
* `broker04` - backup of broker03
* **Cluster2** - consisting of following four brokers:
* `broker05` - live/primary
* `broker06` - backup of broker05
* `broker07` - live/primary
* `broker08` - backup of broker07
As part of cluster1 config, following interconnect routers are also created and setup (in the same VPC):
* router01 - Hub router - accepts connections from consumers/producers
* router02 - Spoke router - connects to live brokers in Cluster1 and also to Hub router (router01)
As part of cluster2 config, following interconnect router is also created and setup (in the same VPC):
* router03 - Spoke router - connects to live brokers in Cluster2 and also to Hub router (router01) that is part of
the config for Cluster1
### Prerequisites - Region 1
* _`MAIN_CONFIG_DIR` environment variable should be setup as part of [Checkout config](#checkout-setup-config) step_
<br>
### Setup config for IBM API key
* Create a file named `terraform.tfvars`, _in `$MAIN_CONFIG_DIR/terraform-ibm/toronto` directory_, with following content:
```shell
ibmcloud_api_key = "<YOUR_IBM_CLOUD_API_KEY>"
ssh_key = "<NAME_OF_YOUR_SSH_KEY>"
```
_Substitute with your actual IBM Cloud API key here_
<br>
### Setup Region 1 infrastructure
* Terraform is used to setup the infrastructure for region1. Perform infrastructure setup of region 1
(cluster1/cluster2) by running following commands
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/toronto
terraform init
terraform apply -auto-approve \
-var PREFIX="cob-test" \
-var CLUSTER1_PRIVATE_IP_PREFIX="10.70" \
-var CLUSTER2_PRIVATE_IP_PREFIX="10.71"
```
* _All resources created will have the PREFIX provided in the last command_
* Above command will take around 5-7 minutes and should create following resources:
* **VPC**: `cob-test-amq-vpc-ca-tor-1`
* Subnets:
* `cob-test-vpc-ca-tor-subnet-01-ca-tor-1`
* `cob-test-vpc-ca-tor-subnet-02-ca-tor-2`
* `cob-test-vpc-ca-tor-subnet-03-ca-tor-3`
* Security groups named:
* `cob-test-vpc-ca-tor-sec-grp-01`
* This security group adds an inbound rule for ssh and ping
* `cob-test-vpc-ca-tor-sec-grp-02`
* This security group adds inbound rules to allow access to following ports:
* `5672` - AMQP broker amqp accepts connection on this port
* `8161` - AMQ console listens on this port
* `61616` - AMQ broker artemis accepts connection on this port
* `cob-test-vpc-ca-tor-sec-grp-03`
* Adds an inbound rule on port `5773` that will be used by the Hub router to listen for incoming connections
* VSIs (Virtual Server Instance):
* NFS server: `cob-test-ca-tor-1-nfs-server-01`
* Broker01: `cob-test-broker01-live1`
* Broker02: `cob-test-broker02-bak1`
* Broker03: `cob-test-broker03-live2`
* Broker04: `cob-test-broker04-bak2`
* Router01 (hub): `cob-test-hub-router1`
* Router02 (spoke): `cob-test-spoke-router2`
* Floating IPs (Public IPs) for each of the above VSI (Virtual Server Instance)
* **VPC**: `cob-test-amq-vpc-ca-tor-2`
* Subnets:
* `cob-test-vpc-ca-tor-subnet-01-ca-tor-1`
* `cob-test-vpc-ca-tor-subnet-02-ca-tor-2`
* `cob-test-vpc-ca-tor-subnet-03-ca-tor-3`
* Security groups named:
* `cob-test-vpc-ca-tor-sec-grp-01`
* This security group adds an inbound rule for ssh and ping
* `cob-test-vpc-ca-tor-sec-grp-02`
* This security group adds inbound rules to allow access to following ports:
* `5672` - AMQP broker amqp accepts connection on this port
* `8161` - AMQ console listens on this port
* `61616` - AMQ broker artemis accepts connection on this port
* `cob-test-vpc-ca-tor-sec-grp-03`
* Adds an inbound rule on port `5773` that will be used by the Hub router to listen for incoming connections
* VSIs (Virtual Server Instance):
* NFS server: `cob-test-ca-tor-2-nfs-server-02`
* Broker01: `cob-test-broker05-live3`
* Broker02: `cob-test-broker06-bak3`
* Broker03: `cob-test-broker07-live4`
* Broker04: `cob-test-broker08-bak4`
* Router03 (spoke): `cob-test-spoke-router3`
* Floating IPs (Public IPs) for each of the above VSI (Virtual Server Instance)
* **Local Transit Gateway**
* `cob-test-ca-tor-local-01`
* Facilitates communications between Hub router (router 1) and Spoke routers (router 2 and 3).
Spoke router (router 3) is running in a different VPC than the Hub router
* _Purpose of the Local Transit Gateway is to allow communications between the Hub router and spoke routers, within same region_
<br>
## Setup Region 2
Region 1 is setup in **Dallas** that has two clusters:
* **Cluster1** - consisting of following four brokers:
* `broker01` - live/primary
* `broker02` - backup of broker01
* `broker03` - live/primary
* `broker04` - backup of broker03
* **Cluster2** - consisting of following four brokers:
* `broker05` - live/primary
* `broker06` - backup of broker05
* `broker07` - live/primary
* `broker08` - backup of broker07
As part of cluster1 config, following interconnect routers are also created and setup (in the same VPC):
* router01 - Hub router - accepts connections from consumers/producers
* router02 - Spoke router - connects to live brokers in Cluster1 and also to Hub router (router01)
As part of cluster2 config, following interconnect router is also created and setup (in the same VPC):
* router03 - Spoke router - connects to live brokers in Cluster2 and also to Hub router (router01) that is part of
the config for Cluster1
### Prerequisites - Region 2
* _`MAIN_CONFIG_DIR` environment variable should be setup as part of [Checkout config](#checkout-setup-config) step_
* IBM API key should have been setup as part of [setting up API key config](#setup-config-for-ibm-api-key)
* Make sure the ssh key for Region 2 VPC is created as part of [create SSH key](#create-ssh-key-to-work-with-vpc)
### Setup Region 2 infrastructure
* Terraform is used to setup the infrastructure for region1. Perform setup of region 2 (cluster1/cluster2)
by running following commands
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/dallas
cp $MAIN_CONFIG_DIR/terraform-ibm/toronto/terraform.tfvars .
terraform init
terraform apply -auto-approve \
-var PREFIX="cob-test" \
-var CLUSTER1_PRIVATE_IP_PREFIX="10.75" \
-var CLUSTER2_PRIVATE_IP_PREFIX="10.76"
```
* _All resources created will have the PREFIX provided in the last command_
* Above command will take around 4-5 minutes and should create following resources:
* **VPC**: `cob-test-amq-vpc-us-south-1`
* Subnets:
* `cob-test-vpc-us-south-subnet-01-us-south-1`
* `cob-test-vpc-us-south-subnet-02-us-south-2`
* `cob-test-vpc-us-south-subnet-03-us-south-3`
* Security groups named:
* `cob-test-vpc-us-south-sec-grp-01`
* This security group adds an inbound rule for ssh and ping
* `cob-test-vpc-us-south-sec-grp-02`
* This security group adds inbound rules to allow access to following ports:
* `5672` - AMQP broker amqp accepts connection on this port
* `8161` - AMQ console listens on this port
* `61616` - AMQ broker artemis accepts connection on this port
* `cob-test-vpc-us-south-sec-grp-03`
* Adds an inbound rule on port `5773` that will be used by the Hub router to listen for incoming connections
* VSIs (Virtual Server Instance):
* NFS server: `cob-test-us-south-1-nfs-server-01`
* Broker01: `cob-test-broker01-live1`
* Broker02: `cob-test-broker02-bak1`
* Broker03: `cob-test-broker03-live2`
* Broker04: `cob-test-broker04-bak2`
* Router01 (hub): `cob-test-hub-router1`
* Router02 (spoke): `cob-test-spoke-router2`
* Floating IPs (Public IPs) for each of the above VSI (Virtual Server Instance)
* **VPC**: `cob-test-amq-vpc-us-south-2`
* Subnets:
* `cob-test-vpc-us-south-subnet-01-us-south-1`
* `cob-test-vpc-us-south-subnet-02-us-south-2`
* `cob-test-vpc-us-south-subnet-03-us-south-3`
* Security groups named:
* `cob-test-vpc-us-south-sec-grp-01`
* This security group adds an inbound rule for ssh and ping
* `cob-test-vpc-us-south-sec-grp-02`
* This security group adds inbound rules to allow access to following ports:
* `5672` - AMQP broker amqp accepts connection on this port
* `8161` - AMQ console listens on this port
* `61616` - AMQ broker artemis accepts connection on this port
* `cob-test-vpc-us-south-sec-grp-03`
* Adds an inbound rule on port `5773` that will be used by the Hub router to listen for incoming connections
* VSIs (Virtual Server Instance):
* NFS server: `cob-test-us-south-2-nfs-server-02`
* Broker01: `cob-test-broker05-live3`
* Broker02: `cob-test-broker06-bak3`
* Broker03: `cob-test-broker07-live4`
* Broker04: `cob-test-broker08-bak4`
* Router03 (spoke): `cob-test-spoke-router3`
* Floating IPs (Public IPs) for each of the above VSI (Virtual Server Instance)
* **Local Transit Gateway**
* `cob-test-us-south-local-01`
* Facilitates communications between Hub router (router 1) and Spoke routers (router 2 and 3).
Spoke router (router 3) is running in a different VPC than the Hub router
* _Purpose of the Local Transit Gateway is to allow communications between the Hub router and spoke routers, within same region_
<br>
## Global Transit Gateway setup
This section contains information on setting up transit gateways for communications between:
* Cluster1 and Cluster3 - between different regions
* Cluster2 and Cluster4 - between different regions
### Prerequisites - transit gateway setup
* _`MAIN_CONFIG_DIR` environment variable should be setup as part of [Checkout config](#checkout-setup-config) step_
### Transit Gateway config
* Perform setup of Transit Gateways by running following commands
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/transit-gateway/global
terraform init
cp $MAIN_CONFIG_DIR/terraform-ibm/toronto/terraform.tfvars .
terraform apply -auto-approve -var PREFIX="cob-test"
```
* Above command will take around 5-7 minutes and should create following Global Transit Gateways:
* `cob-test-amq-us-south-ca-tor-1`
* Facilitates communications between Cluster1 (Toronto) and Cluster3 (Dallas)
* _This gateway is located in Dallas_
* `cob-test-amq-ca-tor-us-south-2`
* Facilitates communications between Cluster2 (Toronto) and Cluster4 (Dallas)
* _This gateway is located in Toronto_
<br>
## Configure Region 1/2 - ansible
Ansible is used to configure brokers/routers and NFS server to install required packages as well as running
them. _For this purpose, we need to run two manual steps before we can use ansible to configure the system_
### Prerequisites - Ansible config
* _`MAIN_CONFIG_DIR` environment variable should be setup as part of [Checkout config](#checkout-setup-config) step_
### Capture public IP - Manual step
To configure the instances using ansible, we need to extract the public ip for all the instances first.
* Execute following commands to retrieve public ip for region 1 and 2:
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm
# Command given below will extract the public IP for all the instances running in region 1
./capture_ip_host.sh -r r1 -d toronto -s "_ip" -a
# Command given below will extract the public IP for all the instances running in region 2
./capture_ip_host.sh -r r2 -d dallas -s "_ip" -a
```
Copy the `<hostname>: <ip_address>` output (_between START and END tags_), for each of the above commands,
to `$MAIN_CONFIG_DIR/ansible/variable_override.yml`
### Create vault password - Manual step
* Create a file named `.vault_password` in `$MAIN_CONFIG_DIR/ansible` directory with it contents set to following text
* `password`
* Run following command to set the correct username/password for Red Hat login:
* `ansible-vault edit group_vars/routers/vault`
* _Above command will open up an editor_
* Provide values for following keys (**_This is the Red Hat SSO user/password and not the Mac/Linux user/password_**):
* `redhat_username` (_replace `PROVIDE_CORRECT_USERNAME` with correct username_)
* `redhat_password` (_replace `PROVIDE_CORRECT_PASSWORD` with correct password_)
### SSL Setup
* You can setup Brokers & Routers with SSL and the SSL behavior is determined by the SSL variables in `$MAIN_CONFIG_DIR/ansible/variable_override.yml`.
* In most cases just changing (_enable_ssl_) & (_ssl_generate_ca_) should be sufficient and one can change other variables based on specific requirements.
|Variable|Description|
|-----|-----|
| enable_ssl | Enable SSL config in brokers and routers |
| ssl_generate_ca | Whether to generate CA Certificates. For the very first run of the scripts, set this to true, for subsequent runs you may set this to false for reusing the existing CA certificates.|
| ssl_generate_certs | Whether to generate server certificate. For the very first run of the scripts, set this to true, for subsequent runs you may set this to false for reusing the existing certificates. |
### Configure regions
* Perform configuration setup of cluster1 and cluster2 in region 1/2 by running following commands
```shell
cd $MAIN_CONFIG_DIR/ansible
# Below commands will NOT setup mirroring between the two regions
ansible-playbook -i hosts/hosts.yml playbooks/setup_playbook.yml --extra-vars "@variable_override.yml"
ansible-playbook -i hosts/hosts.yml playbooks/run_broker_n_router_playbook.yml --extra-vars "@variable_override.yml"
```
* Above command(s) will configure following resources:
* `amq_runner` user will be created in all the instances of brokers and routers
* Necessary packages will be installed in the NFS server, brokers and routers
* NFS mount points will be created between brokers and NFS server
* Host entries will be added to the brokers (for NFS server) and spoke routers (for hub router and brokers)
* All the brokers will start
* All the routers will start
## Run performance tests
JMeter is being used to run the performance tests on the AMQ brokers and routers.
### Running Jmeter test using Ansible.
Refer this documentation to [perform Jmeter tests using Ansible](readme-jmeter.md)
## Other ansible plays
Ansible can be used to perform other tasks, e.g. reset the config, stop, run the brokers/routers
### Prerequisites - other ansible plays
* _`MAIN_CONFIG_DIR` environment variable should be setup as part of [Checkout config](#checkout-setup-config) step_
### Reset regions
* One can reset the brokers/routers/nfs server to bring them to the initial state by running following commands:
```shell
cd $MAIN_CONFIG_DIR/ansible
ansible-playbook -i hosts/hosts.yml playbooks/reset_playbook.yml --extra-vars "@variable_override.yml"
```
* Above command(s) will perform following tasks:
* Stop broker instances
* Stop router instances
* Remove installed packages for brokers/routers/nfs server
* Remove host entries
* Remove user/groups that were setup by ansible
* Remove all the user directories and any other directories created as part of ansible setup
### Stop brokers/routers
* To stop the running brokers/routers, execute following commands
```shell
cd $MAIN_CONFIG_DIR/ansible
ansible-playbook -i hosts/hosts.yml playbooks/stop_broker_n_router_playbook.yml --extra-vars "@variable_override.yml"
```
* Above command(s) will perform following tasks:
* Stop broker instances
* Stop router instances
### Run brokers/routers
* To stop the running brokers/routers, execute following commands
```shell
cd $MAIN_CONFIG_DIR/ansible
ansible-playbook -i hosts/hosts.yml playbooks/run_broker_n_router_playbook.yml --extra-vars "@variable_override.yml"
```
* Above command(s) will perform following tasks:
* Run broker instances
* Run router instances
### Purge queue
* While doing performance test the queue might need to be purged. There are two ways to do so:
1. Using ansible scripts:
```shell
cd $MAIN_CONFIG_DIR/ansible
ansible-playbook -i hosts/hosts.yml playbooks/purge_queue_playbook.yml --extra-vars "@variable_override.yml"
```
2. **TODO - will be provided by Kamlesh**
* Above command(s) will purge `exampleQueue` on all the live AMQ brokers in region 1 and 2.
_The name of the queue can be overridden from command line by specifying `amq_queue` variable in `variable_override.yml` file_
<br>
<br>
## Start/stop the instances
Sometimes you may need to stop the running instances, or start the instances that are stopped. This section provides
information on that process
### Prerequisites - start/stop instances
* _`MAIN_CONFIG_DIR` environment variable should be setup as part of [Checkout config](#checkout-setup-config) step_
### Start instances - Region 1/2
* To start instances in region 1 and 2, use following commands:
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/start-stop-instance
terraform apply -auto-approve \
-var PREFIX="cob-test" \
-var INSTANCE_ACTION="start" \
-var FORCE_ACTION="false"
```
### Stop instances - Region 1/2
* To perform a graceful shutdown, first execute steps given in [Stop broker and routers](#stop-brokersrouters)
* Stop running instances in region 1 and 2 by perform following commands:
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/start-stop-instance
terraform apply -auto-approve \
-var PREFIX="cob-test" \
-var INSTANCE_ACTION="stop" \
-var FORCE_ACTION="false"
```
_Above command will take a few minutes and will either start or stop the instances (depending on the action)_
<br>
<br>
## Destroy the resources
This section provides information on how to cleanup / delete the resources that were setup for all the clusters in
the two regions
### Prerequisites - destroy resources
* _`MAIN_CONFIG_DIR` environment variable should be setup as part of [Checkout config](#checkout-setup-config) step_
### Destroy Global Transit Gateway
* To delete the Global Transit Gateway, use following commands:
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/transit-gateway/global
terraform plan -destroy -out=destroy.plan \
-var PREFIX="cob-test"
terraform apply destroy.plan
```
### Destroy resources - Region 1
* To delete resources setup in region 1 (cluster 1/2), use following commands:
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/toronto
terraform plan -destroy -out=destroy.plan \
-var PREFIX="cob-test" \
-var CLUSTER1_PRIVATE_IP_PREFIX="10.70" \
-var CLUSTER2_PRIVATE_IP_PREFIX="10.71"
terraform apply destroy.plan
```
### Destroy resources - Region 2
* To delete resources setup in region 2 (cluster 1/2), use following commands:
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/dallas
terraform plan -destroy -out=destroy.plan \
-var PREFIX="cob-test" \
-var CLUSTER1_PRIVATE_IP_PREFIX="10.75" \
-var CLUSTER2_PRIVATE_IP_PREFIX="10.76"
terraform apply destroy.plan
```
<hr style="height:1px"/>
<br>
<br>
## Instance info
This section provides region / zone / private IP address for each of the instance setup in this project
<br>
| Region | Cluster | VPC info | Instance info | Private IP | Zone info | Description |
| ------- | -------- | ----------------------------- | ------------- | -------------- | ---------- | ----------- |
| Toronto | Cluster1 | `cob-test-amq-vpc-ca-tor-1` | NFS | `10.70.0.50` | ca-tor-1 | NFS server in Toronto zone 1 |
| | | | Broker-01 | `10.70.0.51` | ca-tor-1 | Live1 broker in Toronto zone 1 |
| | | | Broker-02 | `10.70.64.51` | ca-tor-2 | Backup1 (of Broker 01) broker in Toronto zone 2 |
| | | | Broker-03 | `10.70.128.51` | ca-tor-3 | Live2 broker in Toronto zone 3 |
| | | | Broker-04 | `10.70.0.52` | ca-tor-1 | Backup2 (backup of Broker 03) broker in Toronto zone 1 |
| | | | Router-01 | `10.70.128.100` | ca-tor-3 | Hub router in Toronto zone 3 |
| | | | Router-02 | `10.70.64.100` | ca-tor-2 | Spoke router in Toronto zone 2 - connecting to Cluster1 |
| | Cluster2 | `cob-test-amq-vpc-ca-tor-2` | NFS | `10.71.0.50` | ca-tor-1 | NFS server in Toronto zone 1 |
| | | | Broker-05 | `10.71.128.61` | ca-tor-3 | Live3 broker in Toronto zone 3 |
| | | | Broker-06 | `10.71.64.61` | ca-tor-2 | Backup3 (of Broker 05) broker in Toronto zone 2 |
| | | | Broker-07 | `10.71.0.61` | ca-tor-1 | Live4 broker in Toronto zone 1 |
| | | | Broker-08 | `10.71.128.62` | ca-tor-3 | Backup4 (backup of Broker 07) broker in Toronto zone 1 |
| | | | Router-03 | `10.71.0.100` | ca-tor-1 | Spoke router in Toronto zone 1 - connecting to Cluster2 |
| Dallas | Cluster1 | `cob-test-amq-vpc-us-south-1` | NFS | `10.75.0.50` | us-south-1 | NFS server in Dallas zone 1 |
| | | | Broker-01 | `10.75.0.51` | us-south-1 | Live5 broker in Dallas zone 1 |
| | | | Broker-02 | `10.75.64.51` | us-south-2 | Backup5 broker (backup of Broker 09) in Dallas zone 2 |
| | | | Broker-03 | `10.75.128.51` | us-south-3 | Live5 broker in Dallas zone 3 |
| | | | Broker-04 | `10.75.0.52` | us-south-1 | Backup6 broker (backup of Broker 11) in Dallas zone 1 |
| | | | Router-01 | `10.75.128.100` | us-south-3 | Hub router in Dallas zone 3 |
| | | | Router-02 | `10.75.64.100` | us-south-2 | Spoke router in Dallas zone 2 - connecting to Cluster1 |
| | Cluster4 | `cob-test-amq-vpc-us-south-2` | NFS | `10.76.64.60` | us-south-1 | NFS server in Dallas zone 2 |
| | | | Broker-05 | `10.76.128.61` | us-south-1 | Live7 broker in Dallas zone 3 |
| | | | Broker-06 | `10.76.0.61` | us-south-2 | Backup7 broker (backup of Broker 13) in Dallas zone 1 |
| | | | Broker-07 | `10.76.64.61` | us-south-3 | Live8 broker in Dallas zone 2 |
| | | | Broker-08 | `10.76.0.62` | us-south-1 | Backup8 broker (backup of Broker 15) in Dallas zone 1 |
| | | | Router-03 | `10.76.0.100` | us-south-2 | Spoke router in Dallas zone 1 - connecting to Cluster4 |
## Setup Region 1 - tmp
Region 1 is setup in **Toronto** that has two clusters:
* **Cluster1** - consisting of following four brokers:
* `broker01` - live/primary
* `broker02` - backup of broker01
* `broker03` - live/primary
* `broker04` - backup of broker03
As part of cluster1 config, following interconnect routers are also created and setup (in the same VPC):
* router01 - Hub router - accepts connections from consumers/producers
* router02 - Spoke router - connects to live brokers in Cluster1 and also to Hub router (router01)
### Prerequisites - Region 1 - tmp
* _`MAIN_CONFIG_DIR` environment variable should be setup as part of [Checkout config](#checkout-setup-config) step_
<br>
### Setup config for IBM API key - tmp
* Create a file named `terraform.tfvars`, _in `$MAIN_CONFIG_DIR/terraform-ibm/toronto-vpc1` directory_, with following content:
```shell
ibmcloud_api_key = "<YOUR_IBM_CLOUD_API_KEY>"
ssh_key = "<NAME_OF_YOUR_SSH_KEY>"
```
_Substitute with your actual IBM Cloud API key here_
<br>
### Setup Region 1 infrastructure - tmp
* Terraform is used to setup the infrastructure for region1. Perform infrastructure setup of region 1
(cluster1/cluster2) by running following commands
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/toronto-vpc1
terraform init
terraform apply -auto-approve \
-var PREFIX="appeng-381" \
-var CLUSTER1_PRIVATE_IP_PREFIX="10.101" \
-var CLUSTER2_PRIVATE_IP_PREFIX="10.102"
```
* _All resources created will have the PREFIX provided in the last command_
* Above command will take around 5-7 minutes and should create following resources:
* **VPC**: `appeng-381-amq-vpc-ca-tor-1`
* Subnets:
* `appeng-381-vpc-ca-tor-subnet-01-ca-tor-1`
* `appeng-381-vpc-ca-tor-subnet-02-ca-tor-2`
* `appeng-381-vpc-ca-tor-subnet-03-ca-tor-3`
* Security groups named:
* `appeng-381-vpc-ca-tor-sec-grp-01`
* This security group adds an inbound rule for ssh and ping
* `appeng-381-vpc-ca-tor-sec-grp-02`
* This security group adds inbound rules to allow access to following ports:
* `5672` - AMQP broker amqp accepts connection on this port
* `8161` - AMQ console listens on this port
* `61616` - AMQ broker artemis accepts connection on this port
* `appeng-381-vpc-ca-tor-sec-grp-03`
* Adds an inbound rule on port `5773` that will be used by the Hub router to listen for incoming connections
* VSIs (Virtual Server Instance):
* NFS server: `appeng-381-ca-tor-1-nfs-server-01`
* Broker01: `appeng-381-broker01-live1`
* Broker02: `appeng-381-broker02-bak1`
* Broker03: `appeng-381-broker03-live2`
* Broker04: `appeng-381-broker04-bak2`
* Router01 (hub): `appeng-381-hub-router1`
* Router02 (spoke): `appeng-381-spoke-router2`
* Floating IPs (Public IPs) for each of the above VSI (Virtual Server Instance)
<br>
### Configure Region 1 - ansible - tmp
Ansible is used to configure brokers/routers and NFS server to install required packages as well as running
them.
#### Create vault password - tmp
* Follow the steps given in [Create vault password](#create-vault-password)
#### Configure region - tmp
* Perform configuration setup of cluster1 in region 1 by running following commands
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm
# Command given below will extract the public IP for all the instances running in VPC1 (cluster1)
./capture_ip_host.sh -r r1 -d toronto-vpc1 -s "_ip" -a
```
Copy the `<hostname>: <ip_address>` output (_between START and END tags_) to `$MAIN_CONFIG_DIR/ansible/variable_override.yml`
* Perform configuration setup of cluster1 in region 1 by running following commands
```shell
cd $MAIN_CONFIG_DIR/ansible
# Below commands will NOT setup mirroring between the two regions
ansible-playbook -i hosts-r1_vpc1.yml setup_playbook.yml --extra-vars "@variable_override.yml"
ansible-playbook -i hosts-r1_vpc1.yml run_broker_n_router_playbook.yml --extra-vars "@variable_override.yml"
```
* Above command(s) will configure following resources:
* `amq_runner` user will be created in all the instances of brokers and routers
* Necessary packages will be installed in the NFS server, brokers and routers
* NFS mount points will be created between brokers and NFS server
* Host entries will be added to the brokers (for NFS server) and spoke routers (for hub router and brokers)
* All the brokers will start
* All the routers will start
<br>
<br>
## Destroy the resources - tmp
This section provides information on how to cleanup / delete the resources that were setup for all the clusters in
the Toronto region (cluster 1)
### Destroy resources - Region 1 - tmp
* To delete resources setup in region 1 (cluster 1), use following commands:
```shell
cd $MAIN_CONFIG_DIR/terraform-ibm/toronto-vpc1
terraform plan -destroy -out=destroy.plan \
-var PREFIX="appeng-381" \
-var CLUSTER1_PRIVATE_IP_PREFIX="10.101" \
-var CLUSTER2_PRIVATE_IP_PREFIX="10.102"
terraform apply destroy.plan
```
## References
* [Hub and spoke router topology setup](https://github.com/RHEcosystemAppEng/amq-cob/tree/master/manualconfig/routertopology/fanout)
* [AMQ Interconnect Router - Hub and Spoke network](https://access.redhat.com/documentation/en-us/red_hat_amq/7.4/html-single/using_amq_interconnect/index#connecting-routers-router)
* [Terraform config location](https://github.com/RHEcosystemAppEng/amq-cob/tree/master/automation/terraform)
* [Ansible config location](https://github.com/RHEcosystemAppEng/amq-cob/tree/master/automation/ansible) |
/*
This a problem from "Problem of the day" of GeeksForGeeks. Date - 23 sep, 2023
Given an array A of n positive numbers. The task is to find the first equilibrium point in an array. Equilibrium point in an array is a position such that the sum of elements before it is equal to the sum of elements after it.
Note: Return equilibrium point in 1-based indexing. Return -1 if no such point exists.
Example 1:
Input:
n = 5
A[] = {1,3,5,2,2}
Output:
3
Explanation:
equilibrium point is at position 3 as sum of elements before it (1+3) = sum of elements after it (2+2).
Example 2:
Input:
n = 1
A[] = {1}
Output:
1
Explanation:
Since there's only element hence its only the equilibrium point.
Your Task:
The task is to complete the function equilibriumPoint() which takes the array and n as input parameters and returns the point of equilibrium.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(1)
Constraints:
1 <= n <= 10^5
1 <= A[i] <= 10^9
*/
//{ Driver Code Starts
#include <iostream>
using namespace std;
// } Driver Code Ends
class Solution{
public:
// Function to find equilibrium point in the array.
// a: input array
// n: size of array
int equilibriumPoint(long long a[], int n)
{
if(n==1)
return 1;
else if(n==2)
return -1;
else
{
int r_sum = 0;
int l_sum = 0;
for(int i=1;i<n;i++)
r_sum += a[i];
for(int i=1;i<n-1;i++)
{
l_sum += a[i-1];
r_sum -= a[i];
if(l_sum == r_sum)
return i+1;
}
return -1;
}
}
};
//{ Driver Code Starts.
int main() {
long long t;
//taking testcases
cin >> t;
while (t--) {
long long n;
//taking input n
cin >> n;
long long a[n];
//adding elements to the array
for (long long i = 0; i < n; i++) {
cin >> a[i];
}
Solution ob;
//calling equilibriumPoint() function
cout << ob.equilibriumPoint(a, n) << endl;
}
return 0;
}
// } Driver Code Ends |
import { useState, useCallback, memo } from "react";
import { useNavigate } from "react-router-dom";
import CryptoJS from "crypto-js";
import { useDispatch } from "react-redux";
import { loginUser } from "../../redux/feature/userSlice";
import { Formik, Form, Field, ErrorMessage, FormikHelpers } from "formik";
import * as Yup from "yup";
import { Usertype, LoginFormValues } from "../../types/Types";
import { toast, Slide } from "react-toastify";
import Show from "../../assets/showpassword.svg";
import Hide from "../../assets/hidepassword.svg";
// Define validation schema using Yup
const validationSchema = Yup.object().shape({
email: Yup.string()
.required("Email is required")
.email("Invalid email address"),
password: Yup.string()
.required("Password is required")
.min(8, "Password must be at least 8 characters long"),
});
export function decryption(password: string): string {
const decrypted = CryptoJS.AES.decrypt(
password,
import.meta.env.VITE_SECRET_KEY
).toString(CryptoJS.enc.Utf8);
return decrypted;
}
function LoginForm() {
const navigate = useNavigate();
const dispatch = useDispatch();
const [showPassword, setShowPassword] = useState(false);
// Function to navigate to signup page
const navigateToSignup = useCallback(() => {
navigate("/signup");
}, [navigate]);
// Toggle password visibility
const handleTogglePassword = useCallback(() => {
setShowPassword((prevShowPassword) => !prevShowPassword);
}, [showPassword]);
// Handle form submission
const handleSubmit = useCallback(
(
values: LoginFormValues,
{ resetForm }: FormikHelpers<LoginFormValues>
) => {
// Get stored users from local storage
const storedUsers = localStorage.getItem("users");
const users: Usertype[] = storedUsers ? JSON.parse(storedUsers) : [];
// Check if the user exists
const isRegister: Usertype[] = users!.filter(
(user: Usertype) => user.email === values.email
);
if (!isRegister) {
// User does not exist, show error toast
toast.error("User Does Not Exist", {
position: toast.POSITION.TOP_RIGHT,
transition: Slide,
autoClose: 1000,
});
return;
} else {
// User exists, check password validity
const user = users.filter(
(user: Usertype) =>
user.email === values.email &&
decryption(user.password) === values.password
);
if (user.length !== 0) {
// Password is correct, dispatch login action, navigate to home, and reset form
dispatch(loginUser(values));
navigate("/");
resetForm();
} else {
// Wrong password, show warning toast
toast.warn("Wrong Password", {
position: toast.POSITION.TOP_RIGHT,
transition: Slide,
autoClose: 1000,
});
navigate("/login");
}
}
},
[dispatch, navigate]
);
return (
<div className="login-form">
<div className="login">Login</div>
<Formik
initialValues={{ email: "", password: "" }}
validationSchema={validationSchema}
onSubmit={handleSubmit}
>
<Form className="main-form">
<div className="form-field">
<label htmlFor="email" className="label">
Email
</label>
<Field
type="text"
id="email"
placeholder="example@domain.com"
name="email"
className="input-field"
/>
<ErrorMessage name="email" component="div" className="error-msg" />
</div>
<div className="form-field">
<label htmlFor="password" className="label">
Password
</label>
<div className="password-field">
<Field
type={showPassword ? "text" : "password"}
id="password"
placeholder="Must have atleast 8 character"
name="password"
className="input-field"
/>
<img
height={20}
width={20}
src={showPassword ? Show : Hide}
onClick={handleTogglePassword}
/>
</div>
<ErrorMessage
name="password"
component="div"
className="error-msg"
/>
</div>
<div className="btns">
<button type="submit" className="loginButton">
Login
</button>
</div>
</Form>
</Formik>
<div>
<div className="signup-text">
Create an account ?
<a onClick={navigateToSignup}>
<span>SignUp</span>
</a>
</div>
</div>
</div>
);
}
export default memo(LoginForm); |
package nl.medify.patientuser.feature_calendar.presentation.make_appointment.vm
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.gms.maps.model.LatLng
import com.prolificinteractive.materialcalendarview.CalendarDay
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import nl.medify.patientuser.feature_calendar.domain.model.DoctorOrCareProvider
import nl.medify.patientuser.feature_calendar.domain.use_case.CalendarUseCases
import nl.medify.patientuser.feature_calendar.presentation.make_appointment.vm.states.AllDoctorsAndCareProvidersOfPatientState
import nl.medify.patientuser.feature_calendar.presentation.make_appointment.vm.states.AvailableTimeSlotsOfParticularDayState
import nl.medify.patientuser.feature_calendar.presentation.make_appointment.vm.states.GeoCodesState
import nl.medify.patientuser.feature_calendar.presentation.make_appointment.vm.states.NotAvailableDaysInThisMonthState
import nl.medify.utilities.util.Resource
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.Month
import javax.inject.Inject
@HiltViewModel
class AppointmentViewModel @Inject constructor(
private val calendarUseCases: CalendarUseCases
) : ViewModel() {
var chosenDateTime: LocalDateTime? = null; private set
var chosenTime: LocalTime? = null; private set
var reasonOfVisit: String? = null; private set
var selectedDoctorOrCareProvider: DoctorOrCareProvider? = null; private set
var chosenDate: LocalDate? = null; private set
var dateToday: LocalDate = LocalDate.now()
var appointmentSuccessfullyCreated: Boolean? = null
fun saveDate(date: LocalDate) { chosenDate = date }
fun saveTime(time: LocalTime) { chosenTime = time; chosenDateTime = chosenTime?.atDate(chosenDate) }
fun saveReasonOfVisit(reason: String) { reasonOfVisit = reason }
fun saveSelectedDoctorOrCareProviderID(doctorOrCareProvider: DoctorOrCareProvider) { selectedDoctorOrCareProvider = doctorOrCareProvider }
private val _allDoctorAndCareProvidersOfPatient = MutableStateFlow(AllDoctorsAndCareProvidersOfPatientState())
var allDoctorAndCareProvidersOfPatient: StateFlow<AllDoctorsAndCareProvidersOfPatientState> = _allDoctorAndCareProvidersOfPatient
private val _notAvailableDaysList = MutableStateFlow(NotAvailableDaysInThisMonthState())
var notAvailableDaysList: StateFlow<NotAvailableDaysInThisMonthState> = _notAvailableDaysList
private val _availableTimeSlots = MutableStateFlow(AvailableTimeSlotsOfParticularDayState())
var availableTimeSlots: StateFlow<AvailableTimeSlotsOfParticularDayState> = _availableTimeSlots
private val _geoCodes = MutableStateFlow(GeoCodesState())
var geoCodes: StateFlow<GeoCodesState> = _geoCodes
fun getAllDoctorsAndCareProvidersOfPatient(id: String) = viewModelScope.launch(Dispatchers.IO) {
calendarUseCases.getAllDoctorsAndCareProvidersOfPatientUseCase.invoke(id).collect {
when (it) {
is Resource.Success -> {
_allDoctorAndCareProvidersOfPatient.value = AllDoctorsAndCareProvidersOfPatientState(allDoctorsAndCareProvidersOfPatient = it.data)
}
is Resource.Loading -> {
_allDoctorAndCareProvidersOfPatient.value = AllDoctorsAndCareProvidersOfPatientState(isLoading = true)
}
is Resource.Error -> {
_allDoctorAndCareProvidersOfPatient.value = AllDoctorsAndCareProvidersOfPatientState(error = it.message ?: "Unexpected error occured.")
}
is Resource.Empty -> {
_allDoctorAndCareProvidersOfPatient.value = AllDoctorsAndCareProvidersOfPatientState(allDoctorsAndCareProvidersOfPatient = ArrayList())
}
else -> {
Log.e(this.javaClass.name, "'it.data' is null")
}
}
}
}
fun postCreateAppointment(patientID: String) = viewModelScope.launch(Dispatchers.IO) {
if (selectedDoctorOrCareProvider?.id?.startsWith("dom-id-gp") == true) {
calendarUseCases.postCreateAppointmentUseCase.invoke(chosenDateTime!!, reasonOfVisit!!, patientID, selectedDoctorOrCareProvider?.id, null)
} else {
calendarUseCases.postCreateAppointmentUseCase.invoke(chosenDateTime!!, reasonOfVisit!!, patientID, null, selectedDoctorOrCareProvider?.id)
}
}
fun getGeoCodes(city: String, street: String, postalcode: String) = viewModelScope.launch(Dispatchers.IO) {
calendarUseCases.getGeoCodesUseCase.invoke(city, street, postalcode).collect {
when (it) {
is Resource.Success -> {
_geoCodes.value = GeoCodesState(geoCode = LatLng(it.data?.get(0)?.lat?.toDouble() ?: 0.0, it.data?.get(0)?.lon?.toDouble() ?: 0.0))
}
is Resource.Loading -> {
_geoCodes.value = GeoCodesState(isLoading = true)
}
is Resource.Error -> {
_geoCodes.value = GeoCodesState(error = it.message ?: "Unexpected error occured.")
}
is Resource.Empty -> {
_geoCodes.value = GeoCodesState(geoCode = LatLng(0.0, 0.0))
}
else -> {
Log.e(this.javaClass.name, "'it.data' is null")
}
}
}
}
fun getNotAvailableDaysInThisMonth(yearNumber: Int, monthNumber: Int, gpId: String) = viewModelScope.launch(Dispatchers.IO) {
calendarUseCases.getNotAvailableDaysInThisMonth.invoke(yearNumber, monthNumber, gpId).collect {
when (it) {
is Resource.Success -> {
_notAvailableDaysList.value = NotAvailableDaysInThisMonthState(notAvailableDaysList = it.data ?: emptyList())
}
is Resource.Loading -> {
_notAvailableDaysList.value = NotAvailableDaysInThisMonthState(isLoading = true)
}
is Resource.Error -> {
_notAvailableDaysList.value = NotAvailableDaysInThisMonthState(error = it.message ?: "Unexpected error occured.")
}
else -> {
Log.e(this.javaClass.name, "'it.data' is null")
}
}
}
}
fun getAvailableTimeSlotsOfParticularDay(yearNumber: Int, monthNumber: Int, monthDay: Int, gpId: String) = viewModelScope.launch(Dispatchers.IO) {
calendarUseCases.getAvailableTimeSlotsOfParticularDay.invoke(yearNumber, monthNumber, monthDay, gpId).collect {
when (it) {
is Resource.Success -> {
_availableTimeSlots.value = AvailableTimeSlotsOfParticularDayState(availableTimeSlots = it.data ?: emptyList())
}
is Resource.Loading -> {
_availableTimeSlots.value = AvailableTimeSlotsOfParticularDayState(isLoading = true)
}
is Resource.Error -> {
_availableTimeSlots.value = AvailableTimeSlotsOfParticularDayState(error = it.message ?: "Unexpected error occured.")
}
else -> {
Log.e(this.javaClass.name, "'it.data' is null")
}
}
}
}
fun findFirstAvailableDay(monthNumber: Month, notAvailableDaysInThisMonth: List<LocalDate>): CalendarDay? {
if(notAvailableDaysInThisMonth.contains(dateToday)) {
val currentMonthLength = monthNumber.length(false)
// +1 because we start from next day. already established in the if() that today is full.
val currentDayOfTheMonth: Int = dateToday.dayOfMonth + 1
for (currentLoopedDay in currentDayOfTheMonth..currentMonthLength)
{
if(!notAvailableDaysInThisMonth.contains(LocalDate.of(dateToday.year, dateToday.monthValue, currentLoopedDay))) {
return CalendarDay.from(dateToday.year, dateToday.monthValue, currentLoopedDay)
}
}
} else {
return CalendarDay.today()
}
return null
}
} |
import React from "react";
import Pet from "./Pet";
import pet from "@frontendmasters/pet";
import { navigate } from "@reach/router";
import Modal from "./Modal";
import Carousel from "./Carousel";
import ErrorBoundary from "./ErrorBoundary";
class Details extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
showModal: false,
};
}
componentDidMount() {
pet.animal(this.props.id).then(({ animal }) => {
this.setState({
name: animal.name,
url: animal.url,
animal: animal.type,
location: `${animal.contact.address.city},${animal.contact.address.state}`,
description: animal.description,
media: animal.photos,
breed: animal.breeds.primary,
loading: false,
});
});
}
toggleModal = () => this.setState({ showModal: !this.state.showModal });
adopt = () => navigate(this.state.url);
render() {
if (this.state.loading) {
return <h1>Loading......</h1>;
}
const {
name,
animal,
breed,
location,
description,
media,
showModal,
} = this.state;
return (
<div className="details">
<Carousel media={media} />
<h1>{name}</h1>
<h2>{`${animal} - ${breed} -${location}`}</h2>
<button onClick={this.toggleModal}>Adopt {name}</button>
<p>{description}</p>
{showModal ? (
<Modal>
<h1>Would you like to adopt {name}?</h1>
<div className="buttons">
<button onClick={this.adopt}>Yes</button>
<button onClick={this.toggleModal}>No, I am a monster</button>
</div>
</Modal>
) : null}
</div>
);
}
}
export default function DetailswithErrorBoundary(props) {
return (
<ErrorBoundary>
<Details {...props} />
</ErrorBoundary>
);
} |
import React, { useRef, useLayoutEffect, useState, useMemo } from "react";
import styled from "styled-components";
const Container = styled.div`
display: flex;
gap: 10px;
background-color: #ffffff;
padding: 20px;
max-width: 1000px;
width: 300px;
position: absolute;
left: ${({ position }) => `${position.x.toString()}px` || "0"};
top: ${({ position }) => `${position.y.toString()}px` || "0"};
transform: ${({
position,
windowWidth,
windowHeight,
widthElem,
heightElem,
}) =>
windowWidth - position.x < widthElem &&
windowHeight - position.y < heightElem
? "translate(-100%, -100%)"
: windowWidth - position.x > widthElem &&
windowHeight - position.y > heightElem
? "translate(-100%, 0)"
: windowWidth - position.x > widthElem &&
windowHeight - position.y < heightElem
? "translate(-100%, -100%)"
: windowWidth - position.x < widthElem &&
windowHeight - position.y > heightElem
? "translate(-100%, 0)"
: "translate(-100%)"};
z-index: 1;
border-radius: 10px;
box-shadow: 0px 5px 10px 0px rgba(0, 0, 0, 0.5);
`;
const TextWrapper = styled.div`
display: flex;
flex-direction: column;
gap: 20px;
`;
const StaffName = styled.h3`
margin: 0;
`;
const Img = styled.img`
object-fit: cover;
width: 100px;
`;
const PersonContainer = (props) => {
const role = useMemo(() => {
switch (props.getStaff.professionKey) {
case "ACTOR":
return "Актер";
case "DIRECTOR":
return "Режессер";
case "DESIGN":
return "Художник";
case "PRODUCER":
return "Продюсер";
case "TRANSLATOR":
return "Переводчик";
case "WRITER":
return "Сценарист";
case "OPERATOR":
return "Оператор";
case "EDITOR":
return "Монтажер";
default:
return "";
}
}, [props.getStaff.professionKey]);
const divBlock = useRef();
const [widthElem, setwidthElem] = useState(0);
const [heightElem, setheightElem] = useState(0);
const [windowWidth, setwindowWidth] = useState(0);
const [windowHeight, setwindowHeight] = useState(0);
useLayoutEffect(() => {
setwidthElem(divBlock.current.offsetWidth);
setheightElem(divBlock.current.offsetHeight);
setwindowWidth(window.innerWidth);
setwindowHeight(window.innerHeight);
}, [widthElem, heightElem, windowWidth, windowHeight]);
return (
<>
{}
<Container
ref={divBlock}
position={props.position}
windowHeight={windowHeight}
windowWidth={windowWidth}
widthElem={widthElem}
heightElem={heightElem}
>
<Img src={props.getStaff.posterUrl} />
<TextWrapper>
<StaffName>
{props.getStaff.nameRu === ""
? props.getStaff.nameEn
: props.getStaff.nameRu}
</StaffName>
<span>
{role}
</span>
</TextWrapper>
</Container>
</>
);
};
export default PersonContainer; |
<!DOCTYPE html>
<html lang="en">
<head>
<title>SUPER CONVERTER</title>
</head>
<body>
<div id="root"></div>
</body>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script src="https://unpkg.com/prop-types@15.7.2/prop-types.js"></script>
<script type="text/babel">
const root = document.getElementById("root");
function Btn({ text = "default", changeValue }) {
// Btn에서 onClick을 함수 인자로 받아 setValue를 실행시킴
return (
<button
onClick={changeValue}
style={{
backgroundColor: "tomato",
color: "white",
padding: "10px 20px",
border: 0,
borderRadius: 10,
}}
>
{text}
</button>
);
}
const MemorizedBtn = React.memo(Btn);
function APP() {
const [value, setValue] = React.useState("Save Changes");
const changeValue = () => setValue("Revert Change");
return (
<div>
<MemorizedBtn text={value} changeValue={changeValue} />
<MemorizedBtn />
</div>
);
}
ReactDOM.render(<APP />, root);
</script>
</html> |
// --- Directions
// Write a program that console logs the numbers
// from 1 to n. But for multiples of three print
// “fizz” instead of the number and for the multiples
// of five print “buzz”. For numbers which are multiples
// of both three and five print “fizzbuzz”.
// --- Example
// fizzBuzz(5);
// 1
// 2
// fizz
// 4
// buzz
function fizzBuzz(n) {
// SOLUTION 1:
// *! Grider's recommended approach
// for (let i = 1; i <= n; i++) {
// if (i % 3 == 0) {
// if (i % 5 == 0) {
// console.log(`fizzbuzz`)
// } else {
// console.log(`fizz`)
// }
// } else if (i % 5 == 0) {
// console.log(`buzz`)
// } else {
// console.log(i)
// }
// }
// SOLUTION 2 : BIT MORE FANCY IF NEEDED
for (let i = 1; i <= n; i++) {
let output = ''
if (i % 3 == 0) output += 'fizz'
if (i % 5 == 0) output += 'buzz'
// if output is empty, print the number itself
console.log(output || i)
}
}
module.exports = fizzBuzz |
import {suite, test} from '@testdeck/mocha';
import {LunarDay, LunarMonth, SolarDay} from '../lib';
import {equal} from 'assert';
@suite
class LunarMonthTest {
@test
test0() {
equal(LunarMonth.fromYm(2359, 7).getName(), '七月');
}
/**
* 闰月
*/
@test
test1() {
equal(LunarMonth.fromYm(2359, -7).getName(), '闰七月');
}
@test
test2() {
equal(LunarMonth.fromYm(2023, 6).getDayCount(), 29);
}
@test
test3() {
equal(LunarMonth.fromYm(2023, 7).getDayCount(), 30);
}
@test
test4() {
equal(LunarMonth.fromYm(2023, 8).getDayCount(), 30);
}
@test
test5() {
equal(LunarMonth.fromYm(2023, 9).getDayCount(), 29);
}
@test
test6() {
equal(LunarMonth.fromYm(2023, 9).getFirstJulianDay().getSolarDay().toString(), '2023年10月15日');
}
@test
test7() {
equal(LunarMonth.fromYm(2023, 1).getSixtyCycle().getName(), '甲寅');
}
@test
test8() {
equal(LunarMonth.fromYm(2023, -2).getSixtyCycle().getName(), '丙辰');
}
@test
test9() {
equal(LunarMonth.fromYm(2023, 3).getSixtyCycle().getName(), '丁巳');
}
@test
test10() {
equal(LunarMonth.fromYm(2024, 1).getSixtyCycle().getName(), '丙寅');
}
@test
test11() {
equal(LunarMonth.fromYm(2023, 12).getSixtyCycle().getName(), '丙寅');
}
@test
test12() {
equal(LunarMonth.fromYm(2022, 1).getSixtyCycle().getName(), '壬寅');
}
@test
test13() {
equal(LunarMonth.fromYm(37, -12).getName(), '闰十二月');
}
@test
test14() {
equal(LunarMonth.fromYm(5552, -12).getName(), '闰十二月');
}
@test
test15() {
equal(LunarMonth.fromYm(2008, 11).next(1).toString(), '农历戊子年十二月');
}
@test
test16() {
equal(LunarMonth.fromYm(2008, 11).next(2).toString(), '农历己丑年正月');
}
@test
test17() {
equal(LunarMonth.fromYm(2008, 11).next(6).toString(), '农历己丑年五月');
}
@test
test18() {
equal(LunarMonth.fromYm(2008, 11).next(7).toString(), '农历己丑年闰五月');
}
@test
test19() {
equal(LunarMonth.fromYm(2008, 11).next(8).toString(), '农历己丑年六月');
}
@test
test20() {
equal(LunarMonth.fromYm(2008, 11).next(15).toString(), '农历庚寅年正月');
}
@test
test21() {
equal(LunarMonth.fromYm(2008, 12).next(-1).toString(), '农历戊子年十一月');
}
@test
test22() {
equal(LunarMonth.fromYm(2009, 1).next(-2).toString(), '农历戊子年十一月');
}
@test
test23() {
equal(LunarMonth.fromYm(2009, 5).next(-6).toString(), '农历戊子年十一月');
}
@test
test24() {
equal(LunarMonth.fromYm(2009, -5).next(-7).toString(), '农历戊子年十一月');
}
@test
test25() {
equal(LunarMonth.fromYm(2009, 6).next(-8).toString(), '农历戊子年十一月');
}
@test
test26() {
equal(LunarMonth.fromYm(2010, 1).next(-15).toString(), '农历戊子年十一月');
}
@test
test27() {
equal(LunarMonth.fromYm(2012, -4).getDayCount(), 29);
}
@test
test28() {
equal(LunarMonth.fromYm(2023, 9).getSixtyCycle().toString(), '癸亥');
}
@test
test29() {
const d = SolarDay.fromYmd(2023, 10, 7).getLunarDay();
equal(d.getMonth().getSixtyCycle().toString(), '壬戌');
equal(d.getMonthSixtyCycle().toString(), '辛酉');
}
@test
test30() {
const d = SolarDay.fromYmd(2023, 10, 8).getLunarDay();
equal(d.getMonth().getSixtyCycle().toString(), '壬戌');
equal(d.getMonthSixtyCycle().toString(), '壬戌');
}
@test
test31() {
const d = SolarDay.fromYmd(2023, 10, 15).getLunarDay();
equal(d.getMonth().getName(), '九月');
equal(d.getMonth().getSixtyCycle().toString(), '癸亥');
equal(d.getMonthSixtyCycle().toString(), '壬戌');
}
@test
test32() {
const d = SolarDay.fromYmd(2023, 11, 7).getLunarDay();
equal(d.getMonth().getSixtyCycle().toString(), '癸亥');
equal(d.getMonthSixtyCycle().toString(), '壬戌');
}
@test
test33() {
const d = SolarDay.fromYmd(2023, 11, 8).getLunarDay();
equal(d.getMonth().getSixtyCycle().toString(), '癸亥');
equal(d.getMonthSixtyCycle().toString(), '癸亥');
}
@test
test34() {
// 2023年闰2月
const m = LunarMonth.fromYm(2023, 12);
equal(m.toString(), '农历癸卯年十二月');
equal(m.next(-1).toString(), '农历癸卯年十一月');
equal(m.next(-2).toString(), '农历癸卯年十月');
}
@test
test35() {
// 2023年闰2月
const m = LunarMonth.fromYm(2023, 3);
equal(m.toString(), '农历癸卯年三月');
equal(m.next(-1).toString(), '农历癸卯年闰二月');
equal(m.next(-2).toString(), '农历癸卯年二月');
equal(m.next(-3).toString(), '农历癸卯年正月');
equal(m.next(-4).toString(), '农历壬寅年十二月');
equal(m.next(-5).toString(), '农历壬寅年十一月');
}
@test
test36() {
const d = SolarDay.fromYmd(1983, 2, 15).getLunarDay();
equal(d.getMonth().getSixtyCycle().toString(), '甲寅');
equal(d.getMonthSixtyCycle().toString(), '甲寅');
}
@test
test37() {
const d = SolarDay.fromYmd(2023, 10, 30).getLunarDay();
equal(d.getMonth().getSixtyCycle().toString(), '癸亥');
equal(d.getMonthSixtyCycle().toString(), '壬戌');
}
@test
test38() {
const d = SolarDay.fromYmd(2023, 10, 19).getLunarDay();
equal(d.getMonth().getSixtyCycle().toString(), '癸亥');
equal(d.getMonthSixtyCycle().toString(), '壬戌');
}
@test
test39() {
const m = LunarMonth.fromYm(2023, 11);
equal(m.toString(), '农历癸卯年十一月');
equal(m.getSixtyCycle().toString(), '乙丑');
}
@test
test40() {
equal(LunarMonth.fromYm(2018, 6).getSixtyCycle().toString(), '己未');
}
@test
test41() {
equal(LunarMonth.fromYm(2017, 12).getSixtyCycle().toString(), '甲寅');
}
@test
test42() {
equal(LunarMonth.fromYm(2018, 1).getSixtyCycle().toString(), '甲寅');
}
@test
test43() {
equal(LunarDay.fromYmd(2018, 6, 26).getMonthSixtyCycle().toString(), '庚申');
}
} |
"use client";
import React, { useState } from "react";
import { projectsData } from "../../lib/data";
import Image from "next/image";
type ProjectProps = (typeof projectsData)[number];
function Project({
title,
description,
tags,
imageUrl,
link,
isLink,
alt,
achievement,
hasAchievement,
}: ProjectProps) {
return (
<div className="mb-6 sm:mb-8 last:mb-0">
<a
href={link}
target={isLink ? "_blank" : "_self"}
rel="noreferrer noopener"
>
<div
className="rounded-xl transition ease-in-out bg-black/0 hover:bg-[#7a92f006] duration-300
relative flex flex-col-reverse sm:flex-row group"
>
<div className="pt-4 pb-7 px-5 sm:w-[50%] sm:pl-5 sm:pr-2 sm:pt-7 sm:flex sm:flex-col sm:h-full group">
<div className="flex text-lg text-slate-200 font-semibold group">
<h3 className="group-hover:text-[#a3b4f6] transition ease-in-out duration-500">
{title}
</h3>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
className={
isLink
? "inline h-4 w-4 ml-2 mt-1 group-hover:translate-x-1 group-hover:-translate-y-0.5 transition ease-in-out duration-500 group-hover:text-[#a3b4f6]"
: "hidden"
}
viewBox="0 0 16 16"
>
<path
fillRule="evenodd"
d="M8.636 3.5a.5.5 0 0 0-.5-.5H1.5A1.5 1.5 0 0 0 0 4.5v10A1.5 1.5 0 0 0 1.5 16h10a1.5 1.5 0 0 0 1.5-1.5V7.864a.5.5 0 0 0-1 0V14.5a.5.5 0 0 1-.5.5h-10a.5.5 0 0 1-.5-.5v-10a.5.5 0 0 1 .5-.5h6.636a.5.5 0 0 0 .5-.5"
/>
<path
fillRule="evenodd"
d="M16 .5a.5.5 0 0 0-.5-.5h-5a.5.5 0 0 0 0 1h3.793L6.146 9.146a.5.5 0 1 0 .708.708L15 1.707V5.5a.5.5 0 0 0 1 0z"
/>
</svg>
</div>
<div
className={
hasAchievement ? "text-sm font-bold" : "hidden"
}
>
{achievement}
</div>
<p className="text-sm mt-2 text-slate-400 sm:mr-5">
{description}
</p>
<ul className="flex flex-wrap mt-4 gap-2">
{tags.map((tag, index) => (
<li
className="bg-[#7a92f0]/15 px-3 py-1 text-[0.65rem] font-medium tracking-wider text-[#a3b4f6] rounded-md"
key={index}
>
{tag}
</li>
))}
</ul>
</div>
<div className="px-4 sm:px-0 sm:w-[50%] group">
<Image
src={imageUrl}
alt={alt}
quality={95}
priority
className="h-[90%] sm:mt-[5%] sm:place-self-center aspect-[5/3] rounded-lg border-2 border-[#7a92f0]/45 sm:border-[#7a92f0]/15 object-cover group-hover:border-[#7a92f0]/50 group-hover:shadow-md group-hover:shadow-indigo-950/20 transition ease-in-out duration-500"
/>
</div>
</div>
</a>
</div>
);
}
export default Project; |
import { MinusSmallIcon, PlusSmallIcon } from "@heroicons/react/24/solid";
import { stripe } from "../../../lib/stripe";
import { formatCurrencyString, useShoppingCart } from "use-shopping-cart";
import Image from "next/image";
import { useState } from "react";
import { toast } from "react-hot-toast";
export default function ProductDetails({ product }) {
const [count, setCount] = useState(1);
const { addItem } = useShoppingCart();
function addItemToCart(event) {
event.preventDefault();
const id = toast.loading(`Added ${count} item${count > 1 ? "'s" : ""} `);
addItem(product, { count });
toast.success(`${count} ${product.name} added!`, { id });
}
return (
<div className="container lg:max-w-screen-lg mx-auto py-12 mt-40">
<div className="flex flex-col md:flex-row justify-between items-center space-y-10 md:space-y-0 md:space-x-12">
<div className="relative w-96 h-96 sm:2-96 sm:h-96 lg:mr-32 ">
<Image
src={product.image}
alt={product.name}
fill
style={{ objectFit: "contain" }}
sizes="100%"
priority
/>
</div>
<div className="lg:w-full md:w-full flex-1 mx-w-md m-4 rounded-md p-6">
<h2 className="text-3xl font-semibold underline">{product.name}</h2>
<div className="mt-6 pt-6">
<p className="text-2xl">
{formatCurrencyString({
value: product.price,
currency: product.currency,
})}
</p>
<div className="mt-4 pt-4">
<div className="mt-1 flex items-center space-x-3">
<span className="text-xl">Quantity:</span>
<button
disabled={count <= 1}
onClick={() => setCount(count - 1)}
className="p-1 rounded-full bg-rose-100 text-rose-500"
>
<MinusSmallIcon className="w-6 h-6 flex-shrink-0" />
</button>
<p className="text-xl">{count}</p>
<button
onClick={() => setCount(count + 1)}
className="p-1 rounded-full bg-green-100 text-green-500"
>
<PlusSmallIcon className="w-6 h-6 flex-shrink-0" />
</button>
</div>
</div>
</div>
<button
onClick={addItemToCart}
className="w-full mt-8 py-2 px-6 bg-red-700 text-white font-semibold disabled:opacity-50 disabled:cursor-not-allowed rounded-md"
>
Add to Cart
</button>
{/* <p className="text-zinc-500 mt-4">Description: </p> */}
<p className="mt-10 text-lg">{product.description}</p>
</div>
</div>
</div>
);
}
export async function getStaticPaths() {
const inventory = await stripe.products.list();
const paths = inventory.data.map((product) => ({
params: { id: product.id },
}));
return {
paths,
fallback: "blocking",
};
}
export async function getStaticProps({ params }) {
const inventory = await stripe.products.list({
expand: ["data.default_price"],
});
const products = inventory.data.map((product) => {
const price = product.default_price;
return {
currency: price.currency,
id: product.id,
name: product.name,
price: price.unit_amount,
image: product.images[0],
description: product.description,
};
});
const product = products.find((product) => product.id === params.id);
return {
props: {
product,
},
revalidate: 60 * 30,
};
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.