prompt
stringlengths 22
383k
| prompt_id
stringlengths 32
32
| index
int64 0
500
| annotator
stringclasses 11
values | timestamp
timestamp[s] | rating
stringclasses 2
values | tags
sequence |
---|---|---|---|---|---|---|
what can I adjust on this blade file, please provide me a table format showing current code new code and the justificaiton for the change
Demographic Information
<hr />
<div>
<div>
<div>
Are you eligible to work in the U.S.?
</div>
</div>
<div>
<div>
What language do you speak at home?
@foreach (MyCareerAdvisor\Language::orderBy('name')->get() as $language)
@endforeach
</div>
</div>
</div>
<div>
<div>
<div>
Race
@foreach (MyCareerAdvisor\Race::all() as $race)
@endforeach
</div>
</div>
@if(\MyCareerAdvisor\Setting::where('name', 'enable_latino')->first()->value)
<div>
<div>
Latino or Hispanic Heritage?
</div>
</div>
@endif
</div>
<h2>Educational Background</h2>
<hr />
<div>
<div>
<div>
Highest Grade Completed
@foreach (MyCareerAdvisor\EducationLevel::all() as $education)
@endforeach
</div>
</div>
<div>
<div>
High School Status
@foreach (MyCareerAdvisor\HighSchoolLevel::all()->filter(function ($x) {return strpos($x, 'System Only') == false;}) as $education)
@endforeach
</div>
</div>
</div>
<h2>Military Background</h2>
<hr />
<div>
<div>
<div>
Have you served in the military?
@foreach (MyCareerAdvisor\VeteranStatus::all() as $status)
@endforeach
</div>
</div>
<div>
<div>
Do you have a family member in the military?
</div>
</div>
</div>
| cb58debf83d45bd637f65587b40f032f | 0 | DaehanKim | 2023-05-29T06:21:44 | good | [
"code"
] |
what can I adjust on this blade file, please provide me a table format showing current code new code and the justificaiton for the change
Demographic Information
<hr />
<div>
<div>
<div>
Are you eligible to work in the U.S.?
</div>
</div>
<div>
<div>
What language do you speak at home?
@foreach (MyCareerAdvisor\Language::orderBy('name')->get() as $language)
@endforeach
</div>
</div>
</div>
<div>
<div>
<div>
Race
@foreach (MyCareerAdvisor\Race::all() as $race)
@endforeach
</div>
</div>
@if(\MyCareerAdvisor\Setting::where('name', 'enable_latino')->first()->value)
<div>
<div>
Latino or Hispanic Heritage?
</div>
</div>
@endif
</div>
<h2>Educational Background</h2>
<hr />
<div>
<div>
<div>
Highest Grade Completed
@foreach (MyCareerAdvisor\EducationLevel::all() as $education)
@endforeach
</div>
</div>
<div>
<div>
High School Status
@foreach (MyCareerAdvisor\HighSchoolLevel::all()->filter(function ($x) {return strpos($x, 'System Only') == false;}) as $education)
@endforeach
</div>
</div>
</div>
<h2>Military Background</h2>
<hr />
<div>
<div>
<div>
Have you served in the military?
@foreach (MyCareerAdvisor\VeteranStatus::all() as $status)
@endforeach
</div>
</div>
<div>
<div>
Do you have a family member in the military?
</div>
</div>
</div>
| cb58debf83d45bd637f65587b40f032f | 0 | dianewan | 2023-05-23T23:17:15 | good | [
"code"
] |
what can I adjust on this blade file, please provide me a table format showing current code new code and the justificaiton for the change
Demographic Information
<hr />
<div>
<div>
<div>
Are you eligible to work in the U.S.?
</div>
</div>
<div>
<div>
What language do you speak at home?
@foreach (MyCareerAdvisor\Language::orderBy('name')->get() as $language)
@endforeach
</div>
</div>
</div>
<div>
<div>
<div>
Race
@foreach (MyCareerAdvisor\Race::all() as $race)
@endforeach
</div>
</div>
@if(\MyCareerAdvisor\Setting::where('name', 'enable_latino')->first()->value)
<div>
<div>
Latino or Hispanic Heritage?
</div>
</div>
@endif
</div>
<h2>Educational Background</h2>
<hr />
<div>
<div>
<div>
Highest Grade Completed
@foreach (MyCareerAdvisor\EducationLevel::all() as $education)
@endforeach
</div>
</div>
<div>
<div>
High School Status
@foreach (MyCareerAdvisor\HighSchoolLevel::all()->filter(function ($x) {return strpos($x, 'System Only') == false;}) as $education)
@endforeach
</div>
</div>
</div>
<h2>Military Background</h2>
<hr />
<div>
<div>
<div>
Have you served in the military?
@foreach (MyCareerAdvisor\VeteranStatus::all() as $status)
@endforeach
</div>
</div>
<div>
<div>
Do you have a family member in the military?
</div>
</div>
</div>
| cb58debf83d45bd637f65587b40f032f | 0 | nazneen | 2023-05-22T18:24:46 | good | [
"code"
] |
Why is this returning a key error for displayed_member_id
if member == ' ' or member == None or member == []:
sg.Popup('No Member found for Member id '+id)
window.Element('-firstn-').update('')
window.Element('-lastn-').update('')
else:
member_id = str(member[0][0])
window.Element('-displayed_member_id_number-').update(member_id)
first_name = str(member[0][1])
window.Element('-firstn-').update(first_name)
last_name = str(member[0][2])
window.Element('-lastn-').update(last_name)
conn = Assignment_3_draft_1.dbconnect()
Assignment_3_draft_1.createBookingTable(
conn=conn)
fitness_classes = Assignment_3_draft_1.dbQuery(
conn=conn, sql="""SELECT booking_table.*,fitness_class.*
from booking_table
INNER JOIN fitness_class on fitness_class.fitness_class_id=booking_table.fitness_class_id
WHERE booking_table.id=?
""", params=(id))
fitness_classes_data(fitness_classes)
if len(fitness_classes) < 3:
update_available_classes(id)
# conn.commit()
conn.close()
elif event=='-Submit-':
print(values['-displayed_member_id_number-'])
the original element:
col1a = [[sg.Text('Member ID', size=(20, 1)), sg.Text('First Name', size=(20, 1))],
[sg.Text(key='-displayed_member_id_number-', size=(20, 1),enable_events=True),
sg.Text(key='-firstn-', size=(20, 1))]
] | 40efff8c22f0b85b2f474a31a5e70b2a | 1 | DaehanKim | 2023-05-29T06:26:40 | bad | [] |
Why is this returning a key error for displayed_member_id
if member == ' ' or member == None or member == []:
sg.Popup('No Member found for Member id '+id)
window.Element('-firstn-').update('')
window.Element('-lastn-').update('')
else:
member_id = str(member[0][0])
window.Element('-displayed_member_id_number-').update(member_id)
first_name = str(member[0][1])
window.Element('-firstn-').update(first_name)
last_name = str(member[0][2])
window.Element('-lastn-').update(last_name)
conn = Assignment_3_draft_1.dbconnect()
Assignment_3_draft_1.createBookingTable(
conn=conn)
fitness_classes = Assignment_3_draft_1.dbQuery(
conn=conn, sql="""SELECT booking_table.*,fitness_class.*
from booking_table
INNER JOIN fitness_class on fitness_class.fitness_class_id=booking_table.fitness_class_id
WHERE booking_table.id=?
""", params=(id))
fitness_classes_data(fitness_classes)
if len(fitness_classes) < 3:
update_available_classes(id)
# conn.commit()
conn.close()
elif event=='-Submit-':
print(values['-displayed_member_id_number-'])
the original element:
col1a = [[sg.Text('Member ID', size=(20, 1)), sg.Text('First Name', size=(20, 1))],
[sg.Text(key='-displayed_member_id_number-', size=(20, 1),enable_events=True),
sg.Text(key='-firstn-', size=(20, 1))]
] | 40efff8c22f0b85b2f474a31a5e70b2a | 1 | dianewan | 2023-05-23T23:17:29 | good | [
"code"
] |
Why is this returning a key error for displayed_member_id
if member == ' ' or member == None or member == []:
sg.Popup('No Member found for Member id '+id)
window.Element('-firstn-').update('')
window.Element('-lastn-').update('')
else:
member_id = str(member[0][0])
window.Element('-displayed_member_id_number-').update(member_id)
first_name = str(member[0][1])
window.Element('-firstn-').update(first_name)
last_name = str(member[0][2])
window.Element('-lastn-').update(last_name)
conn = Assignment_3_draft_1.dbconnect()
Assignment_3_draft_1.createBookingTable(
conn=conn)
fitness_classes = Assignment_3_draft_1.dbQuery(
conn=conn, sql="""SELECT booking_table.*,fitness_class.*
from booking_table
INNER JOIN fitness_class on fitness_class.fitness_class_id=booking_table.fitness_class_id
WHERE booking_table.id=?
""", params=(id))
fitness_classes_data(fitness_classes)
if len(fitness_classes) < 3:
update_available_classes(id)
# conn.commit()
conn.close()
elif event=='-Submit-':
print(values['-displayed_member_id_number-'])
the original element:
col1a = [[sg.Text('Member ID', size=(20, 1)), sg.Text('First Name', size=(20, 1))],
[sg.Text(key='-displayed_member_id_number-', size=(20, 1),enable_events=True),
sg.Text(key='-firstn-', size=(20, 1))]
] | 40efff8c22f0b85b2f474a31a5e70b2a | 1 | nazneen | 2023-05-22T18:25:07 | good | [
"code"
] |
Solve the nonlinear optimization problem
min f (x1,x2) = (x1)^2 −x1x^2 +(x2)^2 −2x2
s.t. g(x1,x2) = x1 +x2 −1 ≤0.
(a) Apply the optimality conditions;
(b) Verify your solution in Excel. Show all steps. | 5ce8d70f0c016a654440ba184dbfa43b | 10 | DaehanKim | 2023-05-29T06:38:45 | good | [] |
Solve the nonlinear optimization problem
min f (x1,x2) = (x1)^2 −x1x^2 +(x2)^2 −2x2
s.t. g(x1,x2) = x1 +x2 −1 ≤0.
(a) Apply the optimality conditions;
(b) Verify your solution in Excel. Show all steps. | 5ce8d70f0c016a654440ba184dbfa43b | 10 | dianewan | 2023-05-23T23:27:16 | bad | [] |
소스에서 폼 전송 ajax방식 스크립트 만들어줘
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="ui" uri="http://egovframework.gov/ctl/ui"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%
/**
* @Class Name : egovSampleList.jsp
* @Description : 비밀번호변경 화면
* @Modification Information
*
* 수정일 수정자 수정내용
* ------- -------- ---------------------------
* 2009.02.01 최초 생성
*
* author 실행환경 개발팀
* since 2009.02.01
*
* Copyright (C) 2009 by MOPAS All right reserved.
*/
%>
<c:import url="../inc/head.jsp">
<c:param name="foo" value="bar"></c:param>
</c:import>
<!-- BEGIN #app -->
<div id="app" class="app app-header-fixed app-sidebar-fixed">
<!-- BEGIN #header -->
<c:import url="../inc/header.jsp">
<c:param name="foo" value="bar"></c:param>
</c:import>
<!-- END #header -->
<!-- BEGIN #sidebar -->
<c:import url="../inc/sidebar.jsp">
<c:param name="foo" value="bar"></c:param>
</c:import>
<!-- END #sidebar -->
<!-- BEGIN #content -->
<div id="content" class="app-content">
<!-- BEGIN breadcrumb -->
<!-- <ol class="breadcrumb float-xl-end">
<li class="breadcrumb-item"><a href="javascript:;">Home</a></li>
<li class="breadcrumb-item"><a href="javascript:;">Library</a></li>
<li class="breadcrumb-item active">Data</li>
</ol> -->
<!-- END breadcrumb -->
<!-- BEGIN page-header -->
<h1 class="page-header">비밀번호 변경 </h1>
<!-- END page-header -->
<!-- BEGIN panel -->
<div class="panel panel-inverse">
<div class="panel-heading">
<h4 class="panel-title">Panel Title here</h4>
<!-- <div class="panel-heading-btn">
<a href="javascript:;" class="btn btn-xs btn-icon btn-default" data-toggle="panel-expand"><i class="fa fa-expand"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-success" data-toggle="panel-reload"><i class="fa fa-redo"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-warning" data-toggle="panel-collapse"><i class="fa fa-minus"></i></a>
<a href="javascript:;" class="btn btn-xs btn-icon btn-danger" data-toggle="panel-remove"><i class="fa fa-times"></i></a>
</div> -->
</div>
<div class="panel-body">
<div class="col-md-6">
<form action="/" method="POST">
<fieldset>
<div class="row mb-2">
<label class="form-label col-form-label col-md-3">현재 비밀번호</label>
<div class="col-md-6">
<input type="password" class="form-control" placeholder="Enter password" />
</div>
</div>
<div class="row mb-2">
<label class="form-label col-form-label col-md-3">새 비밀번호</label>
<div class="col-md-6">
<input type="password" class="form-control" placeholder="Enter password" />
</div>
</div>
<div class="row mb-2">
<label class="form-label col-form-label col-md-3">새 비밀번호 확인</label>
<div class="col-md-6">
<input type="password" class="form-control" placeholder="Enter password" />
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!-- END panel -->
<div class="col-md-6">
<a href="#" class="btn btn-primary">등록</a>
</div>
</div>
<!-- END #content -->
<!-- BEGIN scroll to top btn -->
<a href="javascript:;" class="btn btn-icon btn-circle btn-success btn-scroll-to-top" data-toggle="scroll-to-top"><i class="fa fa-angle-up"></i></a>
<!-- END scroll to top btn -->
</div>
<!-- END #app -->
<!-- ================== BEGIN core-js ================== -->
<c:import url="../inc/footer.jsp">
<c:param name="foo" value="bar"></c:param>
</c:import>
<!-- ================== END core-js ================== -->
<c:import url="../inc/foot.jsp">
<c:param name="foo" value="bar"></c:param>
</c:import>
| 9371046d6ca633fd98d6bcee838e19af | 100 | dianewan | 2023-05-24T23:48:26 | bad | [] |
addapt this code :
def save_data_to_avro(data: dict, channel_name: str, channel_id: int, report_id: str) -> None:
now = datetime.datetime.now()
file_path = Path("yt_data") / f"{report_id}_data" / channel_name / str(now.year) / str(now.month).zfill(2) / str(
now.day).zfill(2) / str(now.hour).zfill(2)
file_path.mkdir(parents=True, exist_ok=True)
file_name = f"{channel_name}_{now:%Y-%m-%d_%H-%M-%S}.avro"
schema = avro.schema.Parse('''
{
"type": "record",
"name": "VideoData",
"fields": [
{"name": "video", "type": "string"},
{"name": "estimatedMinutesWatched", "type": "int"},
{"name": "views", "type": "int"}
]
}
''')
write_avro_file(data, file_path / file_name, schema)
print(f" -> Done for '{channel_name}' channel (ID: {channel_id}) [Report Type: {report_id}]")
def write_avro_file(data: dict, file_path: Path, schema: avro.schema.Schema) -> None:
with open(file_path, 'wb') as out_file:
writer = DataFileWriter(out_file, DatumWriter(), schema)
for row in data['rows']:
video_data = {"video": row[0], "estimatedMinutesWatched": row[1], "views": row[2]}
writer.append(video_data)
writer.close()
there might be sometimes missing elements in the data | c30308f430cf13c7a082640171074915 | 101 | dianewan | 2023-05-24T23:48:37 | bad | [] |
class _BlockingAsyncContextManager(AbstractContextManager):
_enter_future: Future
_exit_future: Future
_exit_event: Event
_exit_exc_info: Tuple[
Optional[Type[BaseException]], Optional[BaseException], Optional[TracebackType]
] = (None, None, None)
def __init__(self, async_cm: AsyncContextManager[T_co], portal: "BlockingPortal"):
self._async_cm = async_cm
self._portal = portal
async def run_async_cm(self) -> Optional[bool]:
try:
self._exit_event = Event()
value = await self._async_cm.__aenter__()
except BaseException as exc:
self._enter_future.set_exception(exc)
raise
else:
self._enter_future.set_result(value)
try:
# Wait for the sync context manager to exit.
# This next statement can raise `get_cancelled_exc_class()` if
# something went wrong in a task group in this async context
# manager.
await self._exit_event.wait()
finally:
# In case of cancellation, it could be that we end up here before
# `_BlockingAsyncContextManager.__exit__` is called, and an
# `_exit_exc_info` has been set.
result = await self._async_cm.__aexit__(*self._exit_exc_info)
return result
def __enter__(self) -> T_co:
self._enter_future = Future()
self._exit_future = self._portal.start_task_soon(self.run_async_cm)
cm = self._enter_future.result()
return cast(T_co, cm)
def __exit__(
self,
__exc_type: Optional[Type[BaseException]],
__exc_value: Optional[BaseException],
__traceback: Optional[TracebackType],
) -> Optional[bool]:
self._exit_exc_info = __exc_type, __exc_value, __traceback
self._portal.call(self._exit_event.set)
return self._exit_future.result()
| 54d2edba388b1627e70e6529d91289bd | 102 | dianewan | 2023-05-24T23:48:52 | bad | [] |
I suggested the below GitHub Charter.md document. It was WAYYY to technical, specific, or otherwise not accurate to the goals of the maintainer. I want you to re-write the charter document but make it have emojis, be more lighthearted, acknowledge the one-person-show, say that this is a hobby project, mention no intent to add more collaborators, and otherwise fit this new direction. Here is a quote from a GitHub Issue that describes the intended new direction:
Hi I'm sorry you feel I'm not communicative enough, you are right. but sadly I cannot invest more time that I already am and not intending adding collaborators at this time.
I would suggest take things with more proportions tho. I aim this repo to be a nice cute side project, easy and lighthearted 🤷 There is no commercial product on the line here... No deadlines... No urgency...
Yes, It may take me few weeks to answer at times. But unless its a user breaking bug, so what?
Im sorry but I have no solutions for this at this time... 😞
Here's the original charter Markdown code:
```md
<!--
This is an official document. Use AP-style title case for headings. This
document MAY be moved to a CHARTER.md or similar location if a more user-focused
README.md is provided.
The convention is "dev containers" in formal settings, but "devcontainers" in
informal settings. The official specification and documentation use "dev
containers", but most external documents use "devcontainers". Both of these are
nouns, not names, and can as such be capitalized.
-->
# [Community Dev Containers] Charter
The [Community Dev Containers] project aims to document, maintain, and improve
on the official devcontainers images, features, and templates to improve the
developer experience for end-users.
## Guiding Principles
The [Community Dev Containers] project operates under principles similar to
those of the [OpenJS Foundation]. It operates collaboratively, openly,
ethically, and transparently. Project proposals, ideas, timelines, and statuses
should not merely be open and available, but also easily visible to outsiders.
Outside users and developers should be able to participate in discussions,
ideas, issues, and make contributions with as little effort as possible.
## Problem
The current official [@devcontainers] project's scope is limited to features,
images, and templates that serve only the highest level of most popular
programming environments.
For instance, the [devcontainers/features] repository contains only 28 different
addons. The [devcontainers/images] repository only has a selection of 15
different development environment baselines.
This project is the centralized unofficial hub for other features, images, and
templates that would not be permitted to fall under the official
[@devcontainers] umbrella.
## Scope
The [@devcontainers-contrib] organization maintains and evolves the images,
features, templates, and documentation content for aspects not covered by the
official [@devcontainers] organization. It provides a stable, yet flexible, set
of supporting software for users who use dev containers that is governed to
accomodate their desires. This project's value is its balance between
administration and community adherence. It's scope includes listening and
responding to user feedback.
### In-scope
- Docker images for ecosystems not covered an official dev containers image
- Feature collections for popular tools that are typical on developer computers
- Templates for popular project configurations and setups
- Conventions and best-practices to follow architecting a dev container
- Make it easy to propose, add, or otherwise discuss additional features,
images, and templates
Tutorials and guides on how to use dev containers are not covered under the
umbrella of the [Community Dev Containers] project. These items can be pursued
by individual members, but are not endorsed or covered under this organization's
scope.
### Out-of-Scope
- Creating a dev container feature for every single Node.js or Python package
- Maintaining a dev container image for all permutations of tooling mashups
- Fixing users' broken dev container configurations
- Answering questions about decisions made by the official [@devcontainers]
organization
[openjs foundation]: https://openjsf.org/
[@devcontainers]: https://github.com/devcontainers
[@devcontainers-contrib]: https://github.com/devcontainers-contrib
[community dev containers]: https://github.com/devcontainers-contrib
[devcontainers/features]: https://github.com/devcontainers/features#readme
[devcontainers/images]: https://github.com/devcontainers/images#readme
``` | 413c49c83a435e02b7775484d0d9f430 | 103 | dianewan | 2023-05-24T23:49:39 | bad | [] |
I have this code where the header slides up on scroll down and slides down on scroll up. The problem is if there's a page that doesn't scroll, the navigation goes away on scroll even though the page is not tall enough to scroll. Write JS for Vue2 that checks if the page is tall enough. If its not tall enough, then disable the navigation going away. If its tall enough and scrollable, then enable the slide up/down. Here's the code to edit:
<template>
<header ref="nav" class="global-header" :style="{ transform: `translateY(${windowWidth >= 1024 ? navTranslateY : 0}px)` }">
<div class="global-header-logo">
<NuxtLink to="/" class="global-header-logo-link">
<Logo :fullLogo="fullLogo"></Logo>
</NuxtLink>
</div>
<nav class="global-header-nav">
<Navigation></Navigation>
</nav>
</header>
</template>
<script>
export default {
props: ['fullLogo'],
data() {
return {
navTranslateY: 0,
previousScrollY: 0,
windowWidth: 0
};
},
mounted() {
this.windowWidth = window.innerWidth;
window.addEventListener("resize", this.handleResize);
window.addEventListener("scroll", this.handleScroll);
},
beforeDestroy() {
window.removeEventListener("resize", this.handleResize);
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleResize() {
this.windowWidth = window.innerWidth;
},
handleScroll() {
if (window.scrollY > this.previousScrollY && this.windowWidth >= 1024) {
this.navTranslateY = -200;
} else {
this.navTranslateY = 0;
}
this.previousScrollY = window.scrollY;
}
}
}
</script>
| 66b3fa3a017c89186b0b24f108ec6fd3 | 104 | dianewan | 2023-05-24T23:49:52 | good | [
"code"
] |
```bash
```
#!/bin/bash
set -eu
snapsToRemove=$(snap list --all | awk '/disabled/{print $1, $2, $3}')
while read snapname version revision; do
if [[ "$revision" == *[a-zA-z]* ]]; then
# Version field is empty. Revision is in second field
revision=$version
fi
snap remove "$snapname" --revision="$revision"
done <<< $snapsToRemove
sudo snap set system refresh.retain=2
``` | 965b6b14c7b8eaeb2c1e543877c44804 | 105 | dianewan | 2023-05-24T23:50:06 | bad | [] |
Hi can you create a .net web api using entity framework based off of this postgres query? SELECT
ch."ChapterId" as "chapterId",
ch."IsActive" as "isActive",
ch."NameEn" as "name",
ch."SortOrder" as "sortOrder",
ch."SubjectId" as "subjectId",
count(ls."MmLessonSetId") as mmLessonSetCount,
SUM(CASE WHEN ls."IsActive" = TRUE THEN 1 ELSE 0 END) as mmLessonSetActiveCount
FROM
"Chapters" as ch
LEFT JOIN
"MmLessonSets" as ls
ON
ls."ChapterId" = ch."ChapterId"
WHERE
ch."SubjectId" = 'SubjectId0011'
AND
ch."IsActive" = TRUE
GROUP BY
ch."ChapterId", ch."IsActive", ch."NameEn", ch."SortOrder", ch."SubjectId"
ORDER BY
ch."SortOrder" | be4c56b02e0e02a09f2944d04415a539 | 106 | dianewan | 2023-05-24T23:50:17 | good | [
"code"
] |
improve this code
<Row>
{hasDiscount ? (
<>
<Col>
<Paragraph className="price-discount">
{listPrice} {t("home.riyal")}
</Paragraph>
</Col>
<Col>
<Paragraph className="discount-amount">
{t("home.discount")} %{Math.ceil(+discountAmount)}
</Paragraph>
</Col>
</>
) : (
<Paragraph className="tabby-cost">
{listPrice > tabbyCost
? (listPrice / 4).toFixed(2) + `${t("home.a_month")}`
: ""}
</Paragraph>
)}
</Row> | 957ae63cdbb2d7f2950527470ddcaeea | 107 | dianewan | 2023-05-24T23:50:20 | good | [
"code"
] |
Please create sample forms based on the following views: from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Resident, School, Billing, Municipality
from .forms import ResidentForm, SchoolForm, BillingForm
def homepage(request):
return render(request, 'homepage.html')
@login_required
def resident_detail(request, resident_id):
resident = get_object_or_404(Resident, pk=resident_id)
return render(request, 'resident_detail.html', {'resident': resident})
@login_required
def resident_edit(request, resident_id):
resident = get_object_or_404(Resident, pk=resident_id)
if request.method == "POST":
form = ResidentForm(request.POST, instance=resident)
if form.is_valid():
resident = form.save(commit=False)
resident.save()
messages.success(request, 'Resident details updated successfully!')
return redirect('resident_detail', resident_id=resident.id)
else:
form = ResidentForm(instance=resident)
return render(request, 'resident_edit.html', {'form': form})
@login_required
def school_list(request):
schools = School.objects.all()
return render(request, 'school_list.html', {'schools': schools})
@login_required
def school_detail(request, school_id):
school = get_object_or_404(School, pk=school_id)
return render(request, 'school_detail.html', {'school': school})
@login_required
def school_edit(request, school_id):
school = get_object_or_404(School, pk=school_id)
if request.method == "POST":
form = SchoolForm(request.POST, instance=school)
if form.is_valid():
school = form.save(commit=False)
school.save()
messages.success(request, 'School details updated successfully!')
return redirect('school_detail', school_id=school.id)
else:
form = SchoolForm(instance=school)
return render(request, 'school_edit.html', {'form': form})
@login_required
def billing_list(request):
bills = Billing.objects.all()
return render(request, 'billing_list.html', {'bills': bills})
@login_required
def billing_detail(request, bill_id):
bill = get_object_or_404(Billing, pk=bill_id)
return render(request, 'billing_detail.html', {'bill': bill})
@login_required
def billing_edit(request, bill_id):
bill = get_object_or_404(Billing, pk=bill_id)
if request.method == "POST":
form = BillingForm(request.POST, instance=bill)
if form.is_valid():
bill = form.save(commit=False)
bill.save()
messages.success(request, 'Billing details updated successfully!')
return redirect('billing_detail', bill_id=bill.id)
else:
form = BillingForm(instance=bill)
return render(request, 'billing_edit.html', {'form': form})
@login_required
def municipality_list(request):
municipalities = Municipality.objects.all()
return render(request, 'municipality_list.html', {'municipalities': municipalities}) | a49ffd3e334f48138589d1910a0f546b | 108 | dianewan | 2023-05-24T23:50:32 | good | [
"code"
] |
So, I want to create a async data holder in C++ which can be got only if it has been initialized asynchronously previously. If it has not been initialized, it will return the default value of the type. Is this sufficient?
template<typename T>
class AsyncDataHolder {
enum class Status { NOT_INITIALIZED, INITIALIZING, INITIALIZED };
std::function<T()> initializer_;
Status status_{NOT_INITIALIZED};
mutable bthread::ConditionVariable cv_;
mutable bthread::Mutex mtx_;
T value_;
public:
AsyncDataHolder(std::function<T()> initializer) : initializer_(initializer) {
}
void InitializeAsync() {
{
std::unique_lock lock(mtx_);
status_ = Status::INITIALIZING;
}
recall::runDetachedBthread([&]() {
std::unique_lock lock(mtx_);
value_ = initializer_();
status_ = Status::INITIALIZED;
cv_.notify_all();
});
}
const T& Get() const {
{
std::shared_lock lock(mtx_);
if (status_ == Status::NOT_INITIALIZED) {
return value_;
}
}
std::unique_lock lock(mtx_);
while (status_ != Status::INITIALIZED) {
cv_.wait(lock);
}
return value_;
}
}; | 24a62a4172a0149a62cc1bb49fab8331 | 109 | dianewan | 2023-05-25T00:19:11 | good | [
"code"
] |
breed [species3 a-species3] ;;
turtles-own [energy rnumber dnumber]
to setup
clear-all
settle-species1
set-default-shape species3 "frog top"
create-species3 sp3-start-number [
set color green
set size 2.5
setxy random-xcor random-ycor
set energy 15
set rnumber random-normal 50 5
set dnumber random-normal 52 5
] ;; use slider for initial number, starting energy level is 15
reset-ticks
if (file-exists? "speciesgrowth.csv")
[file-delete "speciesgrowth.csv"]
file-open "speciesgrowth.csv"
file-type "time,"
file-type "N1,"
file-print "N3"
file-close
ifelse count turtles = 0 [ ]
[file-open "speciesgrowth.csv"
ask one-of turtles
[
file-type (word ticks ",")
file-type (word count patches with [ pcolor = 5 ] ",")
file-print count species3
]
file-close
]
if ( file-exists? "sp3output.csv") ; output file setup
[file-delete "sp3output.csv"]
file-open "sp3output.csv"
file-type "individual,"
file-type "rnumber,"
file-print "dnumber,"
file-close
ifelse count turtles = 0 [ ]
[file-open "sp3output.csv"
ask turtles
[
file-type (word who "," )
file-type (word rnumber ",")
file-print (word dnumber )
]
file-close
]
end
to go
grow-species1
ask species3
[ move
sp3-eat-species1
sp3-reproduce
death ]
file-open "speciesgrowth.csv"
file-type (word ticks ",")
file-type (word count patches with [ pcolor = 5 ] ",")
file-print count species3
file-close
tick
end
to settle-species1 ;; slider determines initial number of species 1 patches
ask n-of sp1-start-number patches [ set pcolor 5 ]
end
to grow-species1 ;; determines numbers of species 1 added each step
ask n-of sp1-growth-rate patches [ set pcolor 5 ]
end
to sp3-eat-species1
if pcolor = 5
[ set pcolor black
set energy energy + 5 ]
end
to sp3-reproduce
if energy > 100
[ set energy (energy - (0.25 * energy))
hatch 1 [
set color green
set rnumber random-normal 50 5
set dnumber random-normal 52 5
set energy ((energy / 0.75) - energy)
bk 1 ] ]
end
to move ;; turtle with cost of 1 energy for each movement
rt random 50
lt random 50
fd 2
set energy energy - 1
end
to death
if energy < 0 [ die
]
end | ae601deb4f596aa3dc75e06deec61e0a | 11 | DaehanKim | 2023-05-29T06:39:30 | bad | [] |
breed [species3 a-species3] ;;
turtles-own [energy rnumber dnumber]
to setup
clear-all
settle-species1
set-default-shape species3 "frog top"
create-species3 sp3-start-number [
set color green
set size 2.5
setxy random-xcor random-ycor
set energy 15
set rnumber random-normal 50 5
set dnumber random-normal 52 5
] ;; use slider for initial number, starting energy level is 15
reset-ticks
if (file-exists? "speciesgrowth.csv")
[file-delete "speciesgrowth.csv"]
file-open "speciesgrowth.csv"
file-type "time,"
file-type "N1,"
file-print "N3"
file-close
ifelse count turtles = 0 [ ]
[file-open "speciesgrowth.csv"
ask one-of turtles
[
file-type (word ticks ",")
file-type (word count patches with [ pcolor = 5 ] ",")
file-print count species3
]
file-close
]
if ( file-exists? "sp3output.csv") ; output file setup
[file-delete "sp3output.csv"]
file-open "sp3output.csv"
file-type "individual,"
file-type "rnumber,"
file-print "dnumber,"
file-close
ifelse count turtles = 0 [ ]
[file-open "sp3output.csv"
ask turtles
[
file-type (word who "," )
file-type (word rnumber ",")
file-print (word dnumber )
]
file-close
]
end
to go
grow-species1
ask species3
[ move
sp3-eat-species1
sp3-reproduce
death ]
file-open "speciesgrowth.csv"
file-type (word ticks ",")
file-type (word count patches with [ pcolor = 5 ] ",")
file-print count species3
file-close
tick
end
to settle-species1 ;; slider determines initial number of species 1 patches
ask n-of sp1-start-number patches [ set pcolor 5 ]
end
to grow-species1 ;; determines numbers of species 1 added each step
ask n-of sp1-growth-rate patches [ set pcolor 5 ]
end
to sp3-eat-species1
if pcolor = 5
[ set pcolor black
set energy energy + 5 ]
end
to sp3-reproduce
if energy > 100
[ set energy (energy - (0.25 * energy))
hatch 1 [
set color green
set rnumber random-normal 50 5
set dnumber random-normal 52 5
set energy ((energy / 0.75) - energy)
bk 1 ] ]
end
to move ;; turtle with cost of 1 energy for each movement
rt random 50
lt random 50
fd 2
set energy energy - 1
end
to death
if energy < 0 [ die
]
end | ae601deb4f596aa3dc75e06deec61e0a | 11 | dianewan | 2023-05-23T23:27:29 | bad | [] |
make this more efficient: public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (arr == null || arr.length == 0)
return;
if (low >= high)
return;
// pick the pivot
int middle = low + (high - low) / 2;
int pivot = arr[middle];
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(arr, low, j);
if (high > i)
quickSort(arr, i, high);
}
public static void main(String[] args) {
int[] arr = {25, 2, 8, 60, 3, 1, 90};
quickSort(arr, 0, arr.length-1);
for(int i : arr){
System.out.print(i);
System.out.print(" ");
}
}
} | 2c5124d38fdab218351300b2f371bb8d | 110 | dianewan | 2023-05-25T00:19:16 | good | [
"code"
] |
pathao
Pathao is Bangladesh’s Largest Consumer Tech Company •• h•“”o
#1
E-Commerce
Logistics
$187M
2022 GMV
$23M
2022 Revenue
#1
2-Wheeler Rides
EBITDA & Cashflow positive
at the Vertical and Consolidated level
#2
4-Wheeler Rides
#2
Food Delivery
#1
8M+
Unique Users
3OOK+
Drivers & Couriers
6OK+
1.7M+
MAU
0.8M
Paid Monthly Users
Digital Consumer Credit
Restaurants & Merchants
pathao
Bangladesh is the Fastest Growing Economy in Asia
poth *'â
8th most populous country and 30th largest economy
Half the population of the US in a country the size of New York State
Population of 165mn and a GDP of $416bn
Consistent GDP Growth
Bangladesh’s GDP per capita (g2,520) is higher than that of India
GDP growth from $1 29bn to
$416bn (2011-2021) with an average GDP growth of 6.5%
Sources: World Bank, CIA World Fac tbook 2020, Bangladesh Census
Young and surging Middle Class
Median age of 27; 86M people in the
Middle Class, expected to
Increase 1.4x to 119M by 2025
Rapid Smartphone Adoption
Smartphone penetration is catching up with regional peers, and is expected that
Adoption will grow to 63% by 2025
pathao
Pathao is uniquely positioned to become the largest data ••'h•”o
driven digital financial services provider
81 Financial Services Provider to the Digital Economy
Digital Credit
Payments Data-Driven Credit Scoring
PathaoPay to launch in QI42022
On-Demand Transport & Logistics Platform
pathao
We are the best known digital brand for urban millennials
pothâ*'â
19M
22M
Target Customer Types
Urban Millennial
(21 -40 Years, Digitallv Savvv. 1 st / 2nd Job)
Navid, 24
Customer Representative
64M
66M
Anika, 27
Graphic Designer
Development
Source: BCG
pathao
We will expand our product to serve the evolving financial •• h•”o
service needs of our customers
Young Family
Rising household credit needs
rot/ng I/l/orying Professional (eg. Motorbike, Pefrigerator)
Established Household Rising household credit needs (eg. house)
35-40
Fresher/ First/ob Basic credit needs — loans for expenses or small purchases
21 -25
Expanding credit needs (eg. AC, Smartphone)
25-30
30-35
Home Loan
CASA CASA
Credit Card
Credit Card
Credit Card
Consumer Finance
Pay Later
Consumer Finance
Pay Later
Consumer Finance
Pay Later
Consumer Finance
Pay Later
Financial Services has a TAM of >$100 bn
USD 5O .OB 1
Digital Payment Transaction Volume
USD 47B1
Digital P2P Money Transfer
USD 2OB4
Offline Retail
Market
USD 9B5
Bill and Education Payments
USD 3B5
Mobile Top—Up Market
USD 2OOM
Digital Commerce Market
SU s B
USD 13B2
Consumer Lending
USD 100M5
2W and MW
Ride-sharing 2022
market size
2025
USD 3OOM
USD 22B3
MSME Lending
USD 100Ms 0 5
Current Food Delivery Market
USD 1.5B°
Insurance Premium
5 0 5
USD 50
Current Annual
No. of Shipments
Sources: 'Bangladesh Bank (BB); 2(includes micro—finance, consumer lending) BB, MRA; *BB; ’Bain Capital Report; 5Company estimates, various sources; ^IDRA pathao
PathaoPay will make digital payments seamless and drive ••'h•”o
data collection (launch in Q2 2023)
pothâ*'âpog
Pathao has recently been awarded a rare Payment Services Provider (PSP) license to offer e-wallet services with the product PathaoPay
Discovery
o•
Agribusiness
Catering Ecommerce
Kitchen
p0S
Phone TopUp
SOCial
CNG
Bus
pathao
Young Bangladeshis have abysmally low access to credit
Millennial consumers hardly have any credit history, making lenders risk averse and reluctant to provide unsecured consumer finance.
poth *'â
No. of Credit Cards per eligible Individual (based on income)
67.2 N
41.6 N
Credit card penetration <1 %1
| 1.7 M I
! 0.64
i i
Bankable Unique Population Bank Accounts
Debit Cards Credit Cards j
Sources: Bangladesh Bank; World Bank Data; Statista
pathao
PathaoPayLater has been designed to address the financial •• h•“”o
needs of urban millennials
pothb'*"opogIoter
Access
Only 1.7M people (<1°/. of population) have access to a credit card
Speed
Credit card from a bank takes upto 2 months and requires multiple pieces of paperwork. We do it in a matter of seconds
User Experience
Ecommerce merchants in Bangladesh face high cart abandonment rates due to payment friction
Usage Online or Offline
pathao
pathao
We are expanding our Financial Services offering for the Ecosystem
poth *'â
."—• + .
jjy Consumer Leasing
Our Target Group:
• 8mn registered 21-40 yr old users
• 300k+ drivers and couriers
Lease Financing for:
• Mobile phones & other electronics
• Household appliances
• Motorbikes
• Partnering with banks/NBFls
Merchant Financing
Our Target Group:
• 40,000+ e-commerce (courier) merchants and restaurant merchants
Working Capital Financing for:
• Working capital for e-comm merchants
• Receivable financing by Pathao
• Partnering with banks/NBFIs
pathao
We assess credit risk using both traditional and alternative ••'h•”o
data sources
Identity verification Location
Database
Pathao Platform
In-app activities (last activity, types)
Acquisition behavior
Purchase and payment behavior Rate of paid transactions
User contactabilit v
Demographic data (age, gender) Employment (salary, experience) Place of residence
Salary & wealth information
Self Reported
Sources of Data
E-Commerce
PathaoPay
Pathao Courier has 2M+ verified shipping
addresses
Shopping categories & frequency Account age
Payment methods used
Mobile top-up
Online & offline payments Utility bill
Salary
Balance information
Past borrowing & repayment historv Credit Blacklist status Information Credit outstanding
Bureau”
Note: Presently banks and financial institutions have access to CIB
Device Based ntelligence
GPS / Location SMS Metadata Downloaded apps
Device details (phone brand, price) Mobile activity (metadata, top up info)
pathao
Pathao is poised to be the country’s largest Digital Financial ••'h•“”o
Services platform
Pharma
Health
Tong
Car
Bike
Food
pOthrf"opoy
8M+ 3OOK+ 6OK+
Unique Users Drivers & Couriers Restaurants & Merchants
potho Fin«nciaIServices
*op-Up BangD
Games
Shop
Parcel
pathao
Strong management team backed by seasoned
investors
poth *'â
Fahim Ahmed
CEO
Ex Goldman Sachs, , SEAF 20 years in tech, banking, & investing; 5 years at Pathao
Asif Khondaker
svp, Accounts
Ex Accenture, Union Capital; 13 years of experience; 5 years at Pathao
Abdullah Noman
Director, Core Product
Ex Kiekback Inc., Bu zzA Ily; 8 years of experience;
/+ years at Pathao
Ahmed Maruf
Director, Courier
Shifat Adnan
Co-Founder & CTO
EX Dugdugi, Hack House; 6 years at Pathao
Razwan Kader Mishu
VP, Engineering
Ex Widespace AB, AdPeople, AIUB; 15 years of experience;
/+ years at Pathao
Nazmul Haque
Director, Pay Product
Ex iPay, Reef Technology; 14 years of experience;
4 years at Pathao
A.T.M Hassan Uzzaman
Director, Pay Engineering
Ahmed Fahad
SVP, Product
Founding Team; 6 years at
Pathao
Abdullah Anwar
ve, oata Engineering
Ex Metigy, Widespace; 15 years experience; 4 years at Pathao
Nabila Mahabub
Director, Marketing
Ex Banglalink (Veon); 10 years experience; 5 years at Pathao
Rahat Ashekeen
Director, Digital Credit
Raisul Amin
svp, Corp Finance
EX IPE Capital, BD Venture; 10 years in finance; 5 years at Pathao
Ehsanul Karim
Director, Data Science
Ex Xero, Airtasker, Hireup; 10 years of experience;
/+ years at 9athao
Asif Shahnewaz
Director, Operations
EX lubee, Truck Lagbe; 1 3 years of experience; 4 years at Pathao
H.A Sweety
Director, HR & Culture
Ex Rocket Internet SE; years of experience;
5 Years at Pathao
Ex HashKloud Pty. Ltd, The Jaxara It Ltd, bGIobaI Sourcing LLC; 16 years of experience; 1 year at Pathao
AN C H O R LE SS
Ex Stripe, Cabbage, JP Morgan; 6 years of experience,
Existing Investors
openspoce VENTU 2E
Ex SSL Wireless;
9 years of experience; 4 years at Pathao
Battery Road
BAN G LAD ES H
Digital Holdings
gojek pathao
Contact Us:
potháÖ
pe
pathao
We have grown our business with a positive Net Inflow Margin
GMV (USD mn)
poth *'â
Revenue Net Inflyo r EBITDA
2018
2019
2020 2021
2022
pathao
We have transformed our business to become EBITDA & Cash •• h•o“
Flow Positive
GMV (USD mn)
HO
(O( )
lH *on *H 2 O*
Rei enue Net Iliflois EBITDA
pathao
Financial Forecasts
Pathao (Rides, Food & Courier)
Pathao Pay 0.5M 0.4M 0.7M 0.8M 2.1M
0.6M 5.5M
3.0M 9.0M
7.5M
Digital Credit 0.01M 0.05M 0.23M 0.45M
GMV
76.9M
58.2M
117.5M
188.IM
838.4M
3,060.5M
6,591.3M
Pathao (Rides, Food & Courier)
Pathao Pay
410.6M 719.0M 1,028.3M
Digital Credit 0.2M 621.0M
Revenue (Consolidated) 11.OM 7.1M 15.0M 22.9M 48.0M 94.6M 149.1M
Take Rate (Blended) 14.30% 12.20% 12.80% 12.20% 5.70% 3.10% 2.30%
Net Inflow (Consolidated) (0.9M) 1.8M 6.9M 10.5M 15.IM 27.IM 58.1M
Net Infiow (aS ‘to of GMV). -1.10‘Xo 3.10% 5.90% 5.60‘Xo 1.80% 0.90% 0.90‘Xo
EBITDA (Consolidated) (10.3M) (4.7M) (0.6M) (0.3M) (0.2M) (1.2M) 18.6M
EBITDA (as % of Revenue): -93.60% -65.70% -4.20% -1.40% -0.50% -1.20% 12.50%
Capex
0.OM
(0.1M)
(0.4M)
(0.7M)
(1.0M)
(1.5M)
(1.6M)
| 9f286c31c483fc0a7ed0adaeac23fbe2 | 111 | dianewan | 2023-05-25T00:19:34 | bad | [] |
I'm getting time="2023-01-08 20:51:59" level=error msg="[Plugin / Upscale Performer image] Traceback (most recent call last):"
time="2023-01-08 20:51:59" level=error msg="[Plugin / Upscale Performer image] File \"B:\\Stash\\plugins\\Performer_Image_Gigapixel\\upscale.py\", line 379, in <module>"
time="2023-01-08 20:51:59" level=error msg="[Plugin / Upscale Performer image] client.upscale_PerformerImage()"
time="2023-01-08 20:51:59" level=error msg="[Plugin / Upscale Performer image] TypeError: upscale_with.upscale_PerformerImage() missing 1 required positional argument: 'performer_id'"
here is my code import config_manager
import configparser
import requests
import sys
import json
import pathlib
import os
import shutil
import psutil
from gigapixel import Gigapixel, Scale, Mode
from pathlib import Path, WindowsPath
from PIL import Image
# Gigapixel needs to save the images to the filesystem, for the GraphQL image update mutation the image needs to be served from a URL, for this to work you need to setup custom mapped folders in Stash (https://github.com/stashapp/stash/pull/620). Below you need to specify both the location to save the images and also the custom Stash mapping for that folder.
# Path to Stash custom Served Folder from root Stash folder, eg. if C:\Stash\static, just enter static
mapped_path = "B:\Stash\custom\static"
# Url to mapped path
mapped_url = "http://localhost:9999/custom"
# Topaz Gigapixel Settings
exe_path = Path('B:\Program Files\Topaz Labs LLC\Topaz Gigapixel AI\Topaz Gigapixel AI.exe')
# Output file suffix. (e.g. pic.jpg -> pic-gigapixel.jpg)
# You should set same value inside Gigapixel (File -> Preferences -> Default filename suffix).
output_suffix = '-gigapixel'
# Global Gigapixel variables
scale_setting = []
mode_setting = []
# Gigapixel tag names
tag_names = ['Upscale Standard:0.5x','Upscale Standard:2x','Upscale Standard:4x','Upscale Standard:6x','Upscale Lines:0.5x','Upscale Lines:2x','Upscale Lines:4x','Upscale Lines:6x','Upscale Art & CG:0.5x','Upscale Art & CG:2x','Upscale Art & CG:4x','Upscale Art & CG:6x','Upscale Low Resolution:0.5x','Upscale Low Resolution:2x','Upscale Low Resolution:4x','Upscale Low Resolution:6x','Upscale Very Compressed:0.5x','Upscale Very Compressed:2x','Upscale Very Compressed:4x','Upscale Very Compressed:6x']
configpath = os.path.join(pathlib.Path(__file__).parent.resolve(), 'config.ini')
def get_config_value(config_file, section, option):
config = configparser.ConfigParser()
config.read(config_file)
return config.get(section, option)
class upscale_with:
def __init__(self, url):
self.url = url
self.api_key = get_config_value(configpath, 'STASH', 'api_key')
stash_url = get_config_value(configpath, 'STASH', 'url')
if not stash_url:
self.error("You need to set the URL in 'config.ini'")
return None
self.stash_url = stash_url + "/graphql"
self.headers = {
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json",
"Accept": "application/json",
"Connection": "keep-alive",
"DNT": "1",
"ApiKey": self.api_key
}
def log(self, level, message):
print(f"[{level.upper()}] {message}")
def __prefix(self,levelChar):
startLevelChar = b'\x01'
endLevelChar = b'\x02'
ret = startLevelChar + levelChar + endLevelChar
return ret.decode()
def __log(self,levelChar, s):
if levelChar == "":
return
print(self.__prefix(levelChar) + s + "\n", file=sys.stderr, flush=True)
def trace(self,s):
self.__log(b't', s)
def debug(self,s):
self.__log(b'd', s)
def info(self,s):
self.__log(b'i', s)
def warning(self,s):
self.__log(b'w', s)
def error(self,s):
self.__log(b'e', s)
def progress(self,p):
progress = min(max(0, p), 1)
self.__log(b'p', str(progress))
def __callGraphQL(self, query, variables=None):
json = {}
json['query'] = query
if variables != None:
json['variables'] = variables
# handle cookies
response = requests.post(self.url, json=json, headers=self.headers)
if response.status_code == 200:
result = response.json()
if result.get("error", None):
for error in result["error"]["errors"]:
raise Exception("GraphQL error: {}".format(error))
if result.get("data", None):
return result.get("data")
else:
raise Exception(
"GraphQL query failed:{} - {}. Query: {}. Variables: {}".format(response.status_code, response.content, query, variables))
def listTags(self):
query = """
query {
allTags {
id
name
}
}"""
result = self.__callGraphQL(query)
return result["allTags"]
def findTagIdWithName(self, tag_names):
query = """
query {
allTags {
id
name
}
}
"""
result = self.__callGraphQL(query)
for tag in result["allTags"]:
if tag["name"] in tag_names:
return tag["id"]
return None
def createTagWithName(self, name):
query = """
mutation tagCreate($input:TagCreateInput!) {
tagCreate(input: $input){
id
}
}
"""
variables = {'input': {
'name': name
}}
result = self.__callGraphQL(query, variables)
return result["tagCreate"]["id"]
def removeTagWithID(self, id):
query = """
mutation tagDestroy($input: TagDestroyInput!) {
tagDestroy(input: $input)
}
"""
variables = {'input': {
'id': id
}}
self.__callGraphQL(query, variables)
def findPerformersByTag(self, id):
query = """query performer_images($performer_filter: PerformerFilterType!) {
findPerformers(performer_filter: $performer_filter filter: {per_page: -1}){
performers{
id
name
image_path
tags{
name
}
}
}
}"""
variables = {'performer_filter': {
'tags': {
'value': id, 'modifier': 'INCLUDES', 'depth':1
}
}}
result = self.__callGraphQL(query, variables)
performers = result["findPerformers"]["performers"]
image_paths_tags = [(performer["image_path"], performer["id"]) for performer in performers]
return image_paths_tags
def processPerformerImage(self, image_path, performer_id, scale, mode):
# code to process image using the gigapixel library
# using the scale and mode values passed as arguments
scale = Scale.__getattr__(scale_setting)
mode = Mode.__getattr__(mode_setting)
# Check if Gigapixel is open, if yes close items
for process in psutil.process_iter():
try:
if process.exe() == exe_path:
# The process was found
process_id = process.pid
break
except psutil.AccessDenied:
# The process cannot be accessed, so skip it
pass
# Create Gigapixel instance.
app = Gigapixel(exe_path, output_suffix)
# Set current directory
current_dir = Path().resolve()
# Variable for saved image
image_name = "image_to_process.jpg"
image_saved = current_dir / image_name
# Download image data from the image URL
r = requests.get(image_path, stream = True)
r.raw.decode_content = True
with open(image_saved, 'wb') as f:
shutil.copyfileobj(r.raw, f)
# Process the image
output_path = app.process(image_saved, scale=scale, mode=mode)
# Delete the original image
os.remove(image_saved)
# move the processed image to custom mapped folder
image_moved = shutil.move(output_path, mapped_path)
image_upload_url = mapped_url + image_name
# Update performer with new image
query = """
mutation performerUpdate($performer_update_input: PerformerUpdateInput!){
performerUpdate(input: $performer_update_input){
id
}
}
"""
variables = {"performer_update_input": {"image": image_upload_url, "id": performer_id}}
result = self.__callGraphQL(query, variables)
# Print the result of the GraphQL mutation
self.error("result: "+str(result))
# Delete the processed image
os.remove(image_moved)
def setup_tags(self):
for tag_name in tag_names:
tag_id = self.findTagIdWithName(tag_name)
if tag_id == None:
tag_id = self.createTagWithName(tag_name)
self.debug("Adding tag: "+tag_name)
else:
self.error("Tag already exists: "+tag_name)
def remove_tags(self):
for tag_name in tag_names:
tag_id = self.findTagIdWithName(tag_name)
if tag_id == None:
self.error("Error: "+tag_name + "doesn't exist")
else:
self.debug("Removing tag: , "+tag_name)
tag_id = self.removeTagWithID(tag_id)
def upscale_PerformerImage(self, performer_id):
global scale_setting
global mode_setting
# Find performers by tag
performers = self.findPerformersByTag(performer_id)
for performer in performers:
tags = performer['tags']
# Check if performer is only tagged with one value
if len(tags) == 1:
tag = tags[0]
# Check if tag is in tag_names
if tag in tag_names:
# Put tag value into a variable
tag_value = tag
# Set variables for scale
if '0.5x' in tag_value:
scale_setting = 'Scale.X05'
elif "2x" in tag_value:
scale_setting = 'Scale.X2'
elif "4x" in tag_value:
scale_setting = 'Scale.X4'
elif "6x" in tag_value:
scale_setting = 'Scale.X6'
else:
print('No scale in tag name')
# Set variables for mode
if 'Standard' in tag_value:
mode_setting = 'Mode.STANDARD'
elif "Lines" in tag_value:
mode_setting = 'Mode.Lines'
elif "Art & CG" in tag_value:
mode_setting = 'Mode.ART_AND_CG'
elif "Low Resolution" in tag_value:
mode_setting = 'Mode.LOW_RESOLUTION'
elif "Very Compressed" in tag_value:
mode_setting = 'Mode.VERY_COMPRESSED'
else:
print('No mode in tag name')
else:
self.error(f"Tag '{tag}' is not a valid tag name")
continue
else:
self.error(f"Performer with ID '{performer_id}' is tagged with more than one value")
continue
tag_id = self.findTagIdWithName(tag_name)
if tag_id is None:
self.error("Tag missing:"+tag_name)
else:
self.info("Tag exists: "+tag_name)
image_paths_tags = self.findPerformersByTag(tag_id)
for image_path, performer_id in image_paths_tags:
scale = Scale.__getattr__(scale_setting)
mode = Mode.__getattr__(mode_setting)
self.processPerformerImage(image_path, performer_id, scale_setting, mode_setting)
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
if len(sys.argv) > 1:
url = "http://localhost:9999/graphql"
if len(sys.argv) > 2:
url = sys.argv[2]
if sys.argv[1] == "setup":
client = upscale_all(url)
client.setup_tags()
elif sys.argv[1] =="upscale_all":
client = upscale_all(url)
client.upscale_PerformerImage()
elif sys.argv[1] =="remove_tags":
client = upscale_all(url)
client.remove_tags()
elif sys.argv[1]== "api":
fragment = json.loads(sys.stdin.read())
scheme=fragment["server_connection"]["Scheme"]
port=fragment["server_connection"]["Port"]
domain="localhost"
if "Domain" in fragment["server_connection"]:
domain = fragment["server_connection"]["Domain"]
if not domain:
domain='localhost'
url = scheme + "://" + domain + ":" +str(port) + "/graphql"
client=upscale_with(url)
mode=fragment["args"]["mode"]
client.debug("Mode: "+mode)
if mode == "setup":
client.setup_tags()
elif mode == "upscale_all":
client.upscale_PerformerImage()
elif mode == "remove_tags":
client.remove_tags()
else:
print("")
| 85f5ffa986d162960b2651560d442e35 | 112 | dianewan | 2023-05-25T00:19:54 | bad | [] |
Rewrite my BotService class so it schedules jobs and runs generateScreenshot, show only the relevant parts of my code
This is a JSON object with an example of an array of jobs.
[{caption: 'Buen día ${hoy} \n _Lugares disponibles:_ bit.ly/3civct4', report: 'capacidades', chatId: ['5217221530884-1442235787@g.us','5217224584227-1436726497@g.us']}, {caption: 'Buenos días, les comparto su última asistencia registrada.', report: 'asistencia', chatId: ['5217223784886-1598620689@g.us','5217224748923-1440559046@g.us','5217221530884-1423926397@g.us']}, {caption: '!eventos', report: 'eventos', chatId: ['5217223784886-1598620689@g.us','5217221508888-1431783389@g.us','5217224748923-1440559046@g.us','5217221530884-1423926397@g.us','120363026399428220@g.us']}, {caption: '!acuerdos', report: 'acuerdos-cover', chatId: ['5217223784886-1598620689@g.us']}, {caption: 'Buenos días, les comparto estadísticos Covid a nivel Nacional;\n Confirmados:', report: 'covid/A', chatId: ['5217222527199-1546534573@g.us']}, {caption: 'Defunciones en los últimos 12 días ', report: 'covid/B', chatId: ['5217222527199-1546534573@g.us']}]
## App\Services\BotService\index.ts
import {
LocalAuth,
Client,
WAState,
ClientInfo,
MessageMedia
}
from "whatsapp-web.js";
import fetch from "node-fetch";
import fs from "fs";
import util from 'util';
import qrcode from "qrcode-terminal";
import actions from "App/Services/ActionsService"
import {
scheduleJob
} from 'node-schedule';
import {
Cluster
} from 'puppeteer-cluster';
import xml2js from 'xml2js';
var parser = new xml2js.Parser();
import * as mysql from "mysql";
import moment from 'moment'
import {
createCanvas,
loadImage
} from 'canvas';
import tmp from 'tmp';
const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);
export default class BotService {
public client: Client;
public qr: string | null = null;
public state: WAState = WAState.UNPAIRED;
public ms = 0;
public lastTitle = "";
public parser: parser;
public initialized(ms) {
this.client.sendMessage(
"5217291065569@c.us",
"_🐺 🤖 Cliente listo después de " + ms + " milisegundos!_ "
);
}
async function generateScreenshot(jobs) {
// Create a new puppeteer cluster with 2 workers.
const cluster = await Cluster.launch({
concurrency: Cluster.CONCURRENCY_CONTEXT,
maxConcurrency: 2,
});
// Define a task that each worker will run to generate a screenshot.
cluster.task(async ({
page,
data: job
}) => {
// Set the viewport and user agent (just in case).
await page.setViewport({
width: 1280,
height: 800
});
await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36');
const url = 'https://reportes.casitaapps.com/' + job.report;
// Navigate to the URL specified in the job object and wait for it to load.
await page.goto(url);
// Wait for the page to indicate that it is ready.
const watchDog = page.waitForFunction('window.status === "ready"');
await watchDog;
// Take a screenshot of the element with the specified selector and return it as a buffer.
const element = await page.$('#frame');
const screenshot = await element.screenshot();
return screenshot;
});
// Generate a screenshot for each job in the array.
const promises = jobs.map((job) => cluster.execute(job));
const screenshotData = await Promise.all(promises);
// Close the cluster when all jobs are finished.
await cluster.close();
return screenshotData;
}
public async delay(): Promise < void > {
const min = Math.ceil(3000);
const max = Math.floor(10000);
const ms = Math.floor(Math.random() * (max - min)) + min;
await new Promise((resolve) => setTimeout(resolve, ms));
}
constructor() {
const authStrategy: LocalAuth = new LocalAuth({
clientId: "client-one",
dataPath: "C:/Server/htdocs/Adonis/whatsapp/.wwebjs_auth/",
});
this.actions = new actions();
this.client = new Client({
puppeteer: {
headless: false,
executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'
},
takeoverOnConflict: true,
takeoverTimeoutMs: 10,
authStrategy,
});
this._listenForReady();
this._listenIncoming();
this._listenForQRCode();
this._listenForChangeState();
this._initializeClient()
.then(async () => {
const version = await this.client.getWWebVersion();
console.log(`WHATSAPP WEB VERSION: v${version}`);
this.state = WAState.CONNECTED;
const {
default: EvaService
} = await import('@ioc:App/Services/EvaService')
this.actions.eva = EvaService;
})
.catch((err) => {
console.log(err);
});
}
protected async _initializeClient(): Promise < void > {
return this.client.initialize();
}
protected _listenForQRCode(): void {
this.client.on("qr", (qr: string) => {
console.log("QR RECEIVED", qr);
this.qr = qr;
qrcode.generate(qr, {
small: true
});
});
}
protected _listenForReady(): void {
this.client.on("ready", () => {
console.log("Client is ready!", "Checking SSN...");
this._checkSSN();
// this._clearMysql();
this._checkScheduled();
this.state = WAState.CONNECTED;
});
}
protected _listenIncoming(): void {
this.client.on("message", async (message) => {
if (message.id.fromMe) return false;
try {
this.actions.response(message, this.client);
} catch (err) {
console.log('An error occurrsed in the responses logic', err);
}
});
this.client.on("message_create", async (message) => {
if (!message.id.fromMe) return false;
try {
this.actions.response(message, this.client);
} catch (err) {
console.log('An error occurrsed in the responses logic', err);
}
});
}
protected _listenForChangeState(): void {
this.client.on("change_state", (state: WAState) => {
console.log("State changed: ");
this.state = state;
});
}
protected _clearMysql(): void {
// setInterval(async () => {
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "Nicole10*",
database: 'control_coordinaciones'
});
var data = [];
const promise = new Promise((resolve, reject) => {
db.query("SELECT CONCAT('KILL ',id,';') as query FROM information_schema.processlist WHERE command='Sleep' AND time > 900;")
.on("error", (err) => {
console.error(err);
reject(err);
})
.on("result", (row) => {
db.pause();
data.push(row.query);
db.resume();
})
.on("end", () => {
resolve(data);
});
});
promise.then((data) => {
//now execute each result as a query and close mysql connection after all queries have been executed.
const promise2 = new Promise((resolve, reject) => {
const killQueries = data.map((killQuery) => {
return new Promise((resolve, reject) => {
db.query(killQuery, (err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
});
Promise.all(killQueries).then(() => {
db.end();
resolve();
}).catch((err) => {
db.end();
reject(err);
});
});
promise2.then(() => {
// console.log("All queries executed successfully");
}).catch((err) => {
console.error(err);
});
}).catch((err) => {
console.error(err);
});
// }, 60000);
}
protected _checkScheduled(): void {
setInterval(async () => {
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "Nicole10*",
database: 'casitaiedis',
charset: 'utf8mb4'
});
var data = [];
const promise = new Promise((resolve, reject) => {
db.query("SELECT id, message, scheduled_at, target_id FROM scheduled_messages WHERE scheduled_at <= NOW() AND scheduled_at >= DATE_SUB(NOW(), INTERVAL 1 MINUTE) AND sent = 0")
.on("error", (err) => {
console.error(err);
reject(err);
})
.on("result", (row) => {
db.pause();
data.push(row);
db.resume();
})
.on("end", () => {
resolve(data);
});
});
promise.then((data) => {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
this.client.sendMessage(
data[i]['target_id'],
data[i].message
);
db.query(`UPDATE scheduled_messages SET sent = '1' WHERE id = '${data[i].id}'`).on("error", (err) => {
console.error(err);
})
db.end();
this._postal();
// this._clearMysql();
}
} else {
db.end();
this._postal();
// this._clearMysql();
console.log(moment().format('HH:mm:ss'), WAState.CONNECTED);
}
});
}, 50000);
}
protected _checkSSN(): void {
setInterval(async () => {
var body = await fetch('http://www.ssn.unam.mx/rss/ultimos-sismos.xml').then(res => res.text());
var xml = await parser.parseStringPromise(body);
var items = xml.rss.channel[0].item;
var title = items[0].title[0].trim();
// var scale = title.split(",")[0]; haz una función por cada grado, un emoji adicional 🚨
// var tipo = parseFloat(scale) > 5 ? "sismo" : "replica";
if (items.length == 1) { //Everyone else
console.log('ssn', this.lastTitle);
var mgntd = parseFloat(title.split(",")[0].replace("Preliminar: M ", ""));
if (title !== this.lastTitle && this.lastTitle) { // only mag 6> can be sent to 7 fa and coords
if (mgntd > 6) {
this.client.sendMessage( //replace with sendMultiple after testing
"5217223784886-1598620689@g.us", //Change
`🚨🚨🚨 Alerta *sismo* Tiempo Real\n\n*${title}*`
);
this.client.sendMessage( //replace with sendMultiple after testing
"5217221508888-1431783389@g.us", //Change
`🚨🚨🚨 Alerta *sismo* Tiempo Real\n\n*${title}*`
);
} else {
this.client.sendMessage(
"5217291065569@c.us", //Just you
`🚨 Alerta sismo *menor* Tiempo Real\n\n*${title}*`
);
}
}
} else if (this.lastTitle) {
if (title !== this.lastTitle) {
this.client.sendMessage(
"5217291065569@c.us", //Just you
`🚨 Alerta sismo *menor* Tiempo Real\n\n*${title}*`
);
}
}
this.lastTitle = title;
}, 60000);
}
protected async _postal(): void {
var db = mysql.createConnection({
host: "localhost",
user: "root",
password: "Nicole10*",
database: 'casitaiedis',
charset: 'utf8mb4'
});
var data = [];
const promise = new Promise((resolve, reject) => {
db.query("select * from ((SELECT id, de as 'text', concat('521',para,'@c.us') as 'to' FROM xmas WHERE sent = '0' and error = '0' LIMIT 10) A INNER JOIN (SELECT x, y, path as imagePath, color FROM xmas_postales ORDER BY RAND() LIMIT 1) B) where id is not null")
.on("error", (err) => {
console.error(err);
reject(err);
})
.on("result", (row) => {
db.pause();
data.push(row);
db.resume();
})
.on("end", () => {
resolve(data);
});
});
var data = await promise;
console.log('Batch of ' + data.length);
const promises = [];
for (var i = 0; i < data.length; i++) {
promises.push(new Promise(async (resolve, reject) => {
var imagePath = data[i].imagePath;
var x = data[i].x;
var y = data[i].y;
var color = data[i].color;
var text = data[i].text;
var to = data[i].to;
var id = data[i].id;
if (!id) {
resolve();
}
console.log(`Sending to ${to} from ${text} at ${x} ${y}`);
await this.delay();
try {
// var buffer = await fetch(`https://bot.casitaapps.com/postal?x=${x}&y=${y}&imagePath=${imagePath}&text=${text}`).then(res => res.buffer());
// var media = new MessageMedia('image/png', buffer);
// await this.client.sendMessage(to, media);
var canvas = createCanvas(1024, 576);
var ctx = canvas.getContext('2d');
var image = await loadImage(imagePath);
ctx.drawImage(image, 0, 0, 1024, 576);
ctx.fillStyle = color;
ctx.font = 'bold 30pt Menlo';
ctx.fillText(text, x, y);
const buffer = canvas.toBuffer('image/png');
const tmpobj = tmp.fileSync();
await writeFile(tmpobj.name, buffer);
const media = await MessageMedia.fromFilePath(tmpobj.name);
media.mimetype = 'image/png'
await this.client.sendMessage(to, media);
console.log(`Sent to ${to}`);
db.query(`UPDATE xmas SET sent = '1' WHERE id = '${id}'`).on("error", (err) => {
console.error(err);
})
resolve();
} catch (err) {
console.log('Errorzote', err);
db.query(`UPDATE xmas SET error = '1' WHERE id = '${id}'`).on("error", (err) => {
console.error(err);
})
resolve();
}
}));
}
await Promise.all(promises);
db.end();
this._clearMysql();
}
protected async _sendMultiple(chatIds, message, args): void {
for (var i = 0; i < chatIds.length; i++) {
await this.delay().then((e) => {
this.client.sendMessage(
chatIds[i],
message,
args
);
});
}
}
} | 0b888342c95111a5d6e4f01c9a1a2ae9 | 113 | dianewan | 2023-05-25T00:20:20 | bad | [] |
I encrypted the passphrase using the following commands for passphrase.enc ($PASSPHRASE_FILE) and the
export.enc ($EXPORT_FILE)
```openssl enc -d -aes-256-cbc -in passphrase.enc```
```openssl enc -d -aes-256-cbc -in export.enc```
I then created a p.12 certificate using an encrypted passphrase from those files above:
```openssl pkcs12 -export -in "$SIGNED_CERT_CRT" -inkey "$SIGNED_CERT_KEY" -passin file:"$PASSPHRASE_FILE" -passout file:"$EXPORT_FILE" -out "$SIGNED_CERT_P12"```
But on MacOS when i aadd the .p12 certificate to the keychain it prompts me for a password, i enter the export.enc password from that file and this doesn't work.
I also wonder how could the following command create the certificate from that encrypted file without asking me for the password that protects the passphrase | 263c40f8d6758e91b68913f97464160c | 114 | dianewan | 2023-05-25T00:20:52 | bad | [] |
글을 읽고 이 글이 어떤 회사와 관련되어 있는지 한 단어로 알려줘.
"* Canada
Travel Canada Vancouver Toronto + Air Canada Sharing Tips
Profile
Mio, 2022. 12. 20. 20:42
Copy URL Add Neighbor
BodyOther functions
There was a place I really wanted to go this year.
That's where I used to live in #Canada :)
I'm sure some of you know,
I lived in Vancouver and worked at Starbucks.
It feels like my second home.
And recently, a close friend of mine said,
#I'm going to Vancouver on Air Canada.
I'm envious and want to go. T_T
#When I go on a trip to Canada,
It's convenient to go by direct flight.
I get really tired when I transfer;
Right now, Air Canada is...
It connects Korea and Canada directly.
7 flights per week from Incheon to Vancouver
Incheon to Toronto 5 times a week
The flight schedule changes from time to time.
As of mid-January 2023,
< Vancouver >
ICN (18:50)-YVR (11:30): 9 hours and 40 minutes
YVR (12:15)-ICN (17:05 +1): 11 hours and 50 minutes
< Toronto >
ICN (15:15)-YZ (14:20): 13 hours and 5 minutes
YYZ (23:05)-ICN (3:50 +2): 14 hours and 45 minutes
It was roughly this kind of flight schedule.
Air Canada is located at Incheon International Airport.
Check-in and boarding are available at Passenger Terminal 1.
Your final destination is not Vancouver or Toronto.
You can use the automatic baggage transfer service.
In other words, after leaving Incheon and passing through Vancouver,
So if you're finally going to Calgary,
I didn't pick up my luggage in Vancouver, a stopover.
You can find it right in Calgary!
By the way, if the final destination is the United States,
I'm going to the U.S. via Canada.
Immigration is easier than direct flights between Korea and the United States.
We're conducting customs inspection in Canada.
You know that immigration in the U.S. is very difficult.
If you use Air Canada's signature class,
You can use Maple Leaf Lounge before boarding.
Lounge located at 16 airports in Canada, the United States, and Europe.
You can enjoy snacks and drinks for free before boarding the plane.
Shower rooms and business centers are also available.
Before the long flight, in the lounge,
I can't believe I can rest like this.
Don't you think it'll be so nice? Hah!
The seats in Air Canada are
Economy, Premium Economy,
And with signature class (business class),
I can share it with you :)
Down here is the economy class.
The leg room was spacious and the flight attendants were kind.
I've also had the experience of riding happily.
Snacks and drinks in the middle, too!
Air Canada is famous for its good in-flight meals.
Famous chefs and wine experts curated it.
They say the quality is very high quality. >_<
If you want to make long-haul flights more comfortable,
I recommend premium economy rather than economy.
Even if it's not business, the fatigue level is much lower!
If you can afford the travel expenses,
It's definitely a signature class.
It's a pretty happy thing to fly lying down.
Long-haul flights never tire you. Hah!
Especially when using signature classes.
Concierge services, quick check-in, boarding privileges, etc.
The fact that you can enjoy a variety of benefits!!
Air Canada is a member of Star Alliance.
I'll earn mileage and get Air Canada or...
Star Alliance Airlines is available.
Star Alliance is the world's largest,
It's an aviation alliance, so it has a lot of advantages. >_<
I also have a lot of mileage accumulated here!
Canada is now a winter country.
There's a pretty Christmas market.
It's a perfect season for skiing or snowboarding.
My friend who's gone right now went skiing, too.~
Below is Whistler near Vancouver.
A lot of people go skiing or snowboarding here.
It's also good to go to Yellowknife to see the aurora.
I saw aurora and rode a dog sled.
I had a fun and unique time. :D
Aurora is so mysterious.
I didn't know how to take pictures.
Most of them are shaky cuts, but...
If I go back, I want to take a pretty picture.
We can't leave out Toronto when we travel to Canada, right?
Vancouver in the west, Toronto in the east!!!
One of the world's top three waterfalls,
Niagara Falls is really close.~
If you go there in person, you'll be overwhelmed.
Vancouver and Toronto are great cities.
If you go out to the suburbs, you can meet Mother Nature like this.
Below is a travel destination near Toronto called Tobermory.
It's a place with clear water and good air, so it's worth visiting!
It's good to go to Canada for a trip,
Like me, I hope you gain a year of experience as a working holiday.
Or it's a good place to study abroad and settle down.
I've lived in Japan, Germany, Australia, and Canada.
If you ask me where is the best place to live,
It's a landslide victory in Canada. ♥
If I have a chance to travel to the Americas,
Check your ticket at Air Canada's official website below!
Link to Air Canada official site
▼
Air Canada
www.aircanada.com
We receive a small fee from AIR CANADA.
Tags
#Canada, Canada
#AirCanada
#Travel to Canada
#Traveling in America
#Traveling abroad
#Recommendation for overseas travel
#Air Canada in-flight meals
#In-flight meal review
#Airline Recommendation
#Studying in Canada
#Canada flight ticket
#WarhallCanada
#WorkingHoliday
#Studying in the United States
#Warhall, United States"
| f1b00005fc4b826ccd5334efc8d52432 | 115 | dianewan | 2023-05-25T00:21:31 | bad | [] |
c++ opengl I am working on a small game engine. I have a problem regarding rendering 3D models. Models can consist of multiple meshes and meshes consist of multiple verticies. I want to be able to load in a model using Assimp from a file and store the modesl data for each mesh and each vertex, so that we only have to load it once. Later I want to draw the model using a class called Renderer3D which will store the various buffers related to the model's meshes. Below is the code I have for loading a model, what is missing from it to store the relevant data for later binding and drawing?
#include "solpch.h"
#include "OpenGL_Model.h"
#include "GalaxyDraw/Platform/OpenGL/GLMacros.h"
#include
#include
#include
#include
namespace GalaxyDraw
{
struct Vertex {
glm::vec3 Position;
glm::vec3 Normal;
glm::vec2 TexCoords;
};
struct Mesh {
public:
std::vector Vertices;
std::vector Indices;
std::vector> Textures;//TODO replace with material struct
Mesh(std::vector vertices, std::vector indices, std::vector> textures):
Vertices(vertices), Indices(indices), Textures(textures)
{}
};
OpenGL_Model::OpenGL_Model(const std::string& modelpath)
{
LoadModel(modelpath);
}
void OpenGL_Model::SetData(const std::string& path)
{
LoadModel(path);
}
bool OpenGL_Model::operator==(const Model& other) const
{
return m_RendererID == ((OpenGL_Model&)other).m_RendererID;
}
void OpenGL_Model::LoadModel(const std::string& modelpath)
{
Assimp::Importer import;
const aiScene* scene = import.ReadFile(modelpath, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenNormals | aiProcess_JoinIdenticalVertices);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
std::cout << "ERROR::ASSIMP::" << import.GetErrorString() << std::endl;
return;
}
m_ModelDirectory = modelpath.substr(0, modelpath.find_last_of('/'));
ProcessNode(scene->mRootNode, scene);
}
void OpenGL_Model::ProcessNode(aiNode* node, const aiScene* scene)
{
// process all the node's meshes (if any)
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
m_Meshes.push_back(ProcessMesh(mesh, scene));
}
// then do the same for each of its children
for (unsigned int i = 0; i < node->mNumChildren; i++)
{
ProcessNode(node->mChildren[i], scene);
}
}
Mesh OpenGL_Model::ProcessMesh(aiMesh* mesh, const aiScene* scene)
{
std::vector vertices;
std::vector indices;
std::vector> textures;
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
Vertex vertex;
glm::vec3 vector;
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
vertex.Position = vector;
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.Normal = vector;
// does the mesh contain texture coordinates?
if (mesh->mTextureCoords[0])
{
glm::vec2 vec;
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.TexCoords = vec;
}
else
{
vertex.TexCoords = glm::vec2(0.0f, 0.0f);
}
vertices.push_back(vertex);
}
// LMAO, I wish C# procedural shit went like this
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++)
{
indices.push_back(face.mIndices[j]);
}
}
// Checks if any material exists at all
//if (mesh->mMaterialIndex >= 0)
//{
// // gets the material cached within that specific index
// aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
// std::vector diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
// textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
// std::vector specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
// textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
//}
return Mesh(vertices, indices, textures);
}
}
| a163631808b5ae980554a69c87c811b6 | 116 | dianewan | 2023-05-25T00:21:50 | good | [
"code"
] |
what does this code do?
const LevelPickerApp = () => {
const { iTwinId, iModelId, authClient } = useViewerContext();
const uiProviders = [new LevelSelectorWidgetProvider()];
/** Setup view state */
const viewportOptions: ViewerViewportControlOptions = {
viewState: async (iModelConnection) => {
const viewState = await ViewSetup.getDefaultView(iModelConnection);
return viewState;
},
};
const onIModelAppInit = async () => {
IModelApp.viewManager.onViewOpen.addOnce(ITwinLink.initializeLink);
IModelApp.viewManager.onViewOpen.addOnce(async () => {
await ITwinLink.getLevels();
})
}
return authClient &&
<Viewer
iTwinId={iTwinId}
iModelId={iModelId}
authClient={authClient}
viewportOptions={viewportOptions}
defaultUiConfig={default3DSandboxUi}
mapLayerOptions={mapLayerOptions}
onIModelConnected={onIModelAppInit}
enablePerformanceMonitors={false}
uiProviders={uiProviders}
theme="dark"
/>;
};
| aadfe91ed5c679b06a208f9eec2ae573 | 117 | dianewan | 2023-05-25T00:22:22 | good | [
"code"
] |
import { Injectable } from '@nestjs/common';
import type { AssistantAPI } from 'Assistant';
import 'isomorphic-fetch';
const importDynamic = new Function('modulePath', 'return import(modulePath)');
@Injectable()
export class ChatgptUnofficialProxyApiService {
async sendMessage(prompt: string): Promise<{ text: string }> {
const { AssistantAPIBrowser } = await importDynamic('Assistant');
const api = new AssistantAPIBrowser({
email: '996251389@qq.com',
password: 'Qwer123@',
});
await api.initSession();
const result = await api.sendMessage(prompt);
return { text: JSON.stringify(result) };
}
}
帮我优化上述代码,要求:只初始化一次 | dc434d9e71ab2be942c6840910c1a1e3 | 118 | dianewan | 2023-05-25T00:22:26 | bad | [] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./utils/MetaContext.sol";
import "./interfaces/IPosition.sol";
contract Position is ERC721Enumerable, MetaContext, IPosition {
function ownerOf(uint _id) public view override(ERC721, IERC721, IPosition) returns (address) {
return ERC721.ownerOf(_id);
}
using Counters for Counters.Counter;
uint constant public DIVISION_CONSTANT = 1e10; // 100%
mapping(uint => mapping(address => uint)) public vaultFundingPercent;
mapping(address => bool) private _isMinter; // Trading contract should be minter
mapping(uint256 => Trade) private _trades; // NFT id to Trade
uint256[] private _openPositions;
mapping(uint256 => uint256) private _openPositionsIndexes;
mapping(uint256 => uint256[]) private _assetOpenPositions;
mapping(uint256 => mapping(uint256 => uint256)) private _assetOpenPositionsIndexes;
mapping(uint256 => uint256[]) private _limitOrders; // List of limit order nft ids per asset
mapping(uint256 => mapping(uint256 => uint256)) private _limitOrderIndexes; // Keeps track of asset -> id -> array index
// Funding
mapping(uint256 => mapping(address => int256)) public fundingDeltaPerSec;
mapping(uint256 => mapping(address => mapping(bool => int256))) private accInterestPerOi;
mapping(uint256 => mapping(address => uint256)) private lastUpdate;
mapping(uint256 => int256) private initId;
mapping(uint256 => mapping(address => uint256)) private longOi;
mapping(uint256 => mapping(address => uint256)) private shortOi;
function isMinter(address _address) public view returns (bool) { return _isMinter[_address]; }
function trades(uint _id) public view returns (Trade memory) {
Trade memory _trade = _trades[_id];
_trade.trader = ownerOf(_id);
if (_trade.orderType > 0) return _trade;
int256 _pendingFunding;
if (_trade.direction && longOi[_trade.asset][_trade.tigAsset] > 0) {
_pendingFunding = (int256(block.timestamp-lastUpdate[_trade.asset][_trade.tigAsset])*fundingDeltaPerSec[_trade.asset][_trade.tigAsset])*1e18/int256(longOi[_trade.asset][_trade.tigAsset]);
if (longOi[_trade.asset][_trade.tigAsset] > shortOi[_trade.asset][_trade.tigAsset]) {
_pendingFunding = -_pendingFunding;
} else {
_pendingFunding = _pendingFunding*int256(1e10-vaultFundingPercent[_trade.asset][_trade.tigAsset])/1e10;
}
} else if (shortOi[_trade.asset][_trade.tigAsset] > 0) {
_pendingFunding = (int256(block.timestamp-lastUpdate[_trade.asset][_trade.tigAsset])*fundingDeltaPerSec[_trade.asset][_trade.tigAsset])*1e18/int256(shortOi[_trade.asset][_trade.tigAsset]);
if (shortOi[_trade.asset][_trade.tigAsset] > longOi[_trade.asset][_trade.tigAsset]) {
_pendingFunding = -_pendingFunding;
} else {
_pendingFunding = _pendingFunding*int256(1e10-vaultFundingPercent[_trade.asset][_trade.tigAsset])/1e10;
}
}
_trade.accInterest += (int256(_trade.margin*_trade.leverage/1e18)*(accInterestPerOi[_trade.asset][_trade.tigAsset][_trade.direction]+_pendingFunding)/1e18)-initId[_id];
return _trade;
}
function openPositions() public view returns (uint256[] memory) { return _openPositions; }
function openPositionsIndexes(uint _id) public view returns (uint256) { return _openPositionsIndexes[_id]; }
function assetOpenPositions(uint _asset) public view returns (uint256[] memory) { return _assetOpenPositions[_asset]; }
function assetOpenPositionsIndexes(uint _asset, uint _id) public view returns (uint256) { return _assetOpenPositionsIndexes[_asset][_id]; }
function limitOrders(uint _asset) public view returns (uint256[] memory) { return _limitOrders[_asset]; }
function limitOrderIndexes(uint _asset, uint _id) public view returns (uint256) { return _limitOrderIndexes[_asset][_id]; }
Counters.Counter private _tokenIds;
string public baseURI;
constructor(string memory _setBaseURI, string memory _name, string memory _symbol) ERC721(_name, _symbol) {
baseURI = _setBaseURI;
_tokenIds.increment();
}
function _baseURI() internal override view returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
/**
* @notice Update funding rate after open interest change
* @dev only callable by minter
* @param _asset pair id
* @param _tigAsset tigAsset token address
* @param _longOi long open interest
* @param _shortOi short open interest
* @param _baseFundingRate base funding rate of a pair
* @param _vaultFundingPercent percent of earned funding going to the stablevault
*/
function updateFunding(uint256 _asset, address _tigAsset, uint256 _longOi, uint256 _shortOi, uint256 _baseFundingRate, uint _vaultFundingPercent) external onlyMinter {
if(longOi[_asset][_tigAsset] < shortOi[_asset][_tigAsset]) {
if (longOi[_asset][_tigAsset] > 0) {
accInterestPerOi[_asset][_tigAsset][true] += ((int256(block.timestamp-lastUpdate[_asset][_tigAsset])*fundingDeltaPerSec[_asset][_tigAsset])*1e18/int256(longOi[_asset][_tigAsset]))*int256(1e10-vaultFundingPercent[_asset][_tigAsset])/1e10;
}
accInterestPerOi[_asset][_tigAsset][false] -= (int256(block.timestamp-lastUpdate[_asset][_tigAsset])*fundingDeltaPerSec[_asset][_tigAsset])*1e18/int256(shortOi[_asset][_tigAsset]);
} else if(longOi[_asset][_tigAsset] > shortOi[_asset][_tigAsset]) {
accInterestPerOi[_asset][_tigAsset][true] -= (int256(block.timestamp-lastUpdate[_asset][_tigAsset])*fundingDeltaPerSec[_asset][_tigAsset])*1e18/int256(longOi[_asset][_tigAsset]);
if (shortOi[_asset][_tigAsset] > 0) {
accInterestPerOi[_asset][_tigAsset][false] += ((int256(block.timestamp-lastUpdate[_asset][_tigAsset])*fundingDeltaPerSec[_asset][_tigAsset])*1e18/int256(shortOi[_asset][_tigAsset]))*int256(1e10-vaultFundingPercent[_asset][_tigAsset])/1e10;
}
}
lastUpdate[_asset][_tigAsset] = block.timestamp;
int256 _oiDelta;
if (_longOi > _shortOi) {
_oiDelta = int256(_longOi)-int256(_shortOi);
} else {
_oiDelta = int256(_shortOi)-int256(_longOi);
}
fundingDeltaPerSec[_asset][_tigAsset] = (_oiDelta*int256(_baseFundingRate)/int256(DIVISION_CONSTANT))/31536000;
longOi[_asset][_tigAsset] = _longOi;
shortOi[_asset][_tigAsset] = _shortOi;
vaultFundingPercent[_asset][_tigAsset] = _vaultFundingPercent;
}
/**
* @notice mint a new position nft
* @dev only callable by minter
* @param _mintTrade New trade params in struct
*/
function mint(
MintTrade memory _mintTrade
) external onlyMinter {
uint newTokenID = _tokenIds.current();
Trade storage newTrade = _trades[newTokenID];
newTrade.margin = _mintTrade.margin;
newTrade.leverage = _mintTrade.leverage;
newTrade.asset = _mintTrade.asset;
newTrade.direction = _mintTrade.direction;
newTrade.price = _mintTrade.price;
newTrade.tpPrice = _mintTrade.tp;
newTrade.slPrice = _mintTrade.sl;
newTrade.orderType = _mintTrade.orderType;
newTrade.id = newTokenID;
newTrade.tigAsset = _mintTrade.tigAsset;
_safeMint(_mintTrade.account, newTokenID);
if (_mintTrade.orderType > 0) {
_limitOrders[_mintTrade.asset].push(newTokenID);
_limitOrderIndexes[_mintTrade.asset][newTokenID] = _limitOrders[_mintTrade.asset].length-1;
} else {
initId[newTokenID] = accInterestPerOi[_mintTrade.asset][_mintTrade.tigAsset][_mintTrade.direction]*int256(_mintTrade.margin*_mintTrade.leverage/1e18)/1e18;
_openPositions.push(newTokenID);
_openPositionsIndexes[newTokenID] = _openPositions.length-1;
_assetOpenPositions[_mintTrade.asset].push(newTokenID);
_assetOpenPositionsIndexes[_mintTrade.asset][newTokenID] = _assetOpenPositions[_mintTrade.asset].length-1;
}
_tokenIds.increment();
}
/**
* @param _id id of the position NFT
* @param _price price used for execution
* @param _newMargin margin after fees
*/
function executeLimitOrder(uint256 _id, uint256 _price, uint256 _newMargin) external onlyMinter {
Trade storage _trade = _trades[_id];
if (_trade.orderType == 0) {
return;
}
_trade.orderType = 0;
_trade.price = _price;
_trade.margin = _newMargin;
uint _asset = _trade.asset;
_limitOrderIndexes[_asset][_limitOrders[_asset][_limitOrders[_asset].length-1]] = _limitOrderIndexes[_asset][_id];
_limitOrders[_asset][_limitOrderIndexes[_asset][_id]] = _limitOrders[_asset][_limitOrders[_asset].length-1];
delete _limitOrderIndexes[_asset][_id];
_limitOrders[_asset].pop();
_openPositions.push(_id);
_openPositionsIndexes[_id] = _openPositions.length-1;
_assetOpenPositions[_asset].push(_id);
_assetOpenPositionsIndexes[_asset][_id] = _assetOpenPositions[_asset].length-1;
initId[_id] = accInterestPerOi[_trade.asset][_trade.tigAsset][_trade.direction]*int256(_trade.margin*_trade.leverage/1e18)/1e18;
}
/**
* @notice modifies margin and leverage
* @dev only callable by minter
* @param _id position id
* @param _newMargin new margin amount
* @param _newLeverage new leverage amount
*/
function modifyMargin(uint256 _id, uint256 _newMargin, uint256 _newLeverage) external onlyMinter {
_trades[_id].margin = _newMargin;
_trades[_id].leverage = _newLeverage;
}
/**
* @notice modifies margin and entry price
* @dev only callable by minter
* @param _id position id
* @param _newMargin new margin amount
* @param _newPrice new entry price
*/
function addToPosition(uint256 _id, uint256 _newMargin, uint256 _newPrice) external onlyMinter {
_trades[_id].margin = _newMargin;
_trades[_id].price = _newPrice;
initId[_id] = accInterestPerOi[_trades[_id].asset][_trades[_id].tigAsset][_trades[_id].direction]*int256(_newMargin*_trades[_id].leverage/1e18)/1e18;
}
/**
* @notice Called before updateFunding for reducing position or adding to position, to store accumulated funding
* @dev only callable by minter
* @param _id position id
*/
function setAccInterest(uint256 _id) external onlyMinter {
_trades[_id].accInterest = trades(_id).accInterest;
}
/**
* @notice Reduces position size by %
* @dev only callable by minter
* @param _id position id
* @param _percent percent of a position being closed
*/
function reducePosition(uint256 _id, uint256 _percent) external onlyMinter {
_trades[_id].accInterest -= _trades[_id].accInterest*int256(_percent)/int256(DIVISION_CONSTANT);
_trades[_id].margin -= _trades[_id].margin*_percent/DIVISION_CONSTANT;
initId[_id] = accInterestPerOi[_trades[_id].asset][_trades[_id].tigAsset][_trades[_id].direction]*int256(_trades[_id].margin*_trades[_id].leverage/1e18)/1e18;
}
/**
* @notice change a position tp price
* @dev only callable by minter
* @param _id position id
* @param _tpPrice tp price
*/
function modifyTp(uint _id, uint _tpPrice) external onlyMinter {
_trades[_id].tpPrice = _tpPrice;
}
/**
* @notice change a position sl price
* @dev only callable by minter
* @param _id position id
* @param _slPrice sl price
*/
function modifySl(uint _id, uint _slPrice) external onlyMinter {
_trades[_id].slPrice = _slPrice;
}
/**
* @dev Burns an NFT and it's data
* @param _id ID of the trade
*/
function burn(uint _id) external onlyMinter {
_burn(_id);
uint _asset = _trades[_id].asset;
if (_trades[_id].orderType > 0) {
_limitOrderIndexes[_asset][_limitOrders[_asset][_limitOrders[_asset].length-1]] = _limitOrderIndexes[_asset][_id];
_limitOrders[_asset][_limitOrderIndexes[_asset][_id]] = _limitOrders[_asset][_limitOrders[_asset].length-1];
delete _limitOrderIndexes[_asset][_id];
_limitOrders[_asset].pop();
} else {
_assetOpenPositionsIndexes[_asset][_assetOpenPositions[_asset][_assetOpenPositions[_asset].length-1]] = _assetOpenPositionsIndexes[_asset][_id];
_assetOpenPositions[_asset][_assetOpenPositionsIndexes[_asset][_id]] = _assetOpenPositions[_asset][_assetOpenPositions[_asset].length-1];
delete _assetOpenPositionsIndexes[_asset][_id];
_assetOpenPositions[_asset].pop();
_openPositionsIndexes[_openPositions[_openPositions.length-1]] = _openPositionsIndexes[_id];
_openPositions[_openPositionsIndexes[_id]] = _openPositions[_openPositions.length-1];
delete _openPositionsIndexes[_id];
_openPositions.pop();
}
delete _trades[_id];
}
function assetOpenPositionsLength(uint _asset) external view returns (uint256) {
return _assetOpenPositions[_asset].length;
}
function limitOrdersLength(uint _asset) external view returns (uint256) {
return _limitOrders[_asset].length;
}
function getCount() external view returns (uint) {
return _tokenIds.current();
}
function userTrades(address _user) external view returns (uint[] memory) {
uint[] memory _ids = new uint[](balanceOf(_user));
for (uint i=0; i<_ids.length; i++) {
_ids[i] = tokenOfOwnerByIndex(_user, i);
}
return _ids;
}
function openPositionsSelection(uint _from, uint _to) external view returns (uint[] memory) {
uint[] memory _ids = new uint[](_to-_from);
for (uint i=0; i<_ids.length; i++) {
_ids[i] = _openPositions[i+_from];
}
return _ids;
}
function setMinter(address _minter, bool _bool) external onlyOwner {
_isMinter[_minter] = _bool;
}
modifier onlyMinter() {
require(_isMinter[_msgSender()], "!Minter");
_;
}
// META-TX
function _msgSender() internal view override(Context, MetaContext) returns (address sender) {
return MetaContext._msgSender();
}
function _msgData() internal view override(Context, MetaContext) returns (bytes calldata) {
return MetaContext._msgData();
}
}
find smart contract vulnerbelities a and add possible solution | 70a8bec9f479442a732082e8daf02094 | 119 | dianewan | 2023-05-25T00:23:22 | bad | [] |
for (const [notifType,notifArr] of Object.entries(notifObj)) {
const message = notifArr[0].message;
return <div>{notifType}{message}</div>
} | 6c4e4e61e3e1701c4d27402fb4ccf86d | 12 | DaehanKim | 2023-05-29T06:39:51 | bad | [] |
for (const [notifType,notifArr] of Object.entries(notifObj)) {
const message = notifArr[0].message;
return <div>{notifType}{message}</div>
} | 6c4e4e61e3e1701c4d27402fb4ccf86d | 12 | dianewan | 2023-05-23T23:27:35 | bad | [] |
What does this statute mean
Intercepting, recording, or divulging private communication—Consent required—Exceptions.
(1) Except as otherwise provided in this chapter, it shall be unlawful for any individual, partnership, corporation, association, or the state of Washington, its agencies, and political subdivisions to intercept, or record any:
(a) Private communication transmitted by telephone, telegraph, radio, or other device between two or more individuals between points within or without the state by any device electronic or otherwise designed to record and/or transmit said communication regardless how such device is powered or actuated, without first obtaining the consent of all the participants in the communication;
(b) Private conversation, by any device electronic or otherwise designed to record or transmit such conversation regardless how the device is powered or actuated without first obtaining the consent of all the persons engaged in the conversation.
(2) Notwithstanding subsection (1) of this section, wire communications or conversations (a) of an emergency nature, such as the reporting of a fire, medical emergency, crime, or disaster, or (b) which convey threats of extortion, blackmail, bodily harm, or other unlawful requests or demands, or (c) which occur anonymously or repeatedly or at an extremely inconvenient hour, or (d) which relate to communications by a hostage holder or barricaded person as defined in RCW 70.85.100, whether or not conversation ensues, may be recorded with the consent of one party to the conversation.
(3) Where consent by all parties is needed pursuant to this chapter, consent shall be considered obtained whenever one party has announced to all other parties engaged in the communication or conversation, in any reasonably effective manner, that such communication or conversation is about to be recorded or transmitted: PROVIDED, That if the conversation is to be recorded that said announcement shall also be recorded.
(4) An employee of any regularly published newspaper, magazine, wire service, radio station, or television station acting in the course of bona fide news gathering duties on a full-time or contractual or part-time basis, shall be deemed to have consent to record and divulge communications or conversations otherwise prohibited by this chapter if the consent is expressly given or if the recording or transmitting device is readily apparent or obvious to the speakers. Withdrawal of the consent after the communication has been made shall not prohibit any such employee of a newspaper, magazine, wire service, or radio or television station from divulging the communication or conversation.
(5) This section does not apply to the recording of custodial interrogations pursuant to RCW 10.122.040. | 9f006eec30fd55eece9c9c3909ad8054 | 120 | dianewan | 2023-05-25T00:23:48 | bad | [] |
Write some documentation for this python function:
def healthy(self) -> bool:
# pylint: disable=no-else-raise
try:
with self._connector.conn():
_logger.info(f"{self.name} state: {DependencyState.HEALTHY}")
self._metric_reporter.report_success(self.name)
return True
except Exception as e:
self._metric_reporter.report_failure(self.name)
if self.raises_exception_when_unhealthy:
raise UnhealthyCheckException(
f"{self.name} state: {DependencyState.UNHEALTHY}"
) from e
else:
_logger.warning(f"{self.name} state: {DependencyState.UNHEALTHY}: {e}")
return False | c7c556737862e9e67985890d6a06d3de | 121 | dianewan | 2023-05-25T00:23:52 | good | [
"code"
] |
<div><p class="">Tell me reasons why i should exercise more, but say everything in the speaking style of a pirate. And give me reasons only a pirate would give.</p></div> | 638ea4f28581849f374599abd659702b | 122 | dianewan | 2023-05-25T00:23:59 | bad | [] |
convert this to tailwind and get rid of the style tag. for the after pseudoclass, use the after: prefix in tailwind classes
const Hr = () => (
<div>
<style jsx>{`
div {
border-style: none;
margin-top: 30px;
margin-bottom: 30px;
text-align: center;
}
div::after {
content: "***";
text-align: center;
display: inline;
}
`}</style>
</div>
);
export default Hr;
| 0d50ce1ea333cc14f46b8aa7be7130ad | 123 | dianewan | 2023-05-25T00:24:11 | good | [
"code"
] |
what the name of this programming language
org 0x00
movf 0 * 20 w;w=X
movwf 0 * 26 ;y=x-w
clr 0x27
movf 0 * 20 ;w=x btfsc 0x20,7
sublw 0x00 ; w = - x = 0 - w
bsf STATUS,RP1;BANK2[0x122] movwf 0 * 122 ;a-abs(x)
b=a<<3;
movf 0x122,w
bsf STATUS,RP1 bef STATUS,RPO
movwf OxA2
clr 0xA3
rlf 0xA2,f
rlf OxA3,f
rlf 0xA2,f
rlf 0xA3,f
rlf OxA2,f
rlf OxA3,f
movlw b'11111000'
andwf OxA2,f
movlw OxB6
addwf OxA2, w
c=b+950;
bsf STATUS,RP1
bcf STATUS,RPO
movwf Ox150
bsf STATUS,RPO
bcf STATUS,RP1
movlw 0x03
addwf OxA3,w
bsf STATUS,RP1
bcf STATUS,RPO
movwf Ox151
end | bdb8d44cbcaf7b541586a2f4931b0fb9 | 124 | dianewan | 2023-05-25T00:24:43 | bad | [] |
Please explain the main functionality of this contract, a description for its functions. Be as technical as possible
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ERC2771Context } from "./libs/ERC2771Context.sol";
contract OpenPeerEscrow is ERC2771Context {
using SafeERC20 for IERC20;
// Settings
// Address of the arbitrator (currently OP staff)
address public arbitrator;
// Address to receive the fees
address public feeRecipient;
address public immutable seller;
address public immutable buyer;
address public immutable token;
uint256 public immutable amount;
uint32 public immutable fee;
uint32 public sellerCanCancelAfter;
bool public dispute;
/// @notice Settings
/// @param _buyer Buyer address
/// @param _token Token address or 0x0000000000000000000000000000000000000000 for native token
/// @param _fee OP fee (bps) ex: 30 == 0.3%
/// @param _arbitrator Address of the arbitrator (currently OP staff)
/// @param _feeRecipient Address to receive the fees
/// @param _trustedForwarder Forwarder address
constructor(
address _buyer,
address _token,
uint256 _amount,
uint8 _fee,
address _arbitrator,
address _feeRecipient,
address _trustedForwarder
) ERC2771Context(_trustedForwarder) {
require(_amount > 0, "Invalid amount");
require(_buyer != _msgSender(), "Seller and buyer must be different");
require(_buyer != address(0), "Invalid buyer");
seller = _msgSender();
token = _token;
buyer = _buyer;
amount = _amount;
fee = uint32(amount * _fee / 10_000);
arbitrator = _arbitrator;
feeRecipient = _feeRecipient;
}
// Events
event Created();
event Released();
event CancelledByBuyer();
event SellerCancelDisabled();
event CancelledBySeller();
event DisputeOpened();
event DisputeResolved();
modifier onlySeller() {
require(_msgSender() == seller, "Must be seller");
_;
}
modifier onlyArbitrator() {
require(_msgSender() == arbitrator, "Must be arbitrator");
_;
}
modifier onlyBuyer() {
require(_msgSender() == buyer, "Must be buyer");
_;
}
/// @notice Create and fund a new escrow.
function escrow() payable external {
require(sellerCanCancelAfter == 0, "Funds already escrowed");
if (token == address(0)) {
require(msg.value == amount + fee, "Incorrect MATIC sent");
} else {
IERC20(token).safeTransferFrom(_msgSender(), address(this), amount + fee );
}
sellerCanCancelAfter = uint32(block.timestamp) + 24 hours;
emit Created();
}
/// @notice Release ether or token in escrow to the buyer.
/// @return bool
function release() external onlySeller returns (bool) {
transferEscrowAndFees(buyer, amount, fee);
emit Released();
return true;
}
/// @notice Transfer the value of an escrow
/// @param _to Recipient address
/// @param _amount Amount to be transfered
/// @param _fee Fee to be transfered
function transferEscrowAndFees(address _to, uint256 _amount, uint32 _fee) private {
withdraw(_to, _amount);
if (_fee > 0) {
withdraw(feeRecipient, _fee);
}
}
/// @notice Cancel the escrow as a buyer with 0 fees
/// @return bool
function buyerCancel() external onlyBuyer returns (bool) {
transferEscrowAndFees(seller, amount + fee, 0);
emit CancelledByBuyer();
return true;
}
/// @notice Cancel the escrow as a seller
/// @return bool
function sellerCancel() external onlySeller returns (bool) {
if (sellerCanCancelAfter <= 1 || sellerCanCancelAfter > block.timestamp) {
return false;
}
transferEscrowAndFees(seller, amount + fee, 0);
emit CancelledBySeller();
return true;
}
/// @notice Disable the seller from cancelling
/// @return bool
function markAsPaid() external onlyBuyer returns (bool) {
sellerCanCancelAfter = 1;
emit SellerCancelDisabled();
return true;
}
/// @notice Withdraw values in the contract
/// @param _to Address to withdraw fees in to
/// @param _amount Amount to withdraw
function withdraw(address _to, uint256 _amount) private {
if (token == address(0)) {
(bool sent,) = payable(_to).call{value: _amount}("");
require(sent, "Failed to send MATIC");
} else {
require(IERC20(token).transfer(payable(_to), _amount), "Failed to send tokens");
}
}
/// @notice Allow seller or buyer to open a dispute
function openDispute() external {
require(_msgSender() == seller || _msgSender() == buyer, "Must be seller or buyer");
require(sellerCanCancelAfter > 0, "Funds not escrowed yet");
dispute = true;
emit DisputeOpened();
}
/// @notice Allow arbitrator to resolve a dispute
/// @param _winner Address to receive the escrowed values - fees
function resolveDispute(address payable _winner) external onlyArbitrator {
require(dispute, "Dispute is not open");
require(_winner == seller || _winner == buyer, "Winner must be seller or buyer");
emit DisputeResolved();
transferEscrowAndFees(_winner, amount, fee);
}
/// @notice Version recipient
function versionRecipient() external pure returns (string memory) {
return "1.0";
}
} | aca5d7fa38a0cafc689d88e6266bbca5 | 125 | dianewan | 2023-05-25T00:24:55 | good | [
"code"
] |
int32_t getWebACLMaxInspectionBytes(Lmdb_WebACLHandle *handle, GokuLmdbString http_source_string) {
int max_inspection_bytes = 64 * 1024;
if (handle) {
try {
std::string http_source(reinterpret_cast(http_source_string.value));
const goku::apiv2::lmdb::types::WebACL *webACL = (const goku::apiv2::lmdb::types::WebACL *) handle->webACL;
const goku::apiv2::lmdb::types::AssociationConfig *associationConfig = webACL->associationConfig();
const flatbuffers::Vector >
*resourceTypeVec = associationConfig->requestBodyAssociatedResourceTypeConfig();
std::unordered_map sourceMap = {
{"CF", goku::apiv2::lmdb::types::AssociatedResourceType_CLOUDFRONT},
{"ALB", goku::apiv2::lmdb::types::AssociatedResourceType_APPLICATION_LOAD_BALANCER},
{"APIGW", goku::apiv2::lmdb::types::AssociatedResourceType_API_GATEWAY},
{"APPSYNC", goku::apiv2::lmdb::types::AssociatedResourceType_APPSYNC},
{"COGNITOIDP", goku::apiv2::lmdb::types::AssociatedResourceType_COGNITO_USER_POOL},
{"APPRUNNER", goku::apiv2::lmdb::types::AssociatedResourceType_CLOUDFRONT},
{"-", goku::apiv2::lmdb::types::AssociatedResourceType_CLOUDFRONT}
};
auto it = sourceMap.find(http_source);
if (it != sourceMap.end()) {
goku::apiv2::lmdb::types::AssociatedResourceType associatedResourceType = it->second; //the assoc res
// Find AssociatedResourceType in the RequestBodyAssociatedResourceTypeConfig
for (const auto &requestBodyAssociatedResourceTypeConfig: *resourceTypeVec) {
if (requestBodyAssociatedResourceTypeConfig->associatedResourceType() ==
associatedResourceType) {
// Get the SizeInspectionLimit from the RequestBodyAssociatedResourceTypeConfig
goku::apiv2::lmdb::types::SizeInspectionLimit sizeInspectionLimit = requestBodyAssociatedResourceTypeConfig->defaultSizeInspectionLimit();
// Use the SizeInspectionLimit to determine the max_inspection_bytes
switch (sizeInspectionLimit) {
case goku::apiv2::lmdb::types::SizeInspectionLimit_KB_8:
max_inspection_bytes = 8 * 1024;
break;
case goku::apiv2::lmdb::types::SizeInspectionLimit_KB_16:
max_inspection_bytes = 16 * 1024;
break;
case goku::apiv2::lmdb::types::SizeInspectionLimit_KB_32:
max_inspection_bytes = 32 * 1024;
break;
case goku::apiv2::lmdb::types::SizeInspectionLimit_KB_64:
max_inspection_bytes = 64 * 1024;
break;
default:
max_inspection_bytes = 8 * 1024;
break;
}
break;
}
}
}
}
catch (const std::exception &e) {
LOG4CPLUS_ERROR(handle->loggerHandle->logger,
"lmdbDeserializer:GetWebACLMaxInspectionBytes: Caught std::exception: " << e.what());
} catch (...) {
LOG4CPLUS_ERROR(handle->loggerHandle->logger,
"lmdbDeserializer:GetWebACLMaxInspectionBytes: Caught unknown exception");
}
}
return max_inspection_bytes;
} | 17fd6edafabb1a2709779af4ca9f2c9e | 126 | dianewan | 2023-05-25T00:25:23 | bad | [] |
whats wrong with this code?
```
import os
import platform
from ctypes import *
class IDomSDK:
"""IDomSDK."""
def __init__(self) -> None:
"""Initialize."""
print("IDomSDK")
idom_sdk_file_name = None
if platform.system() == "Linux":
if platform.architecture()[0] == '64bit':
idom_sdk_file_name = 'libiDom3SDKLiteLinuxX86_64.so'
else:
idom_sdk_file_name = 'libiDom3SDKLiteLinuxX86_32.so'
if not idom_sdk_file_name:
raise Exception('can find sdk for current system')
current_dir = os.path.dirname(__file__)
sdk_file = os.path.join(current_dir, idom_sdk_file_name)
self.idom_sdk = CDLL(sdk_file)
def init (self, cycle_time = 0):
return self.idom_sdk.idom_init(cycle_time)
def connect (self, remote_host_addr: str, remote_host_port: int):
print('connect', remote_host_addr, remote_host_port)
return bool(self.idom_sdk.idom_connect(remote_host_addr, remote_host_port))
def pump_events (self):
print('pump_events')
self.idom_sdk.idom_pump_events()
connection_state_cb_type = CFUNCTYPE(None, c_int)
def reg_connection_state_cb(self, cb):
return self.idom_sdk.idom_reg_connection_state_cb(
self.connection_state_cb_type(cb)
)
object_data_cb_type = CFUNCTYPE(None, c_int, POINTER(c_char_p), c_char_p, c_bool, c_char_p, c_char_p)
def reg_object_data_cb(self, cb):
self.idom_sdk.idom_reg_object_data_cb(
self.object_data_cb_type(cb)
)
system_file_cb_type = CFUNCTYPE(None, c_int, c_char, c_char_p, c_int)
def reg_system_file_cb(self, cb):
self.idom_sdk.idom_reg_system_file_cb(
self.system_file_cb_type(cb)
)
``` | ecc894fa35253770f2342a9f998456c9 | 127 | dianewan | 2023-05-25T00:25:32 | good | [
"code"
] |
Translate network management software GUI from English to Traditional Chinese. GUI string file is in XML format.
XML content:
<string name="ACLInfoNetworkHeader">Network-wide Access Control</string>
<string name="ACLInfoSSIDHeader">Set Up Access Policy on Wi-Fi(SSIDs)</string>
<string name="ACLNetworkMessage">Apply policy for all Wi-Fi(SSIDs) within this Network</string>
<string name="AP">AP</string>
<string name="APINotSupportMessage">Your device not support this function.</string>
<string name="APMesEnabledhMessage">Exclude this AP from the Mesh Network</string>
<string name="APP_Language">App Language</string>
<string name="AP_List">AP List</string>
<string name="AP_Name">AP Name</string>
<string name="AP_Offline_Count">AP Offline Count</string>
<string name="AP_Online_Count">AP Online Count</string>
<string name="APs">APs</string>
<string name="About_EnGenius">About EnGenius</string>
<string name="Access">Access</string>
<string name="Access_Control">Access Control</string>
<string name="Access_Point">Access Point</string>
<string name="Access_Points">Access Points</string>
<string name="Access_Time">Access Time</string>
<string name="AccountPlaceHolder">EnGenius Cloud account</string>
<string name="Account_Recovery">Account Recovery</string>
<string name="Accounting_Server">Accounting Server</string>
<string name="Action_Taken">Action Taken</string>
<string name="Actions">Actions</string>
<string name="Active">Active</string>
<string name="ActivePortMessage">%s Active</string>
<string name="Add">Add</string>
<string name="AddBackupTitle">Add Backup List</string>
<string name="AddSSIDTitle">New Wi-Fi (SSID)</string>
<string name="Add_Device">Add Device</string>
<string name="Add_New_Photo">Add New Photo</string>
<string name="Add_Note">Add Note</string>
<string name="Add_VLAN">+ Add VLAN</string>
<string name="AlertOfflineTitle">%s goes offline for</string>
<string name="AlertSTPStatusChangeTitle">Switch STP port status change</string>
<string name="AlertSeverityPrefixTitle">Event with severity</string>
<string name="AlertSeveritySuffixTitle">and above occurs</string>
<string name="Alert_Settings">Alert Settings</string>
| f90062624819fa6a558aa5bb438d688d | 128 | dianewan | 2023-05-25T00:26:01 | good | [
"code"
] |
Can you help me complete the TODO part of this code?
def computeSphericalWarpMappings(dstShape, f, k1, k2):
'''
Compute the spherical warp. Compute the addresses of each pixel of the
output image in the source image.
Input:
dstShape -- shape of input / output image in a numpy array.
[number or rows, number of cols, number of bands]
f -- focal length in pixel as int
See assignment description on how to find the focal length
k1 -- horizontal distortion as a float
k2 -- vertical distortion as a float
Output:
uvImg -- warped image in terms of addresses of each pixel in the
source image in a numpy array.
The dimensions are (rows, cols, addresses of pixels
[:,:,0] are x (i.e., cols) and [:,:,1] are y (i.e., rows)).
'''
# calculate minimum y value
vec = np.zeros(3)
vec[0] = np.sin(0.0) * np.cos(0.0)
vec[1] = np.sin(0.0)
vec[2] = np.cos(0.0) * np.cos(0.0)
min_y = vec[1]
# calculate spherical coordinates
# (x,y) is the spherical image coordinates.
# (xf,yf) is the spherical coordinates, e.g., xf is the angle theta
# and yf is the angle phi
one = np.ones((dstShape[0],dstShape[1]))
xf = one * np.arange(dstShape[1])
yf = one.T * np.arange(dstShape[0])
yf = yf.T
xf = ((xf - 0.5 * dstShape[1]) / f)
yf = ((yf - 0.5 * dstShape[0]) / f - min_y)
# BEGIN TODO 1
# add code to apply the spherical correction, i.e.,
# compute the Euclidean coordinates,
# and project the point to the z=1 plane at (xt/zt,yt/zt,1),
# then distort with radial distortion coefficients k1 and k2
# Use xf, yf as input for your code block and compute xt, yt
# as output for your code. They should all have the shape
# (img_height, img_width)
# TODO-BLOCK-BEGIN
raise Exception("TODO in warp.py not implemented")
# TODO-BLOCK-END
# END TODO
# Convert back to regular pixel coordinates
xn = 0.5 * dstShape[1] + xt * f
yn = 0.5 * dstShape[0] + yt * f
uvImg = np.dstack((xn,yn))
return uvImg | a06d3892feecd3b7d091a06320394b1a | 129 | dianewan | 2023-05-25T00:26:08 | good | [
"code"
] |
Responsibilities
5.1 General
The certification system, which shall be controlled and administered by a certification body, includes
all procedures necessary to demonstrate the qualification and the competence of an individual to carry
out tasks in a specific NDT method and product or industrial sector, leading to certification.
5.2 Certification body
5.2.1 The certification body shall fulfil the requirements of ISO/IEC 17024.
5.2.2 The certification body:
a) shall initiate, promote, maintain and administer the certification scheme according to ISO/IEC 17024
and this document;
b) shall be independent of any single interest;
ISO 9712:2021(E)
© ISO 2021 – All rights reserved
6
c) shall be responsible for the definition of sectors (see Annex A);
d) shall publish information regarding the scope of the certification scheme and a general description
of the certification process;
e) shall provide information for training courses that include the syllabi which embody the content of
recognized documents; ISO/TS 25107 or equivalent can be used as guidance;
f) shall conduct an initial audit and subsequent periodic surveillance audits of the authorized
qualification body(ies) to ensure their conformity to the specifications;
g) shall monitor, in accordance with a documented procedure, all delegated functions;
h) shall approve properly staffed and equipped examination centres, which it shall monitor on a
periodic basis;
i) shall administer examinations through approved examination centres;
j) shall bear full responsibilities for examinations conducted on temporary basis at external premises;
k) shall be responsible for ensuring the security of all examination materials (examination specimens,
specimen master reports, question banks, examination papers, etc.) and shall ensure that these
materials are not in use for training purposes;
l) shall be responsible for granting, extension, suspension, withdrawal or revalidation of certification;
m) shall establish an appropriate system for the maintenance of records, which shall be retained for at
least one certification cycle;
n) shall require all candidates and certificate holders to give a signed or stamped undertaking to
abide by a code of ethics which it shall develop for the purpose and publish;
o) may approve training bodies; ISO/TS 25108 can be used as guidance;
p) may delegate, under its direct responsibility, the detailed administration of qualification to
authorized qualification bodies, to which it shall issue specifications and/or procedures covering
facilities, personnel, verification and control of NDT equipment, examination materials, specimens,
conduct of examinations, examination grading, records, etc.;
q) shall establish a process to authorize examiners;
r) shall establish the conditions for the supervision of work activities, which candidates may claim
experience under 7.3;
s) shall establish a process for the recognition of higher education;
t) shall establish a process for the approval of non-certified individuals as a referee;
u) shall establish a process for the approval of a structured credit system, where used;
v) may specify a minimum age requirement for candidates under 7.1;
w) shall maintain and update the question bank and the examination specimens along with their
specimen master report;
x) shall conduct the examination only in the presence of, and under the control of, an authorized
invigilator of the certification body, to ensure that impartiality is maintained;
y) shall establish a process for the approval of a structured experience program, where used.
ISO 9712:2021(E)
© ISO 2021 – All rights reserved 7
5.3 Authorized qualification body
Where established, the authorized qualification body shall:
a) work under the control of and apply the specifications issued by the certification body;
b) be independent of any single predominant interest;
c) ensure that it is impartial with respect to each candidate seeking qualification, bringing to the
attention of the certification body any actual or potential threat to its impartiality;
d) apply a documented quality management system approved by the certification body;
e) have the resources and expertise necessary to establish, monitor and control examinations centres,
including examinations and the verification and control of the equipment;
f) conduct qualification of candidates including review of application and decision on eligibility;
g) prepare, supervise and administer examinations;
h) provide the certification body with the results of qualification needed to make a decision on
certification by the certification body;
i) maintain appropriate qualification and examination records according to the requirements of the
certification body.
5.4 Examination centre
5.4.1 The examination centre shall:
a) work under the control of the certification body or authorized qualification body;
b) apply a documented quality procedure approved by the certification body;
c) have the resources needed to prepare and conduct examinations, including the verification and
control of equipment;
d) have adequate qualified staff, premises and equipment to ensure satisfactory examinations for the
levels, methods, and sectors concerned; the use of external premises is allowed;
e) prepare and conduct examinations under the responsibility of an examiner authorized by the
certification body, using only examination questionnaires and specimens established or approved
by the certification body for that purpose;
f) maintain appropriate examination documents according to the requirements of the certification
body.
5.4.2 An examination centre may operate within the certification body; or within an authorized
qualification body; or be an independent legal entity or part of a legal entity. An examination centre
can be situated at an employer’s premises. In this case, the certification body shall require controls
to preserve impartiality and protect confidentiality of the examinations. The examinations shall
be conducted only in the presence of, and under the control of, an authorized representative of the
certification body.
5.5 Employer
5.5.1 The employer shall document the personal information which shall include the declaration
of education, training and industrial experience and visual acuity needed to determine the eligibility
ISO 9712:2021(E)
© ISO 2021 – All rights reserved
8
of the candidate. If the candidate is self-employed, the industrial experience shall be attested to by a
referee.
All documentation obtained from the employer shall be verified by the certification body.
5.5.2 In respect of certified NDT personnel under their control the employer shall be responsible for:
a) all that concerns the authorization to operate, i.e. providing job-specific training (if necessary);
b) issuing the written authorization to operate;
c) the results of NDT activities;
d) ensuring that the annual vision requirements of 7.4 are met;
e) maintaining documentary evidence confirming the continuous application of the NDT method in
the relevant sector(s) without significant interruption; this action shall be done every 12 months;
f) ensuring that personnel hold valid certification relevant to their tasks within the organization;
g) maintaining appropriate records.
These responsibilities shall be described in a documented procedure.
5.5.3 A self-employed individual shall assume all responsibilities ascribed to the employer.
5.5.4 Certification to this document provides an attestation of general competence of the certified
NDT personnel. It does not represent an authorization to operate, since this remains the responsibility
of the employer; and the certified NDT personnel may require additional specialized knowledge of
parameters such as equipment, NDT procedures, materials and products specific for the employer.
Where required by regulatory requirements and codes, the authorization to operate shall be given in
writing by the employer in accordance with a quality procedure that specifies any employer-required
job-specific training and examinations designed to verify the certificate holder's knowledge of relevant
industry code(s), standard(s), NDT procedures, equipment, and acceptance criteria for the tested
products.
5.6 Candidate
Candidates shall:
a) provide documentary evidence of training in accordance with 7.2;
b) provide documentary evidence that the required experience has been gained under supervision;
c) provide documentary evidence of vision satisfying the requirements of 7.4;
d) abide by a code of ethics published by the certification body;
e) provide other requisites requested by the certification body.
5.7 Certificate holders
Certificate holders shall:
a) abide by a code of ethics published by the certification body;
b) maintain records demonstrating evidence that vision requirements have been fulfilled in
accordance with 7.4;
ISO 9712:2021(E)
© ISO 2021 – All rights reserved 9
c) notify the certification body and the employer if the conditions of certification are not maintained
(see 9.3).
5.8 Examiners
5.8.1 Examiners shall:
— be authorized by the certification body to conduct, supervise and grade examinations;
— be certified to Level 3 in the NDT method in the product and/or industrial sector for which they are
authorized.
5.8.2 An examiner shall not be permitted to examine any candidate:
— that they have trained for the examination for a period of two years from the date of the conclusion
of the training;
— who is working (permanently or temporarily) in the same facility as the examiner unless the
certification body has established a documented confidentiality and impartiality management
procedure for such a situation.
5.9 Referee
A referee shall be:
a) certified to Level 2 or 3 in any NDT method; or
b) non-certified personnel who, approved by the certification body, possess the knowledge, skill,
training and experience required to attest to the candidate’s industrial experience.
generate a work procedure document compliant with the information above, for a company named Global Compliance Service - Inspection Division. there will be 9 sections, this will be the 1st section | 5259f08d1d4ffa7f9579317e758303cd | 13 | DaehanKim | 2023-05-29T06:40:46 | good | [] |
Responsibilities
5.1 General
The certification system, which shall be controlled and administered by a certification body, includes
all procedures necessary to demonstrate the qualification and the competence of an individual to carry
out tasks in a specific NDT method and product or industrial sector, leading to certification.
5.2 Certification body
5.2.1 The certification body shall fulfil the requirements of ISO/IEC 17024.
5.2.2 The certification body:
a) shall initiate, promote, maintain and administer the certification scheme according to ISO/IEC 17024
and this document;
b) shall be independent of any single interest;
ISO 9712:2021(E)
© ISO 2021 – All rights reserved
6
c) shall be responsible for the definition of sectors (see Annex A);
d) shall publish information regarding the scope of the certification scheme and a general description
of the certification process;
e) shall provide information for training courses that include the syllabi which embody the content of
recognized documents; ISO/TS 25107 or equivalent can be used as guidance;
f) shall conduct an initial audit and subsequent periodic surveillance audits of the authorized
qualification body(ies) to ensure their conformity to the specifications;
g) shall monitor, in accordance with a documented procedure, all delegated functions;
h) shall approve properly staffed and equipped examination centres, which it shall monitor on a
periodic basis;
i) shall administer examinations through approved examination centres;
j) shall bear full responsibilities for examinations conducted on temporary basis at external premises;
k) shall be responsible for ensuring the security of all examination materials (examination specimens,
specimen master reports, question banks, examination papers, etc.) and shall ensure that these
materials are not in use for training purposes;
l) shall be responsible for granting, extension, suspension, withdrawal or revalidation of certification;
m) shall establish an appropriate system for the maintenance of records, which shall be retained for at
least one certification cycle;
n) shall require all candidates and certificate holders to give a signed or stamped undertaking to
abide by a code of ethics which it shall develop for the purpose and publish;
o) may approve training bodies; ISO/TS 25108 can be used as guidance;
p) may delegate, under its direct responsibility, the detailed administration of qualification to
authorized qualification bodies, to which it shall issue specifications and/or procedures covering
facilities, personnel, verification and control of NDT equipment, examination materials, specimens,
conduct of examinations, examination grading, records, etc.;
q) shall establish a process to authorize examiners;
r) shall establish the conditions for the supervision of work activities, which candidates may claim
experience under 7.3;
s) shall establish a process for the recognition of higher education;
t) shall establish a process for the approval of non-certified individuals as a referee;
u) shall establish a process for the approval of a structured credit system, where used;
v) may specify a minimum age requirement for candidates under 7.1;
w) shall maintain and update the question bank and the examination specimens along with their
specimen master report;
x) shall conduct the examination only in the presence of, and under the control of, an authorized
invigilator of the certification body, to ensure that impartiality is maintained;
y) shall establish a process for the approval of a structured experience program, where used.
ISO 9712:2021(E)
© ISO 2021 – All rights reserved 7
5.3 Authorized qualification body
Where established, the authorized qualification body shall:
a) work under the control of and apply the specifications issued by the certification body;
b) be independent of any single predominant interest;
c) ensure that it is impartial with respect to each candidate seeking qualification, bringing to the
attention of the certification body any actual or potential threat to its impartiality;
d) apply a documented quality management system approved by the certification body;
e) have the resources and expertise necessary to establish, monitor and control examinations centres,
including examinations and the verification and control of the equipment;
f) conduct qualification of candidates including review of application and decision on eligibility;
g) prepare, supervise and administer examinations;
h) provide the certification body with the results of qualification needed to make a decision on
certification by the certification body;
i) maintain appropriate qualification and examination records according to the requirements of the
certification body.
5.4 Examination centre
5.4.1 The examination centre shall:
a) work under the control of the certification body or authorized qualification body;
b) apply a documented quality procedure approved by the certification body;
c) have the resources needed to prepare and conduct examinations, including the verification and
control of equipment;
d) have adequate qualified staff, premises and equipment to ensure satisfactory examinations for the
levels, methods, and sectors concerned; the use of external premises is allowed;
e) prepare and conduct examinations under the responsibility of an examiner authorized by the
certification body, using only examination questionnaires and specimens established or approved
by the certification body for that purpose;
f) maintain appropriate examination documents according to the requirements of the certification
body.
5.4.2 An examination centre may operate within the certification body; or within an authorized
qualification body; or be an independent legal entity or part of a legal entity. An examination centre
can be situated at an employer’s premises. In this case, the certification body shall require controls
to preserve impartiality and protect confidentiality of the examinations. The examinations shall
be conducted only in the presence of, and under the control of, an authorized representative of the
certification body.
5.5 Employer
5.5.1 The employer shall document the personal information which shall include the declaration
of education, training and industrial experience and visual acuity needed to determine the eligibility
ISO 9712:2021(E)
© ISO 2021 – All rights reserved
8
of the candidate. If the candidate is self-employed, the industrial experience shall be attested to by a
referee.
All documentation obtained from the employer shall be verified by the certification body.
5.5.2 In respect of certified NDT personnel under their control the employer shall be responsible for:
a) all that concerns the authorization to operate, i.e. providing job-specific training (if necessary);
b) issuing the written authorization to operate;
c) the results of NDT activities;
d) ensuring that the annual vision requirements of 7.4 are met;
e) maintaining documentary evidence confirming the continuous application of the NDT method in
the relevant sector(s) without significant interruption; this action shall be done every 12 months;
f) ensuring that personnel hold valid certification relevant to their tasks within the organization;
g) maintaining appropriate records.
These responsibilities shall be described in a documented procedure.
5.5.3 A self-employed individual shall assume all responsibilities ascribed to the employer.
5.5.4 Certification to this document provides an attestation of general competence of the certified
NDT personnel. It does not represent an authorization to operate, since this remains the responsibility
of the employer; and the certified NDT personnel may require additional specialized knowledge of
parameters such as equipment, NDT procedures, materials and products specific for the employer.
Where required by regulatory requirements and codes, the authorization to operate shall be given in
writing by the employer in accordance with a quality procedure that specifies any employer-required
job-specific training and examinations designed to verify the certificate holder's knowledge of relevant
industry code(s), standard(s), NDT procedures, equipment, and acceptance criteria for the tested
products.
5.6 Candidate
Candidates shall:
a) provide documentary evidence of training in accordance with 7.2;
b) provide documentary evidence that the required experience has been gained under supervision;
c) provide documentary evidence of vision satisfying the requirements of 7.4;
d) abide by a code of ethics published by the certification body;
e) provide other requisites requested by the certification body.
5.7 Certificate holders
Certificate holders shall:
a) abide by a code of ethics published by the certification body;
b) maintain records demonstrating evidence that vision requirements have been fulfilled in
accordance with 7.4;
ISO 9712:2021(E)
© ISO 2021 – All rights reserved 9
c) notify the certification body and the employer if the conditions of certification are not maintained
(see 9.3).
5.8 Examiners
5.8.1 Examiners shall:
— be authorized by the certification body to conduct, supervise and grade examinations;
— be certified to Level 3 in the NDT method in the product and/or industrial sector for which they are
authorized.
5.8.2 An examiner shall not be permitted to examine any candidate:
— that they have trained for the examination for a period of two years from the date of the conclusion
of the training;
— who is working (permanently or temporarily) in the same facility as the examiner unless the
certification body has established a documented confidentiality and impartiality management
procedure for such a situation.
5.9 Referee
A referee shall be:
a) certified to Level 2 or 3 in any NDT method; or
b) non-certified personnel who, approved by the certification body, possess the knowledge, skill,
training and experience required to attest to the candidate’s industrial experience.
generate a work procedure document compliant with the information above, for a company named Global Compliance Service - Inspection Division. there will be 9 sections, this will be the 1st section | 5259f08d1d4ffa7f9579317e758303cd | 13 | dianewan | 2023-05-23T23:28:01 | bad | [] |
I amigo, i have a request for you.
i have a C# Solution with a Database Project inside it. In the DataBase project i defined a Role like this:
GO
CREATE ROLE db_KteUsers
GO
DENY EXECUTE TO db_KteUsers
GO
GRANT SELECT TO db_KteUsers
GO
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA :: [cfg] TO db_KteUsers
When deployed if i granted more things to the role, i would like that when i publish the db again this newly added permissions are revoked. something like, when i publish the db reset the role as i describe it in the project.
Can you help me with this? | 74c56d72f909e5f2a89424a94ac7ec22 | 130 | dianewan | 2023-05-25T00:26:22 | good | [
"code"
] |
$searchValue = $data['data']['query'];
$results = [];
foreach ($processed as $object) {
if (in_array($searchValue, (array) $object)) {
$results[] = $object;
}
} | f8cb43cf409fa5fa2d2ad624fd803c6b | 131 | dianewan | 2023-05-25T00:26:28 | bad | [] |
Here is my flatbuffer data:
namespace goku.apiv2.lmdb.types;
table WebACL {
owner:string (id: 0);
payerToken:string (id: 1);
defaultAction:DefaultAction (id: 3);
rules:[Rule] (id: 4);
visibilityConfig: VisibilityConfig (id: 5);
isolationStatus:IsolationStatus (id: 6);
version:int (id: 7);
changeNumber:long (id: 8);
wcuCapacity:long (id: 9);
customResponseBodies: [CustomResponseBody] (id: 10);
labelNamespace: string (id: 11);
globalCaptchaConfig: CaptchaConfig (id: 12);
oversizeFieldsHandlingCompliant:bool (id: 13);
globalChallengeConfig: ChallengeConfig (id: 14);
tokenDomains: [string] (id: 15);
associationConfig: AssociationConfig (id: 16);
}
table AssociationConfig {
requestBodyAssociatedResourceTypeConfig: [RequestBodyAssociatedResourceTypeConfig] (id: 0);
}
table RequestBodyAssociatedResourceTypeConfig {
associatedResourceType: AssociatedResourceType (id: 0);
defaultSizeInspectionLimit: SizeInspectionLimit (id: 1);
}
enum AssociatedResourceType: int {
CLOUDFRONT = 0,
APPLICATION_LOAD_BALANCER = 1,
API_GATEWAY = 2,
APPSYNC = 3,
COGNITO_USER_POOL = 4
}
enum SizeInspectionLimit: int {
KB_8 = 0,
KB_16 = 1,
KB_32 = 2,
KB_64 = 3
}
| ffe931309f9562404ba83084d522ba84 | 132 | dianewan | 2023-05-25T00:26:38 | bad | [] |
I have a button that runs an onClick function as follows:
<button
onClick={handler}
id="generate"
className="flex items-center justify-center gap-2 rounded-lg border border-[#404040] bg-[#0570eb] px-4 py-2 font-medium shadow-lg hover:bg-[#0465d3]"
>
<RefreshCw size={18} />
Generate
</button>
const handler= () => {
let generator = new PasswordGenerator()
setPassword(generator.generatePassword(strengthOption, numbersOption, symbolsOption))
}
Why can't I just do <button onClick={setPassword(generator.generatePassword(...))}> instead? Currently I'm using an arrow function that executes the same generatePassword()? Why does it have to be an arrow function for the onClick button? | c43eadd110620a70886f48eddafd77b4 | 133 | dianewan | 2023-05-25T00:26:44 | good | [
"code"
] |
what are vulnerabilities in the following code? from django.db.utils import IntegrityError
from rest_framework import permissions, viewsets, generics, status
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from .models import CertificationRequest, Status, Competence
from .serializers import CertificationRequestSerializer
from .permissions import IsVolunteer
# Create your views here.
class CertificationRequestViewSet(viewsets.ModelViewSet):
"""Viewset for certification requests"""
serializer_class = CertificationRequestSerializer # use the serializer class defined in serializers.py
permission_classes = [permissions.IsAdminUser | IsVolunteer]
http_method_names = ['get', 'head', 'delete', 'post']
def get_queryset(self):
"""Only show certification requests of the current user if not admin"""
if self.request.user.is_staff:
return CertificationRequest.objects.all()
return CertificationRequest.objects.filter(user=self.request.user)
def perform_create(self, serializer):
"""Create a certification request for the current user if not admin"""
try:
if self.request.user.is_staff:
raise ValidationError(
"Admins can't create certification requests")
# save the certification request with the current user
serializer.save(user=self.request.user)
except IntegrityError as e:
raise ValidationError(
'An identical Certification Request already exists')
class AnswerCertificationRequest(generics.GenericAPIView):
"""View to answer certification requests"""
permission_classes = [permissions.IsAuthenticated]
def post(self, request):
# check if id and status is provided
if not(request.data.get('id') and request.data.get('status')):
return Response({'error': 'id and status is required'}, status=status.HTTP_400_BAD_REQUEST)
certification_request = CertificationRequest.objects.get(
id=request.data['id'])
if certification_request is None: # check if certification request exists
return Response({'error': 'Certification Request does not exist'}, status=status.HTTP_400_BAD_REQUEST)
if certification_request.status != 'P': # check if certification request is pending
return Response({'error': 'Certification Request is not pending'}, status=status.HTTP_400_BAD_REQUEST)
state = request.data['status']
if state == 'A': # if accepted
certification_request.status = Status.ACCEPTED
elif state == 'D': # if declined
certification_request.status = Status.DECLINED
else:
return Response({'error': 'Status must be A or D'}, status=status.HTTP_400_BAD_REQUEST)
certification_request.save()
return Response(status=status.HTTP_200_OK)
class GetCertificationStatus(generics.GenericAPIView):
"""View to get certification status.
Returns a dictionary with the status of all competences."""
permission_classes = [permissions.IsAuthenticated]
def get(self, request):
result = {}
for s in Competence:
certification_request = CertificationRequest.objects.filter(
user=self.request.user, competence=s).first()
if certification_request:
body = {
'status': certification_request.status,
'created': certification_request.created,
'id': certification_request.id
}
else:
body = {
'status': None,
'created': None,
'id': None
}
result[s] = body
return Response(result, status=status.HTTP_200_OK)
| 91593ad42a56529152811960de5bf83a | 134 | dianewan | 2023-05-25T00:26:55 | good | [
"code"
] |
Can you take this script:
import feedparser
import time
# URL of the existing RSS feed
rss_url = "https://www.example.com/rss"
# Generate the new RSS feed
def generate_rss():
# Parse the RSS feed
feed = feedparser.parse(rss_url)
new_rss = """<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
<channel>
<title>{title}</title>
<link>{link}</link>
<description>{description}</description>
<language>{language}</language>
""".format(title=feed.feed.title, link=feed.feed.link, description=feed.feed.description, language=feed.feed.language)
# Add each entry in the existing RSS feed to the new RSS feed
for entry in feed.entries:
new_rss += """
<item>
<title>{title}</title>
<link>{link}</link>
<description>{description}</description>
<pubDate>{pubDate}</pubDate>
</item>
""".format(title=entry.title, link=entry.link, description=entry.description, pubDate=entry.published)
# Close the new RSS feed
new_rss += """
</channel>
</rss>"""
# Save the new RSS feed to a file
with open("new_rss.xml", "w") as f:
f.write(new_rss)
# Update the RSS feed every 5 minutes
while True:
generate_rss()
time.sleep(300) # sleep for 5 minutes
----
And make it prompt the user for the URL for the rss feed | aff2ce09f47d21944f07dfd9b3d26fca | 135 | dianewan | 2023-05-25T00:27:12 | bad | [] |
Can you rate this code on the following parameters: General Coding Practices, Functional Correctness, Security (exclude overflows), Gas Optimisations, and Code Readability
1 is the lowest score for a parameter and 5 is the score for a parameter. Give detailed reasoning on the score for each parameter.
pragma solidity ^0.8.4;
contract Streaming {
address public immutable owner;
uint256 private streamIdCounter;
mapping(uint256 => Stream) private streams;
modifier streamExists(uint256 streamId) {
require(streams[streamId].deposit > 0, "stream does not exist");
_;
}
struct Stream {
address recipient;
address sender;
uint256 deposit;
uint256 currentStartTime;
uint256 stopTime;
uint256 rate;
uint256 balance;
uint256 originalStartTime;
}
event CreateStream(
uint256 indexed streamId,
address indexed sender,
address indexed recipient,
uint256 deposit,
uint256 startTime,
uint256 stopTime
);
event WithdrawFromStream(
uint256 indexed streamId,
address indexed recipient
);
event CancelStream(
uint256 indexed streamId,
address indexed sender,
address indexed recipient,
uint256 senderFunds,
uint256 recipientFunds
);
constructor() {
owner = msg.sender;
}
function createStream(
address recipient,
uint256 startTime,
uint256 stopTime
) external payable returns (uint256) {
require(recipient != address(0), "Stream to the zero address");
require(recipient != address(this), "Stream to the contract itself");
require(recipient != msg.sender, "Stream to the caller");
require(msg.value > 0, "Deposit is equal to zero");
require(
startTime >= block.timestamp,
"Start time before block timestamp"
);
require(
startTime < stopTime,
"Stop time is not greater than than start time"
);
uint256 duration = stopTime - startTime;
require(msg.value >= duration, "Deposit smaller than duration");
require(
msg.value % duration == 0,
"Deposit is not a multiple of time delta"
);
uint256 currentStreamId = ++streamIdCounter;
uint256 rate = msg.value / duration;
streams[currentStreamId] = Stream({
balance: msg.value,
deposit: msg.value,
rate: rate,
recipient: recipient,
sender: msg.sender,
currentStartTime: startTime,
stopTime: stopTime,
originalStartTime: startTime
});
emit CreateStream(
currentStreamId,
msg.sender,
recipient,
msg.value,
startTime,
stopTime
);
return currentStreamId;
}
function balanceOf(uint256 streamId)
external
view
streamExists(streamId)
returns (uint256 balance)
{
Stream memory stream = streams[streamId];
require(
msg.sender == stream.sender || msg.sender == stream.recipient,
"caller is not the sender or the recipient of the stream"
);
uint256 due = elapsedTimeFor(streamId) * stream.rate;
if (msg.sender == stream.recipient) {
return due;
} else {
return stream.balance - due;
}
}
function elapsedTimeFor(uint256 streamId)
private
view
returns (uint256 delta)
{
Stream memory stream = streams[streamId];
// Before the start of the stream
if (block.timestamp <= stream.originalStartTime) return 0;
// During the stream
if (block.timestamp < stream.stopTime)
return block.timestamp - stream.currentStartTime;
// After the end of the stream
return stream.stopTime - stream.currentStartTime;
}
function withdrawFromStream(uint256 streamId)
external
streamExists(streamId)
{
Stream memory streamCopy = streams[streamId];
require(
streamCopy.recipient == msg.sender,
"only the recipient can call this method"
);
Stream storage stream = streams[streamId];
uint256 due = elapsedTimeFor(streamId) * streamCopy.rate;
require(due > 0, "Available balance is 0");
stream.balance = streamCopy.balance - due;
stream.currentStartTime = block.timestamp;
emit WithdrawFromStream(streamId, streamCopy.recipient);
(bool success, ) = payable(streamCopy.recipient).call{value: due}("");
require(success, "Transfer to recipient failed!");
}
function cancelStream(uint256 streamId) external streamExists(streamId) {
Stream memory streamCopy = streams[streamId];
require(
msg.sender == streamCopy.sender ||
msg.sender == streamCopy.recipient,
"caller is not the sender or the recipient of the stream"
);
Stream storage stream = streams[streamId];
uint256 recipientFunds = elapsedTimeFor(streamId) * streamCopy.rate;
uint256 senderFunds = streamCopy.balance - recipientFunds;
stream.balance = 0;
stream.currentStartTime = streamCopy.stopTime;
emit CancelStream(
streamId,
streamCopy.sender,
streamCopy.recipient,
senderFunds,
recipientFunds
);
if (senderFunds > 0) {
(bool senderSendSuccess, ) = payable(streamCopy.sender).call{
value: senderFunds
}("");
require(senderSendSuccess, "Transfer to sender failed!");
}
if (recipientFunds > 0) {
(bool recipientSendSuccess, ) = payable(streamCopy.recipient).call{
value: recipientFunds
}("");
require(recipientSendSuccess, "Transfer to recipient failed!");
}
}
function getStream(uint256 streamId)
external
view
streamExists(streamId)
returns (
address sender,
address recipient,
uint256 deposit,
uint256 originalStartTime,
uint256 currentStartTime,
uint256 stopTime,
uint256 rate,
uint256 balance
)
{
Stream memory stream = streams[streamId];
sender = stream.sender;
recipient = stream.recipient;
deposit = stream.deposit;
originalStartTime = stream.originalStartTime;
currentStartTime = stream.currentStartTime;
stopTime = stream.stopTime;
rate = stream.rate;
balance = stream.balance;
}
} | 3a90ee3b434599c148a0b2dd8c1733d3 | 136 | dianewan | 2023-05-25T00:27:27 | bad | [] |
def load_housing_data():
tarball_path = Path("datasets/housing.tgz")
if not tarball_path.is_file():
Path("datasets").mkdir(parents=True, exist_ok=True)
url = "https://github.com/ageron/data/raw/main/housing.tgz"
urllib.request.urlretrieve(url, tarball_path)
with tarfile.open(tarball_path) as housing_tarball:
housing_tarball.extractall(path="datasets")
return pd.read_csv(Path("datasets/housing/housing.csv"))
explain the code | eb557caa6e7ed3ff3d87a064be9e1a01 | 137 | dianewan | 2023-05-25T00:27:34 | good | [
"code"
] |
Somewhere in my css is something that causes <li><p>item</p></li> to render with a line break between the <li> bullet point and the beginning of <p>. What should I change to fix this? I use Tailwind CSS. Is there a solution that involves the inline: parameter? | 41757632b09d9e04b38e3c77b6a67c49 | 138 | dianewan | 2023-05-25T00:27:58 | good | [
"code"
] |
Im gonna send you code in two seperate messages, could you break it down for me?
//sampling period is 224.38 us
#define Adresa_MCP4725 96 //DAC adress
#define pin_ADC A15 //ADC input pin
#define pin_BAT A13 //Battery voltage input pin
#define WHITE 0xFFFF //color
#define BLACK 0x0000 //color
#define RED 0xF800 //color
#define GREEN 0x07E0 //color
#define DKBLUE 0x000D //color
#define buton_sus 7
#define buton_OK 6
#define buton_jos 5
#define senzor_pas 3
#define SDC_CS 53 //SD card control pin
#include <Wire.h>
#include <arduinoFFT.h>
#include <TFT_HX8357.h>
#include "Free_Fonts.h"
#include <SD.h>
TFT_HX8357 tft = TFT_HX8357();
arduinoFFT FFT = arduinoFFT();
File fisier;
const word nivele_bat[3] = {384, 392, 401}; //battery voltage threshold levels: low - med1 - med2 (V_bat/5V*1023*0.4)
//GPR global parameters
const double pas_deplasare_GPR = 0.24; //GPR horizontal step [m]
const double banda = 587000000; //GPR bandwidth [Hz]; 910 MHz - 323 MHz
const double amplitudine_maxima = 30000; //maximum FFT module value (for scaling)
const word nr_esant = 256; //sample no.
//menus
const char *medii_propagare[] = {"Air - 0.3 m/ns", "Ice - 0.16 m/ns", "Dry sand - 0.15 m/ns", "Dry soil (Granite) - 0.13 m/ns", "Limestone - 0.12 m/ns", "Asphalt - 0.11 m/ns", "Concrete - 0.1 m/ns", "Moist soil - 0.09 m/ns", "Wet soil (Silt) - 0.07 m/ns", "Saturated sand (Clay) - 0.06 m/ns", "Sweet water - 0.03 m/ns", "Salt water - 0.01 m/ns"};
const double viteze[] = {300000000, 160000000, 150000000, 130000000, 120000000, 110000000, 100000000, 90000000, 70000000, 60000000, 30000000, 10000000};
const word adancimi[] = {16, 32, 64, 128}; //resolution multiples
const double pasi_adanc[] = {10, 5, 2.5, 1, 0.5, 0.25, 0.1, 0.05, 0.025, 0.01};
const word zecimale_pasi_adanc[] = {0, 0, 1 , 0, 1, 2, 1, 2, 3, 2};
const word distante[] = {12, 24, 48, 96};
//graph constants
const word orig_x = 60, orig_y = 290, latime_grafic = 400, inaltime_grafic = 256; //graph origin coord. and dimensions [pixels]
//variabile globale afisare grafic
double max_dist, pas_dist, max_adanc, min_adanc, pas_adanc, rezolutie; // [m]
double c; //[m/s]
word nr_cel_rez_oriz, nr_cel_rez_vert, inaltime_cel_rez, latime_cel_rez, nr_zecimale_pasi_adanc, xpos, ypos, pas = 0;
//antenna coupling correction (anechoic chamber acquisition)
//const word corectie[nr_esant] = {497, 497, 477, 383, 251, 163, 125, 113, 146, 210, 305, 430, 550, 682, 801, 893, 947, 964, 922, 787, 654, 569, 521, 486, 455, 446, 451, 454, 439, 409, 377, 352, 337, 332, 323, 334, 342, 354, 371, 384, 397, 410, 420, 433, 449, 468, 496, 528, 560, 596, 637, 674, 705, 726, 733, 735, 735, 738, 749, 757, 760, 754, 731, 699, 657, 597, 520, 432, 342, 264, 213, 180, 164, 164, 173, 194, 222, 252, 288, 316, 350, 390, 425, 459, 491, 522, 548, 571, 590, 606, 624, 642, 660, 681, 694, 703, 706, 701, 692, 676, 651, 623, 590, 557, 528, 501, 477, 457, 443, 433, 429, 429, 431, 433, 439, 449, 462, 476, 492, 508, 525, 543, 566, 587, 604, 609, 603, 589, 570, 547, 519, 482, 434, 376, 326, 277, 233, 194, 159, 147, 167, 224, 306, 383, 449, 503, 545, 576, 601, 611, 615, 616, 617, 617, 616, 614, 613, 609, 602, 593, 584, 577, 571, 566, 559, 553, 545, 539, 533, 528, 524, 521, 518, 515, 510, 505, 500, 496, 493, 490, 485, 480, 477, 475, 474, 475, 476, 479, 484, 490, 496, 502, 508, 514, 522, 532, 538, 542, 541, 540, 538, 536, 536, 534, 531, 525, 520, 511, 503, 497, 491, 487, 483, 479, 473, 467, 468, 468, 466, 466, 466, 466, 467, 467, 470, 468, 467, 467, 466, 466, 465, 465, 467, 468, 467, 468, 467, 471, 473, 475, 477, 480, 482, 484, 486, 489, 491, 494, 495, 497, 497, 498, 498, 499, 498, 498};
//global variables
word i, amplitudine_scalata, culoare, esantioane[nr_esant];
double real[nr_esant], imag[nr_esant], amplitudine_corectata_cu_dist;
boolean cont, card;
//------------------------------------------------------------------------
void setup()
{
Wire.begin();
Wire.setClock(400000);
tft.begin();
tft.fillScreen(BLACK);
tft.setRotation(1);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.setTextDatum(TC_DATUM); // Centered
tft.setFreeFont(FSB12);
xpos = tft.width() / 2; // Middle screen
ypos = (tft.height() / 2) - tft.fontHeight(GFXFF); // Middle screen
pinMode(buton_sus, INPUT);
pinMode(buton_OK, INPUT);
pinMode(buton_jos, INPUT);
pinMode(senzor_pas, INPUT);
tft.drawString("<c> Mirel Paun 2020", xpos, ypos, GFXFF);
delay(1000);
tft.fillScreen(BLACK);
if (!digitalRead(buton_OK))
{
card = false; //do nor store on SD Card
while (!digitalRead(buton_OK)) ;
}
else
{
if (SD.begin(SDC_CS))
{
card = true;
Serial.begin(115200);
delay(1000);
tft.drawString("Waiting for PC to connect ...", xpos, ypos, GFXFF);
tft.drawString("Press OK to continue ...", xpos, ypos + tft.fontHeight(GFXFF), GFXFF);
while ((Serial.available() <= 0) && (digitalRead(buton_OK))) //wait for PC or OK button
{
delay(100);
}
if (Serial.available() > 0)
{
if (Serial.read() == 'A')
{
fisier = SD.open("Date.dat");
if (fisier)
//Send stored data
{
tft.fillScreen(BLACK);
tft.drawString("Connected. Sending file!", xpos, ypos, GFXFF);
while (fisier.available())
{
Serial.write(fisier.read());
}
fisier.close();
tft.fillScreen(BLACK);
tft.drawString("Deleting file ...", xpos, ypos, GFXFF);
if (SD.remove("Date.dat")) {
tft.drawString("Deleted!", xpos, ypos + tft.fontHeight(GFXFF), GFXFF);
}
else {
tft.drawString("Error deleting file!", xpos, ypos + tft.fontHeight(GFXFF), GFXFF);
}
while (1) {
; // Stop
}
}
else
{
tft.fillScreen(BLACK);
tft.drawString("Error! File missing!", xpos, ypos, GFXFF);
while (1) {
; // Stop
}
}
}
}
}
else
{
card = false; //no SD card
tft.drawString("SD Card missing!!!", xpos, ypos, GFXFF);
delay(2000);
}
tft.fillScreen(BLACK);
}
//DAC at 0
Wire.beginTransmission(Adresa_MCP4725);
Wire.write( 0 ); //MSB
Wire.write( 0 ); //LSB
Wire.endTransmission();
delay(10);
//Velocities menu--------------------------------------------------------------
while (!digitalRead(buton_OK)) ;
ypos = 10;
tft.setFreeFont(FSB12);
tft.drawString("Select propagation speed c:", xpos, ypos, GFXFF);
ypos += tft.fontHeight(GFXFF);
tft.setFreeFont(FSB9);
for (i = 0; i < (sizeof(medii_propagare) / sizeof(medii_propagare[0])); i++)
{
tft.drawString(medii_propagare[i], xpos, ypos, GFXFF);
ypos += tft.fontHeight(GFXFF);
}
i = 0;
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED); //Draw cursor
cont = false;
do {
while (digitalRead(buton_sus) && digitalRead(buton_jos) && digitalRead(buton_OK)) {
; // wait
}
delay(10);
if (!digitalRead(buton_jos))
{
if (i < (sizeof(medii_propagare) / sizeof(medii_propagare[0]) - 1)) {
i++;
}
else {
i = 0;
}
tft.drawRect(90, ypos, 300, 22, BLACK);
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED);
delay(500);
}
else if (!digitalRead(buton_sus))
{
if (i > 0) {
i--;
}
else {
i = (sizeof(medii_propagare) / sizeof(medii_propagare[0]) - 1);
}
tft.drawRect(90, ypos, 300, 22, BLACK);
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED);
delay(500);
}
else if (!digitalRead(buton_OK))
{
c = viteze[i];
cont = true;
}
} while (!cont);
rezolutie = c / (2.0 * banda); //depth resolution [m]
min_adanc = -4 * rezolutie; //offset cables + antennas (aprox. 4 * rezolution)
if (card)
{
//Verify file existance, if missing, create it and write speed index
if (!SD.exists("Date.dat")) {
fisier = SD.open("Date.dat", FILE_WRITE);
fisier.write(highByte(i));
fisier.write(lowByte(i));
fisier.close();
}
}
//Depth menu--------------------------------------------------------------
i = 0;
word ind_adanc_max = sizeof(adancimi) / sizeof(adancimi[0]) - 1;
tft.fillScreen(BLACK);
while (!digitalRead(buton_OK)) ;
ypos = 10;
tft.setFreeFont(FSB12);
tft.drawString("Select maximum displayed depth:", xpos, ypos, GFXFF);
ypos += tft.fontHeight(GFXFF);
tft.setFreeFont(FSB9);
for (i = 0; i <= ind_adanc_max; i++)
{
double adancime_temp = adancimi[i] * rezolutie + min_adanc;
double zecimale = adancime_temp - floor(adancime_temp);
String sir;
if (zecimale < (adancime_temp / 10)) sir = String(adancime_temp, 0) + " m";
else sir = String(adancime_temp, 1) + " m";
char text[6];
sir.toCharArray(text, 6);
tft.drawString(text, xpos, ypos, GFXFF);
ypos += tft.fontHeight(GFXFF);
}
i = 0;
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED); //Draw cursor
cont = false;
delay(1000);
do {
while (digitalRead(buton_sus) && digitalRead(buton_jos) && digitalRead(buton_OK)) {
; // wait
}
delay(10);
if (!digitalRead(buton_jos))
{
if (i < ind_adanc_max) {
i++;
}
else {
i = 0;
}
tft.drawRect(90, ypos, 300, 22, BLACK);
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED);
delay(500);
}
else if (!digitalRead(buton_sus))
{
if (i > 0) {
i--;
}
else {
i = ind_adanc_max;
}
tft.drawRect(90, ypos, 300, 22, BLACK);
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED);
delay(500);
}
else if (!digitalRead(buton_OK))
{
nr_cel_rez_vert = adancimi[i];
max_adanc = nr_cel_rez_vert * rezolutie + min_adanc;
double pas_adanc_temp = (max_adanc - min_adanc) / 4;
i = 0;
while ((abs(pas_adanc_temp - pasi_adanc[i]) > abs(pas_adanc_temp - pasi_adanc[i + 1])) && ((i + 1) < (sizeof(pasi_adanc) / sizeof(pasi_adanc[0]) - 1)))
{
i++;
}
if (abs(pas_adanc_temp - pasi_adanc[i]) > abs(pas_adanc_temp - pasi_adanc[i + 1])) i++;
pas_adanc = pasi_adanc[i];
nr_zecimale_pasi_adanc = zecimale_pasi_adanc[i];
cont = true;
}
} while (!cont);
//Distance menu--------------------------------------------------------------
tft.fillScreen(BLACK);
while (!digitalRead(buton_OK)) ;
ypos = 10;
tft.setFreeFont(FSB12);
tft.drawString("Select horizontal distance on screen:", xpos, ypos, GFXFF);
ypos += tft.fontHeight(GFXFF);
tft.setFreeFont(FSB9);
for (i = 0; i < (sizeof(distante) / sizeof(distante[0])); i++)
{
String sir = String(distante[i]) + " m";
char text[5];
sir.toCharArray(text, 5);
tft.drawString(text, xpos, ypos, GFXFF);
ypos += tft.fontHeight(GFXFF);
}
i = 0;
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED); //Draw cursor
cont = false;
delay(1000);
do {
while (digitalRead(buton_sus) && digitalRead(buton_jos) && digitalRead(buton_OK)) {
; // wait
}
delay(10);
if (!digitalRead(buton_jos))
{
if (i < (sizeof(distante) / sizeof(distante[0]) - 1)) {
i++;
}
else {
i = 0;
}
tft.drawRect(90, ypos, 300, 22, BLACK);
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED);
delay(500);
}
else if (!digitalRead(buton_sus))
{
if (i > 0) {
i--;
}
else {
i = (sizeof(distante) / sizeof(distante[0]) - 1);
}
tft.drawRect(90, ypos, 300, 22, BLACK);
ypos = 34 + i * tft.fontHeight(GFXFF);
tft.drawRect(90, ypos, 300, 22, RED);
delay(500);
}
else if (!digitalRead(buton_OK))
{
max_dist = distante[i];
pas_dist = max_dist / 6;
cont = true;
}
} while (!cont);
//graph parameters
inaltime_cel_rez = inaltime_grafic / nr_cel_rez_vert; //[pixels]
nr_cel_rez_oriz = max_dist / pas_deplasare_GPR;
latime_cel_rez = latime_grafic / nr_cel_rez_oriz; //[pixels]
// Draw grid
tft.fillScreen(BLACK);
Graph(tft, orig_x, orig_y, latime_grafic, inaltime_grafic, 0, max_dist, pas_dist, min_adanc, max_adanc, pas_adanc, "GPR", "Distance [m]", "Depth [m]");
afis_card();
masurare_afis_bat();
} | 36ebf82afab147ede3528f17a1e5af8c | 139 | dianewan | 2023-05-25T00:28:08 | bad | [] |
@using DevExtreme.AspNet.Mvc.Builders
@using XS.ERP.Core.Entities
@using XS.ERP.UI.Web.Razor.Models
@using XS.ERP.Common.Constant
@using XS.ERP.UI.Web.Razor.V2.Models.ApiDto
@model ProductInventoryViewModel
<script>
</script>
@Html.AntiForgeryToken()
<div class="content-block">
<div style="margin-top:20px;">
@(
Html.DevExtreme().DataGrid<DtoInventory>()
.ID("gridProductInventory")
.DataSource(new JS("arraySOHeaderData"))
.Height(750)
.StateStoring(s => s.Enabled(true).Type(StateStoringType.LocalStorage).StorageKey("gridProductInventory"))
.Columns(columns =>
{
columns.AddFor(m => m.Id).Caption("Id");
columns.AddFor(m => m.Product.Name).Caption("Product").Width(200);
columns.AddFor(m => m.Product.Description).Caption("Description");
columns.Add().Caption("Quantity").CellTemplate(
@<text><%= formatNumberWithDecimalPlaces(data.Qty) %> </text>
);
columns.AddFor(m => m.Booked).Caption("Booked").Format(f => f.Type(Format.FixedPoint).Precision(2));
columns.AddFor(m => m.Reserved).Caption("Reserved").Format(f => f.Type(Format.FixedPoint).Precision(2));
columns.AddFor(m => m.CreatedDate).Caption("Create Date");
}
)
</div>
</div> | 9815523b7efd73e7ee6d6270dd7ef10b | 14 | DaehanKim | 2023-05-29T06:40:56 | bad | [] |
@using DevExtreme.AspNet.Mvc.Builders
@using XS.ERP.Core.Entities
@using XS.ERP.UI.Web.Razor.Models
@using XS.ERP.Common.Constant
@using XS.ERP.UI.Web.Razor.V2.Models.ApiDto
@model ProductInventoryViewModel
<script>
</script>
@Html.AntiForgeryToken()
<div class="content-block">
<div style="margin-top:20px;">
@(
Html.DevExtreme().DataGrid<DtoInventory>()
.ID("gridProductInventory")
.DataSource(new JS("arraySOHeaderData"))
.Height(750)
.StateStoring(s => s.Enabled(true).Type(StateStoringType.LocalStorage).StorageKey("gridProductInventory"))
.Columns(columns =>
{
columns.AddFor(m => m.Id).Caption("Id");
columns.AddFor(m => m.Product.Name).Caption("Product").Width(200);
columns.AddFor(m => m.Product.Description).Caption("Description");
columns.Add().Caption("Quantity").CellTemplate(
@<text><%= formatNumberWithDecimalPlaces(data.Qty) %> </text>
);
columns.AddFor(m => m.Booked).Caption("Booked").Format(f => f.Type(Format.FixedPoint).Precision(2));
columns.AddFor(m => m.Reserved).Caption("Reserved").Format(f => f.Type(Format.FixedPoint).Precision(2));
columns.AddFor(m => m.CreatedDate).Caption("Create Date");
}
)
</div>
</div> | 9815523b7efd73e7ee6d6270dd7ef10b | 14 | dianewan | 2023-05-23T23:28:22 | bad | [] |
import khan
import flight
import flight.operators as fo
import flight.operators.sku as sku
mixer = khan.client("mixer")
@mixer.implements("top_items_by_department", flight=True)
async def flight_path(
client_id: int,
department: str,
diversity_coefficient: float = 0.5,
limit:int = 10
):
take_n = (
sku.Kaleidoset(score_col="psale", rho=diversity_coefficient, n=limit)
if diversity_coefficient > 0
else fo.Limit(n=limit)
)
pipeline = (
flight.Pipeline("top_items_by_department").initialize(
include_candidates=[
sku.AvailableSkusByChannel(channel="shop_your_look"),
sku.Qualifications(),
sku.ShopPSaleSource(score_col="psale"),
],
)
| sku.SkuAugment(columns=["style_variant_id", "department"])
| fo.Equals(column="department", value=department)
| fo.Sort(order_by="psale")
| take_n
)
return await pipeline.execute(
client_id=client_id,
item_type="sku_id",
debug=False,
verbose=False,
) | 6d874da7342cbc2c55f3353b8e17a734 | 140 | dianewan | 2023-05-25T00:28:17 | bad | [] |
The following CalculateProjectilePath function returns a Vector3[] path that a cannonball follows when fired, for a Unity game. Treat the path as a list of Bezier curve control points and change the function to return a Bezier curve instead. Also, since it's a Bezier curve, the number of control points could probably be reduced (but not TOO much).
public static class CannonballTrajectory
{
private const double g = 9.8; // Acceleration due to gravity (m/s^2)
public static Vector3[] CalculateProjectilePath(Vector3 aimVector, double muzzleVelocity)
{
Vector3[] path = new Vector3[100];
for (int i = 0; i < 100; i++)
{
float t = i * 0.1f; // Time elapsed in seconds
float x = aimVector.x * muzzleVelocity * t;
float y = aimVector.y * muzzleVelocity * t - 0.5f * g * t * t;
float z = aimVector.z * muzzleVelocity * t;
path[i] = new Vector3(x, y, z);
}
return path;
}
} | 09919cb87021374f219b67a851435260 | 141 | dianewan | 2023-05-25T00:28:28 | good | [
"code"
] |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 36