text
stringlengths 184
4.48M
|
|---|
A Tour of Go
Code examples from the tour of Go
Read the tour at http://tour.golang.org/
Table of contents are as follows:
01. Hello, 世界
02. Go local
03. The Go Playground
04. Packages
05. Imports
06. Exported names
07. Functions
08. Functions continued
09. Multiple results
10. Named results
11. Variables
12. Variables with initializers
13. Short variable declarations
14. Basic types
15. Type conversions
16. Constants
17. Numeric Constants
18. For
19. For continued
20. For is Go's "while"
21. Forever
22. If
23. If with a short statement
24. If and else
25. Exercise: Loops and Functions
26. Structs
27. Struct Fields
28. Pointers
29. Struct Literals
30. The new function
31. Arrays
32. Slices
33. Slicing slices
34. Making slices
35. Nil slices
36. Range
37. Range continued
38. Exercise: Slices
39. Maps
40. Map literals
41. Map literals continued
42. Mutating Maps
43. Exercise: Maps
44. Function values
45. Function closures
46. Exercise: Fibonacci closure
47. Switch
48. Switch evaluation order
49. Switch with no condition
50. Advanced Exercise: Complex cube roots
51. Methods and Interfaces
52. Methods
53. Methods continued
54. Methods with pointer receivers
55. Interfaces
56. Interfaces are satisfied implicitly
57. Errors
58. Exercise: Errors
59. Web servers
60. Exercise: HTTP Handlers
61. Images
62. Exercise: Images
63. Exercise: Rot13 Reader
64. Concurrency
65. Goroutines
66. Channels
67. Buffered Channels
68. Range and Close
69. Select
70. Default Selection
71. Exercise: Equivalent Binary Trees
72. Exercise: Equivalent Binary Trees
73. Exercise: Web Crawler
If you feel anything wrong, feedbacks or pull requests are welcomed.
|
package dev.glory.demo.domain.auth.repository;
import static org.assertj.core.api.Assertions.assertThat;
import java.time.LocalDateTime;
import java.util.UUID;
import dev.glory.demo.IntegratedTestSupport;
import dev.glory.demo.domain.auth.RefreshToken;
import dev.glory.demo.domain.user.User;
import dev.glory.demo.domain.user.repository.UserRepository;
import dev.glory.demo.domain.user.role.Role;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
class RefreshTokenRepositoryTest extends IntegratedTestSupport {
@Autowired
private RefreshTokenRepository refreshTokenRepository;
@Autowired
private UserRepository userRepository;
private void createRefreshToken(User user, String refreshToken) {
RefreshToken token = RefreshToken.builder()
.user(user)
.refreshToken(refreshToken)
.expireDt(LocalDateTime.now().plusMinutes(30))
.build();
refreshTokenRepository.save(token);
}
@AfterEach
void tearDown() {
refreshTokenRepository.deleteAllInBatch();
userRepository.deleteAllInBatch();
}
@DisplayName("User 으로 RefreshToken 조회 한다")
@Test
void when_findByUser_expect_token() throws Exception {
// given
String username = setUp();
User user = userRepository.findByUsername(username).orElseThrow();
String refreshToken = UUID.randomUUID().toString();
createRefreshToken(user, refreshToken);
// when
RefreshToken findToken = refreshTokenRepository.findByUser(user).orElseThrow();
// then
assertThat(findToken.getRefreshToken()).isEqualTo(refreshToken);
assertThat(findToken.getUser().getUsername()).isEqualTo(user.getUsername());
}
@DisplayName("refresh token 으로 RefreshToken 조회 한다")
@Test
void when_findByRefreshToken_expect_token() throws Exception {
// given
String username = setUp();
User user = userRepository.findByUsername(username).orElseThrow();
String refreshToken = UUID.randomUUID().toString();
createRefreshToken(user, refreshToken);
// when
RefreshToken findToken = refreshTokenRepository.findByRefreshToken(refreshToken).orElseThrow();
// then
assertThat(findToken.getRefreshToken()).isEqualTo(refreshToken);
assertThat(findToken.getUser().getUsername()).isEqualTo(user.getUsername());
}
@DisplayName("User 의 RefreshToken 을 삭제 한다")
@Test
void when_deleteByUser_expect_deleteToken() throws Exception {
// given
String username = setUp();
User user = userRepository.findByUsername(username).orElseThrow();
String refreshToken = UUID.randomUUID().toString();
createRefreshToken(user, refreshToken);
// when
long deleted = refreshTokenRepository.deleteByUser(user);
// then
assertThat(deleted).isOne();
assertThat(refreshTokenRepository.findByRefreshToken(refreshToken)).isEmpty();
}
private String setUp() {
String username = UUID.randomUUID().toString().substring(0, 8);
User user = User.builder()
.username(username)
.password("mypassword123!@#")
.name("test")
.email("test@abc.com")
.enabled(true)
.locked(false)
.role(Role.SUPER)
.build();
userRepository.save(user);
return username;
}
}
|
<script setup lang="ts">
import EditPersonalInfo from 'src/components/admin/user/editUserForm/EditPersonalInfo.vue'
import EditSocialInfo from 'src/components/admin/user/editUserForm/EditSocialInfo.vue'
import EditAddressInfo from 'src/components/admin/user/editUserForm/EditAddressInfo.vue'
import EditFavoriteLinkInfo from 'src/components/admin/user/editUserForm/EditFavoriteLinkInfo.vue'
import EditExperienceInfo from 'src/components/admin/user/editUserForm/EditExperienceInfo.vue'
import EditLanguageInfo from 'src/components/admin/user/editUserForm/EditLanguageInfo.vue'
import { onBeforeMount, ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import editUserStore from 'src/stores/editUserStore'
import EditSkillsInfo from 'src/components/admin/user/editUserForm/EditSkillsInfo.vue'
import EditPrivacyInfo from 'src/components/admin/user/editUserForm/EditPrivacyInfo.vue'
import EditNotificationInfo from 'src/components/admin/user/editUserForm/EditNotificationInfo.vue'
import EditPasswordInfo from 'src/components/admin/user/editUserForm/EditPasswordInfo.vue'
const router = useRouter();
const route = useRoute();
const tab = ref('personal')
const editUser = editUserStore()
onBeforeMount(async () => {
await editUser.getInitialValues(route.params.id as string)
})
</script>
<template>
<div class="q-pa-md">
<div class="q-gutter-y-md">
<div class="row items-center q-gutter-sm">
<q-icon name="keyboard_backspace" size="30px" style="cursor: pointer" @click="() => {
router.push({ name: 'admin.user.index' });
}
" />
<span class="text-h6"> Edit User </span>
</div>
<q-card flat>
<q-tabs v-model="tab" dense class="text-grey" active-color="primary" indicator-color="primary" align="start"
narrow-indicator>
<q-tab name="personal" label="Personal" />
<q-tab name="address" label="Address" />
<q-tab name="social" label="Social Links" />
<q-tab name="favoritLinks" label="Favorite Links" />
<q-tab name="experience" label="Experience" />
<q-tab name="language" label="Language" />
<q-tab name="skill" label="Skills" />
<q-tab name="privacy" label="Privacy" />
<q-tab name="notifications" label="Notifications" />
<q-tab name="passwword" label="Reset Password" />
</q-tabs>
<q-separator />
<q-tab-panels v-model="tab" animated>
<q-tab-panel name="personal">
<div class="text-h6">Edit Personal Information</div>
<EditPersonalInfo />
</q-tab-panel>
<q-tab-panel name="address">
<div class="text-h6">Edit Address</div>
<EditAddressInfo />
</q-tab-panel>
<q-tab-panel name="social">
<div class="text-h6">Edit Social Links</div>
<EditSocialInfo />
</q-tab-panel>
<q-tab-panel name="favoritLinks">
<div class="text-h6">Edit Favorite Links</div>
<EditFavoriteLinkInfo />
</q-tab-panel>
<q-tab-panel name="experience">
<div class="text-h6">Edit Work Experience</div>
<EditExperienceInfo />
</q-tab-panel>
<q-tab-panel name="language">
<div class="text-h6">Edit Languages</div>
<EditLanguageInfo />
</q-tab-panel>
<q-tab-panel name="skill">
<div class="text-h6">Edit Skills</div>
<EditSkillsInfo />
</q-tab-panel>
<q-tab-panel name="privacy">
<div class="text-h6">Edit Privacy</div>
<EditPrivacyInfo />
</q-tab-panel>
<q-tab-panel name="notifications">
<div class="text-h6">Edit Notifications</div>
<EditNotificationInfo />
</q-tab-panel>
<q-tab-panel name="passwword">
<div class="text-h6">Reset Password</div>
<EditPasswordInfo />
</q-tab-panel>
</q-tab-panels>
</q-card>
</div>
</div>
</template>
|
@if $use-rules == true{
/*------------------------------------*\
$RULES
\*------------------------------------*/
/**
* Horizontal rules, extend `hr`.
*
* Demo: jsfiddle.net/inuitcss/L6GuZ
*
*/
.rule{
@include rems(margin-bottom, $base-spacing-unit - 1);
color:$base-ui-color;
border:none;
border-bottom-width:1px;
border-bottom-style:solid;
}
/**
* Dotted rules
*/
.rule--dotted{
border-bottom-style:dotted;
}
/**
* Dashed rules
*/
.rule--dashed{
border-bottom-style:dashed;
}
/**
* Ornamental rules. Places a § over the rule.
*/
.rule--ornament{
position:relative;
&:after{
content:"\00A7";
position:absolute;
top: 0;
right: 0;
left: 0;
line-height:0;
text-align:center;
}
/**
* Pass in an arbitrary ornament though a data attribute, e.g.:
*
<hr class="rule rule--ornament" data-ornament="!">
*
*/
&[data-ornament]:after{
content:attr(data-ornament);
}
}
}//endif
|
<template>
<dialog class="login-popup-box" open>
<img src="../assets/money.png" class="money-logo-topright" />
<div class="popup-content">
<h1 class="stylized-text">Change Password</h1>
<form @submit.prevent="changePassword">
<div class="input-container">
<label for="currentPassword" class="regular-text">Current Password</label>
<input type="password" id="currentPassword" v-model="currentPassword" required class="input-text" />
</div>
<div class="input-container">
<label for="newPassword" class="regular-text">New Password</label>
<input type="password" id="newPassword" v-model="newPassword" required class="input-text" />
</div>
<div class="change-password-button">
<button class="filled-button-green" type="submit">
<p class="button-text">Change Password</p>
</button>
</div>
</form>
<p v-if="errorMessage" class="error">{{ errorMessage }}</p>
<p v-if="successMessage" class="success">{{ successMessage }}</p>
</div>
<img src="../assets/money.png" class="money-logo-bottomleft" />
</dialog>
</template>
<script>
import { ref } from 'vue';
import { useStore } from '@/store';
import { useRouter } from 'vue-router';
import Swal from 'sweetalert2';
export default {
setup() {
const store = useStore();
const router = useRouter();
const currentPassword = ref('');
const newPassword = ref('');
const errorMessage = ref('');
const successMessage = ref('');
const changePassword = async () => {
const success = await store.changePassword(currentPassword.value, newPassword.value);
if (success) {
Swal.fire('Success!', 'Password changed successfully', 'success');
setTimeout(() => {
router.push('/profile');
}, 2000);
} else {
Swal.fire('Error!', 'Failed to change password', 'error');
}
};
return {
currentPassword,
newPassword,
errorMessage,
successMessage,
changePassword,
};
},
};
</script>
<style scoped>
h1.stylized-text {
margin: 10px;
font-family: 'Newsreader';
color: black;
font-size: 3em;
}
.popup-content {
display: flex;
flex-direction: column;
overflow: hidden;
}
.input-container {
display: flex;
flex-direction: column;
}
.input-text {
margin: 10px 0; }
.filled-button-green {
cursor: pointer;
}
</style>
|
---
title: Pricing
sidebar_position: 4
---
# Pricing Hypotheses
Foosoft's pricing model must reflect the complex dynamics of the technology
consulting industry while aligning with customer value perception and business
strategy. The company will explore an array of pricing strategies, adapting and
responding to market feedback and project outcomes.
## Pricing Strategy
Foosoft is dedicated to creating a pricing structure that emphasizes the bespoke
nature of its consulting services, tying costs to the value delivered.
1. A hybrid pricing approach will be evaluated, starting with several models
including day rates, fixed fees, weekly team pricing, value-based, and
retained services.
2. Client feedback and project analysis will play a crucial role in refining
Foosoft's pricing models to best suit different client segments and project
types.
3. We will establish margins that reflect Foosoft's value proposition,
competitive positioning, and the premium nature of the services delivered.
## Pricing Models Exploration
Foosoft acknowledges the need for agile pricing models that can address the
unique requirements and sensitivities of its diverse client base.
### Day Rate Pricing
Appropriate for clients with targeted, clearly defined scope engagements.
1. Transparent and easy to understand for clients who need specialized input for
a short duration.
2. While simplistic, this model may not align incentives for fast and efficient
project completion.
### Weekly Team Pricing
Suitable for medium-term projects that require a dedicated team's focus for
consecutive periods.
1. Promotes collaboration and consistent progress through regular immersion in
the client’s business.
2. Needs oversight to avoid inefficiency or scope creep, ensuring time is
optimally used to drive results.
### Fixed Fee Pricing
Offers a singular comprehensive price for a project, typically calculated based
on the overall scope and anticipated deliverables.
1. Provides clear cost expectations upfront, which can be appealing for clients
with fixed budgets.
2. Foosoft, however, recognizes the inherent risk of underestimating the project
scope – changes can lead to additional costs or strained relationships,
making this model less favorable.
3. May not allow for the flexibility required in dynamic project environments
where scope evolves over time.
### Retained Services
Ensures ongoing support, with clients paying a recurring fee for continuous
access to services.
1. Ideal for clients seeking long-term maintenance, support, or iterative
development.
2. Fosters stable, predictable relationships and revenue streams, although it
might not be suited for clients with ad-hoc service needs.
### Value-Based Pricing
Reflects Foosoft's commitment to delivering services that create significant
business value.
1. Encourages alignment with clients' strategic goals and success metrics.
2. Necessitates clear articulation of project benefits and may involve complex
negotiations to define the value delivered.
## Price Sensitivity Analysis
Foosoft intends to conduct in-depth analysis to find pricing that reflects the
intricate balance of exceptional service and market competitiveness.
1. Comparative pricing analysis will include varied industry benchmarks, with
large firms like Accenture that can range from $1500 to $1900+ per day,
mid-sized firms like Thoughtworks with day rates often between $1300 to
$1600, and very small boutique agencies which could position themselves
anywhere from $900 to $1200 per day.
2. Client responsiveness to pricing changes across these segments will be
scrutinized to adjust and position Foosoft's offerings attractively.
3. The niche expertise and high-touch, personalized service offered may carve
out a distinct pricing scope within the upper bracket of the boutique agency
range.
Through iterative analysis and client engagement, Foosoft plans to cultivate a
pricing approach that is not only market-aware but also responsive to its
clients' evolving needs and perceptions of value.
|
package org.wildstang.autonomous.programs;
import org.wildstang.autonomous.AutonomousProgram;
import org.wildstang.autonomous.steps.control.AutonomousStepDelay;
import org.wildstang.autonomous.steps.drivebase.AutonomousStepDriveManual;
import org.wildstang.autonomous.steps.drivebase.AutonomousStepSetShifter;
import org.wildstang.autonomous.steps.intake.AutonomousStepSetIntakeIn;
import org.wildstang.autonomous.steps.intake.AutonomousStepSetIntakeOff;
import org.wildstang.autonomous.steps.lift.AutonomousStepSetLiftBottom;
import org.wildstang.config.DoubleConfigFileParameter;
import org.wildstang.config.IntegerConfigFileParameter;
import edu.wpi.first.wpilibj.DoubleSolenoid;
public class AutonomousProgramKnockOverBinAndPickUp extends AutonomousProgram {
protected final IntegerConfigFileParameter DRIVE_DURATION = new IntegerConfigFileParameter(this.getClass().getName(), "drive_duration", 500);
protected final DoubleConfigFileParameter DRIVE_SPEED = new DoubleConfigFileParameter(this.getClass().getName(), "drive_speed", 0.5);
protected final IntegerConfigFileParameter BIN_TIP_TIME = new IntegerConfigFileParameter(this.getClass().getName(), "bin_tip_time", 1000);
protected final IntegerConfigFileParameter INTAKE_ENGAGE_DELAY = new IntegerConfigFileParameter(this.getClass().getName(), "intake_engage_delay", 1000);
@Override
protected void defineSteps() {
// Shift into high gear and begins driving
addStep(new AutonomousStepSetShifter(true));
addStep(new AutonomousStepDriveManual(DRIVE_SPEED.getValue(), 0));
addStep(new AutonomousStepDelay(DRIVE_DURATION.getValue()));
// Stop
addStep(new AutonomousStepDriveManual(0.0, 0));
// Wait for bin to tip
addStep(new AutonomousStepDelay(BIN_TIP_TIME.getValue()));
// Drive backwards
addStep(new AutonomousStepDriveManual(-DRIVE_SPEED.getValue(), 0));
addStep(new AutonomousStepDelay(DRIVE_DURATION.getValue()));
// Stop
addStep(new AutonomousStepDriveManual(0.0, 0));
// Allow the robot to settle
addStep(new AutonomousStepDelay(300));
// Lower the lift
addStep(new AutonomousStepSetLiftBottom());
// Wait for the lift to reach the bottom
addStep(new AutonomousStepDelay(1500));
// Allow things to settle
addStep(new AutonomousStepDelay(300));
// Shift into low gear and drive forward slowly to pick up the bin
addStep(new AutonomousStepSetShifter(false));
addStep(new AutonomousStepDriveManual(0.2, 0.0));
// Begin running intake
addStep(new AutonomousStepSetIntakeIn());
// After the specified delay, close intake
addStep(new AutonomousStepDelay(INTAKE_ENGAGE_DELAY.getValue()));
// Continue driving forward
addStep(new AutonomousStepDelay(1000));
// Stop driving, disable intake
addStep(new AutonomousStepDriveManual(0.0, 0.0));
addStep(new AutonomousStepSetIntakeOff());
}
@Override
public String toString() {
return "Drive to knock over bin";
}
}
|
let toolbox = createElementWithId("form", "ngen-toolbox");
let writebox = createElementWithId("iframe", "ngen-writebox");
writebox.setAttribute("name", "ngenFrame");
writebox.setAttribute("src", "about:blank");
tool1 = createElementWithId("div", "ngen-tool1");
tool2 = createElementWithId("div", "ngen-tool2");
tool3 = createElementWithId("div", "ngen-tool3");
tool4 = createElementWithId("div", "ngen-tool4");
tool5 = createElementWithId("div", "ngen-tool5");
tool1.append(createButtonWithCmd("h1", "H1"));
tool1.append(createButtonWithCmd("h2", "H2"));
tool1.append(createButtonWithCmd("h3", "H3"));
tool1.append(createButtonWithCmd("p", "x"));
tool2.append(createStyleButtonWithCmd("bold", "B"));
tool2.append(createStyleButtonWithCmd("italic", "I"));
tool2.append(createStyleButtonWithCmd("underline", "U"));
tool2.append(createStyleButtonWithCmd("strikeThrough", "S"));
tool3.append(createButtonList("insertUnorderedList", "•≡"));
tool3.append(createButtonList("insertOrderedList", "1≡"));
tool4.append(createButton("insertImage", "🖼️"));
tool5.append(createButton("insertLink", "🔗"));
toolbox.append(tool1)
toolbox.append(tool2)
toolbox.append(tool3)
toolbox.append(tool4)
toolbox.append(tool5)
document.getElementById("ngen-editor").append(toolbox);
document.getElementById("ngen-editor").append(writebox);
ngenFrame.document.designMode = "On";
ngenFrame.document.open();
ngenFrame.document.write("");
ngenFrame.document.close();
imageBox = createElementWithId("div", "ngen-image-box");
imageBox.innerHTML = "<input type='file' id='ngen-image-source' name='ngen-image-source' placeholder='Please select a image'><button type='button' id='ngen-insert-image' name='ngen-insert-image' disabled=true>Done</button>";
toolbox.append(imageBox)
linkBox = createElementWithId("div", "ngen-link-box");
linkBox.innerHTML = "<input type='input' id='ngen-link-url' name='ngen-link-url' placeholder='URL'><button type='button' id='ngen-insert-link' name='ngen-insert-link' disabled=true>Done</button>";
toolbox.append(linkBox)
function createElementWithId(_type, _id) {
newDiv = document.createElement(_type);
newDiv.setAttribute("id", _id);
return newDiv;
}
function createButtonWithCmd(_cmd, _letter) {
newBtn = document.createElement("Button");
newBtn.setAttribute("type", "button");
newBtn.setAttribute("tool-cmd", _cmd);
letter = document.createElement("b");
letter.innerHTML = _letter;
newBtn.append(letter)
return newBtn;
}
function createStyleButtonWithCmd(_cmd, _letter) {
newBtn = document.createElement("Button");
newBtn.setAttribute("type", "button");
newBtn.setAttribute("tool-cmd", _cmd);
letter = document.createElement(_letter);
letter.innerHTML = _letter;
newBtn.append(letter)
return newBtn;
}
function createButtonList(_cmd, _letter) {
newBtn = document.createElement("Button");
newBtn.setAttribute("type", "button");
newBtn.setAttribute("tool-cmd", _cmd);
letter = document.createElement("div");
letter.innerHTML = _letter;
newBtn.append(letter)
return newBtn;
}
function createButton(_cmd, _letter) {
newBtn = document.createElement("Button");
newBtn.setAttribute("type", "button");
newBtn.setAttribute("tool-cmd", _cmd);
letter = document.createElement("div");
letter.innerHTML = _letter;
newBtn.append(letter)
return newBtn;
}
function createButton(_cmd, _letter) {
newBtn = document.createElement("Button");
newBtn.setAttribute("type", "button");
newBtn.setAttribute("tool-cmd", _cmd);
letter = document.createElement("div");
letter.innerHTML = _letter;
newBtn.append(letter)
return newBtn;
}
tool1.addEventListener("click", async(e) => {
const cmd = e.target.closest("button").getAttribute("tool-cmd");
ngenFrame.document.execCommand("formatBlock", false, "<" + cmd + ">");
console.log(getHTML());
});
tool2.addEventListener("click", async(e) => {
const cmd = e.target.closest("button").getAttribute("tool-cmd");
ngenFrame.document.execCommand(cmd, false, null);
console.log(getHTML());
});
tool3.addEventListener("click", async(e) => {
const cmd = e.target.closest("button").getAttribute("tool-cmd");
ngenFrame.document.execCommand(cmd, false, null);
console.log(getHTML());
});
tool4.addEventListener("click", async(e) => {
if (imageBox.style.display == "inline-grid")
imageBox.style.display = "";
else
imageBox.style.display = "inline-grid";
});
tool5.addEventListener("click", async(e) => {
if (linkBox.style.display == "inline-grid") {
linkBox.style.display = "";
document.getElementById("ngen-link-text").value = "";
document.getElementById("ngen-link-url").value = "";
}
else {
document.getElementById("ngen-link-url").disabled = false;
linkBox.style.display = "inline-grid";
document.getElementById("ngen-link-url").placeholder = "URL"
if (ngenFrame.document.getSelection() == "") {
document.getElementById("ngen-link-url").placeholder = "Please select a text first"
document.getElementById("ngen-link-url").disabled = true;
}
}
});
ngenFrame.addEventListener("click", async(e) => {
imageBox.style.display = "";
linkBox.style.display = "";
});
let tempImageStorage = "";
document.getElementById("ngen-image-source").addEventListener("change", async(e) => {
document.getElementById("ngen-insert-image").disabled = false;
var file = e.target.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(){
tempImageStorage = reader.result
}
})
document.getElementById("ngen-insert-image").addEventListener("click", async(e) => {
document.getElementById("ngen-insert-image").disabled = true;
document.getElementById("ngen-image-source").value = "";
ngenFrame.document.execCommand("insertImage", false, tempImageStorage);
tempImageStorage = "";
})
document.getElementById("ngen-link-url").addEventListener("change", async(e) => {
if (ngenFrame.document.getSelection() != "" && document.getElementById("ngen-link-url") != "")
document.getElementById("ngen-insert-link").disabled = false;
})
document.getElementById("ngen-insert-link").addEventListener("click", async(e) => {
const url = document.getElementById("ngen-link-url").value;
document.getElementById("ngen-insert-link").disabled = true;
document.getElementById("ngen-link-url").value = "";
ngenFrame.document.execCommand("createLink", false, url);
})
function getHTML() {
let result = "";
result = ngenFrame.document.body.innerHTML.replace(/<div>/g, "<p>").replace(/<\/div>/g, "</p>")
result = result.replace(/<br><\/p>$/g, "</p>")
result = result.replace(/<p><br><\/p>/g, "<br>")
result = result.replace(/<\/p><p>/g, "<br>")
result = result.replace(/<\/p><br><p>/g, "</p><p>")
result = result.replace(/<\/p>((<br>)+)<br><p>/g, "</p>$1<p>")
result = result.replace(/<\/p><br>$/g, "</p>")
return result;
}
|
syntax = "proto3";
option csharp_namespace = "TestGfCat";
package messages;
import "google/protobuf/empty.proto";
import "google/api/annotations.proto";
service MessagesService{
rpc ListMessages(google.protobuf.Empty) returns (ListReply){
option (google.api.http) = {
get : "/message"
};
};
rpc GetMessage(GetAdventMessageRequest) returns (AdventMessageReply){
option (google.api.http) = {
get : "/message/{id}"
};
};
rpc CreateMessage(CreateAdventMessageRequest) returns (AdventMessageReply){
option (google.api.http) = {
post : "/message"
body : "*"
};
};
rpc UpdateMessage(UpdateAdventMessageRequest) returns (AdventMessageReply){
option (google.api.http) = {
put : "/message"
body : "*"
};
};
rpc DeleteMessage(DeleteAdventMessageRequest) returns (google.protobuf.Empty){
option (google.api.http) = {
delete: "/message/{id}"
};
};
}
message CreateAdventMessageRequest{
int32 id = 1;
string message = 2;
}
message GetAdventMessageRequest{
int32 id =1;
}
message UpdateAdventMessageRequest{
int32 id=1; //id is bound from route parameter
string message=2;
}
message DeleteAdventMessageRequest{
int32 id =1;
}
message ListReply{
repeated AdventMessageReply AdventMessages = 1;
}
message AdventMessageReply{
int32 id = 1;
string message=2;
}
|
package com.webcon.sus.utils;
import android.media.AudioRecord;
import android.util.Log;
import com.webcon.wp.utils.WPApplication;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import vieboo.test.record.utils.IRecordData;
import vieboo.test.record.utils.TransferDecoding;
/**
* 录音工具
* @author m
*/
public class AudioRecorder {
private static final String TAG = "AudioRecorder";
// 文件输出流
private FileOutputStream fos;
// 录音工具
private AudioRecord mAudioRecord;
// 录音数组的长度
private final int bufferSize = AudioUtils.RECORD_BUFFER_SIZE;
// 原始录音保存的short数组
private byte[] buffer;
// 正在录音标识
private boolean isRecording = false;
// 应用类型,本地/网络
private int applyType;
// 编码工具
private TransferDecoding mEncoder;
// 回调接口,用于网络
private IRecordData callback;
public AudioRecorder(IRecordData callback) {
if(callback == null){
//本地
applyType = AudioUtils.APPLY_TYPE_LOCAL;
createFile();
}else{
//网络
this.callback = callback;
applyType = AudioUtils.APPLY_TYPE_ONLINE;
}
init();
}
private void init(){
buffer = new byte[bufferSize];
initRecorder();
}
private void createFile(){
File file = new File(AudioUtils.WAV_FILE);
if(file.exists()){
file.delete();
}
try {
if(file.createNewFile()){
fos = new FileOutputStream(file);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
/**
* 初始化
*/
private void initRecorder(){
//初始化编码库
mEncoder = new TransferDecoding();
mEncoder.g722_encoder_init(AudioUtils.BITRATE, AudioUtils.SAMEPLE_RATE_HZ);
//获得录音缓冲区
int recordBufferSize = AudioRecord.getMinBufferSize(
AudioUtils.SAMEPLE_RATE_HZ, AudioUtils.CHANNEL_CONFIG, AudioUtils.AUDIO_FORMAT);
//获得录音对象
mAudioRecord = new AudioRecord(
AudioUtils.AUDIO_SOURCE, AudioUtils.SAMEPLE_RATE_HZ,
AudioUtils.CHANNEL_CONFIG, AudioUtils.AUDIO_FORMAT, recordBufferSize * 10);
}
//--------------------------------------
public void start(){
if(isRecording){
return;
}
isRecording = true;
new RecordThread().start();
}
public void stop(){
isRecording = false;
}
private void release(){
if(WPApplication.DEBUG){
Log.i(TAG,"---release---");
}
mAudioRecord.stop();
mAudioRecord.release();
mAudioRecord = null;
mEncoder.g722_encoder_release();
try {
if(fos != null){
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void execute(byte[] buffer, int length){
//数据处理
byte[] newData = new byte[length];
int enLength = mEncoder.g722_encoder(newData, buffer, length);
byte[] enData = new byte[enLength];
System.arraycopy(newData, 0, enData, 0, enLength);
//保存到本地,或者发送到网络
if(applyType == AudioUtils.APPLY_TYPE_LOCAL && fos != null){
try {
fos.write(enData, 0, enLength);
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}else if (applyType == AudioUtils.APPLY_TYPE_ONLINE && callback != null){
callback.onRecordData(enData, enLength);
}
}
//--------------------------
/**
* 录音线程
*
*/
class RecordThread extends Thread{
@Override
public void run(){
if(mAudioRecord == null){
release();
}
//开始录音
mAudioRecord.startRecording();
int length = 0;
try{
while(isRecording){
length = mAudioRecord.read(buffer, 0, bufferSize);
execute(buffer, length);
}
}finally {
release();
}
}
}
}
|
import React, { ReactNode, ReactElement, JSXElementConstructor } from 'react'
import { act, fireEvent, render } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect.js'
import FormProvider from '../src/FormProvider'
import * as useFieldsAndValidationHook from '../src/hooks/useFieldsAndValidations'
import { EnrichedChildren } from '../src/types'
const extendedChildren = (
<div>
<input
name="name1"
onChange={() => {
return null
}}
type="text"
value="value"
data-testid="name1"
/>
<input
name="name2"
data-testid="name2"
onChange={() => {
return null
}}
type="text"
value="value"
/>
</div>
)
const smallerChildren = (
<input
name="name1"
onChange={() => {
return null
}}
type="text"
value="value"
data-testid="name1"
/>
)
const renderForm = (
children: ReactNode,
props: Record<string, any> = {}
): any => {
const mockFunction = jest.fn()
return render(
<FormProvider data-testid="form" onSubmit={mockFunction} {...props}>
{children}
</FormProvider>
)
}
describe('Form, --success cases', () => {
it('should display error message', async () => {
const submitMock = jest.fn()
const inputName = 'name1'
const { getByTestId, getByText } = renderForm(smallerChildren, {
onSubmit: submitMock,
})
const input = getByTestId(inputName)
await act(async () => {
await fireEvent.change(input, {
target: { value: '' },
})
})
expect(
getByText(`The field ${inputName} has an invalid value`)
).toBeInTheDocument()
})
it('should return form correct object with input values and names on submit', () => {
const submitMock = jest.fn()
const { container, getByTestId } = renderForm(extendedChildren, {
onSubmit: submitMock,
})
fireEvent.change(getByTestId('name1'), {
target: { value: 'value1' },
})
fireEvent.submit(container.querySelector('form'))
expect(submitMock).toHaveBeenCalled()
expect(submitMock).toHaveBeenCalledWith({
name1: 'value1',
name2: 'value',
})
})
it('should change specific input value', () => {
const submitMock = jest.fn()
const { getByTestId } = renderForm(smallerChildren, {
onSubmit: submitMock,
})
const inputField = getByTestId('name1')
fireEvent.change(inputField, {
target: { value: 'value1' },
})
expect(inputField).toHaveValue('value1')
})
it('should call useFieldsAndValidations functions', () => {
const submitMock = jest.fn()
const getFieldsValuesMock = jest.fn()
const checkIfAllFieldsAreValidMock = jest.fn()
const getInputByNameResponse:
| ReactElement<EnrichedChildren, string | JSXElementConstructor<any>>
| undefined = {
key: null,
props: {
name: 'name1',
type: 'text',
value: 'value',
onChange: () => {
return null
},
selectedValue: 'value',
},
type: 'input',
}
jest.spyOn(useFieldsAndValidationHook, 'default').mockReturnValue({
getFieldsValues: getFieldsValuesMock,
getFieldsValidities: () => {
return { name1: true }
},
checkIfAllFieldsAreValid: checkIfAllFieldsAreValidMock,
getInputByName: () => {
return getInputByNameResponse
},
})
const { container } = renderForm(smallerChildren, {
onSubmit: submitMock,
})
act(() => {
fireEvent.submit(container.querySelector('form'))
})
expect(checkIfAllFieldsAreValidMock).toHaveBeenCalledTimes(1)
expect(getFieldsValuesMock).toHaveBeenCalledTimes(1)
})
})
|
# System Architecture
The Integrated Sales and Customer Management System is built using Node.js and follows a modular structure. The application includes controllers, models, views (pages), and static assets.
## Directory Structure
- **index.js**: The entry point of the application.
- **package.json, package-lock.json**: Node.js package configuration files.
- **README.md**: Documentation for the project.
- **controll/**: Controllers responsible for handling different aspects of the application.
- **doc/**: Documentation folder.
- **model/**: Models representing the data structure, defining the **Schemas** and business logic of the application.
- **pages/**: EJS templates for rendering HTML pages.
- **public/**: Static assets like JavaScript files.
## Components
### 1. Entry Point (index.js)
- Initializes the Express application.
- Configures middleware and routes.
### 2. Controllers (controll/)
- **cart.js**: Manages cart-related operations.
- **extras.js**: Additional functionalities.
- **login.js**: Handles user authentication and login.
- **mail.js**: Responsible for email-related functionalities.
- **pages.js**: Controls rendering of different pages.
- **register.js**: Handles user registration.
- **router.js**: Defines routes and connects them to corresponding controllers.
- **sales.js**: Manages sales-related operations.
### 3. Models (model/)
- **admin.js**: Represents the admin data model.
- **cart.js**: Represents the cart data model.
- **customer.js**: Represents the customer data model.
- **customerdetail.js**: Represents detailed customer information.
- **items.js**: Represents the item data model.
- **order.js**: Represents the order data model.
- **sales.js**: Represents sales-related data.
### 4. Views (pages/)
- **admin.ejs**: Admin page template.
- **cart.ejs**: Cart page template.
- **items.ejs**: Items page template.
- **loginform.ejs**: Login form template.
- **order.ejs**: Order page template.
- **orders.ejs**: Orders page template.
- **sorders.ejs**: Sales orders page template.
### 5. Static Assets (public/)
- **cartsupport.js**: JavaScript file for cart-related support.
- **salessupport.js**: JavaScript file for sales-related support.
## Application Flow
1. **User Interaction:**
- Users interact with the application through the provided views (EJS templates).
- Requests are sent to the server for processing.
2. **Server Processing:**
- The server, implemented using Express, processes incoming requests.
- Requests are routed to the appropriate controller based on defined routes.
3. **Controller Logic:**
- Controllers contain logic for handling specific functionalities (e.g., cart management, order processing).
4. **Model Interaction:**
- Controllers interact with models to perform CRUD operations on data (e.g., interacting with the database).
5. **View Rendering:**
- Rendered views are sent back to the client for display.
6. **Static Assets:**
- Static assets (JavaScript files) in the `public` folder enhance client-side functionality.
## Dependencies
- Express: Web application framework for Node.js.
- EJS: Templating engine for rendering views.
## Setup and Usage
Refer to the `README.md` file for instructions on setting up and running the application.
|
## Learn SQL Database Programming
## Query and Manipulate databases from popular relational database servers using SQL
## Josephine Bush
### Introduction To Relational Database Management Systems
Questions
1. What is SQL?
Structured Query Language or SQL is the language that is used for querying
and maniulating data and defining structures in databases. SQL is powerful and
simple. With SQL you can execute queries, retrieve, insert, update, and delete
data, create databases and tables.
2. What are the different subdivisions of SQL?
The subdivisions of SQL are Data Definition Language (DDL), Data Manipulation Language (DML),
and Data Control Language (DCL).
- We use DDL commands to specify database schema:
- CREATE: This is used to create a database or objects in the database.
- ALTER: This is used to alter a database or objects in a database.
- DROP: This is used to delete a database or objects in a database.
- TRUNCATE: This is used to remove all data from a table instantaneously.
- We use DML commands to query and modify data:
- SELECT: This is used to retrieve data from a database.
- INSERT: This is used to insert data into a database.
- UPDATE: This is used to update data in a database.
- DELETE: This is used to remove data from a database.
- We use DCL commands to control permissions and translations:
- GRANT: This is used to give access to a user.
- REVOKE: This is used to take access away from a user.
- COMMIT: This is used to save changes in a transaction.
- ROLLBACK: This is used to remove the saved changes in a transaction.
3. What are the elements of a SQL statement?
- Queries that retrieve data based on specific criteria.
- Clauses that are components of statements or queries.
- Predicates that are logical conditions that evaluate to true or false.
These help you narrow down the results of your queries.
- Expressions that produce either scalar values or tables of columns and rows.
Expressions are part of predicates.
- Statements that are run against a database, comprised of clauses and, optionally,
expressions and predicates.
- White space that is generally ignored in SQL statements and queries, making it
easier to format for readability because you don't have to worry so much about
particular spacing for the SQL to run correctly.

4. What are the reasons to normalize a database?
We should normalize our databases in order to avoid redundant data, optimize database performance,
and ensure data integrity.
Without database normalization it is possible to have data redundancy and it can also
be difficult to update and maintain the database without data loss.
5. What are the levels of database normalization?
There are three levels of database normalization:
- First normal form (1NF)
- define data, columns, data types and put data into columns
- eliminate repeating grouops of data:
- no repeating columns (e.g. Year1, Year2) instead have year
- not multiple values in same field - eg 1985, 1987 - place year in a row
- No exact duplicate rows
- Second normal form (2NF)
- Meet the requirements of 1NF
- Remove partial dependencies - narrow tables to single purpose
- Third normal form (3NF)
- Meet the requirements of 2NF
- No attributes depend on other non-key attributes
6. What is data integrity?
Data integrity refers to the consistency and accuracy of data. There are three
types of data integrity: entity integrity, referential integrity and domain
integrity. Entity integrity ensures rows in a table are identifiably unique.
Referential integrity ensures that tables can be linked together. You achieve
referential integrity by having a primary key on the parent table and a foreign
key on the child table.
7. What are the different ways you can enforce data integrity?
For entity integrity we can use unique constraints, not null constraints and primary keys.
Unique constraints ensure that values in a column or columns are different from each other.
If we create a unique constraint on one column, it forces the table to have unique values in
that specific column. If they are not unique, then the row will not be able to be inserted or
updated. This avoids duplicate data.
Not null constraints ensure that all values in a column are not null.
Primary keys are used to ensure that all values in a column are not null and unique.
Referential integrity refers to the consistency and accuracy between tables that can
be linked together. Primary key on the parent table and foreign keys on the child
table ensure referential integrity. The foreign key can maintain three types of table
relationships:
- one to one - one table has one corresponding row on another table - eg employees and computers
- one to many - one table has none, one or many corresponding rows on another table. Adults and children.
- many to many - Many rows in one table correspond to many rows in another table. customers and products.
Domain integrity refers to the defined rules for formatting, range, and value
using check and default constraints. Check constraints can check that values in a column are in a range of
values such as "Y" and "N" for instance. Default constraints ensure a default
value for a field such as "false".
8. What types of RDMS exist?
There are four main types of RDMS, Oracle, MySQL, SQL Server and PostgreSQL.
Oracle - has a lot of functionality for database administrators.
MySQL - free easy to implement - support is not free.
SQL Server - offers replication and high availabity and partitioning
PostgreSQL - high availability and partitioning - scalable and can handle
terabytes of data.
9. What is the main advantage of MySQL?
It is free, open source and easy to implement.
10. What is the main disadvantage of Oracle and SQL Server?
They are expensive.
|
import type {
CreateRequestBody,
FieldsToUpdate,
Update,
DeleteOne,
PushAsset,
} from "../types/unit";
import { time } from "../utils/constants.util";
import { Unit } from "../mongo/models";
import AppLog from "../events/AppLog";
import { NonNullCompanyDocument } from "../types/collections";
export async function create(data: CreateRequestBody) {
const result = await new Unit(data).save({
validateBeforeSave: false,
});
AppLog({ type: "Repository", text: "Unit instance inserted" });
return result;
}
export async function pushAsset({ id, asset, company }: PushAsset) {
AppLog({ type: "Repository", text: "Push asset into Unit" });
const unit = __findUnit(company, id);
if (!unit) return false;
unit.assets.push(asset);
const [single, nested] = await Promise.all([
Unit.findByIdAndUpdate(id, {
$push: { assets: asset },
last_update: time.CURRENT_TIME,
}).exec(),
company.save(),
]);
if (!single || !nested) return false;
return true;
}
export async function updateOne(data: Update) {
const { id, body, company } = data;
const fieldsToUpdate: FieldsToUpdate = {};
__sanitizeObject();
AppLog({ type: "Repository", text: "Update Unit" });
const unit = __findUnit(company, id);
if (!unit) return false;
unit.set({ ...fieldsToUpdate, last_update: time.CURRENT_TIME });
const [single, nested] = await Promise.all([
Unit.findByIdAndUpdate(id, {
...fieldsToUpdate,
last_update: time.CURRENT_TIME,
}).exec(),
company.save(),
]);
if (!single || !nested) return false;
return true;
function __sanitizeObject() {
for (const [key, value] of Object.entries(body)) {
if (!value) continue;
fieldsToUpdate[key] = value;
}
}
}
export async function deleteOne(data: DeleteOne) {
const { id, company } = data;
const unit = __findUnit(company, id);
if (!unit) return false;
unit.remove();
const [single, nested] = await Promise.all([
Unit.findByIdAndDelete(id).exec(),
company.save(),
]);
if (!single || !nested) return false;
AppLog({ type: "Repository", text: "Delete Unit instance" });
return true;
}
function __findUnit(company: NonNullCompanyDocument, id: string) {
return company.units.find((unit) => unit._id?.toString() === id);
}
|
use std::{thread, time::Duration};
use anyhow::Result;
use esp_idf_hal::{
gpio::{AnyOutputPin, PinDriver},
prelude::*,
};
use std_display::display::Display;
use network_node::serial::SerialTrait;
use std_display::serial::Serial;
fn main() -> Result<()> {
let peripheral = Peripherals::take().expect("never fails");
// display
let spi = peripheral.spi2;
let sclk = peripheral.pins.gpio8;
let dc = PinDriver::output(peripheral.pins.gpio4).expect("failed to set dc pin");
let sdo = peripheral.pins.gpio10;
let rst = PinDriver::output(peripheral.pins.gpio3).expect("failed to set rst pin");
let hertz = 30.MHz().into();
let mut display = Display::new(spi, sclk, sdo, dc, rst, hertz);
display.print("display initialized", true);
display.print("start serial test...", false);
let uart = peripheral.uart1;
let tx = peripheral.pins.gpio21;
let rx = peripheral.pins.gpio20;
let enable: AnyOutputPin = peripheral.pins.gpio5.into();
let hertz = 115200;
let mut serial = Serial::new(uart, tx, rx, enable, hertz);
loop {
match serial.send(b"hello!!!") {
Ok(_) => {
display.print(&format!("send data: 'hello!!!'({:?})", b"hello!!!"), true);
display.print(&format!("bdata: {:?}", b"hello!!!"), true);
println!("Sent: hello!!!");
println!("Data: {:?}", b"hello!!!");
}
Err(e) => {
display.print(&format!("send error: {:?}", e), true);
println!("SendError: {:?}", e);
}
}
loop {
let data = match serial.receive() {
Ok(data) => data,
Err(e) => {
display.print(&format!("receive error: {:?}", e), true);
println!("ReceiveError: {:?}", e);
break;
// None
}
};
match data {
Some(t) => {
display.print(&format!("received: {:?}", t), true);
display.print(
&format!("received: {:?}", String::from_utf8(t.to_vec())),
true,
);
println!("Received: {:?}", t);
println!("Received: {:?}", String::from_utf8(t.to_vec()));
}
None => {
display.print("no data received", true);
println!("No data received");
break;
}
}
}
thread::sleep(Duration::from_secs(1));
}
}
|
import React, { useState } from 'react';
import { Card, Image, Rating, Button } from 'semantic-ui-react';
const CardGallery2 = ({ data }) => {
const [cardsToShow, setCardsToShow] = useState(3);
const handleShowMore = () => {
setCardsToShow((prevCardsToShow) => prevCardsToShow + 3);
};
const handleShowLess = () => {
setCardsToShow(3);
};
return (
<div className='card-gallery'>
<h3 className='features'>Featured Customers</h3>
<Card.Group itemsPerRow={3} className="card-gallery">
{data.slice(0, cardsToShow).map((item, index) => (
<Card key={index} className="gallery-card">
<Image src={item.imageUrl} className="gallery-image" wrapped ui={false} />
<Card.Content>
<Card.Header>{item.name}</Card.Header>
<Card.Description>{item.description}</Card.Description>
</Card.Content>
<Card.Content extra>
<Rating icon='star' rating={item.rating} maxRating={5} disabled />
</Card.Content>
</Card>
))}
</Card.Group>
{cardsToShow < data.length ? (
<div className="show-more-button">
<Button onClick={handleShowMore}>Show More</Button>
</div>
) : (
<div className="show-more-button">
<Button onClick={handleShowLess}>Show Less</Button>
</div>
)}
</div>
);
};
export default CardGallery2;
|
"use client";
import { ResetSchema } from "@/schemas/zod/loginSchemas";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { useEffect, useState } from "react";
import { forgotPasswordAction } from "@/server_actions/form_actions";
import {
FormFieldWrapper,
SubmitBtn,
SubmitStatus,
} from "@/components/formUI/formUI";
// notification
import 'react-toastify/dist/ReactToastify.css';
import { toast, ToastContainer } from "react-toastify";
import { useRouter } from "next/navigation";
import { DEFAULT_LOGIN_REDIRECT } from "@/routes";
type ResultStatus = 'init' | 'error' | 'success';
export const ResetForm = () => {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<z.infer<typeof ResetSchema>>({
resolver: zodResolver(ResetSchema),
defaultValues: {
email: '',
},
});
// result of action
const [result, setResult] = useState<{
status: ResultStatus,
message: string;
}>({
status: 'init',
message: '',
});
const router = useRouter();
const onSubmit = async (data: z.infer<typeof ResetSchema>) => {
// reset
setResult({
status: 'init',
message: '',
});
const result = await forgotPasswordAction(data);
if (result.success) {
setResult({
status: 'success',
message: result.success,
});
}
else {
setResult({
status: 'error',
message: result.error as string,
});
}
};
// TOAST event
useEffect(() => {
if (result.status === 'success') {
toast(result.message, {
theme: 'colored',
type: 'success',
onClose: () => {
router.push(DEFAULT_LOGIN_REDIRECT);
},
});
}
else if (result.status === 'error') {
toast(result.message, {
theme: 'colored',
type: 'error',
});
}
}, [result, router]);
return (
<form onSubmit={handleSubmit(onSubmit)}>
<ToastContainer
position='top-right'
autoClose={2000}
/>
<FormFieldWrapper
labelText=""
isError={errors.email ? true : false}
errorText={errors.email?.message}
>
<input
{...register("email")}
data-invalid={errors.email ? true : false}
placeholder="ivan.ivanov@email.com"
/>
</FormFieldWrapper>
<SubmitBtn isDisabled={isSubmitting} />
{isSubmitting && (
<SubmitStatus status="pending" />
)}
{result.status === 'error' && (
<SubmitStatus
status="error"
message={result.message}
/>
)}
{result.status === 'success' && (
<SubmitStatus
status="success"
message={result.message}
/>
)}
</form>
);
};
|
import { NgModule, NO_ERRORS_SCHEMA } from '@angular/core';
import { NativeScriptModule } from 'nativescript-angular/nativescript.module';
import { AppRoutingModule } from '@src/app/app-routing.module';
import { AppComponent } from '@src/app/app.component';
import { TestComponent } from '@src/app/test/test.component';
import { BarcodeScanner } from 'nativescript-barcodescanner';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { CustomLoader } from '@src/app/core/services/translate-loader.service';
import { CoreSharedModule } from '@src/app/shared/modules/core-shared.module';
import { MainWrapperComponent } from '@src/app/core/layouts/main-wrapper/main-wrapper.component';
import { HeaderComponent } from '@src/app/core/layouts/web/header/header.component';
import { MenuComponent } from '@src/app/core/layouts/web/menu/menu.component';
import { FooterComponent } from '@src/app/core/layouts/web/footer/footer.component';
import { NotificationModule } from '@src/app/core/notification/notification.module';
// Uncomment and add to NgModule imports if you need to use two-way binding
// import { NativeScriptFormsModule } from 'nativescript-angular/forms';
// Uncomment and add to NgModule imports if you need to use the HTTP wrapper
// import { NativeScriptHttpClientModule } from 'nativescript-angular/http-client';
@NgModule( {
declarations: [
AppComponent,
TestComponent,
MainWrapperComponent,
HeaderComponent,
MenuComponent,
FooterComponent,
],
imports: [
NativeScriptModule,
AppRoutingModule,
NotificationModule,
TranslateModule.forRoot( {
loader: {
provide: TranslateLoader,
useClass: CustomLoader,
},
isolate: false
} ),
CoreSharedModule,
CoreSharedModule,
CoreSharedModule,
],
providers: [
BarcodeScanner
],
bootstrap: [ AppComponent ],
schemas: [ NO_ERRORS_SCHEMA ]
} )
export class AppModule {
}
|
from hall_of_fame_pokemon import HallOfFamePokemon
from hall_of_fame_record import HallOfFameRecord
from hall_of_fame import HallOfFame
from simulator import Simulation
import abc
from typing import Union, Dict, List
class Setup(abc.ABC):
"""
Abstract class for a setup
"""
@abc.abstractmethod
def run(self) -> None:
"""
Run the setup
"""
pass
@abc.abstractmethod
def get_offsets(self) -> dict:
"""
Get the execution offsets for the setup
"""
pass
class BackupSaveItemSetup(Setup):
def get_offsets(self, key_items: Union[Dict, int], hm_items: Union[List, None] = None) -> Dict:
"""
Get the execution offsets for the setup
"""
max_offset = 0x1102E8
for hm in ["HM07", "HM08", 7, 8]:
if hm in hm_items:
min_offset = 0x110128 + 2* 2* len(hm_items) # 2 bytes id, 2 bytes quantity
return {"min_offset": min_offset, "max_offset": max_offset}
key_item_count = key_items if isinstance(key_items, int) else len(key_items)
min_offset = 0x110060 + 2* 2* key_item_count # could be lowered by ordering the key items in the bag
return {"min_offset": min_offset, "max_offset": max_offset}
class GyaradosSetup(BackupSaveItemSetup):
"""
The current best setup, using an RNG'd Gyarados.
"""
def __init__(self):
self.name = 'RNG-based Gyarados setup'
self.version = '0.0.1'
self.author = "Jorik Devreese (RETIREglitch)"
def run(self, plot: bool = True) -> float:
# TM slot in item data of backup save file
# This is the memory section used in current ASE setups
mandatory_hm_items = ["HM01", "HM6"]
all_hms = [i for i in range(1, 9)]
execution_offsets = self.get_offsets(0, all_hms)
pokemon = HallOfFamePokemon(species="Gyarados",
level=0x16,
forme=0,
pid=0xE1656,
trainer_id=0xffff,
secret_id=0xffff,
name="h",
trainer_name="kh",
move1="Thunder",
move2=0x0,
move3=0x0,
move4=0x0
)
record = HallOfFameRecord(party=[pokemon], year=2076, month=1, day=1)
# put 30 if you want to fill the entire hall of fame, with record_start = 0
# Since only records 28-30 are used, I only fill those 3 records.
# Note that the code expects 0-indexed records, so record_start = 27
records = [record] * 3
hall_of_fame = HallOfFame(records=records, record_start=27)
simulation = Simulation(execution_offsets=execution_offsets, hall_of_fame=hall_of_fame)
success_log = simulation.simulate_full()
simulation.plot_simulations(success_log, plot)
return simulation.get_success_rate(success_log)
class KakunaSetup(BackupSaveItemSetup):
"""
The current best setup if the user does not want to perform RNG manipulation.
It requires the user to have a Kakuna, which can be traded from another game.
"""
def __init__(self, plot: bool = False):
self.name = 'Kakuna setup'
self.version = '0.0.1'
self.author = "Jorik Devreese (RETIREglitch)"
def run(self, plot: bool = True) -> float:
# TM slot in item data of backup save file
# This is the memory section used in current ASE setups
mandatory_hm_items = ["HM01", "HM6"]
all_hms = [i for i in range(1, 9)]
execution_offsets = self.get_offsets(0, all_hms)
pokemon = HallOfFamePokemon(species="Kakuna",
level=0x16,
forme=0,
pid=0x12345678,
trainer_id=0xffff,
secret_id=0xffff,
name="h",
trainer_name="kh",
move1="Bug Bite",
move2=0x0,
move3=0x0,
move4=0x0
)
record_28 = HallOfFameRecord(party=[pokemon], year=2022, month=12, day=23)
record_29 = HallOfFameRecord(party=[pokemon], year=2022, month=12, day=22)
record_30 = HallOfFameRecord(party=[pokemon])
records = [record_28, record_29, record_30]
# put 30 if you want to fill the entire hall of fame, with record_start = 0
# Since only records 28-30 are used, I only fill those 3 records.
# Note that the code expects 0-indexed records, so record_start = 27
hall_of_fame = HallOfFame(records=records, record_start=27)
simulation = Simulation(execution_offsets=execution_offsets, hall_of_fame=hall_of_fame)
success_log = simulation.simulate_full()
simulation.plot_simulations(success_log, plot)
return simulation.get_success_rate(success_log)
|
package Aula_7.Ex1;
public class Circulo extends Forma{
public double raio;
public Circulo(double r){
this.raio = r;
}
public void setCirculo(double raio){
this.raio = raio;
}
public double getRaio() {
return raio;
}
public static Boolean value(double raio){
boolean valid = false;
if(raio>0){
valid = true;
}
return valid;
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof Circulo)) {
return false;
}
Circulo c = (Circulo) o;
return Double.compare(raio, c.raio) == 0
&& cor.equalsIgnoreCase(c.cor);
}
@Override
public String toString() {
if(Boolean.TRUE.equals(value(raio)))
return String.format("Raio: %s || Cor: %s", this.raio, this.cor);
else{
return "Raio inválido!";
}
}
public double area () {
return Math.PI * Math.pow(raio, 2);
}
public double perimetro () {
return 2 * Math.PI * raio;
}
}
|
package com.stampcrush.backend.api.docs.visitor.reward;
import com.epages.restdocs.apispec.ResourceSnippetParameters;
import com.epages.restdocs.apispec.Schema;
import com.stampcrush.backend.api.docs.DocsControllerTest;
import com.stampcrush.backend.application.visitor.reward.dto.VisitorRewardsFindResultDto;
import com.stampcrush.backend.entity.reward.Reward;
import com.stampcrush.backend.fixture.RewardFixture;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders;
import java.util.List;
import java.util.Optional;
import static com.epages.restdocs.apispec.MockMvcRestDocumentationWrapper.document;
import static com.epages.restdocs.apispec.ResourceDocumentation.parameterWithName;
import static com.epages.restdocs.apispec.ResourceDocumentation.resource;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName;
import static org.springframework.restdocs.operation.preprocess.Preprocessors.*;
import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
class VisitorRewardsFindApiDocsControllerTest extends DocsControllerTest {
@Test
void 리워드_조회() throws Exception {
// given, when
when(customerRepository.findById(CUSTOMER.getId())).thenReturn(Optional.of(CUSTOMER));
when(customerRepository.findByLoginId(CUSTOMER.getLoginId())).thenReturn(Optional.of(CUSTOMER));
Reward reward = RewardFixture.REWARD_USED_FALSE;
when(visitorRewardsFindService.findRewards(CUSTOMER.getId(), false))
.thenReturn(
List.of(
VisitorRewardsFindResultDto.from(reward)
)
);
when(authTokensGenerator.isValidToken(anyString())).thenReturn(true);
when(authTokensGenerator.extractMemberId(anyString())).thenReturn(CUSTOMER.getId());
// then
mockMvc.perform(
RestDocumentationRequestBuilders.get("/api/rewards")
.param("used", "false")
.contentType(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, CUSTOMER_BEARER_HEADER))
.andDo(document("visitor/rewards/find-rewards",
preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
resource(
ResourceSnippetParameters.builder()
.tag("고객 모드")
.description("리워드 조회")
.requestHeaders(headerWithName("Authorization").description("Bearer"))
.queryParameters(parameterWithName("used").description("false(사용 가능한 리워드), true(사용한 리워드)"))
.responseFields(
fieldWithPath("rewards[].id").description("리워드 ID"),
fieldWithPath("rewards[].rewardName").description("리워드 이름"),
fieldWithPath("rewards[].cafeName").description("카페 이름"),
fieldWithPath("rewards[].createdAt").description("리워드 생성일"),
fieldWithPath("rewards[].usedAt").description("리워드 사용일")
)
.responseSchema(Schema.schema("VisitorRewardsFindResponse"))
.build()
)
)
)
.andExpect(status().isOk());
}
}
|
package bguspl.set.ex;
import bguspl.set.Env;
import bguspl.set.UserInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* This class manages the dealer's threads and data
*/
public class Dealer implements Runnable {
/**
* The game environment object.
*/
private final Env env;
/**
* Game entities.
*/
private final Table table;
private final Player[] players;
/**
* The list of card ids that are left in the dealer's deck.
*/
private final List<Integer> deck;
/**
* True iff game should be terminated.
*/
private volatile boolean terminate;
private ArrayList<Integer> tokensToRemove;
protected volatile ArrayBlockingQueue<Integer> waitingForCheck;
long lastReset;
private Integer claimerId;
/**
* The time when the dealer needs to reshuffle the deck due to turn timeout.
*/
private long reshuffleTime = Long.MAX_VALUE;
public Dealer(Env env, Table table, Player[] players) {
this.env = env;
this.table = table;
this.players = players;
this.deck = IntStream.range(0, env.config.deckSize).boxed().collect(Collectors.toList());
this.reshuffleTime = System.currentTimeMillis() + env.config.turnTimeoutMillis;
this.tokensToRemove = new ArrayList<Integer>(env.config.featureSize);
this.waitingForCheck = new ArrayBlockingQueue<>(players.length);
lastReset = System.currentTimeMillis();
}
/**
* The dealer thread starts here (main loop for the dealer thread).
*/
@Override
public void run() {
env.logger.info("thread " + Thread.currentThread().getName() + " starting.");
for (Player p : players) {
new Thread(p, "Player" + p.id).start();
}
updateTimerDisplay(true);
while (!shouldFinish()) {
placeCardsOnTable();
timerLoop();
updateTimerDisplay(true);
removeAllCardsFromTable();
}
terminate();
announceWinners();
env.logger.info("thread " + Thread.currentThread().getName() + " terminated.");
}
/**
* The inner loop of the dealer thread that runs as long as the countdown did
* not time out.
*/
private void timerLoop() {
while (!terminate && System.currentTimeMillis() < reshuffleTime) {
updateTimerDisplay(false);
sleepUntilWokenOrTimeout();
updateTimerDisplay(false);
checkSets();
}
}
/**
* Called when the game should be terminated.
*/
public void terminate() {
for (int i = players.length-1; i >= 0; i--) {
players[i].terminate();
}
terminate = true;
}
/**
* Check if the game should be terminated or the game end conditions are met.
*
* @return true iff the game should be finished.
*/
private boolean shouldFinish() {
return (terminate || (env.util.findSets(deck, 1).size() == 0));
}
/**
* Checks cards should be removed from the table and removes them.
*/
private void removeCardsFromTable() {
// if a player gets a set
synchronized (table) {
table.tableIsReady(false);
while (!tokensToRemove.isEmpty()) {
Integer slot = tokensToRemove.remove(0);
for (Player p : players) {
p.getQueue().remove(slot);
if (table.tokens[p.id][slot] == true)
p.myTokens.remove(slot);
}
table.removeCard(slot);
}
}
}
/**
* Check if any cards can be removed from the deck and placed on the table.
*/
private void placeCardsOnTable() {
synchronized (table) {
Collections.shuffle(deck);
for (int i = 0; i < table.slotToCard.length & !deck.isEmpty(); i++) {
if (table.slotToCard[i] == null) {
Integer card = deck.get(0);
deck.remove(0);
table.placeCard(card, i);
}
}
table.tableIsReady(true);
}
}
/**
* Sleep for a fixed amount of time or until the thread is awakened for some
* purpose.
*/
private void sleepUntilWokenOrTimeout() {
synchronized (this) {
try {
if (System.currentTimeMillis() / 1000 == lastReset / 1000){
claimerId = waitingForCheck.poll(Math.abs(900 - lastReset % 1000), TimeUnit.MILLISECONDS);
} else {
claimerId = waitingForCheck.poll();
}
} catch (InterruptedException e) {
System.out.println("Thread was interrupted.");
}
}
}
/**
* Reset and/or update the countdown and the countdown display.
*/
private void updateTimerDisplay(boolean reset) {
if (env.config.turnTimeoutMillis < 0)
return;
else if (env.config.turnTimeoutMillis == 0) {
long elapsedTime = System.currentTimeMillis() - lastReset;
env.ui.setElapsed(elapsedTime);
} else {
if (!reset) {
// long elapsedTime = System.currentTimeMillis() - lastReset;
boolean warn = false;
if (reshuffleTime - System.currentTimeMillis() < env.config.turnTimeoutWarningMillis) {
warn = true;
}
env.ui.setCountdown((reshuffleTime - System.currentTimeMillis()), warn);
} else {
lastReset = System.currentTimeMillis();
reshuffleTime = lastReset + env.config.turnTimeoutMillis;
env.ui.setCountdown(env.config.turnTimeoutMillis, false);
}
}
}
/**
* Returns all the cards from the table to the deck.
*/
private void removeAllCardsFromTable() {
synchronized (table) {
table.tableIsReady(false);
for (int i = 0; i < env.config.tableSize && table.slotToCard[i] != null; i++) {
deck.add(table.slotToCard[i]);
table.removeCard(i);
}
//clean the players requests and wake them
tokensToRemove.clear();
for(Integer id: waitingForCheck){
try {
players[id].awaitDealer.put(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
waitingForCheck.clear();
for (Player p : players) {
p.myTokens.clear();
p.checked = true;
p.state = 0;
}
}
}
/**
* Check who is/are the winner/s and displays them.
*/
private void announceWinners() {
int maxScore = 0;
for (int i = 0; i < players.length; i++) {
if (players[i].score() >= maxScore) {
maxScore = players[i].getScore();
}
}
int counter = 0;
for (int i = 0; i < players.length; i++) {
if (players[i].score() == maxScore) {
counter++;
}
}
int[] winners = new int[counter];
counter = 0;
for (int i = 0; i < players.length; i++) {
if (players[i].score() == maxScore) {
winners[counter] = i;
counter++;
}
}
env.ui.announceWinner(winners);
}
public void checkSets() {
synchronized (this) {
if (claimerId != null) {
Player claimer = players[claimerId];
ArrayList<Integer> firstSet = new ArrayList<Integer>(claimer.myTokens);
if(firstSet.size() < env.config.featureSize){ //check set'svalidility
claimer.state =0;
claimer.checked = true;
try{
claimer.awaitDealer.put(0);
} catch(InterruptedException ignored){}
return;
}
if (isSet(firstSet)) { //if legal set
tokensToRemove = firstSet;
removeSetsContainSameValue(firstSet);
claimer.state = 1;
removeCardsFromTable();
placeCardsOnTable();
updateTimerDisplay(true);
} else {
claimer.state = -1;
}
claimer.checked = true;
try { //notify the player
claimer.awaitDealer.put(0);
} catch (InterruptedException e) {
}
}
}
}
public void removeSetsContainSameValue(ArrayList<Integer> firstSet) {
int third = firstSet.get(0);
int second = firstSet.get(1);
int first = firstSet.get(2);
for (Integer Id : waitingForCheck) {
if (players[Id].myTokens.contains(third) ||
players[Id].myTokens.contains(second) ||
players[Id].myTokens.contains(first)) {
waitingForCheck.remove(Id);
players[Id].checked = true;
try {
players[Id].awaitDealer.put(0);
} catch (InterruptedException e) {}
;
continue;
}
}
}
public boolean isSet(ArrayList<Integer> mySet) {
synchronized (table) {
int[] cardToCheck = new int[env.config.featureSize];
boolean allGood = true;
if (table.slotToCard[mySet.get(0)] == null ||
table.slotToCard[mySet.get(1)] == null ||
table.slotToCard[mySet.get(2)] == null) {
allGood = false;
}
if (allGood) {
cardToCheck[0] = table.slotToCard[mySet.get(0)];
cardToCheck[1] = table.slotToCard[mySet.get(1)];
cardToCheck[2] = table.slotToCard[mySet.get(2)];
return env.util.testSet(cardToCheck);
}
}
return false;
}
}
|
#include <iostream>
#include <iomanip>
struct IntType {
private:
static int numIntType;
static bool getNumIntType() { return numIntType >= 1 ? true : false; }
public:
IntType() {
if (!this->getNumIntType()) { numIntType += 1; } else {
std::cerr << "The object has been made." << std::endl;
std::exit(1);
}
}
void hex() {
std::cout << std::hex;
}
void oct() {
std::cout << std::oct;
}
void dec() {
std::cout << std::dec;
}
void upperCase() {
std::cout << std::uppercase;
}
void lowerCase() {
std::cout << std::nouppercase;
}
void showbase() {
std::cout << std::showbase;
}
void showpos() {
std::cout << std::showpos;
}
void showpoints() {
std::cout << std::showpoint;
}
void precision(int precisionNum, bool fixedValue = true) {
std::cout << std::setprecision(precisionNum);
if (fixedValue == false) {
this->stop_fix();
} else {
this->fix();
}
}
void scientific() {
std::cout << std::scientific;
}
void fix() {
std::cout << std::fixed;
}
void stop_showbase() {
std::cout << std::noshowbase;
}
void stop_showpos() {
std::cout << std::noshowpos;
}
void stop_showpoints() {
std::cout << std::noshowpoint;
}
void stop_scientific() {
std::cout << std::resetiosflags(std::ios::scientific);
}
void stop_fix() {
std::cout << std::resetiosflags(std::ios::fixed);
}
void reset() {
this->showbase();
this->stop_showpos();
this->precision(8);
this->dec();
this->stop_scientific();
this->fix();
}
void CPPReset() {
this->stop_showbase();
this->stop_showpos();
this->precision(6);
this->dec();
this->stop_scientific();
this->stop_fix();
}
};
int IntType::numIntType = 0;
struct BoolType {
private:
static int numBoolType;
static bool getNumBoolType() { return numBoolType >= 1 ? true : false; }
public:
BoolType() {
if (!this->getNumBoolType()) { numBoolType += 1; } else {
std::cerr << "The object has been made." << std::endl;
std::exit(1);
}
}
void strform() {
std::cout << std::boolalpha;
}
void stop_strform() {
std::cout << std::noboolalpha;
}
void reset() {
this->strform();
}
void CPPReset() {
this->stop_strform();
}
};
int BoolType::numBoolType = 0;
struct GenType
{
private:
static int numGenType;
static bool getNumGenType() { return numGenType >= 1 ? true : false; }
public:
GenType() {
if (!this->getNumGenType()) { numGenType += 1; } else {
std::cerr << "The object has been made." << std::endl;
std::exit(1);
}
}
void fill(char fillChar) {
std::cout << std::setfill(fillChar);
}
void setw(int num) {
std::cout << std::setw(num);
}
void left() {
std::cout << std::left;
}
void reset() {
this->fill('-');
}
void CPPReset() {
this->fill(' ');
}
};
int GenType::numGenType = 0;
struct ArrayType {
private:
static int numArrayType;
static bool getNumArrayType() { return numArrayType >= 1 ? true : false; }
public:
ArrayType() {
if (!getNumArrayType()) { numArrayType += 1; } else {
std::cerr << "The object has been made." << std::endl;
std::exit(1);
}
}
void binayRefences() {};
};
int ArrayType::numArrayType = 0;
|
package tests;
import base.BaseTest;
import org.testng.Assert;
import org.testng.annotations.Test;
import pages.SideMenu;
import pages.DashBoard;
import pages.LoginPage;
import pages.PIMPage;
import testdata.CustomDataProviders;
public class PIMPageTest extends BaseTest {
SideMenu sideMenu;
PIMPage pimPage;
@Test(priority = 1, description = "Test to PIM page is displayed when module is selected from main menu.", dataProvider = "validCredentials", dataProviderClass = CustomDataProviders.class)
public void testToValidatePIMModuleIsDisplayed(String usernameValue, String passwordValue) {
LoginPage loginPage = new LoginPage(driver);
DashBoard dashBoard = loginPage.performLogin(usernameValue, passwordValue);
sideMenu = new SideMenu(driver);
pimPage = sideMenu.gotoPIMModule();
Assert.assertTrue(pimPage.isPageHeaderDisplayed());
Assert.assertEquals(pimPage.getPageHeaderString(), "PIM");
}
}
|
<div class="regContainer">
<form [formGroup]="postForm" class="register-form" (ngSubmit)="onSubmit()">
<mat-form-field class="registerFormField">
<mat-label>Username</mat-label>
<input type="" matInput formControlName="username" placeholder="">
@if (postForm.get('username')?.hasError('required')) {
<mat-error>Username is <strong>required</strong></mat-error>
}
</mat-form-field>
<mat-form-field class="registerFormField">
<mat-label>Email</mat-label>
<input type="email" matInput formControlName="email" placeholder="">
@if (postForm.get('email')?.hasError('email') && !postForm.get('email')?.hasError('required')) {
<mat-error>Please enter a valid email address</mat-error>
}
@if (postForm.get('email')?.hasError('required')) {
<mat-error>Email is <strong>required</strong></mat-error>
}
</mat-form-field>
<mat-form-field class="registerFormField">
<mat-label>Password</mat-label>
<input type="password" matInput formControlName="password" placeholder="">
@if (postForm.get('password')?.hasError('required')) {
<mat-error>Password is <strong>required</strong></mat-error>
}
</mat-form-field>
<button type="submit" mat-raised-button color="primary">Add User</button>
</form>
</div>
|
package materialDeConstrucao.model;
import javax.swing.*;
import java.util.ArrayList;
public class StockedProduct {
private static ArrayList<Product> products = new ArrayList<>();
public static void addProductToStock(int quantity, Product product) {
if (!products.contains(product)) {
// If product isn't on Stock, add it!
products.add(product);
}
product.setQuantity(quantity + product.getQuantity());
}
public static String listStockedProducts() {
String list = "Produto | Valor | Quantidade";
for (Product product : products) {
list += "\n" + product.getDescription() + " | " + String.format("%.2f", product.getPrice()) + " | "
+ product.getQuantity();
}
return list;
}
public static void sellStockedProduct(int productIndex, int quantity) {
double value = 0;
Product productToSell = products.get(productIndex); // Get product by selected option
if (productToSell.getQuantity() - quantity < 0) {
// Can't sell! Don't have enough quantity!
JOptionPane.showMessageDialog(null, "Voce nao possui quantidade suficiente desse " +
"produto para vender!");
return; // End method
} else if (productToSell.getQuantity() - quantity == 0) {
// Set the product's quantity to zero and remove from Stock
productToSell.setQuantity(0);
products.remove(productIndex);
} else {
// Decrease product's quantity by selling
productToSell.setQuantity(productToSell.getQuantity() - quantity);
}
value = productToSell.getPrice() * quantity;
// Create new tax coupon
TaxCouponList.createTaxCoupon(productToSell.getDescription(), productToSell.getPrice(), value, quantity);
}
public static boolean verifyStockedProductsIsEmpty() {
return products.isEmpty();
}
public static String[] createMenuStockedProducts(){
String[] menuOptions = new String[products.size()];
for (Product product : products) {
// For each product from registered product, add to menu options
menuOptions[products.indexOf(product)] = product.getDescription() + " | " + String.format("%.2f",product.getPrice()) + " | " +
product.getQuantity();
}
return menuOptions;
}
}
|
created: 20190604222345968
modified: 20210314143959205
revision: 0
tags: Stochastik
title: Charakteristische Funktion
type: text/vnd.tiddlywiki
Sei $$X$$ eine reellwertige [[Zufallsvariable]]. Dann heißt die Funktion $$\Bbb R\to \Bbb C$$
$$
\chi_X(t)\coloneqq
\Bbb E{\left[ e^{itX} \right]}
=\Bbb E[\cos(tX)]+i\Bbb E[\sin(tX)]
$$
//charakteristische Funktion// oder [[Fourier-Transformation]] der Zufallsvariablen $$X.$$
* <div>Ist $$X$$ diskret verteilt mit Werten $$x_n,$$ so ist
$$
\chi_X(t)=\sum_n \Bbb P(X=x_n)e^{itx_n}.
$$
</div>
* <div>Ist $$X$$ stetig verteilt mit [[Dichte]] $$f,$$ so ist
$$
\chi_X(t)=\int_\R e^{itx} f(x)\,\mathrm dx.
$$</div>
* <div>Ist $$\Bbb X=(X_1,\dots,X_n)$$ ein [[Zufallsvektor|Zufallsvariable]], so definieren wir seine charakteristische Funktion als
$$
\chi_\Bbb X(\lambda)\coloneqq
\Bbb E\left[ e^{i\langle \lambda,\Bbb X\rangle} \right],
\quad\lambda\in\R^n.
$$</div>
* Die ([[gemeinsame|Gemeinsame Verteilung]]) [[Verteilung]] von $$X$$ ist durch ihre charakteristische Funktion eindeutig bestimmt.
* <div>Besitzt $$X$$ endliches $$n$$-tes Moment, d.h. $$\Bbb E(|X|^n)<\infty,$$ so folgt
$$
\Bbb E(X^n)=i^{-n}\chi_X{}^{(n)}(0).
$$</div>
* <div>Seien $$X_1,\dots,X_n$$ unabhängige Zufallsvariablen. Dann gilt für $$S_n\coloneqq X_1+\dots+X_n$$
$$
\chi_{S_n}(t)=\chi_{X_1}(t)\cdots\chi_{X_n}(t).
$$</div>
* Es gilt folgender Konvergenzsatz (Stetigkeitssatz von Lévy): Seien $$X,X_1,X_2,\dots$$ Zufallsvariablen. Dann sind Äquivalent:
** $$\lim_{n\to\infty} F_{X_n}(x)=F_X(x)$$ für alle Stetigkeitspunkte von $$F.$$
** $$\lim_{n\to\infty} \chi_{X_n}(t)=\chi_X(t)$$ für alle $$t\in\R.$$
|
<div class="container">
<header class="my-3">
<h1 class="text-center my-4"> {{title}} </h1>
<h6 class="text-center"><i>V- 2.1.0</i></h6>
</header>
<div class="row">
<div class="col-12 col-md-6 mx-auto">
<div class="d-none">
<div *ngIf="isUpdating" class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar"
aria-label="Animated striped example" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"
style="width: 100%">
</div>
</div>
</div>
</div>
</div>
<div class="row row-cols-2 mx-auto">
<div class="col-6 d-flex justify-content-end">
<select [(ngModel)]="fromSymbol" [disabled]="isUpdatingFrom ? true : false" name="countryFrom" id="select-country"
(change)="checkSelect($event)">
<option *ngFor="let rate of fromRates" [value]="rate[0]"> {{rate[0]}} - {{ rate[1] }}</option>
</select>
</div>
<div class="col-6">
<i class="fa fa-long-arrow-down fs-4" aria-hidden="true"></i>
<input [disabled]="isUpdatingFrom ? true : false" type="text" name="currencyFrom" id="FromAmount"
[(ngModel)]="fromValue">
<div class="ms-3 position-absolute">
<i *ngIf="incorrectFrom"class="text-danger danger fw-semibold">Cannot convert Alphabet</i>
</div>
</div>
<div class="col-6 d-flex justify-content-end">
<select class="mt-3" [(ngModel)]="toSymbol" [disabled]="isUpdatingTo ? true : false" name="countryTo" id="select-country"
(change)="checkSelect($event)">
<option *ngFor="let rate of toRates" [value]="rate[0]"> {{rate[0]}} - {{ rate[1] }}</option>
</select>
</div>
<div class="col-6 mt-4">
<i class="fa fa-long-arrow-up fs-4" aria-hidden="true"></i>
<input [disabled]="isUpdatingTo ? true : false" type="text" name="currencyTo" id="ToAmount" [(ngModel)]="toValue">
<div class="ms-3 position-absolute">
<i *ngIf="incorrectTo" class="text-danger danger fw-semibold">Cannot convert Alphabet</i>
</div>
</div>
</div>
<div class="col-6">
<div *ngIf="isExchangeRateUpdated" class="position-absolute update slideOutUp animated">
<p class="bg-success text-white d-inline p-2">Exchange Rates Updated</p>
</div>
</div>
<div *ngIf="isExchangeRateUpdateFailed" class="position-absolute updateFailed">
<p class="bg-danger text-white p-2">{{errorDetails}}</p>
</div>
</div>
|
from drf_yasg.utils import swagger_auto_schema
from rest_framework.response import Response
from ..models.season_workflows import SeasonWorkflows
from ..serializers.season_workflows import SeasonWorkflowsSerializer
from .base import BaseDetailView, BaseListView
class SeasonWorkflowsDetail(BaseDetailView):
"""
Season Worfkflows Detail view.
get:
Retrieve a specific workflow by id.
patch:
Update a specific workflow by id.
delete:
Delete a specific workflow by id.
"""
model = SeasonWorkflows
serializer_class = SeasonWorkflowsSerializer
@swagger_auto_schema(request_body=SeasonWorkflowsSerializer)
def patch(self, request, pk: str) -> Response:
return super().patch(request, pk)
class SeasonWorkflowList(BaseListView):
"""
Season Workflows Detail view.
get:
Retrieve all workflows.
post:
Create a new Workflow.
"""
model = SeasonWorkflows
serializer_class = SeasonWorkflowsSerializer
@swagger_auto_schema(request_body=SeasonWorkflowsSerializer)
def post(self, request) -> Response:
return super().post(request)
|
<?php
/*
$Id$
CE Phoenix, E-Commerce made Easy
https://phoenixcart.org
Copyright (c) 2021 Phoenix Cart
Released under the GNU General Public License
*/
abstract class abstract_module {
const CONFIG_KEY_BASE = self::CONFIG_KEY_BASE;
public $code;
public $title;
public $description;
public $enabled = false;
protected $_check;
protected $config_key_base;
protected $status_key;
public $sort_order;
protected static function get_constant($constant_name) {
return defined($constant_name) ? constant($constant_name) : null;
}
public function base_constant($suffix) {
return $this->get_constant($this->config_key_base . "$suffix");
}
public function name_status_key() {
return $this->config_key_base . 'STATUS';
}
public function __construct() {
if (is_null($this->config_key_base)) {
$this->config_key_base = static::CONFIG_KEY_BASE;
}
$this->code = get_class($this);
$this->title = self::get_constant(static::CONFIG_KEY_BASE . 'TEXT_TITLE')
?? self::get_constant(static::CONFIG_KEY_BASE . 'TITLE');
$this->description = self::get_constant(static::CONFIG_KEY_BASE . 'TEXT_DESCRIPTION')
?? self::get_constant(static::CONFIG_KEY_BASE . 'DESCRIPTION');
$this->status_key = $this->name_status_key();
if (defined($this->status_key)) {
$this->enabled = ('True' === constant($this->status_key));
}
$this->sort_order = $this->base_constant('SORT_ORDER') ?? 0;
}
public function isEnabled() {
return $this->enabled;
}
public function check() {
if (!isset($this->_check)) {
$check_query = $GLOBALS['db']->query("SELECT configuration_value FROM configuration WHERE configuration_key = '" . $this->status_key . "'");
$this->_check = mysqli_num_rows($check_query);
}
return $this->_check;
}
protected function _install($parameters) {
$sort_order = 1;
foreach ($parameters as $key => $data) {
$sql_data = [
'configuration_title' => $data['title'],
'configuration_key' => $key,
'configuration_value' => ($data['value'] ?? ''),
'configuration_description' => $data['desc'],
'configuration_group_id' => 6,
'sort_order' => (int)$sort_order,
'date_added' => 'NOW()',
];
if (isset($data['set_func'])) {
$sql_data['set_function'] = $data['set_func'];
}
if (isset($data['use_func'])) {
$sql_data['use_function'] = $data['use_func'];
}
$GLOBALS['db']->perform('configuration', $sql_data);
$sort_order++;
}
}
public function install($parameter_key = null) {
$parameters = $this->get_parameters();
if (isset($parameter_key)) {
$parameters = isset($parameters[$parameter_key])
? [$parameter_key => $parameters[$parameter_key]]
: [];
}
self::_install($parameters);
}
public function remove() {
$GLOBALS['db']->query("DELETE FROM configuration WHERE configuration_key IN ('" . implode("', '", $this->keys()) . "')");
}
public function keys() {
$parameters = $this->get_parameters();
if ($this->check()) {
$missing_parameters = array_filter($parameters, function ($k) { return !defined($k); }, ARRAY_FILTER_USE_KEY);
if ($missing_parameters) {
self::_install($missing_parameters);
}
}
return array_keys($parameters);
}
abstract protected function get_parameters();
public static function list_exploded($value) {
return nl2br(implode("\n", explode(';', $value)));
}
}
|
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { ContactusComponent } from './contactus/contactus.component';
import { StudentmarksComponent } from './studentmarks/studentmarks.component';
import { StudentfeeComponent } from './studentfee/studentfee.component';
import { HttpClientModule } from '@angular/common/http';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
ContactusComponent,
StudentmarksComponent,
StudentfeeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
|
//
// ItemRow.swift
// iDine
//
// Created by Michael Barabolak on 8/11/20.
// Copyright © 2020 Michael Barabolak. All rights reserved.
//
import SwiftUI
struct ItemRow: View {
//Assigning colors to each item if it has certain restrictions D = dairy V = vegetarian N = nuts
static let colors: [String: Color] = ["D": .purple, "G": .black, "N": .red, "S": .blue, "V": .green]
var item: MenuItem
var body: some View {
//Navigation link when pressing item on menu
NavigationLink(destination: ItemDetail(item:item)){
//Horizontal stacking
HStack{
Image(item.thumbnailImage)
.clipShape(Circle()) //making image a circle
.overlay(Circle().stroke(Color.blue, lineWidth: 2)) //making a gray border of image
// verticle stack
VStack(alignment: .leading) { //aligning items
Text(item.name) //name of item
.font(.headline) //chunky font
Text("$\(item.price)")
}.layoutPriority(1) //VStack showing full names of foods on menu no ...
Spacer() //forcing restriction text away from the rest of the items in HStack
//Looking at each item and saying what the restrictions are project 4/14
ForEach(item.restrictions, id: \.self) { restriction in
Text(restriction) // showing what restrictions
.font(.caption) //changing font
.fontWeight(.black) //making font bold
.padding(5) // separating each restriction
.background(Self.colors[restriction, default: .black]) //setting background colors
.clipShape(Circle()) // shape of colors
.foregroundColor(.white) // color of font
} // ForEach
} // HStack stacking items to show
}// navigation link
} // var body: some View {
} // struct ItemRow: View {
struct ItemRow_Previews: PreviewProvider {
static var previews: some View {
ItemRow(item: MenuItem.example)
}
}
|
import React, { useState } from "react";
const SettingsContext = React.createContext();
const SettingsProvider = ({ children }) => {
let settings = JSON.parse(localStorage.getItem('settings')) || {
showComplete: true,
itemsPerPage: 3,
sort: 'difficulty'
}
const [showComplete, setShowComplete] = useState(settings.showComplete)
const [itemsPerPage, setItemsPerPage] = useState(settings.itemsPerPage)
const [sort, setSort] = useState(settings.sort)
const [defaultValues, setDefaultValues] = useState({ difficulty: 4 });
const [list, setList] = useState([]);
const [incomplete, setIncomplete] = useState([]);
const values = {
showComplete, setShowComplete,
itemsPerPage, setItemsPerPage,
sort, setSort,
defaultValues, setDefaultValues,
list, setList,
incomplete, setIncomplete
}
return (
<SettingsContext.Provider value={values}>
{children}
</SettingsContext.Provider>
)
}
export { SettingsContext, SettingsProvider }
|
import { Config, JsonDB } from 'node-json-db';
import { CartaoDeCredito } from '../../models/CartaoDeCredito';
import { StatusEnum } from '../../models/Ciclista';
import { CreditCardRepository } from '../../models/repositories/CreditCardRepository';
describe('CreditCardRepository', () => {
let creditCardRepository: CreditCardRepository;
beforeEach(() => {
const db = new JsonDB(new Config('database.test.json', true, false, '/'));
prepareDatabaseForTests(db);
creditCardRepository = new CreditCardRepository(db);
});
describe('Create', () => {
it('should create a credit card', async () => {
const creditCard = new CartaoDeCredito();
creditCard.numero = '12345678910';
creditCard.validade = new Date('2020-01-01');
creditCard.cvv = '123';
creditCard.nomeTitular = 'John Doe';
const createdCreditCard = await creditCardRepository.create(creditCard);
expect(createdCreditCard).toHaveProperty('id');
expect(createdCreditCard.numero).toBe('12345678910');
expect(createdCreditCard.cvv).toBe('123');
});
it('should get a invalid credit card error when try to create a credit card with no data', async () => {
try {
await creditCardRepository.create(null);
} catch (e) {
expect(e.message).toBe('Cartão de crédito inválido.');
}
});
describe('Find a credit card by id', () => {
it('should get a creditCard by id', async () => {
const creditCard = await creditCardRepository.findOne('2ab87bf4-bca5-4d00-971c-ca1ad4009401');
expect(creditCard).toHaveProperty('id');
expect(creditCard.numero).toBe('12345678910');
expect(creditCard.cvv).toBe('123');
});
it('should get a not found error when try to find a creditCard with a id that does not exist', async () => {
try {
await creditCardRepository.findOne('2ab87bf4-bca5-4d00-971c-ca1ad4009400');
} catch (e) {
expect(e.message).toBe('Cartão de crédito não encontrado.');
}
});
it('should get a invalid uuid then try to findOne creditCard with a id that is not valid', async () => {
try {
await creditCardRepository.findOne('123');
} catch (e) {
expect(e.message).toBe('uuid inválido.');
}
});
});
});
it('should get a not implemented then try to findAll creditCard', async () => {
try {
await creditCardRepository.findAll();
} catch (e) {
expect(e.message).toBe('Method not implemented.');
}
});
describe('Update a credit card', () => {
it('should update a credit card', async () => {
const creditCard = new CartaoDeCredito();
creditCard.numero = '12345678911';
creditCard.validade = new Date('2020-01-01');
creditCard.cvv = '123';
creditCard.id = '2ab87bf4-bca5-4d00-971c-ca1ad4009401';
creditCard.nomeTitular = 'John Doe';
const updatedCreditCard = await creditCardRepository.update('2ab87bf4-bca5-4d00-971c-ca1ad4009401', creditCard);
expect(updatedCreditCard).toHaveProperty('id');
expect(updatedCreditCard.numero).toBe('12345678911');
expect(updatedCreditCard.cvv).toBe('123');
});
it('should get a id invalid error when try to update a credit card with invalid id', async () => {
try {
const creditCard = new CartaoDeCredito();
creditCard.numero = '12345678911';
creditCard.validade = new Date('2020-01-01');
creditCard.cvv = '123';
creditCard.nomeTitular = 'John Doe';
await creditCardRepository.update('12345', creditCard);
} catch (e) {
expect(e.message).toBe('Id não é válido');
}
});
it('should get a not found error when try to update a credit card with a id that does not exist', async () => {
try {
const creditCard = new CartaoDeCredito();
creditCard.numero = '12345678911';
creditCard.validade = new Date('2020-01-01');
creditCard.cvv = '123';
creditCard.nomeTitular = 'John Doe';
await creditCardRepository.update('2ab87bf4-bca5-4d00-971c-ca1ad4009400', creditCard);
} catch (e) {
expect(e.message).toBe('Cartão de crédito não encontrado.');
}
});
});
it('should get a not implemented then try to delete creditCard', async () => {
try {
await creditCardRepository.delete('123');
} catch (e) {
expect(e.message).toBe('Method not implemented.');
}
});
});
function prepareDatabaseForTests(db: JsonDB) {
db.delete('/ciclistas');
db.delete('/cartoesDeCredito');
db.push('/ciclistas', [
{
nome: 'John Doe',
nascimento: '1990-01-01',
cpf: '12345678910',
email: 'johndoe@email.com',
passaporte: {
numero: '12345678910',
validade: '2020-01-01',
pais: 'Brazil',
},
status: StatusEnum.AguardandoConfirmacao,
id: 'ca67326d-8d9d-41b8-91ad-fcba610ddd3b',
id_cartao_de: '2ab87bf4-bca5-4d00-971c-ca1ad4009401'
},
{
nome: 'John Doe 2',
nascimento: '1990-01-01',
cpf: '12345678911',
email: 'johndoe2@email.com',
passaporte: {
numero: '12345678911',
validade: '2020-01-01',
pais: 'Brazil',
},
status: StatusEnum.Ativo,
id: 'd11dec00-ae9d-4e71-821f-a0d7ad3a8a7a'
}
], true);
db.push('/cartoesDeCredito', [
{
numero: '12345678910',
validade: '2020-01-01',
cvv: '123',
nomeTitular: 'John Doe',
id: '2ab87bf4-bca5-4d00-971c-ca1ad4009401'
}
], true);
}
|
import { AppProps } from "next/app";
import Head from "next/head";
import { MantineProvider } from "@mantine/core";
import { NextPage } from "next";
import { ReactElement, ReactNode } from "react";
import "../lib/firebase";
import "../styles/globals.scss";
import { NotificationsProvider } from "@mantine/notifications";
export type NextPageWithLayout<P = {}, IP = P> = NextPage<P, IP> & {
getLayout?: (page: ReactElement) => ReactNode;
};
type AppPropsWithLayout = AppProps & {
Component: NextPageWithLayout;
};
export default function App(props: AppPropsWithLayout) {
const { Component, pageProps } = props;
const getLayout = Component.getLayout ?? ((page) => page);
return getLayout(
<>
<MantineProvider
withCSSVariables
theme={{
/** Put your mantine theme override here */
colorScheme: "light",
}}
>
<NotificationsProvider position="top-right">
<Component {...pageProps} />
</NotificationsProvider>
</MantineProvider>
</>
);
}
|
<?php
/**
* The template for displaying Archive pages.
*
* Used to display archive-type pages if nothing more specific matches a query.
* For example, puts together date-based pages if no date.php file exists.
*
* If you'd like to further customize these archive views, you may create a
* new template file for each specific one.
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @since 1.0.0
*/
get_header(); ?>
<?php if ( have_posts() ) : ?>
<div class="container title-container">
<div class="row">
<div class="col-sm-12">
<h1 class="page-title">
<?php if ( is_category() ) : ?>
<?php echo single_cat_title( '', false ); ?>
<?php elseif ( is_author() ) : ?>
<?php printf( __( 'Author Archive for %s', 'matheson' ), get_the_author_meta( 'display_name', get_query_var( 'author' ) ) ); ?>
<?php elseif ( is_tag() ) : ?>
<?php printf( __( 'Tag Archive for %s', 'matheson' ), single_tag_title( '', false ) ); ?>
<?php elseif ( is_day() ) : ?>
<?php printf( __( 'Daily Archives: %s', 'matheson' ), get_the_date() ); ?>
<?php elseif ( is_month() ) : ?>
<?php printf( __( 'Monthly Archives: %s', 'matheson' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'matheson' ) ) ); ?>
<?php elseif ( is_year() ) : ?>
<?php printf( __( 'Yearly Archives: %s', 'matheson' ), get_the_date( _x( 'Y', 'yearly archives date format', 'matheson' ) ) ); ?>
<?php else : ?>
<?php _e( 'Blog Archive', 'matheson' ); ?>
<?php endif; ?>
</h1><!-- .page-title -->
<?php
$description = term_description();
if ( is_author() )
$description = get_the_author_meta( 'description' );
if ( $description )
printf( '<h2 class="archive-meta">%s</h2>', $description );
?>
</div>
</div>
</div>
</header><!-- #archive-header -->
<?php endif; ?>
<main id="content">
<?php if(is_category('projects')){ ?>
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="widget widget-menu">
<h3 class="widget-title">Active</h3>
<?php get_template_part( 'content', 'active' ); ?>
</div>
</div>
<div class="col-md-4">
<div class="widget widget-menu">
<h3 class="widget-title">Completed</h3>
<?php get_template_part( 'content', 'archived' ); ?>
</div>
</div>
<div class="col-md-4">
<?php get_sidebar(); ?>
</div>
</div>
</div>
<?php } ?>
<?php get_footer(); ?>
|
package ru.g0rd1.peoplesfinder.ui.groups.users
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import dagger.hilt.android.lifecycle.HiltViewModel
import ru.g0rd1.peoplesfinder.base.BaseViewModel
import ru.g0rd1.peoplesfinder.base.error.Error
import ru.g0rd1.peoplesfinder.common.ResourceManager
import ru.g0rd1.peoplesfinder.control.groupmembersloader.GroupMembersLoaderManager
import ru.g0rd1.peoplesfinder.repo.group.local.LocalGroupsRepo
import ru.g0rd1.peoplesfinder.ui.groups.GroupViewData
import ru.g0rd1.peoplesfinder.util.observeOnUI
import javax.inject.Inject
@HiltViewModel
class UsersGroupsViewModel @Inject constructor(
private val groupMembersLoaderManager: GroupMembersLoaderManager,
private val localGroupsRepo: LocalGroupsRepo,
private val errorHandler: Error.Handler,
private val resourceManager: ResourceManager,
) : BaseViewModel() {
val showContent = ObservableBoolean(false)
val showLoader = ObservableBoolean(false)
val groupViewModels: ObservableField<List<GroupViewData>> = ObservableField()
override fun onStart() {
observe()
}
private fun observe() {
observeGroups()
}
private fun observeGroups() {
showLoader.set(true)
showContent.set(false)
localGroupsRepo.observeUserGroups()
.observeOnUI()
.subscribe(
{ groups ->
showContent.set(true)
groupViewModels.set(
groups.sortedBy { it.membersCount }.map { group ->
GroupViewData(
id = group.id,
name = group.name,
photo = group.photo,
membersCount = group.membersCount,
loadedMembersCount = group.loadedMembersCount,
hasAccessToMembers = group.hasAccessToMembers
)
}
)
showLoader.set(false)
showContent.set(true)
},
{
showLoader.set(false)
showContent.set(false)
errorHandler.handle(it, ::observeGroups)
}
).disposeLater()
}
}
|
<nav x-data="{ open: false }" class="bg-white border-b border-gray-100">
<!-- Primary Navigation Menu -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex items-center">
<!-- Logo -->
<div class="shrink-0 flex items-center">
<a href="{{ route('admin.home.create') }}">
<x-ui.logo class="block h-9 w-auto fill-current text-gray-800" />
</a>
</div>
<!-- Navigation Links -->
<div class="hidden space-x-3 sm:-my-px sm:ms-10 sm:flex sm:h-fit">
<x-ui.nav-link :href="route('admin.home.create')" :active="request()->routeIs('admin.home.create')">
{{ __('Home') }}
</x-ui.nav-link>
<x-ui.nav-link :href="route('admin.imageList.create')" :active="request()->routeIs('admin.imageList.*')">
{{ __('Image list') }}
</x-ui.nav-link>
</div>
</div>
<!-- Settings Dropdown -->
<div class="hidden sm:flex sm:items-center sm:ms-6">
<x-ui.form action="{{ route('admin.logout') }}">
<button onclick="event.preventDefault(); this.closest('form').submit();"
class="relative w-full flex cursor-pointer hover:text-gray-700 select-none hover:bg-gray-100/70 items-center rounded-full py-2 px-4 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round" class="w-4 h-4 mr-2">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" x2="9" y1="12" y2="12"></line>
</svg>
<span>{{ __('Log Out') }}</span>
</button>
</x-ui.form>
</div>
<!-- Hamburger -->
<div class="-me-2 flex items-center sm:hidden">
<button @click="open = ! open"
class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 hover:text-gray-500 hover:bg-gray-100 focus:outline-none focus:bg-gray-100 focus:text-gray-500 transition duration-150 ease-in-out">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path :class="{ 'hidden': open, 'inline-flex': !open }" class="inline-flex"
stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 6h16M4 12h16M4 18h16" />
<path :class="{ 'hidden': !open, 'inline-flex': open }" class="hidden" stroke-linecap="round"
stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
</div>
<!-- Responsive Navigation Menu -->
<div :class="{ 'block': open, 'hidden': !open }" class="hidden sm:hidden">
<div class="pt-2 pb-3 space-y-1">
<x-ui.responsive-nav-link :href="route('admin.imageList.create')" :active="request()->routeIs('imagelist')">
{{ __('Image list') }}
</x-ui.responsive-nav-link>
</div>
<!-- Responsive Settings Options -->
<div class="pt-4 pb-1 border-t border-gray-200">
<div class="px-4">
<div class="font-medium text-base text-gray-800">{{ Auth::user()->name }}</div>
<div class="font-medium text-sm text-gray-500">{{ Auth::user()->email }}</div>
</div>
<div class="mt-3 space-y-1">
<!-- Authentication -->
<x-ui.form action="{{ route('admin.logout') }}">
<x-ui.responsive-nav-link :href="route('admin.logout')"
onclick="event.preventDefault();
this.closest('form').submit();">
{{ __('Log Out') }}
</x-ui.responsive-nav-link>
</x-ui.form>
</div>
</div>
</div>
</nav>
|
/*
* Copyright (C) 2006, 2009 by the Widelands Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef FXSET_H
#define FXSET_H
#include <vector>
#include <SDL_mixer.h>
class Sound_Handler;
/// Predefined priorities for easy reading
/// \warning DO NOT CHANGE !! The values have meaning beyond just being numbers
/// \todo These values should not have any meaning beyond just being numbers.
#define PRIO_ALWAYS_PLAY 255
#define PRIO_ALLOW_MULTIPLE 128
#define PRIO_MEDIUM 63
/** A collection of several sound effects meant for the same event.
*
* An FXset encapsulates a number of interchangeable sound effects, e.g.
* all effects that might be played when a blacksmith is happily hammering away.
* It is possible to select the effects one after another or in random order.
* The fact that an FXset really contains several different effects is hidden
* from the outside
*/
struct FXset {
friend class Sound_Handler;
FXset(uint8_t priority = PRIO_MEDIUM);
~FXset();
void add_fx(Mix_Chunk * fx, Uint8 prio = PRIO_MEDIUM);
Mix_Chunk * get_fx();
bool empty() {return fxs_.empty();}
protected:
/// The collection of sound effects
std::vector<Mix_Chunk *> fxs_;
/** When the effect was played the last time (milliseconds since SDL
* initialization). Set via SDL_GetTicks()
*/
Uint32 last_used_;
/** How important is it to play the effect even when others are running
* already?
*
* Value 0-127: probability between 0.0 and 1.0, only one instance can
* be playing at any time
*
* Value 128-254: probability between 0.0 and 1.0, many instances can
* be playing at any time
*
* Value 255: always play; unconditional
*/
uint8_t priority_;
};
#endif
|
import React, { useContext } from "react";
import { GContext } from "../cartContext/CartContext";
import CartItem from "../cartItem/CartItem";
import { Link } from "react-router-dom";
import "../cart/cart.css"
import {getFirestore, collection, addDoc} from "firebase/firestore";
import Swal from "sweetalert2";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faArrowLeftLong, faCircleCheck } from "@fortawesome/free-solid-svg-icons";
const Cart = () => {
const { itemsCarrito, removeItem, clear, total } = useContext(GContext);
const tot = total();
const buy = () =>{
Swal.fire({
icon: "info",
title: "Complete el formulario, para proceder con la compra",
html: `
<input type="text" id="swal-input1" class="swal2-input" required placeholder="Nombre">
<input type="text" id="swal-input2" class="swal2-input" required placeholder="Apellido">
<input type="email" id="swal-input3" class="swal2-input" required placeholder="Correo">
<input type="number" id="swal-input4" class="swal2-input" required placeholder="Teléfono">
<input type="password" id="swal-input5" class="swal2-input" required placeholder="Contraseña">
`,
focusConfirm: true,
confirmButtonText: "Confirmar",
preConfirm: () => {
return [
document.getElementById("swal-input1").value,
document.getElementById("swal-input2").value,
document.getElementById("swal-input3").value,
document.getElementById("swal-input4").value,
document.getElementById("swal-input5").value,
];
},
}).then((result) => {
if (result.value) {
const [nombre, apellido, correo, password, telefono] = result.value;
if (
nombre === "" ||
apellido === "" ||
correo === "" ||
password === "" ||
telefono === ""
) {
Swal.fire({
icon: "error",
title: "Error",
text: "Por favor complete todos los campos",
confirmButtonText: "Aceptar",
});
} else {
const db = getFirestore();
const orderCollection = collection(db, "orders");
const usuario = {
nombre: nombre,
apellido: apellido,
correo: correo,
contrasena: password,
telefono: telefono,
total: tot,
items: itemsCarrito,
fecha: new Date(),
};
addDoc(orderCollection, usuario).then((res) => {
Swal.fire({
icon: "success",
type: "success",
title: "Compra realizada con exito",
html: `<div>Muchas gracias por su compra <strong> ${usuario.nombre} ${usuario.apellido}.</strong></div>
<div>Su número de orden es: <strong>${res.id}</strong></div>
<div>Recibira un correo con los detalles y el seguimiento de su pedido</div>`,
confirmButtonText: "Aceptar",
preConfirm: () => {
clear();
window.location.href = "/";
},
});
});
}
}
});
}
return (
<>
{itemsCarrito.length === 0 ? (
<>
<h4 className="text-center fw-bolder mt-4">El carrito esta vacio</h4>
<div className="divVolver d-flex justify-content-center mt-4">
<Link to={"/"}>
<button className="btnVolver">Volver</button>
</Link>
</div>
</>
) : (
<>
{itemsCarrito.map((element) => (
<CartItem
item={element.item}
quantity={element.quantity}
removeItem={removeItem}
key={element.id}
/>
))}
<button className="btnVaciar m-4" onClick={() => clear()}>
Vaciar carrito
</button>
<div className=" tituloTotal d-flex m-4 ">
<h4>Total : USD ${tot.toFixed(3)}</h4>
</div>
<Link to={"/"} ><button className="btnVaciar m-4"><FontAwesomeIcon icon={faArrowLeftLong} /> Volver</button> </Link>
<div className="d-flex justify-content-end m-4"><button className="btnCheckout" onClick={buy}>Finalizar Compra <FontAwesomeIcon icon={ faCircleCheck}/></button></div>
</>
)}
</>
);
};
export default Cart;
|
import { useState, useEffect } from "react";
import Book from "./Book";
import Loader from "../Loader";
const BooksCard = () => {
const [books, setBooks] = useState([]);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
fetch("/booksData.json")
.then((res) => res.json())
.then((data) => setBooks(data));
setIsLoading(false);
}, []);
return (
<div>
<div className="mx-auto text-center my-5">
<h2 className="text-3xl font-bold">Books</h2>
</div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-x-5 justify-center items-center">
{isLoading ? (
<div className="flex justify-center items-center h-screen">
<Loader />
</div>
) : (
books.map((book) => <Book key={book.book_id} book={book} />)
)}
</div>
</div>
);
};
export default BooksCard;
|
using YAT.Attributes;
using YAT.Enums;
using YAT.Helpers;
using YAT.Interfaces;
using YAT.Scenes.Terminal;
namespace YAT.Commands
{
[Command("quickcommands", "Manages Quick Commands.", "[b]Usage[/b]: quickcommands [i]action[/i] [i]name[/i] [i]command[/i]", "qc")]
[Argument("action", "[add, remove, list]", "The action to perform.")]
[Option("-name", "string", "The name of the quick command.")]
[Option("-command", "string", "The command to execute when the quick command is called.")]
public sealed class QuickCommands : ICommand
{
public YAT Yat { get; set; }
public QuickCommands(YAT Yat) => this.Yat = Yat;
public CommandResult Execute(System.Collections.Generic.Dictionary<string, object> cArgs, params string[] args)
{
string action = (string)cArgs["action"];
string name = cArgs.TryGetValue("-name", out object nameObj) ? (string)nameObj : null;
string command = cArgs.TryGetValue("-command", out object commandObj) ? (string)commandObj : null;
if (action != "list" && string.IsNullOrEmpty(name))
{
Yat.Terminal.Print("You need to provide a command name for this action.", Terminal.PrintType.Error);
return CommandResult.Failure;
}
switch (action)
{
case "add":
return AddQuickCommand(name, command);
case "remove":
return RemoveQuickCommand(name);
default:
foreach (var qc in Yat.Terminal.Context.QuickCommands.QuickCommands.Commands)
{
Yat.Terminal.Print($"[b]{qc.Key}[/b] - {TextHelper.EscapeBBCode(qc.Value)}");
}
break;
}
return CommandResult.Success;
}
private CommandResult AddQuickCommand(string name, string command)
{
if (string.IsNullOrEmpty(command))
{
Yat.Terminal.Print("You need to provide command for this action.", Terminal.PrintType.Error);
return CommandResult.Failure;
}
bool status = Yat.Terminal.Context.QuickCommands.AddQuickCommand(name, command);
string message;
if (status) message = $"Added quick command '{name}'.";
else message = $"Failed to add quick command '{name}'.";
Yat.Terminal.Print(message, status ? Terminal.PrintType.Success : Terminal.PrintType.Error);
return status ? CommandResult.Success : CommandResult.Failure;
}
private CommandResult RemoveQuickCommand(string name)
{
bool status = Yat.Terminal.Context.QuickCommands.RemoveQuickCommand(name);
string message;
if (status) message = $"Removed quick command '{name}'.";
else message = $"Failed to remove quick command '{name}'.";
Yat.Terminal.Print(message, status ? Terminal.PrintType.Success : Terminal.PrintType.Error);
return status ? CommandResult.Success : CommandResult.Failure;
}
}
}
|
import { createGlobalState, useStorage } from '@vueuse/core'
import { dayjs } from '@codeanker/helpers'
interface DashboardState {
passangers: number
radius: number
date: Date
origin?: {
latLng: [number, number]
formattedAddress: string
}
destination?: {
latLng: [number, number]
formattedAddress: string
}
}
export const useDashboardState = createGlobalState(() => {
const defaultDashboardState: DashboardState = {
passangers: 1 as number,
radius: 10 as number,
date: dayjs().toDate() as Date,
origin: undefined,
destination: undefined,
}
const dashboard = useStorage('dasboard-storage', defaultDashboardState)
function resetState() {
dashboard.value = defaultDashboardState
}
return {
resetState,
dashboard,
}
})
|
import html from "./MatchQ.component.html";
import css from "./MatchQ.component.css";
import { QuestionBody } from "../../EzComponent_subclasses";
import { Term, Set } from "../../database";
import { QuestionComponent } from "../question/question.component";
import { BindValue } from "@gsilber/webez";
import {
BindCSSClassToBooleanSRA,
ClickSRA,
MouseEventSRA,
} from "../../decoratorsSRA";
/**
* @description A button class to help with MatchQComponent
* @class Button
* @property {boolean} done Whether this button has been correctly matched
* @property {Term} term The term this button is representing
* @readonly @property {0 | 1 | 2} index The index of the button (i.e. top, middle, bottom)
* @readonly @property {"answer" | "prompt"} type In the answer or prompt column; which to display
*/
class Button {
public done = false;
public term: Term = new Term();
/**
* @description Creates an instance of Button
* @readonly @param {0 | 1 | 2} index See class docs
* @readonly @param {"answer" | "prompt"} type See class docs
* @private @readonly @param {MatchQComponent} component The component that's displaying the button
* @memberof Button
* @constructor
*/
constructor(
public readonly index: 0 | 1 | 2,
public readonly type: "answer" | "prompt",
private readonly component: MatchQComponent,
) {}
/**
* @description Gets if this button is the one that's clicked
* @memberof Button
* @type {boolean}
*/
get clicked(): boolean {
return this === this.component.clicked;
}
/**
* @description Handle what happens when/if this button is clicked
* @memberof Button
* @returns {void}
*/
click(): void {
if (this.clicked) this.component.clicked = undefined;
else if ((this.component.clicked?.type ?? this.type) === this.type)
this.component.clicked = this;
else this.component.answer(this);
this.component.update();
}
}
/**
* @description A generator for the transforms used in `BindCSSClassToBooleanSRA()` on `MatchQComponent.answers/prompts`
* @param {"done" | "clicked"} value What to check about the button (what CSS class we're interested in)
* @param {0 | 1 | 2} index Which button to look at
* @returns {(v: Button[]): boolean}
*/
function transform(
value: "done" | "clicked",
index: 0 | 1 | 2,
): (v: Button[]) => boolean {
return (v: Button[]) => {
return v[index][value];
};
}
/**
* @description A class for handling all of the behaviour related to the MatchQ question type
* @class Button
* @extends QuestionBody
* @property {Button | undefined} clicked The current button that's clicked
*/
export class MatchQComponent extends QuestionBody {
/**
* @description The 3-tuple storing the three answer buttons
* @memberof MatchQComponent
* @type {[Button, Button, Button]}
* @private
* @summary Is bound to the actual buttons in HTML s.t. they have the correct
* character and styling
* @NOTE For the decorators to take effect, you must do the example:
* @example this.answers = [...this.answers]; // shallow copy, so the decorators update
*/
@BindValue("ans0", (v: Button[]) => v[0].term.answer)
@BindValue("ans1", (v: Button[]) => v[1].term.answer)
@BindValue("ans2", (v: Button[]) => v[2].term.answer)
@BindCSSClassToBooleanSRA("ans0", "done", transform("done", 0))
@BindCSSClassToBooleanSRA("ans1", "done", transform("done", 1))
@BindCSSClassToBooleanSRA("ans2", "done", transform("done", 2))
@BindCSSClassToBooleanSRA("ans0", "clicked", transform("clicked", 0))
@BindCSSClassToBooleanSRA("ans1", "clicked", transform("clicked", 1))
@BindCSSClassToBooleanSRA("ans2", "clicked", transform("clicked", 2))
private answers: [Button, Button, Button] = [
new Button(0, "answer", this),
new Button(1, "answer", this),
new Button(2, "answer", this),
];
/**
* @description The 3-tuple storing the three prompt buttons
* @memberof MatchQComponent
* @type {[Button, Button, Button]}
* @private
* @summary Is bound to the actual buttons in HTML s.t. they have the correct
* character and styling
* @NOTE For the decorators to take effect, you must do the example:
* @example this.prompts = [...this.prompts]; // shallow copy, so the decorators update
*/
@BindValue("pro0", (v: Button[]) => v[0].term.prompt)
@BindValue("pro1", (v: Button[]) => v[1].term.prompt)
@BindValue("pro2", (v: Button[]) => v[2].term.prompt)
@BindCSSClassToBooleanSRA("pro0", "done", transform("done", 0))
@BindCSSClassToBooleanSRA("pro1", "done", transform("done", 1))
@BindCSSClassToBooleanSRA("pro2", "done", transform("done", 2))
@BindCSSClassToBooleanSRA("pro0", "clicked", transform("clicked", 0))
@BindCSSClassToBooleanSRA("pro1", "clicked", transform("clicked", 1))
@BindCSSClassToBooleanSRA("pro2", "clicked", transform("clicked", 2))
private prompts: [Button, Button, Button] = [
new Button(0, "prompt", this),
new Button(1, "prompt", this),
new Button(2, "prompt", this),
];
public clicked: Button | undefined = undefined;
/**
* @description Creates an instance of MatchQComponent
* @param {Term} term The term we're testing the user on to start
* @param {Set} set The set the term comes from, so we can update it
* @param {Set[]} sets The sets the user is studying, so we can go to another term
* @param {QuestionComponent} parent The parent component, for additional handling
* @memberof MatchQComponent
* @constructor
*/
constructor(term: Term, set: Set, sets: Set[], parent: QuestionComponent) {
super("Matching", term, set, sets, parent, html, css);
let choices = this.getOptions();
for (let i = 0; i < choices.length; i++)
this.answers[i].term = choices[i];
/**Shuffle algorithm adapted from https://bost.ocks.org/mike/shuffle/compare.html */
let i: number = choices.length;
while (i) {
let ind = Math.floor(Math.random() * i--);
let t = choices[i];
choices[i] = choices[ind];
choices[ind] = t;
}
for (let i = 0; i < choices.length; i++)
this.prompts[i].term = choices[i];
this.update();
this.parent.prompt = " ";
}
/**
* @description Get the three (other two) terms for use in matching
* @memberof MatchQComponent
* @returns {[Term, Term, Term]}
* @throws {Error} If we somehow didn't catch that there weren't enough terms (maybe should be `EzError`?)
*/
getOptions(): [Term, Term, Term] {
let allOptions = this.term.allOptions([this.set]);
if (allOptions.length < 2)
throw new Error(
"Oops! We didn't catch that there weren't enough terms!",
);
let out: [Term, Term, Term] = [this.term, this.term, this.term];
for (let i = 1; i < 3; i++) {
let ind = Math.floor(Math.random() * allOptions.length);
out[i] = allOptions[ind];
allOptions[ind] = allOptions[allOptions.length - 1];
allOptions.pop();
}
return out;
}
/**
* @description See the examples for this.answers and this.prompts
* @memberof MatchQComponent
* @returns {void}
*/
update(): void {
this.answers = [...this.answers];
this.prompts = [...this.prompts];
}
/**
* @description Called when one of the answer buttons is pressed, calls `.click()` on that button
* @memberof MatchQComponent
* @param {MouseEventSRA} e The event created when the button is pressed, includes the id of the decorator
* @returns {void}
*/
@ClickSRA("ans0")
@ClickSRA("ans1")
@ClickSRA("ans2")
actA(e: MouseEventSRA): void {
this.answers[parseInt(e.idSRA.at(-1)!)].click();
}
/**
* @description Called when one of the prompt buttons is pressed, calls `.click()` on that button
* @memberof MatchQComponent
* @param {MouseEventSRA} e The event created when the button is pressed, includes the id of the decorator
* @returns {void}
*/
@ClickSRA("pro0")
@ClickSRA("pro1")
@ClickSRA("pro2")
actP(e: MouseEventSRA): void {
this.prompts[parseInt(e.idSRA.at(-1)!)].click();
}
/**
* @description Handles everything that needs to happen when an answer is given
* @memberof MatchQComponent
* @param {Button} expect The button that was pressed, to be checked agains this.clicked
* @returns {void}
*/
answer(expect: Button): void {
if (this.clicked?.type === expect.type || !this.clicked) return; // should never be the case
const correct = this.clicked.term === expect.term;
expect.term.update(correct, this.type, this.main);
this.clicked.term.update(correct, this.type, this.main);
if (correct) {
expect.done = true;
this.clicked.done = true;
}
this.clicked = undefined;
if (this.checkAll()) this.parent.continue();
this.update();
}
/**
* @description Checks to see if all of the buttons are done
* @memberof MatchQComponent
* @returns {boolean}
* @summary Actually checks if all buttons in either cattegory are done, though that
* should always result in all buttons being done
*/
checkAll(): boolean {
return (
this.answers.reduce(
(acc: boolean, v: Button) => acc && v.done,
true,
) ||
this.prompts.reduce(
(acc: boolean, v: Button) => acc && v.done,
true,
)
);
}
}
|
<template>
<DeviceSelector v-model="device" :devices="devices" />
<ProfileSelector
v-model="profile"
:profiles="profiles"
@on-profile-add="onProfileAdd"
/>
<ButtonList
:buttons="buttons"
@on-button-click="onDeckButtonClick"
@on-drag-start="onDragStart"
@on-drag-enter="onDragEnter"
/>
<SDPagination
v-model:active-page="page"
:pages="pages.length"
class="SDPagination"
@on-page-add="onPageAdd"
@on-dnd-page-change="onDndPageChange"
/>
<ButtonDialog
v-model:opened="buttonDialogShowed"
:button="selectedButtonConfig"
@on-update="onButtonUpdate"
/>
</template>
<style scoped>
.SDPagination {
margin-top: 40px;
}
</style>
<script>
import bg from "../assets/bg.jpg";
import ButtonList from "./ButtonList.vue";
import SDPagination from "./SDPagination.vue";
import ProfileSelector from "./ProfileSelector.vue";
import DeviceSelector from "./DeviceSelector.vue";
import ButtonDialog from "./ButtonDialog.vue";
import { wsMessages, getDummyButton } from "../utils";
export default {
name: "UnixStreamDeckWeb",
components: {
ButtonList,
SDPagination,
ProfileSelector,
DeviceSelector,
ButtonDialog,
},
data: () => ({
configs: [],
deviceID: "",
profileID: "",
page: 0,
bg,
buttonDialogShowed: false,
selectedButtonIndex: null,
draggedButton: null,
ws: null,
replaceWhileDrag: false,
allowUpdates: false,
}),
computed: {
devices() {
const devices = this.configs.map((device) => ({
value: device.serial,
text: device.serial,
}));
return devices ?? [];
},
device() {
const device = this.configs.find(
(device) => device.serial === this.deviceID
);
return device ?? { serial: "", profiles: [] };
},
profiles() {
const profiles = this.device.profiles.map((profile) => ({
value: profile.name,
text: profile.name,
}));
return profiles ?? [];
},
profile() {
const profile = this.device.profiles.find(
(profile) => profile.name === this.profileID
);
return profile ?? { name: "", pages: [] };
},
pages() {
return this.profile.pages;
},
buttons() {
const buttons = this.pages[this.page];
return buttons ?? [];
},
selectedButtonConfig() {
const selectedButtonConfig = this.buttons[this.selectedButtonIndex];
return selectedButtonConfig ?? {};
},
},
watch: {
device() {
this.profileID = this.profile.name;
},
profile() {
this.page = 0;
},
configs() {
this.saveConfig();
},
page() {
if (this.draggedButton !== null) {
// First element on new page should be replaced.
// Next elements should be moved.
this.replaceWhileDrag = true;
}
},
},
beforeMount: function () {
this.ws = new WebSocket("ws://192.168.1.100:8080");
this.ws.onopen = () => {
this.ws.send(JSON.stringify(wsMessages.getConfig));
};
this.ws.onmessage = (event) => {
const response = JSON.parse(event.data);
switch (response.type) {
case wsMessages.getConfig.type:
this.configs = JSON.parse(response.data).decks.reduce((acc, deck) => {
if (deck.serial !== "") {
if (this.deviceID === "") {
this.deviceID = deck.serial;
this.profileID = deck.profiles[0].name;
}
for (
let profileIndex = 0;
profileIndex < deck.profiles.length;
profileIndex++
) {
for (
let pagesIndex = 0;
pagesIndex < deck.profiles[profileIndex].pages.length;
pagesIndex++
) {
for (
let buttonIndex = 0;
buttonIndex <
deck.profiles[profileIndex].pages[pagesIndex].length;
buttonIndex++
) {
deck.profiles[profileIndex].pages[pagesIndex][buttonIndex] =
{
...getDummyButton(buttonIndex),
...deck.profiles[profileIndex].pages[pagesIndex][
buttonIndex
],
};
}
}
}
acc.push(deck);
return acc;
}
}, []);
setTimeout(() => (this.allowUpdates = true), 100);
break;
}
};
this.ws.onclose = function () {
console.log("closed");
// todo - show notice that connection is lost
};
this.ws.onerror = function () {
console.log("err");
// todo - show notice that connection is lost
};
},
methods: {
onPageAdd() {
this.configs[this.device][this.profile].push(
Array.from(this.buttons, () => ({}))
);
this.page = this.configs[this.device][this.profile].length - 1;
},
onProfileAdd() {
let baseProfileName = "new profile",
newProfileName = baseProfileName,
index = 0;
while (this.configs[this.device][newProfileName]) {
newProfileName = `${baseProfileName}(${index})`;
index++;
}
this.configs[this.device][newProfileName] = [
Array.from(this.buttons, () => ({})),
];
this.profile = newProfileName;
},
onDeckButtonClick(event, index) {
this.selectedButtonIndex = index;
this.buttonDialogShowed = true;
},
onDragStart(event, index, button) {
this.draggedButton = { button, page: this.page };
},
getPathInfo(config) {
for (let deviceIndex = 0; deviceIndex < config.length; deviceIndex++) {
if (this.deviceID === config[deviceIndex].serial) {
for (
let profileIndex = 0;
profileIndex < config[deviceIndex].profiles.length;
profileIndex++
) {
if (
this.profileID === config[deviceIndex].profiles[profileIndex].name
) {
for (
let pageIndex = 0;
pageIndex <
config[deviceIndex].profiles[profileIndex].pages.length;
pageIndex++
) {
if (this.page === pageIndex) {
return {
deviceIndex: deviceIndex,
profileIndex: profileIndex,
pageIndex: pageIndex,
buttons: [
...config[deviceIndex].profiles[profileIndex].pages[
pageIndex
],
],
};
}
}
}
}
}
}
return false;
},
onDragEnter(event, hoveredButtonIndex) {
if (
this.draggedButton.button.page !== this.page ||
this.draggedButton.button.buttonIndex !== hoveredButtonIndex
) {
const tmpConfigs = [...this.configs];
const pathInfo = this.getPathInfo(tmpConfigs);
if (pathInfo) {
if (this.replaceWhileDrag) {
// Page was changed
// Buttons should be replaced
this.draggedButton.button.buttonIndex = hoveredButtonIndex;
pathInfo.buttons.splice(
hoveredButtonIndex,
1,
this.draggedButton.button
);
this.replaceWhileDrag = false;
} else {
// Same page
// Buttons should be moved
pathInfo.buttons.splice(this.draggedButton.button.buttonIndex, 1);
this.draggedButton.button.buttonIndex = hoveredButtonIndex;
pathInfo.buttons.splice(
hoveredButtonIndex,
0,
this.draggedButton.button
);
}
tmpConfigs[pathInfo.deviceIndex].profiles[
pathInfo.profileIndex
].pages[pathInfo.pageIndex] = pathInfo.buttons;
this.configs = tmpConfigs;
}
}
},
saveConfig() {
if (this.allowUpdates) {
const msg = { ...wsMessages.setConfig };
const config = this.changeButton(
JSON.parse(JSON.stringify(this.configs)), // hack-clone
({ button }) => {
if (
button.type === "" &&
Object.keys(button.options).length === 0
) {
return {};
}
delete button.buttonIndex;
return button;
}
);
msg.data = JSON.stringify({
decks: config,
});
console.log("update", config);
this.ws.send(JSON.stringify(msg));
}
},
changeButton(initialConfig, changeFunction) {
const config = [...initialConfig];
for (let deckIndex = 0; deckIndex < config.length; deckIndex++) {
const deck = config[deckIndex];
for (
let profileIndex = 0;
profileIndex < deck.profiles.length;
profileIndex++
) {
const profile = deck.profiles[profileIndex];
for (
let pagesIndex = 0;
pagesIndex < profile.pages.length;
pagesIndex++
) {
const page = profile.pages[pagesIndex];
for (
let buttonIndex = 0;
buttonIndex < page.length;
buttonIndex++
) {
const button = page[buttonIndex];
config[deckIndex].profiles[profileIndex].pages[pagesIndex][
buttonIndex
] = changeFunction({
config,
button,
deckIndex,
profileIndex,
pagesIndex,
buttonIndex,
});
}
}
}
}
return config;
},
onButtonUpdate(newButtonConfig) {
const tmpConfigs = [...this.configs];
const pathInfo = this.getPathInfo(tmpConfigs);
if (pathInfo) {
pathInfo.buttons.splice(this.selectedButtonIndex, 1, newButtonConfig);
tmpConfigs[pathInfo.deviceIndex].profiles[pathInfo.profileIndex].pages[
pathInfo.pageIndex
] = pathInfo.buttons;
this.configs = tmpConfigs;
}
},
onDndPageChange(page) {
this.page = page;
},
},
};
</script>
|
/*
* Licensed to The OpenNMS Group, Inc (TOG) under one or more
* contributor license agreements. See the LICENSE.md file
* distributed with this work for additional information
* regarding copyright ownership.
*
* TOG licenses this file to You under the GNU Affero General
* Public License Version 3 (the "License") or (at your option)
* any later version. You may not use this file except in
* compliance with the License. You may obtain a copy of the
* License at:
*
* https://www.gnu.org/licenses/agpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the
* License.
*/
package org.opennms.netmgt.icmp.best;
import java.net.InetAddress;
import java.util.List;
import org.opennms.netmgt.icmp.NullPinger;
import org.opennms.netmgt.icmp.PingResponseCallback;
import org.opennms.netmgt.icmp.Pinger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BestMatchPinger implements Pinger {
private static final Logger LOG = LoggerFactory.getLogger(BestMatchPinger.class);
private Pinger m_pinger = null;
private Boolean m_allowFragmentation;
private Integer m_trafficClass;
@Override
public void ping(final InetAddress host, final long timeout, final int retries, final int packetsize, final int sequenceId, final PingResponseCallback cb) throws Exception {
initialize();
m_pinger.ping(host, timeout, retries, packetsize, sequenceId, cb);
}
@Override
public void ping(final InetAddress host, final long timeout, final int retries, final int sequenceId, final PingResponseCallback cb) throws Exception {
initialize();
m_pinger.ping(host, timeout, retries, sequenceId, cb);
}
@Override
public Number ping(final InetAddress host, final long timeout, final int retries, final int packetsize) throws Exception {
initialize();
return m_pinger.ping(host, timeout, retries, packetsize);
}
@Override
public Number ping(final InetAddress host, final long timeout, final int retries) throws Exception {
initialize();
return m_pinger.ping(host, timeout, retries);
}
@Override
public Number ping(final InetAddress host) throws Exception {
initialize();
return m_pinger.ping(host);
}
@Override
public List<Number> parallelPing(final InetAddress host, final int count, final long timeout, final long pingInterval) throws Exception {
initialize();
return m_pinger.parallelPing(host, count, timeout, pingInterval);
}
@Override
public List<Number> parallelPing(final InetAddress host, final int count, final long timeout, final long pingInterval, final int size) throws Exception {
initialize();
return m_pinger.parallelPing(host, count, timeout, pingInterval, size);
}
@Override
public void initialize4() throws Exception {
initialize();
}
@Override
public void initialize6() throws Exception {
initialize();
}
@Override
public boolean isV4Available() {
initialize();
return m_pinger.isV4Available();
}
@Override
public boolean isV6Available() {
initialize();
return m_pinger.isV6Available();
}
@Override
public void setAllowFragmentation(final boolean allow) throws Exception {
if (m_pinger != null) {
m_pinger.setAllowFragmentation(allow);
}
m_allowFragmentation = allow;
}
@Override
public void setTrafficClass(final int tc) throws Exception {
if (m_pinger != null) {
m_pinger.setTrafficClass(tc);
}
m_trafficClass = tc;
}
private void initialize() {
if (m_pinger == null) {
final Class<? extends Pinger> pinger = BestMatchPingerFactory.findPinger();
try {
m_pinger = pinger.newInstance();
} catch (final Throwable t) {
LOG.error("Failed to initialize best match pinger ({}): {} Falling back to the null pinger.", pinger, t.getMessage());
LOG.trace("Failed to initialize best match pinger ({}). Falling back to the null pinger.", pinger, t);
m_pinger = new NullPinger();
}
try {
if (m_allowFragmentation != null) {
m_pinger.setAllowFragmentation(m_allowFragmentation);
}
} catch (final Throwable t) {
LOG.debug("Failed to set 'allow fragmentation' flag on pinger {}: {}", pinger, t.getMessage());
LOG.trace("Failed to set 'allow fragmentation' flag on pinger {}.", pinger, t);
}
try {
if (m_trafficClass != null) {
m_pinger.setTrafficClass(m_trafficClass);
}
} catch (final Throwable t) {
LOG.debug("Failed to set traffic class on pinger {}", pinger, t);
}
}
}
}
|
package com.slin.core.logger
import timber.log.Timber
/**
* author: slin
* date: 2020/9/4
* description: 日志类,使用Timber打印日志
*
*/
object LoggerExt {
fun initLogger(isDebug: Boolean) {
if (isDebug) {
Timber.plant(CoreDebugTree())
} else {
Timber.plant(CrashReportTree())
}
log { "Initialize logger successful, isDebug: $isDebug" }
}
}
class CoreDebugTree : Timber.DebugTree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
val newTag = "STUDY_$tag"
super.log(priority, newTag, message, t)
}
}
inline fun log(supplier: Supplier<String>) = logd(supplier)
inline fun logd(supplier: Supplier<String>) = Timber.d(supplier())
inline fun logi(supplier: Supplier<String>) = Timber.i(supplier())
inline fun logw(supplier: Supplier<String>) = Timber.w(supplier())
inline fun loge(t: Throwable? = null, supplier: Supplier<String>) =
if (t == null) {
Timber.e(supplier())
} else {
Timber.e(t, supplier())
}
typealias Supplier<T> = () -> T
|
<!--
* Example Babbage Certificate Issuer Component
* This code can be customized as needed, pasted into destination files, or iFramed onto external html pages.
-->
<!DOCTYPE html>
<html>
<head>
<script src="BabbageSDK.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="GetCertificateButton" onclick="onGetCertificateClick()" style="visibility: hidden;">Get Certificate</button>
<h4 id="status"></h4>
<!--Setup Get Babbage dropdown menu-->
<nav role="navigation" id="GetBabbageButton" style="visibility: hidden;">
<ul>
<li><a href="#" aria-haspopup="true">Get Babbage</a>
<ul class="dropdown" aria-label="submenu">
<li><a href="https://projectbabbage.com/desktop/res/Babbage%20Desktop.dmg">Install (macOS)</a></li>
<li><a href="https://projectbabbage.com/desktop/res/Babbage%20Desktop.exe">Install (Windows)</a></li>
<li><a href="https://projectbabbage.com/desktop/res/Babbage%20Desktop.snap">Install (Linux snap)</a></li>
<li><a href="https://projectbabbage.com/desktop/res/Babbage%20Desktop.AppImage">Install (Linux AppImage)</a></li>
<li><a href="https://projectbabbage.com/docs/dev-downloads">Stageline & Devline</a></li>
</ul>
</li>
</ul>
</nav>
<script>
// Edit this config object to match the requirements of the certifier
const config = {
certificateType: 'AGfk/WrT1eBDXpz3mcw386Zww2HmqcIn3uY6x4Af1eo=',
fieldObject: {
cool: 'true'
},
certifierUrl: 'https://staging-coolcert.babbage.systems',
certifierPublicKey: '0247431387e513406817e5e8de00901f8572759012f5ed89b33857295bcc2651f8'
}
// ---- Edit the config above this line ----
const init = async () => {
try {
// Check if the user is authenticated
await window.BabbageSDK.getVersion()
document
.getElementById('GetBabbageButton')
.style.visibility = 'hidden'
document
.getElementById('GetCertificateButton')
.style.visibility = 'visible'
} catch (e) {
document
.getElementById('GetBabbageButton')
.style.visibility = 'visible'
document
.getElementById('GetCertificateButton')
.style.visibility = 'hidden'
}
}
init()
// Request a certificate
const onGetCertificateClick = async () => {
// Search for matching certificates issued to the current user
let matchingCertificates = await window.BabbageSDK.getCertificates({
certifiers: [config.certifierPublicKey],
types: {[config.certificateType]: [Object.keys(config.fieldObject)]}
})
// Check if a match was found, or if a new one should be created
if (matchingCertificates.length !== 0) {
document.getElementById('status').innerText = 'You already have a matching certificate!'
} else {
const certificate = await window.BabbageSDK.createCertificate(config)
document.getElementById('status').innerText = `Success! Certificate created for: ${certificate.subject}`
}
}
</script>
<!--Example inline style-->
<style>
#GetCertificateButton {
background-color: #222;
border-radius: 4px;
border-style: none;
box-sizing: border-box;
color: #fff;
cursor: pointer;
display: inline-block;
font-family: "monospace";
font-size: 16px;
font-weight: 700;
line-height: 1.5;
margin: 0;
max-width: none;
min-height: 44px;
min-width: 10px;
outline: none;
overflow: hidden;
padding: 9px 20px 8px;
position: relative;
text-align: center;
text-transform: none;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
/* width: 100%; */
}
#GetCertificateButton:hover,
#GetCertificateButton:focus {
opacity: .9;
}
</style>
</body>
</html>
|
import React from 'react'
import { useState, useEffect } from 'react'
const Component: React.FC = () => {
const [state, updateState] = useState(0)
useEffect(() => {
const interval = setInterval(() => {
updateState(state + 1)
}, 1000)
return () => {
clearInterval(interval)
}
})
return (
<div>
<div>count: {state}</div>
</div>
)
}
export default Component
|
import React, { useEffect, useState } from 'react'
import { ChatState } from '../../Context/chatProvider'
import { IconButton,Box,Text, Spinner, FormControl,Input, useToast } from '@chakra-ui/react';
import { ArrowBackIcon } from '@chakra-ui/icons';
import {getsender,getsenderFull} from '../../config/ChatLogics';
import ScrollableChat from './ScrollableChat';
import axios from 'axios';
import Profile from '../../Miscellaneous/Profile';
import UpdateGroupChatModal from '../../Miscellaneous/updateGroupChatModal';
axios.defaults.baseURL=process.env.REACT_APP_SERVER_DOMAIN;
export default function SingleChat({fetchagain,setfetchagain}) {
const [messages,setmessages]=useState([]);
const [loading,setloading]=useState(false);
const [newMessage,setNewMessage]=useState();
const toast=useToast();
const {user,selectedchat,setselectedchat}=ChatState();
const fetchMessages=async()=>{
if(!selectedchat) return;
try{
const config={
headers:{
"Content-Type":"application/json",
Authorization:`Bearer ${user.token}`,
},
};
setloading(true);
const {data}=await axios.get(`api/message/${selectedchat._id}`,config);
console.log(messages);
setmessages(data);
setloading(false);
}catch(error){
toast({
title:"Error Occured!",
description:'Failed to load messages!',
status:"error",
duration:5000,
isClosable:true,
position:"bottom",
});
}
}
useEffect(()=>{
fetchMessages();
},[selectedchat])
const sendMessage=async(event)=>{
if(event.key==='Enter'&& newMessage){
try{
const config={
headers:{
"Content-Type":'application/json',
Authorization:`Bearer ${user.token}`
},
};
const {data}=await axios.post(`api/message`,{
content:newMessage,
chatId:selectedchat._id,
},config);
console.log(data);
setNewMessage('');
setmessages([...messages,data]);
}catch(error){
toast({
title:"Error Occured!",
description:'Failed to send Message',
status:"error",
duration:5000,
isClosable:true,
position:"bottom",
});
}
}
}
const typehandler=(e)=>{
setNewMessage(e.target.value);
//typing indicator logic
}
return (
<>
{
selectedchat?(
<>
<Text
fontSize={{base:"28px",md:"30px"}}
pb={3}
px={2}
w="100%"
fontFamily="Work sans"
className='singlechat'
><IconButton
d={{base:"flex",md:"none"}}
icon={<ArrowBackIcon/>}
onClick={()=>setselectedchat("")}
></IconButton>
{!selectedchat.Groupchat?(
<>
{getsender(user,selectedchat.users)}
<Profile user={getsenderFull(user,selectedchat.users)}></Profile>
</>
):(
<>
{selectedchat.chatName.toUpperCase()}
<UpdateGroupChatModal fetchagain={fetchagain} setfetchagain={setfetchagain} fetchMessages={fetchMessages}/>
</>
)}
</Text>
<Box className='stylesinglechat' bg='#E8E8E8' w='100%' h='90%' borderRadius="lg" overflowY='hidden'>
{loading?(
<Spinner
size="xl"
w={20}
h={20}
className='stylespinner'
/>
):(
<div className='messages'>
<ScrollableChat messages={messages}/>
</div>
)}
<FormControl onKeyDown={sendMessage} isRequired mt={3}>
<Input
variant='filled'
bg="#E0E0E0"
placeholder='Type a message...'
onChange={typehandler}
value={newMessage}
/>
</FormControl>
</Box>
</>
):(
<Box>
</Box>
)
}
</>
)
}
|
import express from 'express';
import http from 'http';
import sequelize from './config/database';
import bodyParser from 'body-parser';
import cors from 'cors';
import UserRoute from './routes/UserRoute';
import RoleRoute from './routes/RoleRoute';
import OpenQuestionsRoute from './routes/OpenQuestionsRoute';
import ClosedQuestionRoute from './routes/ClosedQuestionRoute';
import CourseRoute from './routes/CourseRoute';
import NewsRoute from './routes/NewsRoute';
import AnaliticsRoute from './routes/AnaliticsRoute';
import SwaggerRoute from './routes/SwaggerRoute';
import path from 'path';
const app = express();
const server = http.createServer(app);
app.use('/images', express.static(path.join(__dirname, 'public/images')));
app.use(cors());
app.use(bodyParser.json());
app.use('/api', UserRoute);
app.use('/api', RoleRoute);
app.use('/api', OpenQuestionsRoute);
app.use('/api', ClosedQuestionRoute);
app.use('/api', CourseRoute);
app.use('/api', NewsRoute);
app.use('/api', AnaliticsRoute);
app.use('/api-docs', SwaggerRoute);
sequelize.sync().then(() => {
server.listen(7890, () => {
console.log("Сервер стартовал на порту 7890");
});
});
|
import { useState, useEffect } from "react";
import '../../index.css'
import newFeed from "../../assets/Home/newFeed.svg";
import newFeedPick from "../../assets/Home/newFeedPick.svg";
import reels from "../../assets/Home/Reels.svg";
import reelsPick from "../../assets/Home/reelsPick.svg";
import HeaderPick from "../../component/header/HeaderPick";
import Slick from "../../component/home/Slick";
import NewPost from "../../component/home/NewPost";
import Post from "../../component/abc/Post";
import CreatePost from "../../component/abc/CreatePost";
import privateAxios from "../../fetchConfig/privateAxios";
import Loading from "../../component/Alert/Loading";
import Success from "../../component/Alert/Success";
import { PostDto } from "../../Dto/Dto";
import PostDetail from "../../component/abc/PostDetail";
import { useAppSelector } from "../../redux/hook";
const icon = [
{ icon: newFeed, iconPick: newFeedPick, name: "Tin", tippy: "News feed" },
{ icon: reels, iconPick: reelsPick, name: "Reels", tippy: "Videos" },
];
const jwtTokent = localStorage.getItem('jwtToken')
console.log(jwtTokent);
export default function Home() {
const [pick, setPick] = useState("/src/assets/Home/newFeed.svg");
const [showCreatePost, setShowCreatePost] = useState(false);
const [successCreatePost, setSuccessCreatePost] = useState<boolean|undefined>(false);
const [dataPost, setDataPost] = useState<[]>();
const [loaddingData, setLoaddingData] = useState(true);
const postId = useAppSelector(state=>state.showDetailPost.postId)
const fetchPost = async () => {
try {
const result = await privateAxios.get("post");
setDataPost(result.data);
setLoaddingData(false)
} catch (error) {
console.log(error);
}
};
console.log(dataPost);
useEffect(() => {
const timeout = setTimeout(() => {
fetchPost();
}, 1000);
return () => clearTimeout(timeout);
}, []);
const parendOffCreatePost = () => {
if (showCreatePost) {
setShowCreatePost(false);
} else {
setShowCreatePost(true);
}
};
useEffect(()=>{
if(successCreatePost==true){
setShowCreatePost(false)
const timeout = setTimeout(()=>{
setSuccessCreatePost(false)
},4000)
return ()=>clearTimeout(timeout)
}
},[successCreatePost])
return (
<div className="min-h-screen">
{postId!==0&&<PostDetail/>}
{successCreatePost&&<div className="fixed w-1/3 -translate-x-1/2 left-1/2 top-[15%] z-50"><Success title="Tạo bài post thành công" /></div>}
{loaddingData&&<div className="fixed left-1/2 -translate-x-1/2 top-[13%] z-20"><Loading/></div>}
{showCreatePost && (
<div>
<CreatePost parendOffCreatePost={parendOffCreatePost} fetchData={fetchPost} setSuccessCreatePost={setSuccessCreatePost}/>
</div>
)}
<div className="mt-6 w-[590px] mx-auto ">
<div className="h-[292px] bg-white rounded-xl shadow-xl border border-gray-200">
<div className=" flex items-center justify-around px-3 ">
{icon.map((item, index) => (
<div
key={index}
className="h-[60px] w-full border-b border-gray-300"
>
<HeaderPick
icon={item.icon}
iconPick={item.iconPick}
pick={pick}
setPick={setPick}
name={item.name}
tippy={item.tippy}
/>
</div>
))}
</div>
<div>
<Slick />
</div>
</div>
<div className="mt-6">
<NewPost parendOffCreatePost={parendOffCreatePost} />
</div>
<div className="mt-6">
{dataPost&&dataPost?.map((item:PostDto[], index:number) =>(
<div key={index}>
{item.map((item:PostDto)=><div className="mt-6 rounded-xl overflow-hidden shadow-md" key={item.id}> <Post post={item} /></div>)}
</div>
))}
</div>
</div>
</div>
);
}
|
import openai
import os
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.getenv("OPENAI_API_KEY")
openai.api_key = API_KEY
def get_input(prompt_message, is_keyword=False):
"""
Genel giriş alma fonksiyonu.
"""
while True:
value = input(prompt_message).strip()
if not value:
print("This field cannot be left empty. Please provide a valid input.")
else:
if is_keyword:
return ', '.join([keyword.strip() for keyword in value.split(',')])
return value
def remove_repeated_sentences(text):
"""
Tekrarlanan cümleleri metinden kaldır.
"""
sentences = text.split("\n")
seen = set()
unique_sentences = [sentence for sentence in sentences if sentence not in seen and not seen.add(sentence)]
return "\n".join(unique_sentences)
def generate_product_description(details):
prompt = f"""
Product: {details['product']}
Category: {details['category']}
Keywords: {details['keywords']}
Product Features: {details['product_features']}
Free Shipping: {details['free_shipping']}
Personalizable: {details['personalizable']}
Customizable: {details['customizable']}
Return: Fast and free shipping, 30-day return warranty
Based on the details provided, craft a compelling product description:
1. Title (Short and attractive):
2. Product Promise (Why is this product unique?):
3. Problem & Solution (What problem does it solve?):
4. Description (Narrative style):
5. Benefits & Features:
- Example: Long-lasting battery
- ...
6. Why Choose Us (Highlight one main feature):
7. Usage Areas (Where or when can this product be used?):
8. CTA: (Note: Avoid using the verb "Enjoy". Use other compelling verbs like "Discover", "Experience")
9. Services (Any additional services?):
10. Shop Introduction (Tell a short story about the shop):
🔍 Ensure that:
- The title is catchy.
- Product promise is clear.
- Keywords are incorporated naturally.
"""
try:
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
temperature=0.1,
max_tokens=600
)
description = response.choices[0].text.strip()
description = remove_repeated_sentences(description)
return description
except Exception as e:
return f"An issue occurred with the OpenAI API: {str(e)}"
if __name__ == "__main__":
details = {
'product': get_input("Please enter your product: "),
'category': get_input("Please enter the category: "),
'keywords': get_input("Please enter the keywords separated by commas: ", is_keyword=True),
'product_features':input("Please enter the product features separated by commas (leave empty if none): "),
'free_shipping': get_input("Is there free shipping? (yes/no): "),
'personalizable': get_input("Is the product personalizable? (yes/no): "),
'customizable': get_input("Is the product customizable? (yes/no): "),
'return': get_input("Is the product returnable? (yes/no): ")
}
description = generate_product_description(details)
print("\nGenerated Product Description:")
print(description)
|
#!/usr/bin/env python
"""
new Koala Bot database manager
Commented using reStructuredText (reST)
"""
import random
import traceback
# Futures
# Built-in/Generic Imports
# Libs
from contextlib import contextmanager
from functools import wraps
from sqlalchemy import select, delete, and_, create_engine, VARCHAR
from sqlalchemy.orm import sessionmaker
from koala.env import DB_URL, DB_TYPE
from koala.log import logger
from koala.models import mapper_registry, KoalaExtensions, GuildExtensions
# Own modules
from .enums import DatabaseType
# Constants
# Variables
if not DB_URL or DB_TYPE == DatabaseType.SQLITE:
engine = create_engine(DB_URL, future=True)
else:
engine = create_engine(DB_URL, future=True, pool_size=10, max_overflow=20)
Session = sessionmaker(future=True)
Session.configure(bind=engine)
def assign_session(func):
@wraps(func)
def with_session(*args, **kwargs):
if not kwargs.get("session"):
with session_manager() as session:
kwargs["session"] = session
return func(*args, **kwargs)
else:
return func(*args, **kwargs)
return with_session
@contextmanager
def session_manager():
"""
Provide a transactional scope around a series of operations
"""
i = random.randint(0, 1000000)
logger.debug(f"Session Debug: CREATED {i} {traceback.format_stack()}")
session = Session()
try:
yield session
except Exception:
session.rollback()
raise
finally:
session.close()
logger.debug(f"Session Debug: CLOSED {i} {traceback.format_stack()}")
def __create_sqlite_tables():
"""
Creates all tables currently in the metadata of Base
"""
logger.debug("Creating database tables for SQLite")
tables = mapper_registry.metadata.tables.values()
for table in tables:
for column in table.columns:
existing_type = column.type
if type(existing_type) == VARCHAR:
existing_type.collation = None
column.type = existing_type
mapper_registry.metadata.create_all(engine, tables, checkfirst=True)
def insert_extension(extension_id: str, subscription_required: int, available: bool, enabled: bool):
"""
Inserts a Koala Extension into the KoalaExtensions table
:param extension_id: The unique extension ID/ name
:param subscription_required: The required subscription level to unlock this extension
:param available: Is available to be enabled by the public
(false for if a special extension is to be enabled in one server only by the devs)
:param enabled: Is currently enabled and running
(false if down for maintenance)
"""
with session_manager() as session:
extension: KoalaExtensions = session.execute(select(KoalaExtensions)
.where(KoalaExtensions.extension_id == extension_id)
).scalars().one_or_none()
if extension:
extension.subscription_required = subscription_required
extension.available = available
extension.enabled = enabled
else:
session.add(KoalaExtensions(extension_id=extension_id,
subscription_required=subscription_required,
available=available,
enabled=enabled))
session.commit()
def extension_enabled(guild_id, extension_id: str):
"""
Check if a given extension is enabled in a specific guild
:param guild_id: Discord guild ID for a given server
:param extension_id: The Koala extension ID
"""
with session_manager() as session:
result = session.execute(select(GuildExtensions.extension_id)
.where(GuildExtensions.guild_id == guild_id)
).scalars().all()
return "All" in result or extension_id in result
@assign_session
def give_guild_extension(guild_id, extension_id: str, session: Session):
"""
Give a guild the given Koala extension
:param guild_id: Discord guild ID for a given server
:param extension_id: The Koala extension ID
:param session: sqlalchemy Session
:raises NotImplementedError: extension_id doesnt exist
"""
db_extension: KoalaExtensions = session.execute(
select(KoalaExtensions)
.filter_by(extension_id=extension_id, available=1)).scalar()
if db_extension is not None:
if session.execute(
select(GuildExtensions)
.filter_by(extension_id=db_extension.extension_id, guild_id=guild_id)).one_or_none() is None:
session.add(GuildExtensions(extension_id=db_extension.extension_id, guild_id=guild_id))
session.commit()
else:
raise NotImplementedError(f"{extension_id} is not a valid extension")
@assign_session
def remove_guild_extension(guild_id, extension_id: str, session: Session):
"""
Remove a given Koala extension from a guild
:param guild_id: Discord guild ID for a given server
:param extension_id: The Koala extension ID
:param session: sqlalchemy Session
"""
session.execute(delete(GuildExtensions).filter_by(extension_id=extension_id, guild_id=guild_id))
session.commit()
@assign_session # fallback assign session
def get_enabled_guild_extensions(guild_id: int, session: Session):
"""
Gets a list of extensions IDs that are enabled in a server
:param guild_id: Discord guild ID for a given server
:param session: sqlalchemy Session
"""
sql_select_enabled = select(GuildExtensions.extension_id)\
.join(KoalaExtensions, GuildExtensions.extension_id == KoalaExtensions.extension_id)\
.where(
and_(
GuildExtensions.guild_id == guild_id,
KoalaExtensions.available == 1))
return session.execute(sql_select_enabled)\
.scalars(GuildExtensions.extension_id).all() # todo: test if works
@assign_session
def get_all_available_guild_extensions(guild_id: int, session: Session):
"""
Gets all available guild extensions for a given guild
todo: restrict with rules of subscriptions & enabled state
:param guild_id: Discord guild ID for a given server
:param session: sqlalchemy Session
"""
sql_select_all = select(KoalaExtensions.extension_id).filter_by(available=1).distinct()
return session.execute(sql_select_all)\
.scalars(KoalaExtensions.extension_id).all() # todo: test if works
# [extension.extension_id for extension in session.execute(sql_select_all).all()]
def fetch_all_tables():
"""
Fetches all table names within the database
"""
with session_manager() as session:
if DB_TYPE == DatabaseType.SQLITE:
return [table.name for table in
session.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;").all()]
else:
return [row[0] for row in session.execute("SHOW Tables;").all()]
def clear_all_tables(tables):
"""
Clears al the data from the given tables
:param tables: a list of all tables to be cleared
"""
with session_manager() as session:
for table in tables:
session.execute('DELETE FROM ' + table + ';')
session.commit()
|
class BooksController < ApplicationController
def new
raise ActiveRecord::RecordNotFound
end
def create
#データを受け取り新規登録するためのインスタンス作成
@new_book = Book.new(book_params)
# ユーザーIDの紐付け
@new_book.user_id = current_user.id
if @new_book.save
#各idのページにリダイレクト
flash[:notice] = "You have created a book successfully." #フラッシュメッセージ
redirect_to book_path(@new_book.id)
else
@books = Book.all #render用にbooksリスト表示のため(indexアクションは呼び出されない)
render :index
end
end
def index
@books = Book.all
@new_book = Book.new
end
def show
@book = Book.find(params[:id])
@new_book = Book.new
@book_comment = BookComment.new
end
def edit
@book = Book.find(params[:id])
@user = @book.user
unless @user == current_user
redirect_to books_path
end
end
def update
@book = Book.find(params[:id])
if @book.update(book_params)
flash[:notice] = "You have updated a book successfully."
redirect_to book_path(@book.id)
else
render :edit
end
end
def destroy
book = Book.find(params[:id]) # データ(レコード)を1件取得
book.destroy # データ(レコード)を削除
redirect_to books_path # 投稿一覧画面へリダイレクト
end
private
# ストロングパラメータ
def book_params
params.require(:book).permit(:title, :body)
end
end
|
/*! \mainpage Routing for sail software
* \brief small routing software written in c language
* \author Rene Rigault
* \version 0.1
* \date 2024
* \file
* \section Compilation
* gcc -c show4.c `pkg-config --cflags gtk4` -Wdeprecated-declarations
* see "ccall4 file
* \section Documentation
* \li Doc produced by doxygen
* \li see also html help file
* \li Verified with: cppcheck
* \section Description
* \li calculate best route using Isochrone method
* \li use polar boat (wind, waves) and grib files (wind, current)
* \li tws = True Wind Speed
* \li twd = True Wind Direction
* \li twa = True Wind Angle - the angle of the boat to the wind
* \li aws = Apparent Wind Speed - the apparent speed of the wind
* \li awa = Appartent Wind Angle - the apparent angle of the boat to the wind
* \li sog = Speed over Ground of the boat
* \li cog = Course over Ground of the boat
* \section Usage
* \li ./routing [-<option>] [<parameterFile>] */
#include <locale.h>
#include <math.h>
#include <stdbool.h>
#include <ctype.h>
#include <sys/time.h>
#include <time.h>
#include <gtk/gtk.h>
#include <eccodes.h>
#include <curl/curl.h>
///#include <webkit2/webkit2.h>
#include "shapefil.h"
#include "rtypes.h"
#include "rutil.h"
#include "inline.h"
#include "engine.h"
#include "option.h"
#include "gpsutil.h"
#define MAX_N_SURFACE (24*MAX_N_DAYS_WEATHER) // 16 days with timeStep 1 hour
#define MAIN_WINDOW_DEFAULT_WIDTH 1200
#define MAIN_WINDOW_DEFAULT_HEIGHT 600
#define MY_RESPONSE_OK 0 // OK identifier for confirm box
#define APPLICATION_ID "com.routing"
#define MIN_ZOOM_POI_VISIBLE 30
#define BOAT_UNICODE "⛵"
#define DESTINATION_UNICODE "🏁"
#define CAT_UNICODE "\U0001F431"
#define ORTHO_ROUTE_PARAM 20 // for drawing orthodromic route
#define MAX_TEXT_LENGTH 5 // in polar
#define POLAR_WIDTH 800
#define POLAR_HEIGHT 500
#define DISP_NB_LAT_STEP 10
#define DISP_NB_LON_STEP 10
#define QUIT_TIME_OUT 1000
#define ROUTING_TIME_OUT 1000
#define GRIB_TIME_OUT 2000
#define READ_GRIB_TIME_OUT 200
#define MIN_MOVE_FOR_SELECT 50 // minimum move to launch smtp grib request after selection
#define MIN_POINT_FOR_BEZIER 10 // minimum number of point to select bezier representation
#define K_LON_LAT (0.71) // lon deformation
#define LON_LAT_RATIO 2.8 // not that useful
#define GPS_TIME_INTERVAL 2 // seconds
#define MAX_N_ANIMATION 6 // number of values of speed display => animation.tempo
#define DASHBOARD_MIN_SPEED 1
#define DASHBOARD_MAX_SPEED 20
#define DASHBOARD_RADIUS 100
#define CAIRO_SET_SOURCE_RGB_BLACK(cr) cairo_set_source_rgb (cr,0,0,0)
#define CAIRO_SET_SOURCE_RGB_WHITE(cr) cairo_set_source_rgb (cr,1.0,1.0,1.0)
#define CAIRO_SET_SOURCE_RGB_RED(cr) cairo_set_source_rgb (cr,1.0,0,0)
#define CAIRO_SET_SOURCE_RGB_GREEN(cr) cairo_set_source_rgb (cr,0,1.0,0)
#define CAIRO_SET_SOURCE_RGB_BLUE(cr) cairo_set_source_rgb (cr,0,0,1.0)
#define CAIRO_SET_SOURCE_RGB_ORANGE(cr) cairo_set_source_rgb (cr,1.0,165.0/255,0.0)
#define CAIRO_SET_SOURCE_RGB_YELLOW(cr) cairo_set_source_rgb (cr, 1.0,1.0,0.8)
#define CAIRO_SET_SOURCE_RGB_PINK(cr) cairo_set_source_rgb (cr,1.0,0,1.0)
#define CAIRO_SET_SOURCE_RGB_DARK_GRAY(cr) cairo_set_source_rgb (cr,0.2,0.2,0.2)
#define CAIRO_SET_SOURCE_RGB_GRAY(cr) cairo_set_source_rgb (cr,0.5,0.5,0.5)
#define CAIRO_SET_SOURCE_RGB_LIGHT_GRAY(cr) cairo_set_source_rgb (cr,0.8,0.8,0.8)
#define CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr) cairo_set_source_rgb (cr,0.9,0.9,0.9)
#define CAIRO_SET_SOURCE_RGBA_SHP_MAP(cr) cairo_set_source_rgba (cr,157.0/255.0,162.0/255.0,12.0/255.0,0.5) // Polygons in yellow
#define CAIRO_SET_SOURCE_RGBA_FORBID_AREA(cr) cairo_set_source_rgba (cr,0.5,0.5,0.5,0.5) // forbid area in gray
#define CAIRO_SET_SOURCE_RGBA_SELECTION(cr) cairo_set_source_rgba (cr,1.0,0.0,0.0,0.5) // selection in semi-transparent red
#define CAIRO_SET_SOURCE_RGBA_POLAR_TWS(cr) cairo_set_source_rgba (cr,1.0,0.0,0.0,1.0) // specific tws polar red
/*! Structure storing data required to update NOAA URL */
typedef struct {
GtkSpinButton *bottomLatSpin;
GtkSpinButton *leftLonSpin;
GtkSpinButton *topLatSpin;
GtkSpinButton *rightLonSpin;
GtkSpinButton *timeStepSpin;
GtkSpinButton *timeMaxSpin;
GtkTextBuffer *urlBuffer;
int topLat;
int bottomLat;
int leftLon;
int rightLon;
int timeStep; // in hours
int timeMax; // in days
char url [MAX_SIZE_URL];
} DialogData;
DialogData noaaData;
cairo_surface_t *surface [MAX_N_SURFACE];
cairo_t *surface_cr [MAX_N_SURFACE];
char existSurface [MAX_N_SURFACE] = {false};
double vOffsetLocalUTC;
GdkRGBA colors [] = {{1.0,0,0,1}, {0,1.0,0,1}, {0,0,1.0,1},{0.5,0.5,0,1},{0,0.5,0.5,1},{0.5,0,0.5,1},{0.2,0.2,0.2,1},{0.4,0.4,0.4,1},{0.8,0,0.2,1},{0.2,0,0.8,1}}; // Colors for Polar curve
const int nColors = 10;
#define N_WIND_COLORS 6
guint8 colorPalette [N_WIND_COLORS][3] = {{0,0,255}, {0, 255, 0}, {255, 255, 0}, {255, 153, 0}, {255, 0, 0}, {139, 0, 0}};
// blue, green, yellow, orange, red, blacked red
guint8 bwPalette [N_WIND_COLORS][3] = {{250,250,250}, {200, 200, 200}, {170, 170, 170}, {130, 130, 130}, {70, 70, 70}, {10, 10, 10}};
const double tTws [] = {0.0, 15.0, 20.0, 25.0, 30.0, 40.0};
char parameterFileName [MAX_SIZE_FILE_NAME];
int selectedPol = 0; // select polar to draw. 0 = all
double selectedTws = 0; // selected TWS for polar draw
guint gribMailTimeout;
guint routingTimeout;
guint gribReadTimeout;
guint currentGribReadTimeout;
bool destPressed = true;
bool polygonStarted = false;
bool gribRequestRunning = false;
bool selecting = FALSE;
bool updatedColors = false;
int provider = SAILDOCS_GFS;
struct tm startInfo;
long theTime = 0;
int polarType = POLAR;
int segmentOrBezier = SEGMENT;
int selectedPointInLastIsochrone = 0;
int iFlow = WIND;
int typeFlow = WIND; // for openGrib.. WIND or CURRENT.
bool simulationReportExist = false;
bool gpsTrace = false; // used to trace GPS position only one time per session
char traceName [MAX_SIZE_FILE_NAME]; // global var for newTrace ()
/* struct for animation */
struct {
int tempo [MAX_N_ANIMATION];
guint timer;
int active;
} animation = {{1000, 500, 200, 100, 50, 20}, 0, NO_ANIMATION};
/*! struct for url Request */
struct {
char outputFileName [MAX_SIZE_LINE];
char url [MAX_SIZE_BUFFER];
int urlType;
} urlRequest;
/*! struct for dashboard */
struct {
GtkWidget *hourPosZone;
GtkWidget *speedometer;
GtkWidget *compass;
GtkWidget *textZone;
int timeoutId;
} widgetDashboard = {NULL, NULL, NULL, NULL, 0};
GtkApplication *app; // NEW WITH GTK4
GtkWidget *statusbar = NULL; // the status bar
GtkWidget *window = NULL; // main Window
GtkWidget *polarDrawingArea = NULL; // polar
GtkWidget *scaleLabel = NULL; // for polar scale label
GtkWidget *spinnerWindow = NULL;
GtkWidget *drawing_area = NULL; // main window
GtkWidget *spinButtonTimeMax = NULL;
GtkWidget *valSizeEval = NULL;
GtkWidget *menuWindow = NULL; // Pop up menu Right Click
GtkWidget *menuGrib = NULL; // Pop up menu Meteoconsult
GtkWidget *menuHist = NULL; // Pop up menu Hustory Routes
GtkWidget *labelInfoRoute; // label line for route info
Coordinates whereWasMouse, whereIsMouse, whereIsPopup;
/*! displayed zone */
DispZone dispZone;
/*! struct to memorize zone for mail request */
struct {
double lat1;
double lon1;
double lat2;
double lon2;
} mailRequestPar;
static void meteogram ();
static void onRunButtonClicked ();
static gboolean routingCheck (gpointer data);
static void destroySurface ();
/*! launch system command in a thread */
void *commandRun (void *data) {
FILE *fs;
char line [MAX_SIZE_LINE] = "";
strncpy (line, (char *) data, MAX_SIZE_LINE);
printf ("commandRun: %s\n", line);
if ((fs = popen (line, "r")) == NULL)
fprintf (stderr, "Error in commandRun: popen call: %s\n", line);
else
pclose (fs);
printf ("end commandRun\n");
return NULL;
}
/*! destroy the child window before exiting application */
static void onParentDestroy (GtkWidget *widget, gpointer child_window) {
if (GTK_IS_WIDGET(child_window)) {
gtk_window_destroy(GTK_WINDOW(child_window));
}
}
/*! destroy the popWindow window before exiting application */
static void onParentWindowDestroy(GtkWidget *widget, gpointer popWindow) {
if (GTK_IS_WIDGET(popWindow)) {
gtk_widget_unparent (popWindow);
}
}
/*! destroy spinner window */
static void spinnerWindowDestroy () {
if (spinnerWindow != NULL) {
gtk_window_destroy (GTK_WINDOW (spinnerWindow));
spinnerWindow = NULL;
}
}
/*! hide and terminate popover */
static void popoverFinish (GtkWidget *pop) {
if (pop != NULL) {
// gtk_widget_hide (pop);
gtk_widget_set_visible (pop, false);
gtk_widget_unparent (pop);
}
}
/*! dstroy spînner window */
static void stopSpinner () {
chooseDeparture.ret = STOPPED;
}
/*! intSpin for change */
static void intSpinUpdate (GtkSpinButton *spin_button, gpointer user_data) {
int *value = (int *) user_data;
*value = gtk_spin_button_get_value_as_int (spin_button);
}
/*! udpate title of window with right grib file name */
static void titleUpdate () {
char str [MAX_SIZE_LINE];
snprintf (str, sizeof (str), "%s %s %s", PROG_NAME, PROG_VERSION, par.gribFileName);
gtk_window_set_title(GTK_WINDOW(window), str);
}
/*! draw spinner when waiting for something */
static void spinner (const char *title, const char* str) {
spinnerWindow = gtk_application_window_new (app);
gtk_window_set_title(GTK_WINDOW(spinnerWindow), title);
gtk_window_set_default_size(GTK_WINDOW (spinnerWindow), 300, 100);
gtk_window_set_transient_for (GTK_WINDOW (spinnerWindow), GTK_WINDOW (window)); // to make sure spinner is visible above parent: window
gtk_window_set_modal(GTK_WINDOW (spinnerWindow), TRUE); // is it a good idea ?
g_signal_connect (spinnerWindow, "destroy", G_CALLBACK (stopSpinner), NULL);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), spinnerWindow);
GtkWidget *vBox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (spinnerWindow), vBox);
GtkWidget *label = gtk_label_new (str);
GtkWidget *spinner = gtk_spinner_new ();
gtk_box_append (GTK_BOX (vBox), label);
gtk_box_append (GTK_BOX (vBox), spinner);
gtk_spinner_start (GTK_SPINNER(spinner));
gtk_window_present (GTK_WINDOW (spinnerWindow));
}
/*! Confirm Box OK Cancel. Launch of callBack if OK */
static void confirmBox (const char *line, void (*callBack)()) {
GtkAlertDialog *confirmBox = gtk_alert_dialog_new ("%s", line);
const char *labels[] = { "_OK", "_Cancel", NULL};
gtk_alert_dialog_set_buttons (GTK_ALERT_DIALOG(confirmBox), labels);
gtk_alert_dialog_choose (confirmBox, GTK_WINDOW (window), NULL, callBack, NULL);
}
/*! draw info message GTK_MESSAGE_INFO, GTK_MESSAGE_WARNING ou GTK_MESSAGE_ERROR */
static void infoMessage (const char *message, GtkMessageType typeMessage) {
if (typeMessage < 0 || typeMessage > 3) return;
const char *strType [4] = {"Info", "Warning", "", "Error"};
GtkAlertDialog *alertBox = gtk_alert_dialog_new ("%s: %s", strType [typeMessage], message);
gtk_alert_dialog_show (alertBox, GTK_WINDOW (window));
}
/* destroy window when OK is clicked */
static void onOkButtonClicked (GtkWidget *widget, gpointer window) {
gtk_window_destroy(GTK_WINDOW(window));
}
/*! draw info message GTK_MESSAGE_INFO, GTK_MESSAGE_WARNING ou GTK_MESSAGE_ERROR */
static void NinfoMessage (const char *message, GtkMessageType typeMessage) {
GtkWidget *infoWindow = gtk_application_window_new (app);
gtk_widget_set_size_request(infoWindow, 100, -1);
switch (typeMessage) {
case GTK_MESSAGE_INFO:
gtk_window_set_title (GTK_WINDOW(infoWindow), "Info");
break;
case GTK_MESSAGE_WARNING:
gtk_window_set_title (GTK_WINDOW(infoWindow), "Warning");
break;
case GTK_MESSAGE_ERROR:
gtk_window_set_title (GTK_WINDOW(infoWindow), "Error");
break;
default:;
}
GtkWidget *vBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (infoWindow), vBox);
GtkWidget *label = gtk_label_new (message);
GtkWidget *button = gtk_button_new_from_icon_name ("emblem-default");
g_signal_connect (button, "clicked", G_CALLBACK (onOkButtonClicked), infoWindow);
gtk_box_append (GTK_BOX(vBox), label);
gtk_box_append (GTK_BOX(vBox), button);
gtk_window_present (GTK_WINDOW (infoWindow));
}
/*! callback for entryBox change */
static void entryBoxChange (GtkEditable *editable, gpointer user_data) {
gchar *name = (gchar *) user_data;
const gchar *text = gtk_editable_get_text (editable);
g_strlcpy (name, text, MAX_SIZE_BUFFER);
// printf ("%s\n", name);
}
/* action when Cancel is clicked */
static void onCancelButtonClicked (GtkWidget *widget, gpointer theWindow) {
gtk_window_destroy (GTK_WINDOW (theWindow));
}
/*! OK Cancel Line. Launch func if OK */
static GtkWidget *OKCancelLine (void (*func)(), gpointer theWindow) {
GtkWidget *hBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
GtkWidget *OKbutton = gtk_button_new_with_label ("OK");
GtkWidget *cancelButton = gtk_button_new_with_label ("Cancel");
gtk_box_append (GTK_BOX(hBox), OKbutton);
gtk_box_append (GTK_BOX(hBox), cancelButton);
g_signal_connect (OKbutton, "clicked", G_CALLBACK (func), theWindow);
g_signal_connect (cancelButton, "clicked", G_CALLBACK (onCancelButtonClicked), theWindow);
return hBox;
}
/*! draw entry Box and launch callback if OK */
static void entryBox (const char *title, const char *message, char *strValue, void (*callBack) ()) {
GtkWidget *entryWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (entryWindow), title);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), entryWindow);
GtkWidget *vBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (entryWindow), vBox);
GtkWidget *hBox0 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
GtkWidget *label = gtk_label_new (message);
GtkEntryBuffer *buffer = gtk_entry_buffer_new (strValue, -1);
GtkWidget *entryValue = gtk_entry_new_with_buffer (buffer);
int min_width = MAX (300, strlen (strValue) * 10);
gtk_widget_set_size_request (entryValue, min_width, -1);
gtk_box_append (GTK_BOX(hBox0), label);
gtk_box_append (GTK_BOX(hBox0), entryValue);
GtkWidget *hBox1 = OKCancelLine (callBack, entryWindow);
g_signal_connect (entryValue, "changed", G_CALLBACK (entryBoxChange), strValue);
gtk_box_append (GTK_BOX(vBox), hBox0);
gtk_box_append (GTK_BOX(vBox), hBox1);
gtk_window_present (GTK_WINDOW (entryWindow));
}
/* Dialog box for file selection */
GtkFileDialog* selectFile (const char *title, const char *dirName, char *nameFilter, char *strFilter0, char*strFilter1) {
char directory [MAX_SIZE_DIR_NAME];
GtkFileDialog* fileDialog = gtk_file_dialog_new ();
gtk_file_dialog_set_title (fileDialog, title);
// initial folder
snprintf (directory, sizeof (directory), "%s%s", par.workingDir, dirName);
GFile *gDirectory = g_file_new_for_path (directory);
gtk_file_dialog_set_initial_folder (fileDialog, gDirectory);
g_object_unref (gDirectory);
// filter
GtkFileFilter *filter = gtk_file_filter_new();
gtk_file_filter_set_name (filter, nameFilter);
gtk_file_filter_add_pattern (filter, strFilter0);
gtk_file_filter_add_pattern (filter, strFilter1);
GListStore *filter_list = g_list_store_new (GTK_TYPE_FILE_FILTER);
g_list_store_append (filter_list, filter);
gtk_file_dialog_set_filters (fileDialog, (GListModel *) filter_list);
g_object_unref (filter);
return fileDialog;
}
/*! for remote files, no buttons
static void viewer (const char *url) {
const int WEB_WIDTH = 800;
const int WEB_HEIGHT = 450;
char title [MAX_SIZE_LINE];
snprintf (title, sizeof (title), "View: %s", url);
GtkWidget *viewerWindow = gtk_application_window_new (app);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), viewerWindow);
gtk_window_set_default_size (GTK_WINDOW(viewerWindow), WEB_WIDTH, WEB_HEIGHT);
gtk_window_set_title(GTK_WINDOW(viewerWindow), title);
// g_signal_connect(G_OBJECT(viewerWindow), "destroy", G_CALLBACK(gtk_window_destroy), NULL);
GtkWidget *webView = webkit_web_view_new();
webkit_web_view_load_uri (WEBKIT_WEB_VIEW(webView), url);
gtk_window_set_child (GTK_WINDOW (viewerWindow), (GtkWidget *) webView);
gtk_window_present (GTK_WINDOW (viewerWindow));
}*/
/*! open windy
Example: https://www.windytv.com/?36.908,-93.049,8,d:picker */
static void windy (GSimpleAction *action, GVariant *parameter, gpointer *data) {
const char *URL = "https://www.windy.com";
const int zoom = 8; // CLAMP (9 - log2 (diffLat), 2, 19);
char command [MAX_SIZE_LINE * 2];
char mapUrl [MAX_SIZE_LINE];
snprintf (mapUrl, sizeof (mapUrl), "%s?%.2lf%%2C%.2lf%%2C%d%%2Cd:picker", URL, par.pOr.lat, par.pOr.lon, zoom);
snprintf (command, MAX_SIZE_LINE * 2, "%s %s", par.webkit, mapUrl);
g_thread_new ("windy", commandRun, command);
}
/*! open map using open street map or open sea map */
static void openMap (GSimpleAction *action, GVariant *parameter, gpointer *data) {
int comportement = GPOINTER_TO_INT (data);
const char* OSM_URL [] = {"https://www.openstreetmap.org/export/", "https://map.openseamap.org/"};
const double lat = (dispZone.latMin + dispZone.latMax) / 2.0;
const double lon = (dispZone.lonLeft + dispZone.lonRight) / 2.0;
const double diffLat = fabs (dispZone.latMax - dispZone.latMin);
const double zoom = CLAMP (9 - log2 (diffLat), 2.0, 19.0);
//printf ("diffLat : %.2lf zoom:%.2lf\n", diffLat, zoom);
char command [MAX_SIZE_LINE * 2];
char mapUrl [MAX_SIZE_LINE];
if (comportement == 0)
snprintf (mapUrl, sizeof (mapUrl), "%sembed.html?bbox=%.4lf%%2C%.4lf%%2C%.4lf%%2C%.4lf\\&layer=mapnik\\&marker=%.4lf%%2C%.4lf",
OSM_URL[comportement], dispZone.lonLeft, dispZone.latMin, dispZone.lonRight, dispZone.latMax,
par.pOr.lat, par.pOr.lon);
else
snprintf (mapUrl, sizeof (mapUrl), "%s?lat=%.4lf\\&lon=%.4lf\\&zoom=%.2lf", OSM_URL[comportement], lat, lon, zoom);
snprintf (command, MAX_SIZE_LINE * 2, "%s %s", par.webkit, mapUrl);
g_thread_new ("openMap", commandRun, command);
}
/*! Fonction that applies bold style */
static void applyBoldStyle (GtkTextBuffer *buffer, GtkTextIter *start, GtkTextIter *end) {
GtkTextTag *tag = gtk_text_buffer_create_tag(buffer, "bold", "weight", PANGO_WEIGHT_BOLD, NULL);
gtk_text_buffer_apply_tag(buffer, tag, start, end);
}
/*! display text with monochrome police */
static void displayText (guint width, guint height, const char *text, const char *title) {
GtkWidget *textWindow = gtk_application_window_new (app);
gtk_window_set_title(GTK_WINDOW (textWindow), title);
gtk_window_set_default_size (GTK_WINDOW(textWindow), width, height);
// g_signal_connect (G_OBJECT(textWindow), "destroy", G_CALLBACK (gtk_window_destroy), NULL);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), textWindow);
GtkWidget *scrolled_window = gtk_scrolled_window_new ();
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_window_set_child (GTK_WINDOW (textWindow), (GtkWidget *) scrolled_window);
GtkWidget *text_view = gtk_text_view_new();
gtk_text_view_set_monospace (GTK_TEXT_VIEW(text_view), TRUE);
// read only text
gtk_text_view_set_editable (GTK_TEXT_VIEW(text_view), FALSE);
gtk_text_view_set_cursor_visible (GTK_TEXT_VIEW (text_view), FALSE);
gtk_text_view_set_wrap_mode( GTK_TEXT_VIEW (text_view), GTK_WRAP_WORD_CHAR);
gtk_scrolled_window_set_child (GTK_SCROLLED_WINDOW (scrolled_window), text_view);
GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view));
gtk_text_buffer_insert_at_cursor(buffer, text, -1);
GtkTextIter start_iter, end_iter;
gtk_text_buffer_get_start_iter (buffer, &start_iter);
gtk_text_buffer_get_iter_at_line (buffer, &end_iter, 1); // Ligne suivante après la première
applyBoldStyle(buffer, &start_iter, &end_iter);
gtk_window_present (GTK_WINDOW (textWindow));
}
/*! display file with monochrome police
first line is bold according to firstBold parameter */
static void displayFile (const char *fileName, const char *title, bool firstBold) {
FILE *f;
char line [MAX_SIZE_LINE];
if ((f = fopen (fileName, "r")) == NULL) {
infoMessage ("Impossible to open file", GTK_MESSAGE_ERROR);
return;
}
GtkWidget *fileWindow = gtk_application_window_new (app);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), fileWindow);
gtk_window_set_title(GTK_WINDOW(fileWindow), title);
gtk_window_set_default_size(GTK_WINDOW(fileWindow), 750, 450);
// g_signal_connect(G_OBJECT(fileWindow), "destroy", G_CALLBACK(gtk_window_destroy), NULL);
GtkWidget *scrolled_window = gtk_scrolled_window_new ();
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_window_set_child (GTK_WINDOW (fileWindow), (GtkWidget *) scrolled_window);
GtkWidget *text_view = gtk_text_view_new();
gtk_text_view_set_monospace(GTK_TEXT_VIEW(text_view), TRUE);
gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_view), GTK_WRAP_WORD_CHAR);
gtk_text_view_set_editable(GTK_TEXT_VIEW(text_view), FALSE);
gtk_text_view_set_cursor_visible(GTK_TEXT_VIEW(text_view), FALSE);
gtk_scrolled_window_set_child (GTK_SCROLLED_WINDOW (scrolled_window), text_view);
GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view));
while (fgets (line, sizeof(line), f) != NULL) {
gtk_text_buffer_insert_at_cursor(buffer, line, -1);
}
fclose (f);
if (firstBold) {
GtkTextIter start_iter, end_iter;
gtk_text_buffer_get_start_iter(buffer, &start_iter);
gtk_text_buffer_get_iter_at_line(buffer, &end_iter, 1);
// apply bold linr to first linr
applyBoldStyle (buffer, &start_iter, &end_iter);
}
gtk_window_present (GTK_WINDOW (fileWindow));
}
/*! init of display zone */
static void initDispZone () {
double latCenter = (zone.latMin + zone.latMax) / 2;
double lonCenter = (zone.lonRight + zone.lonLeft) / 2;
double deltaLat = MAX (0.1, zone.latMax - latCenter);
double deltaLon = deltaLat * LON_LAT_RATIO;
dispZone.zoom = 180 / deltaLat;
dispZone.latMin = zone.latMin;
dispZone.latMax = zone.latMax;
dispZone.lonLeft = lonCenter - deltaLon;
dispZone.lonRight = lonCenter + deltaLon;
dispZone.latStep = fabs ((dispZone.latMax - dispZone.latMin)) / DISP_NB_LAT_STEP;
dispZone.lonStep = fabs ((dispZone.lonLeft - dispZone.lonRight)) / DISP_NB_LON_STEP;
}
/*! center DispZone on lon, lat */
static void centerDispZone (double lon, double lat) {
double oldLatCenter = (dispZone.latMin + dispZone.latMax) / 2.0;
double deltaLat = MAX (0.1, dispZone.latMax - oldLatCenter);
double deltaLon = deltaLat * LON_LAT_RATIO;
dispZone.zoom = 180 / deltaLat;
dispZone.latMin = lat - deltaLat;
dispZone.latMax = lat + deltaLat;
dispZone.lonLeft = lon - deltaLon;
dispZone.lonRight = lon + deltaLon;
dispZone.latStep = fabs ((dispZone.latMax - dispZone.latMin)) / DISP_NB_LAT_STEP;
dispZone.lonStep = fabs ((dispZone.lonLeft - dispZone.lonRight)) / DISP_NB_LON_STEP;
}
/*! zoom the main window */
static void dispZoom (double z) {
double latCenter = (dispZone.latMin + dispZone.latMax) / 2.0;
double lonCenter = (dispZone.lonLeft + dispZone.lonRight) / 2.0;
double deltaLat = MAX (0.1, dispZone.latMax - latCenter);
double deltaLon = deltaLat * LON_LAT_RATIO;
dispZone.zoom = 180 / deltaLat;
if ((z < 1.0) && (deltaLat < 0.1)) return; // stop zoom
if ((z > 1.0) && (deltaLat > 60)) return; // stop zoom
dispZone.latMin = latCenter - deltaLat * z;
dispZone.latMax = latCenter + deltaLat * z;
dispZone.lonLeft = lonCenter - deltaLon * z;
dispZone.lonRight = lonCenter + deltaLon * z;
dispZone.latStep = fabs ((dispZone.latMax - dispZone.latMin)) / DISP_NB_LAT_STEP;
dispZone.lonStep = fabs ((dispZone.lonLeft - dispZone.lonRight)) / DISP_NB_LON_STEP;
destroySurface ();
}
/*! horizontal and vertical translation of main window */
static void dispTranslate (double h, double v) {
double saveLatMin = dispZone.latMin, saveLatMax = dispZone.latMax;
double saveLonLeft = dispZone.lonLeft, saveLonRight = dispZone.lonRight;
const double K_TRANSLATE = (dispZone.latMax - dispZone.latMin) / 2.0;
dispZone.latMin += h * K_TRANSLATE;
dispZone.latMax += h * K_TRANSLATE;
dispZone.lonLeft += v * K_TRANSLATE;
dispZone.lonRight += v * K_TRANSLATE;
if ((dispZone.latMin < -180) || (dispZone.latMax > 180) || (dispZone.lonLeft < -330) || (dispZone.lonRight > 330)) {
dispZone.latMin = saveLatMin;
dispZone.latMax = saveLatMax;
dispZone.lonLeft = saveLonLeft;
dispZone.lonRight = saveLonRight;
}
destroySurface ();
}
/*! return x as a function of longitude */
static double getX (double lon) {
double kLat = (dispZone.yB - dispZone.yT) / (dispZone.latMax - dispZone.latMin);
//double kLon = (dispZone.xR - dispZone.xL) / (dispZone.lonRight - dispZone.lonLeft);
double kLon = kLat * K_LON_LAT; //cos (DEG_TO_RAD * (dispZone.latMax + dispZone.latMin)/2.0);
return kLon * (lon - dispZone.lonLeft) + dispZone.xL;
}
/*! return y as a function of latitude */
static double getY (double lat) {
double kLat = (dispZone.yB - dispZone.yT) / (dispZone.latMax - dispZone.latMin);
return kLat * (dispZone.latMax - lat) + dispZone.yT;
}
/*! return longitude as a function of x (inverse of getX) */
static inline double xToLon (double x) {
//double kLon = (dispZone.xR - dispZone.xL) / (dispZone.lonRight - dispZone.lonLeft);
double kLat = (dispZone.yB - dispZone.yT) / (dispZone.latMax - dispZone.latMin);
double kLon = kLat * K_LON_LAT; // cos (DEG_TO_RAD * (dispZone.latMax + dispZone.latMin)/2.0);
double lon = dispZone.lonLeft + ((x - dispZone.xL -1) / kLon);
return lonCanonize (lon);
}
/*! return latitude as a function of y (inverse of getY) */
static inline double yToLat (double y) {
double kLat = (dispZone.yB - dispZone.yT) / (dispZone.latMax - dispZone.latMin);
return dispZone.latMax - ((y - dispZone.yT - 1) / kLat);
}
/*! draw a polygon */
static void drawPolygon (cairo_t *cr, MyPolygon *po) {
double x = getX (po->points[0].lon);
double y = getY (po->points[0].lat);
cairo_move_to (cr, x, y);
for (int k = 1; k < po->n; k++) {
x = getX (po->points [k].lon);
y = getY (po->points [k].lat);
cairo_line_to (cr, x, y);
}
cairo_close_path(cr);
cairo_fill(cr);
}
/*! exclusion zone is an array of polygons */
static void drawForbidArea (cairo_t *cr) {
CAIRO_SET_SOURCE_RGBA_FORBID_AREA(cr);
for (int i = 0; i < par.nForbidZone; i++)
drawPolygon (cr, &forbidZones [i]);
}
/*! draw trace */
static void drawTrace (cairo_t *cr) {
FILE *f;
char line [MAX_SIZE_LINE];
double lat, lon, time, x, y;
bool first = true;
cairo_set_line_width (cr, 0.5);
//cairo_set_line_width (cr, 4);
CAIRO_SET_SOURCE_RGB_BLACK (cr);
if ((f = fopen (par.traceFileName, "r")) == NULL) {
fprintf (stderr, "In drawTrace: Error Impossible to open: %s\n", par.traceFileName);
return;
}
while (fgets (line, MAX_SIZE_LINE, f) != NULL ) {
if (sscanf (line, "%lf;%lf;%lf", &lat, &lon, &time) >= 3) {
x = getX (lon);
y = getY (lat);
if (first) {
cairo_move_to (cr, x, y);
first = false;
}
else
cairo_line_to (cr, x, y);
}
}
cairo_stroke (cr);
fclose (f);
}
/*! association of color r g b with wind speed twd */
static void mapColors (double tws, guint8 *r, guint8 *g, guint8 *b) {
int i;
double ratio;
guint8 (*wColors)[3] = (par.showColors == B_W) ? bwPalette : colorPalette;
for (i = 0; i < N_WIND_COLORS; i++) {
if (tTws [i] > tws) break;
}
if (i <= 0) {
*r = wColors [0][0]; *g = wColors [0][1]; *b = wColors [0][2];
return;
}
if (i >= N_WIND_COLORS) {
*r = wColors [N_WIND_COLORS-1][0]; *g = wColors [N_WIND_COLORS-1][1]; *b = wColors [N_WIND_COLORS-1][2];
return;
}
ratio = (tws - tTws [i-1]) / (tTws [i] - tTws [i-1]);
*r = wColors [i-1][0] + ratio * (wColors [i][0] - wColors [i-1][0]);
*g = wColors [i-1][1] + ratio * (wColors [i][1] - wColors [i-1][1]);
*b = wColors [i-1][2] + ratio * (wColors [i][2] - wColors [i-1][2]);
}
/*! gray if night
static void paintDayNight (cairo_t *cr, int width, int height) {
double lat, lon;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
lat = yToLat (y);
lon = xToLon (x);
if (! isDayLight (theTime, lat, lon)) {
cairo_set_source_rgba (cr, 0.5, 0.5, 0.5, 0.5);
cairo_rectangle (cr, x, y, 1, 1);
cairo_fill (cr);
}
}
}
}*/
/*! update colors for wind */
static void createWindSurface (cairo_t *cr, int index, int width, int height) {
double u, v, gust, w, twd, tws, lat, lon;
double val = 0.0;
guint8 red, green, blue;
int nCall = 0;
surface [index] = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, width, height);
surface_cr [index] = cairo_create(surface [index]);
existSurface [index] = true;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
lat = yToLat (y);
lon = xToLon (x);
if (isInZone (lat, lon, &zone)) {
nCall += 1;
switch (par.averageOrGustDisp) {
case WIND_DISP:
findWindGrib (lat, lon, theTime, &u, &v, &gust, &w, &twd, &tws);
val = tws;
break;
case GUST_DISP:
findWindGrib (lat, lon, theTime, &u, &v, &gust, &w, &twd, &tws);
val = MAX (tws, MS_TO_KN * gust);
break;
case WAVE_DISP:
findWindGrib (lat, lon, theTime, &u, &v, &gust, &w, &twd, &tws);
val = w;
break;
case RAIN_DISP:
val = findRainGrib (lat, lon, theTime) * 250000;
break;
case PRESSURE_DISP:
// normalize a value between 0 to 50 associated to 950 to 1050 hP
val = findPressureGrib (lat, lon, theTime)/ 100; // hPa
val -= 990;
val *= 1;
if (val > 50) val = 50;
if (val < 0) val = 0;
// printf ("val: %.2lf\n", val);
break;
default:;
}
mapColors (val, &red, &green, &blue);
cairo_set_source_rgba (surface_cr [index], red/255.0, green/255.0, blue/255.0, 0.5);
cairo_rectangle (surface_cr [index], x, y, 1, 1);
cairo_fill (surface_cr [index]);
}
}
}
// printf ("nCall in PaintWind to findWindGrib: %d\n", nCall);
}
/*! clean surface */
static void destroySurface () {
for (int i = 0; i < MAX_N_SURFACE; i++) {
if (existSurface[i]) {
cairo_destroy(surface_cr [i]);
cairo_surface_destroy(surface [i]);
}
}
memset (existSurface, false, MAX_N_SURFACE);
}
/*! update colors for wind
static void OpaintWind (cairo_t *cr, int width, int height) {
double u, v, gust, w, twd, tws, lat, lon;
guint8 red, green, blue;
int nCall = 0;
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
lat = yToLat (y);
lon = xToLon (x);
if (isInZone (lat, lon, &zone)) {
findWindGrib (lat, lon, theTime, &u, &v, &gust, &w, &twd, &tws);
nCall += 1;
if (par.averageOrGustDisp != 0)
tws = MAX (tws, MS_TO_KN * gust);
mapColors (tws, &red, &green, &blue);
cairo_set_source_rgba (cr, red/255.0, green/255.0, blue/255.0, 0.5);
cairo_rectangle (cr, x, y, 1, 1);
cairo_fill (cr);
}
}
}
// printf ("nCall in PaintWind to findWindGrib: %d\n", nCall);
}*/
/*! callback for palette */
static void cbDrawPalette (GtkDrawingArea *area, cairo_t *cr, int width, int height, gpointer user_data) {
double tws;
guint8 r, g, b;
char label [9];
for (int x = 0; x < width; x++) {
tws = (double) x * 50.0 / (double) width;
mapColors (tws, &r, &g, &b);
cairo_set_source_rgba (cr, r/255.0, g/255.0, b/255.0, 0.5);
cairo_rectangle(cr, x, 0, 1, height / 2);
cairo_fill(cr);
}
for (tws = 0; tws < 50; tws += 5.0) {
int x = (int) (tws * (double) width / 50.0);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
cairo_move_to (cr, x, height / 2);
cairo_line_to (cr, x, height);
cairo_stroke (cr);
snprintf (label, sizeof(label), "%0.2lf", tws);
cairo_move_to(cr, x + 5, height - 5);
cairo_show_text(cr, label);
}
}
/*! Palette */
static void paletteDraw () {
GtkWidget *paletteWindow = gtk_application_window_new (app);
gtk_window_set_title(GTK_WINDOW (paletteWindow), "TWS (knots)");
gtk_window_set_default_size(GTK_WINDOW (paletteWindow), 800, 100);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), paletteWindow);
// g_signal_connect (paletteWindow, "destroy", G_CALLBACK(gtk_window_destroy), NULL);
GtkWidget *drawing_area = gtk_drawing_area_new();
gtk_widget_set_size_request(drawing_area, 800, 100);
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (drawing_area), cbDrawPalette, NULL, NULL);
gtk_window_set_child (GTK_WINDOW (paletteWindow), (GtkWidget *) drawing_area);
gtk_window_present (GTK_WINDOW (paletteWindow));
}
/*! make calculation over Ortho route */
static void calculateOrthoRoute () {
wayPoints.t [0].lCap = directCap (par.pOr.lat, par.pOr.lon, wayPoints.t [0].lat, wayPoints.t [0].lon);
wayPoints.t [0].oCap = wayPoints.t [0].lCap + givry (par.pOr.lat, par.pOr.lon, wayPoints.t [0].lat, wayPoints.t [0].lon);
wayPoints.t [0].ld = loxoDist (par.pOr.lat, par.pOr.lon, wayPoints.t [0].lat, wayPoints.t [0].lon);
wayPoints.t [0].od = orthoDist (par.pOr.lat, par.pOr.lon, wayPoints.t [0].lat, wayPoints.t [0].lon);
wayPoints.totLoxoDist = wayPoints.t [0].ld;
wayPoints.totOrthoDist = wayPoints.t [0].od;
for (int i = 0; i < wayPoints.n; i++) {
wayPoints.t [i+1].lCap = directCap (wayPoints.t [i].lat, wayPoints.t [i].lon, wayPoints.t [i+1].lat, wayPoints.t [i+1].lon);
wayPoints.t [i+1].oCap = wayPoints.t [i+1].lCap + givry (wayPoints.t [i].lat, wayPoints.t [i].lon, wayPoints.t [i+1].lat, wayPoints.t [i+1].lon);
wayPoints.t [i+1].ld = loxoDist (wayPoints.t [i].lat, wayPoints.t [i].lon, wayPoints.t [i+1].lat, wayPoints.t [i+1].lon);
wayPoints.t [i+1].od = orthoDist (wayPoints.t [i].lat, wayPoints.t [i].lon, wayPoints.t [i+1].lat, wayPoints.t [i+1].lon);
wayPoints.totLoxoDist += wayPoints.t [i+1].ld;
wayPoints.totOrthoDist += wayPoints.t [i+1].od;
}
}
/*! draw orthoPoints */
static void orthoPoints (cairo_t *cr, double lat1, double lon1, double lat2, double lon2, int n) {
double lSeg;
double lat = lat1;
double lon = lon1;
double angle, x1, y1, x2, y2;
double x = getX (lon1);
double y = getY (lat1);
cairo_move_to (cr, x, y);
CAIRO_SET_SOURCE_RGB_GREEN(cr);
n = 10;
for (int i = 0; i < n - 2; i ++) {
angle = orthoCap (lat, lon, lat2, lon2);
lSeg = orthoDist (lat, lon, lat2, lon2) / (n - i);
lat += lSeg * cos (angle * DEG_TO_RAD) / 60;
lon += (lSeg * sin (angle * DEG_TO_RAD) / cos (DEG_TO_RAD * lat)) / 60;
x = getX (lon);
y = getY (lat);
angle = orthoCap (lat, lon, lat2, lon2);
lSeg = orthoDist (lat, lon, lat2, lon2) / (n - i - 1);
lat += lSeg * cos (angle * DEG_TO_RAD) / 60;
lon += (lSeg * sin (angle * DEG_TO_RAD) / cos (DEG_TO_RAD * lat)) / 60;
x1 = getX (lon);
y1 = getY (lat);
angle = orthoCap (lat, lon, lat2, lon2);
lSeg = orthoDist (lat, lon, lat2, lon2) / (n - i - 2);
lat += lSeg * cos (angle * DEG_TO_RAD) / 60;
lon += (lSeg * sin (angle * DEG_TO_RAD) / cos (DEG_TO_RAD * lat)) / 60;
x2 = getX (lon);
y2 = getY (lat);
cairo_curve_to(cr, x, y, x1, y1, x2, y2);
}
x = getX (lon2);
y = getY (lat2);
cairo_line_to (cr, x, y);
cairo_stroke (cr);
}
/*! return label associated to x */
static GtkWidget *doubleToLabel (double x) {
char str [MAX_SIZE_LINE];
snprintf (str, sizeof (str), "%.2lf", x);
GtkWidget *label = gtk_label_new (str);
gtk_label_set_yalign (GTK_LABEL(label), 0);
gtk_label_set_xalign (GTK_LABEL(label), 0);
return label;
}
/*! return label associated to str with optionnally i*/
static GtkWidget *strToLabel (const char *str0, int i) {
char str [MAX_SIZE_LINE];
if (i >= 0) snprintf (str, sizeof (str), "%s %d", str0, i);
else strncpy (str, str0, sizeof (str) - 1);
GtkWidget *label = gtk_label_new (str);
gtk_label_set_yalign(GTK_LABEL(label), 0);
gtk_label_set_xalign(GTK_LABEL(label), 0);
return label;
}
/*! return label in bold associated to str */
static GtkWidget *strToLabelBold (const char *str) {
GtkWidget *label = gtk_label_new (str);
PangoAttrList *attrs = pango_attr_list_new();
PangoAttribute *attr = pango_attr_weight_new(PANGO_WEIGHT_BOLD);
pango_attr_list_insert(attrs, attr);
gtk_label_set_attributes(GTK_LABEL(label), attrs);
pango_attr_list_unref(attrs);
gtk_label_set_yalign(GTK_LABEL(label), 0);
gtk_label_set_xalign(GTK_LABEL(label), 0);
return label;
}
/*! dump orthodomic route into str */
static void niceWayPointReport () {
char strLat [MAX_SIZE_LINE];
char strLon [MAX_SIZE_LINE];
calculateOrthoRoute ();
GtkWidget *wpWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (wpWindow), "Orthodomic and Loxdromic Waypoint routes");
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), niceWayPointReport);
GtkWidget *grid = gtk_grid_new();
GtkWidget *separator = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
gtk_window_set_child (GTK_WINDOW (wpWindow), (GtkWidget *) grid);
gtk_grid_set_column_spacing(GTK_GRID(grid), 10);
gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
gtk_grid_set_row_homogeneous(GTK_GRID(grid), FALSE);
gtk_grid_set_column_homogeneous(GTK_GRID(grid), FALSE);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Point"), 0, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Lat."), 1, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Lon."), 2, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Ortho Cap."), 3, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Ortho Dist."),4, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Loxo Cap."), 5, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Loxo Dist."), 6, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), separator, 0, 1, 7, 1);
int i;
for (i = -1; i < wayPoints.n; i++) {
if (i == -1) {
gtk_grid_attach (GTK_GRID (grid), strToLabel("Origin", -1), 0, 2, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabel(latToStr (par.pOr.lat, par.dispDms, strLat), -1), 1, 2, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabel(lonToStr (par.pOr.lon, par.dispDms, strLon), -1), 2, 2, 1, 1);
}
else {
gtk_grid_attach (GTK_GRID (grid), strToLabel("Waypoint", i), 0, i+3, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabel(latToStr (wayPoints.t[i].lat, par.dispDms, strLat), -1), 1, i+3, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabel(lonToStr (wayPoints.t[i].lon, par.dispDms, strLon), -1), 2, i+3, 1, 1);
}
gtk_grid_attach (GTK_GRID (grid), doubleToLabel (wayPoints.t [i+1].oCap), 3, i+3, 1, 1);
gtk_grid_attach (GTK_GRID (grid), doubleToLabel (wayPoints.t [i+1].od), 4, i+3, 1, 1);
gtk_grid_attach (GTK_GRID (grid), doubleToLabel (wayPoints.t [i+1].lCap), 5, i+3, 1, 1);
gtk_grid_attach (GTK_GRID (grid), doubleToLabel (wayPoints.t [i+1].ld), 6, i+3, 1, 1);
}
gtk_grid_attach (GTK_GRID (grid), strToLabel("Destination", -1), 0, i+3, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabel(latToStr (par.pDest.lat, par.dispDms, strLat), -1), 1, i+3, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabel(lonToStr (par.pDest.lon, par.dispDms, strLon), -1), 2, i+3, 1, 1);
i += 1;
separator = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
gtk_grid_attach(GTK_GRID(grid), separator, 0, i+3, 7, 1);
i += 1;
gtk_grid_attach (GTK_GRID (grid), strToLabel("Total Orthodomic Distance", -1), 0, i+3, 3, 1);
gtk_grid_attach (GTK_GRID (grid), doubleToLabel (wayPoints.totOrthoDist), 3, i+3, 1, 1);
i += 1;
separator = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
gtk_grid_attach(GTK_GRID(grid), separator, 0, i+3, 7, 1);
i += 1;
gtk_grid_attach (GTK_GRID (grid), strToLabel("Total Loxodromic Distance", -1), 0, i+3, 3, 1);
gtk_grid_attach (GTK_GRID (grid), doubleToLabel (wayPoints.totLoxoDist), 3, i+3, 1, 1);
gtk_window_present (GTK_WINDOW (wpWindow));
}
/*! draw loxodromie */
static void drawLoxoRoute (cairo_t *cr) {
double x = getX (par.pOr.lon);
double y = getY (par.pOr.lat);
CAIRO_SET_SOURCE_RGB_LIGHT_GRAY(cr);
cairo_move_to (cr, x, y);
for (int i = 0; i < wayPoints.n; i++) {
x = getX (wayPoints.t [i].lon);
y = getY (wayPoints.t [i].lat);
cairo_line_to (cr, x, y);
}
if (destPressed) {
x = getX (par.pDest.lon);
y = getY (par.pDest.lat);
cairo_line_to (cr, x, y);
}
cairo_stroke (cr);
}
/*! draw orthodromic routes from waypoints to next waypoints */
static void drawOrthoRoute (cairo_t *cr, int n) {
double prevLat = par.pOr.lat;
double prevLon = par.pOr.lon;
for (int i = 0; i < wayPoints.n; i++) {
orthoPoints (cr, prevLat, prevLon, wayPoints.t [i].lat, wayPoints.t [i].lon, n);
prevLat = wayPoints.t [i].lat;
prevLon = wayPoints.t [i].lon;
}
if (destPressed)
orthoPoints (cr, prevLat, prevLon, par.pDest.lat, par.pDest.lon, n);
}
/*! draw a circle */
static void circle (cairo_t *cr, double lon, double lat, double red, double green, double blue) {
cairo_arc (cr, getX (lon), getY (lat), 4.0, 0, 2 * G_PI);
cairo_set_source_rgb (cr, red, green, blue);
cairo_fill (cr);
}
/*! draw the boat or cat or ... */
static void showUnicode (cairo_t *cr, const char *unicode, double x, double y) {
PangoLayout *layout = pango_cairo_create_layout(cr);
PangoFontDescription *desc = pango_font_description_from_string ("DejaVuSans 16");
pango_layout_set_font_description(layout, desc);
pango_font_description_free(desc);
pango_layout_set_text(layout, unicode, -1);
cairo_move_to (cr, x, y);
pango_cairo_show_layout(cr, layout);
g_object_unref(layout);
}
/*! draw all isochrones stored in isocArray as points */
static gboolean drawAllIsochrones0 (cairo_t *cr) {
double x, y;
Pp pt;
for (int i = 0; i < nIsoc; i++) {
GdkRGBA color = colors [i % nColors];
cairo_set_source_rgba (cr, color.red, color.green, color.blue, color.alpha);
for (int k = 0; k < isoDesc [i].size; k++) {
pt = isocArray [i][k];
x = getX (pt.lon);
y = getY (pt.lat);
cairo_arc (cr, x, y, 1.0, 0, 2 * G_PI);
cairo_fill (cr);
}
}
return FALSE;
}
/*! draw closest points to pDest in each isochrones */
static gboolean drawClosest (cairo_t *cr) {
double x, y;
Pp pt;
CAIRO_SET_SOURCE_RGB_RED(cr);
for (int i = 0; i < nIsoc; i++) {
pt = isocArray [i][isoDesc [i].closest];
//printf ("lat: %.2lf, lon: %.2lf\n", pt.lat, pt.lon);
x = getX (pt.lon);
y = getY (pt.lat);
cairo_arc (cr, x, y, 2, 0, 2 * G_PI);
cairo_fill (cr);
}
return FALSE;
}
/*! draw focal points */
static gboolean drawFocal (cairo_t *cr) {
double x, y, lat, lon;
CAIRO_SET_SOURCE_RGB_GREEN(cr);
for (int i = 0; i < nIsoc; i++) {
lat = isoDesc [i].focalLat;
lon = isoDesc [i].focalLon;
//printf ("lat: %.2lf, lon: %.2lf\n", pt.lat, pt.lon);
x = getX (lon);
y = getY (lat);
cairo_arc (cr, x, y, 2, 0, 2 * G_PI);
cairo_fill (cr);
}
return FALSE;
}
/*! draw all isochrones stored in isocArray as segments or curves */
static gboolean drawAllIsochrones (cairo_t *cr, int style) {
double x, y, x1, y1, x2, y2;
//GtkWidget *drawing_area = gtk_drawing_area_new();
Pp pt;
Isoc newIsoc;
int index;
if (par.closestDisp) drawClosest (cr);
if (par.focalDisp) drawFocal (cr);
if (style == NOTHING) return true;
if (style == JUST_POINT) return drawAllIsochrones0 (cr);
CAIRO_SET_SOURCE_RGB_BLUE(cr);
cairo_set_line_width(cr, 1.0);
for (int i = 0; i < nIsoc; i++) {
// GdkRGBA color = colors [i % nColors];
// cairo_set_source_rgba (cr, color.red, color.green, color.blue, color.alpha);
index = isoDesc [i].first;
for (int j = 0; j < isoDesc [i].size; j++) {
newIsoc [j] = isocArray [i][index];
index += 1;
if (index == isoDesc [i].size) index = 0;
}
pt = newIsoc [0];
x = getX (pt.lon);
y = getY (pt.lat);
cairo_move_to (cr, x, y);
if ((isoDesc [i].size < MIN_POINT_FOR_BEZIER) || style == SEGMENT) { // segment if number of points < 4 or style == 2
for (int k = 1; k < isoDesc [i].size; k++) {
pt = newIsoc [k];
x = getX (pt.lon);
y = getY (pt.lat);
cairo_line_to (cr, x, y);
}
cairo_stroke(cr);
}
else { // curve if number of point >= 4 and style == 2
int k;
for (k = 1; k < isoDesc [i].size - 2; k += 3) {
pt = newIsoc [k];
x = getX (pt.lon);
y = getY (pt.lat);
pt = newIsoc [k+1];
x1 = getX (pt.lon);
y1 = getY (pt.lat);
pt = newIsoc [k+2];
x2 = getX (pt.lon);
y2 = getY (pt.lat);
cairo_curve_to(cr, x, y, x1, y1, x2, y2);
}
for (int kk = k; kk < isoDesc [i].size; kk++) { // others with segment
pt = newIsoc [kk];
x = getX (pt.lon);
y = getY (pt.lat);
cairo_line_to(cr, x, y);
}
cairo_stroke(cr);
}
cairo_stroke(cr);
}
return FALSE;
}
/*! find index in route with closest time to t
-1 if terminated */
static int findIndexInRoute (double t) {
int i;
if (t < route.t[0].time) return 0;
if (t > route.t[route.n - 1].time) return -1;
for (i = 0; i < route.n; i++) {
if (route.t[i].time > t) break;
}
if ((t - route.t[i-1].time) < (route.t[i].time - t))
return i - 1;
else return i;
}
/*! find index in route just before now
-1 if terminated */
static int findIndexInRouteNow () {
time_t now = time (NULL);
// tDeltaNow is the number of hours between beginning of grib to now */
double tDeltaNow = (now - vOffsetLocalUTC)/ 3600.0; // offset between local and UTC in hours
tDeltaNow -= gribDateTimeToEpoch (zone.dataDate [0], zone.dataTime [0]) / 3600.0;
int i = (tDeltaNow - par.startTimeInHours) / par.tStep;
// printf ("tDeltaNow: %.2lf, i = %d\n", tDeltaNow, i);
return i;
}
/*! give the focus on point in route at theTime */
static void focusOnPointInRoute (cairo_t *cr) {
char strDate [MAX_SIZE_LINE], strLat [MAX_SIZE_NAME] = "", strLon [MAX_SIZE_NAME] = "";
char sInfoRoute [MAX_SIZE_LINE] = "";
int i;
double lat, lon;
if (route.n == 0) {
gtk_label_set_text (GTK_LABEL(labelInfoRoute), sInfoRoute);
return;
}
i = findIndexInRoute (theTime);
if (route.destinationReached && (i == -1)) {
lat = par.pDest.lat;
lon = par.pDest.lon;
snprintf (sInfoRoute, sizeof (sInfoRoute),
"Destination Reached on: %s Lat: %-12s Lon: %-12s", \
newDateWeekDay (zone.dataDate [0], zone.dataTime [0]/100 + par.startTimeInHours + route.duration, strDate), \
latToStr (lat, par.dispDms, strLat), lonToStr (lon, par.dispDms, strLon));
}
else {
if (i > route.n) {
i = route.n - 1;
lat = lastClosest.lat;
lon = lastClosest.lon;
}
else {
lat = route.t[i].lat;
lon = route.t[i].lon;
}
int twa = fTwa (route.t[i].lCap, route.t[i].twd);
snprintf (sInfoRoute, sizeof (sInfoRoute),
"Route Date: %s Lat: %-12s Lon: %-12s COG: %4.0f° SOG:%5.2lfKn TWD:%4d° TWA:%4d° TWS:%5.2lfKn Gust: %5.2lfKn Wave: %5.2lfm %s", \
newDateWeekDay (zone.dataDate [0], (zone.dataTime [0]/100) + route.t[i].time, strDate), \
latToStr (route.t[i].lat, par.dispDms, strLat), lonToStr (route.t[i].lon, par.dispDms, strLon), \
route.t[i].lCap, route.t[i].ld/par.tStep, \
(int) (route.t[i].twd + 360) % 360,\
twa, route.t[i].tws, \
MS_TO_KN * route.t[i].g, route.t[i].w,
(isDayLight (route.t[i].time, lat, lon)) ? "Day" : "Night");
}
showUnicode (cr, BOAT_UNICODE, getX (lon), getY (lat) - 20);
gtk_label_set_text (GTK_LABEL(labelInfoRoute), sInfoRoute);
circle (cr, lon, lat, 00, 0.0, 1.0); // blue
}
/* set color of route according to motor and amure */
static inline void routeColor (cairo_t *cr, bool motor, int amure) {
if (motor)
CAIRO_SET_SOURCE_RGB_RED(cr);
else {
if (amure == BABORD)
CAIRO_SET_SOURCE_RGB_BLACK(cr);
else CAIRO_SET_SOURCE_RGB_GRAY(cr);
}
}
/*! draw the routes based on route table, from pOr to pDest or best point */
static void drawRoute (cairo_t *cr) {
char line [MAX_SIZE_LINE];
int motor = route.t[0].motor;
int amure = route.t[0].amure;
double x = getX (par.pOr.lon);
double y = getY (par.pOr.lat);
cairo_set_line_width (cr, 5);
routeColor (cr, motor, amure);
cairo_move_to (cr, x, y);
for (int i = 1; i < route.n; i++) {
x = getX (route.t[i].lon);
y = getY (route.t[i].lat);
cairo_line_to (cr, x, y);
if ((route.t[i].motor != motor) || (route.t[i].amure != amure)) {
cairo_stroke (cr);
amure = route.t[i].amure;
motor = route.t[i].motor;
routeColor (cr, motor, amure);
cairo_move_to (cr, x, y);
}
}
if (route.destinationReached) {
x = getX (par.pDest.lon);
y = getY (par.pDest.lat);
cairo_line_to (cr, x, y);
}
cairo_stroke (cr);
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size (cr, 15);
cairo_move_to (cr, x +5, y + 5);
snprintf (line, MAX_SIZE_LINE, "Rte: %d", historyRoute.n - 1);
cairo_show_text (cr, line);
cairo_stroke(cr);
}
/*! draw the route based on route table index */
static void drawHistoryRoute (cairo_t *cr, int k) {
char line [MAX_SIZE_LINE];
double x = getX (historyRoute.r[k].t[0].lon);
double y = getY (historyRoute.r[k].t[0].lat);
CAIRO_SET_SOURCE_RGB_PINK(cr);
cairo_set_line_width (cr, 2);
cairo_move_to (cr, x, y);
for (int i = 1; i < historyRoute.r[k].n; i++) {
x = getX (historyRoute.r[k].t[i].lon);
y = getY (historyRoute.r[k].t[i].lat);
cairo_line_to (cr, x, y);
}
cairo_stroke (cr);
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size (cr, 15);
cairo_move_to (cr, x +5, y + 5);
snprintf (line, MAX_SIZE_LINE, "Rte: %d", k);
cairo_show_text (cr, line);
cairo_stroke(cr);
}
/*! draw the routes based on route table */
static void drawAllRoutes (cairo_t *cr) {
for (int k = 0; k < historyRoute.n - 1; k++) {
drawHistoryRoute (cr, k);
}
drawRoute (cr);
}
/*! draw Point of Interests */
static void drawPoi (cairo_t *cr) {
double x, y;
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size (cr, 10);
for (int i = 0; i < nPoi; i++) {
x = getX (tPoi [i].lon);
y = getY (tPoi [i].lat);
if (tPoi [i].level <= par.maxPoiVisible) {
switch (tPoi [i].type) {
case UNVISIBLE:
break;
case CAT:
showUnicode (cr, CAT_UNICODE, x, y - 20);
break;
case NORMAL: case NEW:
circle (cr, tPoi [i].lon, tPoi [i].lat, 0.0, 0.0, 0.0);
cairo_move_to (cr, x+10, y);
cairo_show_text (cr, tPoi [i].name);
break;
case PORT:
if (dispZone.zoom > MIN_ZOOM_POI_VISIBLE) {
CAIRO_SET_SOURCE_RGB_BLACK (cr); // points
cairo_move_to (cr, x+10, y);
gchar *utf8String = g_locale_to_utf8(tPoi [i].name, -1, NULL, NULL, NULL);
cairo_show_text (cr, utf8String);
g_free (utf8String);
cairo_rectangle (cr, x, y, 1, 1);
cairo_fill (cr);
}
break;
default:;
}
}
}
cairo_stroke (cr);
}
/*! return true if rectangle defined by parameters interects with display zone */
static bool isRectangleIntersecting (double latMin, double latMax, double lonMin, double lonMax) {
return (latMin <= dispZone.latMax && latMax >= dispZone.latMin && lonMin <= dispZone.lonRight && lonMax >= dispZone.lonLeft);
}
/*! draw shapefile with different color for sea and earth */
static gboolean drawShpMap (cairo_t *cr) {
register double x, y;
register int step = 1, deb, end;
// Dessiner les entités
for (int i = 0; i < nTotEntities; i++) {
if ((entities [i].nSHPType != SHPT_POINT) && \
(! isRectangleIntersecting (entities[i].latMin, entities[i].latMax, entities[i].lonMin, entities[i].lonMax)))
continue;
step = (dispZone.zoom < 5) ? 128
: (dispZone.zoom < 20) ? 64
: (dispZone.zoom < 50) ? 32
: (dispZone.zoom < 100) ? 16
: (dispZone.zoom < 500) ? 8
: 1;
//printf ("draw_sh_map zoom: %.2lf, step: %d\n", dispZone.zoom, step);
switch (entities [i].nSHPType) {
case SHPT_POLYGON: // case SHPT_POLYGONZ:// Traitement pour les polygones
CAIRO_SET_SOURCE_RGBA_SHP_MAP(cr); //lignes
for (int iPart = 0; iPart < entities [i].maxIndex; iPart++) {
// CAIRO_SET_SOURCE_RGB_BLACK(cr); // useful for bordes
deb = entities [i].index [iPart];
end = (iPart == entities [i].maxIndex - 1) ? entities [i].numPoints : entities [i].index [iPart + 1];
// printf ("entity: %d, part: %d, deb %d, end %d\n", i, iPart, deb, end);
x = getX (entities[i].points[deb].lon);
y = getY (entities[i].points[deb].lat);
cairo_move_to (cr, x, y);
for (int j = deb + 1; j < end; j += step) {
x = getX (entities[i].points[j].lon);
y = getY (entities[i].points[j].lat);
cairo_line_to (cr, x, y);
}
cairo_close_path(cr);
// cairo_stroke_preserve(cr); // usful for borders
// CAIRO_SET_SOURCE_RGBA_SHP_MAP(cr); //lignes
cairo_fill(cr);
// cairo_move_to (cr, x, y);
}
break;
case SHPT_ARC: //case SHPT_ARCZ: // manage lines (arcs). BE CAREFUL: Multipart not considered
CAIRO_SET_SOURCE_RGB_RED(cr); //lignes
x = getX (entities[i].points[0].lon);
y = getY (entities[i].points[0].lat);
cairo_move_to (cr, x, y);
for (int j = 1; j < entities[i].numPoints; j += step) {
x = getX (entities[i].points[j].lon);
y = getY (entities[i].points[j].lat);
cairo_line_to (cr, x, y);
}
cairo_stroke(cr);
break;
case SHPT_POINT:
CAIRO_SET_SOURCE_RGB_RED(cr); // points
x = getX (entities[i].points[0].lon);
y = getY (entities[i].points[0].lat);
cairo_rectangle (cr, x, y, 1, 1);
cairo_fill (cr);
break;
case SHPT_NULL: // empty
break;
default: fprintf (stderr, "Error in drawShpMap: SHPtype unknown: %d\n", entities [i].nSHPType);
}
}
return FALSE;
}
/*! draw something that represent the waves */
static void showWaves (cairo_t *cr, double lat, double lon, double w) {
double x = getX (lon);
double y = getY (lat);
char str [MAX_SIZE_NUMBER];
if ((w <= 0) || (w > 100)) return;
CAIRO_SET_SOURCE_RGB_GRAY(cr);
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size (cr, 6);
cairo_move_to (cr, x, y);
snprintf (str, MAX_SIZE_NUMBER, "%.2lf", w);
cairo_show_text (cr, str);
}
/*! draw arrow that represent the direction of the wind */
static void arrow (cairo_t *cr, double head_x, double head_y, double u, double v, double twd, double tws, int typeFlow) {
const double arrowSize = 10.0;
if (tws == 0 || fabs (u) > 100 || fabs (v) > 100) return;
// Calculer les coordonnées de la queue
double tail_x = head_x - 30 * u/tws;
double tail_y = head_y + 30 * v/tws;
if (typeFlow == WIND) CAIRO_SET_SOURCE_RGB_BLACK (cr);
else CAIRO_SET_SOURCE_RGB_ORANGE (cr);
cairo_set_line_width (cr, 1.0);
cairo_set_font_size (cr, 6);
if (tws < 1) { // no wind : circle
cairo_move_to (cr, head_x, head_y);
cairo_show_text (cr, "o");
return;
}
// Dessiner la ligne de la flèche
cairo_move_to(cr, head_x, head_y);
cairo_line_to(cr, tail_x, tail_y);
cairo_stroke(cr);
// Dessiner le triangle de la flèche à l'extrémité
cairo_move_to (cr, head_x, head_y);
cairo_line_to (cr, head_x + arrowSize * sin (DEG_TO_RAD * twd - G_PI/6), head_y - arrowSize * cos(DEG_TO_RAD * twd - G_PI/6));
cairo_stroke(cr);
cairo_move_to (cr, head_x, head_y);
cairo_line_to (cr, head_x + arrowSize * sin(DEG_TO_RAD * twd + G_PI/6), head_y - arrowSize * cos(DEG_TO_RAD * twd + G_PI/6));
cairo_stroke(cr);
}
/*! draw barbule that represent the wind */
static void barbule (cairo_t *cr, double lat, double lon, double u, double v,\
double tws, int typeFlow) {
int i, j, k;
double barb0_x, barb0_y, barb1_x, barb1_y, barb2_x, barb2_y;
/*if (tws == 0 || u <= (MISSING + 1) || v <= (MISSING +1) || fabs (u) > 100 || fabs (v) > 100) {
//printf ("In barbule, strange value lat: %.2lf, lon: %.2lf, u: %.2lf, v: %.2lf\n", pt.lat, pt.lon, u, v);
return;
}*/
// Calculer les coordonnées de la tête
double head_x = getX (lon);
double head_y = getY (lat);
// Calculer les coordonnées de la queue
double tail_x = head_x - 30 * u/tws;
double tail_y = head_y + 30 * v/tws;
if (typeFlow == WIND) CAIRO_SET_SOURCE_RGB_BLACK(cr);
else CAIRO_SET_SOURCE_RGB_ORANGE(cr);
cairo_set_line_width (cr, 1.0);
cairo_set_font_size (cr, 6);
if (tws < 1) { // no wind : circle
cairo_move_to (cr, head_x, head_y);
cairo_show_text (cr, "o");
//cairo_arc (cr, head_x, head_y, 3, 0, 2*G_PI);
//cairo_stroke (cr);
return;
}
// Dessiner la ligne de la flèche
cairo_move_to (cr, tail_x, tail_y);
cairo_line_to (cr, head_x, head_y);
cairo_stroke (cr);
cairo_arc (cr, head_x, head_y, 1, 0, 2*G_PI);
cairo_fill (cr);
// determiner le nombre de barbules de chaque type
tws += 2; // pour arrondi
int barb50 = (int)tws/50;
int barb10 = ((int)tws % 50)/10;
int barb5 = ((int)(tws) % 10) / 5;
// signes de u et v
int signU = (u >= 0) ? 1 : -1;
int signV = (v >= 0) ? 1 : -1;
k = 25; // hauteur
for (i = 0; i < barb50; i++) {
barb0_x = tail_x + (10 * i) * u/tws;
barb0_y = tail_y - (10 * i) * v/tws;
barb1_x = barb0_x - k * signU * signV * fabs(v/tws);
barb1_y = barb0_y - k * fabs (u/tws);
barb2_x = tail_x + (10 * (i+1)) * u/tws;
barb2_y = tail_y - (10 * (i+1)) * v/tws;
cairo_move_to (cr, barb0_x, barb0_y);
cairo_line_to (cr, barb1_x, barb1_y);
cairo_line_to (cr, barb2_x, barb2_y);
cairo_close_path (cr);
cairo_fill (cr);
}
k = 20; // hauteur
for (j = 0; j < barb10; j++) {
barb0_x = tail_x + (12 * i + 8 * j) * u/tws;
barb0_y = tail_y - (12 * i + 8 * j) * v/tws;
barb1_x = barb0_x - k * signU * signV * fabs(v/tws);
barb1_y = barb0_y - k * fabs (u/tws);
cairo_move_to (cr, barb0_x, barb0_y);
cairo_line_to (cr, barb1_x, barb1_y);
cairo_stroke (cr);
}
k = 10; // hauteur
if (barb5 != 0) {
barb0_x = tail_x + (12 * i + 8 * j) * u/tws;
barb0_y = tail_y - (12 * i + 8 * j) * v/tws;
barb1_x = barb0_x - k * signU * signV * fabs(v/tws);
barb1_y = barb0_y - k * fabs (u/tws);
cairo_move_to (cr, barb0_x, barb0_y);
cairo_line_to (cr, barb1_x, barb1_y);
cairo_stroke (cr);
}
}
/*! update status bar */
static void statusBarUpdate () {
if (statusbar == NULL) return;
char totalDate [MAX_SIZE_DATE];
char sStatus [MAX_SIZE_BUFFER];
double lat, lon;
double u = 0, v = 0, g = 0, w = 0, uCurr = 0, vCurr = 0, currTwd = 0, currTws = 0;
char seaEarth [MAX_SIZE_NAME];
char strLat [MAX_SIZE_NAME] = "", strLon [MAX_SIZE_NAME] = "";
double tDeltaCurrent = zoneTimeDiff (¤tZone, &zone);
double twd, tws;
lat = yToLat (whereIsMouse.y);
lon = xToLon (whereIsMouse.x);
lon = lonCanonize (lon);
findWindGrib (lat, lon, theTime, &u, &v, &g, &w, &twd, &tws);
strcpy (seaEarth, (isSea (lat, lon)) ? "Authorized" : "Forbidden");
findCurrentGrib (lat, lon, theTime - tDeltaCurrent, &uCurr, &vCurr, &currTwd, &currTws);
snprintf (sStatus, sizeof (sStatus), "%s %3ld/%3ld %s %s, %s\
Wind: %03d° %05.2lf Knots Gust: %05.2lf Knots Waves: %05.2lf Current: %03d° %05.2lf Knots %s Zoom: %.2lf %s",
newDate (zone.dataDate [0], (zone.dataTime [0]/100) + theTime, totalDate),\
theTime, zone.timeStamp [zone.nTimeStamp-1], " ",\
latToStr (lat, par.dispDms, strLat),\
lonToStr (lon, par.dispDms, strLon),\
(int) (twd + 360) % 360, tws, MS_TO_KN * g, w,
(int) (currTwd + 360) % 360, currTws,
seaEarth,
dispZone.zoom,
(gribRequestRunning || readGribRet == -1) ? "WAITING GRIB" : "");
gtk_label_set_text (GTK_LABEL (statusbar), sStatus);
}
/*! draw scale, scaleLen is for one degree. Modified if not ad hoc */
static void drawScale (cairo_t *cr, DispZone *dispZone) {
const int DELTA = 4;
char line [MAX_SIZE_LINE];
double scaleX, scaleY, scaleLen;;
CAIRO_SET_SOURCE_RGB_BLACK (cr);
cairo_set_line_width (cr, 2.0);
int val = 60;
if ((dispZone->latMax - dispZone ->latMin) <= 2.0) return; // no scale for small zone
// vertical
scaleLen = (getY (dispZone->latMax - 1) - getY (dispZone->latMax));
//scaleX = getX (ceil (dispZone->lonLeft));
scaleX = 30;
scaleY = getY (ceil (dispZone->latMin));
cairo_move_to (cr, scaleX, scaleY);
cairo_line_to (cr, scaleX, scaleY - scaleLen);
cairo_stroke(cr);
cairo_move_to (cr, scaleX + 15, scaleY);
snprintf (line, MAX_SIZE_LINE, "Lat: %d miles", val);
cairo_show_text (cr, line);
cairo_stroke(cr);
cairo_move_to (cr, scaleX - DELTA, scaleY);
cairo_line_to (cr, scaleX + DELTA, scaleY);
cairo_stroke(cr);
cairo_move_to (cr, scaleX + DELTA, scaleY - scaleLen);
cairo_line_to (cr, scaleX - DELTA, scaleY - scaleLen);
cairo_stroke(cr);
// horizontal
scaleLen = (getX (dispZone->lonRight) - getX (dispZone->lonRight - 1))\
/ MAX (0.1, cos (DEG_TO_RAD * (dispZone->latMax + dispZone->latMin)/2));
scaleX = getX (round ((dispZone->lonLeft + dispZone->lonRight) / 2.0 + 1));
scaleY = getY (ceil (dispZone->latMin));
cairo_move_to (cr, scaleX, scaleY);
cairo_line_to (cr, scaleX + scaleLen, scaleY);
cairo_stroke(cr);
cairo_move_to (cr, scaleX, scaleY - 15);
snprintf (line, MAX_SIZE_LINE, "Lon: %d miles", val);
cairo_show_text (cr, line);
cairo_stroke(cr);
cairo_move_to (cr, scaleX, scaleY - DELTA);
cairo_line_to (cr, scaleX, scaleY + DELTA);
cairo_stroke(cr);
cairo_move_to (cr, scaleX + scaleLen, scaleY - DELTA);
cairo_line_to (cr, scaleX + scaleLen, scaleY + DELTA);
cairo_stroke(cr);
}
/* Provide resume of information */
static void drawInfo (cairo_t *cr, int width, int height) {
double lat, lon, distToDest;
char str [MAX_SIZE_BUFFER];
char strDate [MAX_SIZE_LINE];
const guint INFO_X = 30;
const guint INFO_Y = 50;
const int DELTA = 50;
cairo_select_font_face(cr, "Courier", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
CAIRO_SET_SOURCE_RGB_DARK_GRAY(cr);
cairo_set_font_size (cr, 30.0);
char fileName [MAX_SIZE_FILE_NAME];
buildRootName (par.traceFileName, fileName);
double od, ld, rd, sog;
if (infoDigest (fileName, &od, &ld, &rd, &sog)) {
snprintf (str, MAX_SIZE_LINE, "Miles from Origin...: %8.2lf, Real Dist.......: %.2lf", od, rd);
}
else fprintf (stderr, "Error in distance trace calculation");
cairo_move_to (cr, INFO_X, INFO_Y);
cairo_show_text (cr, str);
if (my_gps_data.OK) {
lat = my_gps_data.lat;
lon = my_gps_data.lon;
}
else {
lat = par.pOr.lat;
lon = par.pOr.lon;
}
distToDest = orthoDist (lat, lon, par.pDest.lat, par.pDest.lon);
snprintf (str, MAX_SIZE_LINE, "Miles to Destination: %8.2lf", distToDest);
cairo_move_to (cr, INFO_X, INFO_Y + DELTA);
cairo_show_text (cr, str);
if (route.n > 0) {
newDateWeekDay (zone.dataDate [0], zone.dataTime [0]/100 + par.startTimeInHours + route.duration, strDate);
snprintf (str, MAX_SIZE_BUFFER, "By Sail to Dest.....: %8.2lf, Expected arrival: %s", route.totDist, strDate);
cairo_move_to (cr, INFO_X, INFO_Y + 2 * DELTA);
cairo_show_text (cr, str);
}
}
/*! draw grid with meridians and parallels */
static void drawGrid (cairo_t *cr, DispZone *dispZone, int step) {
const int MAX_LAT = 85;
CAIRO_SET_SOURCE_RGB_LIGHT_GRAY (cr);
cairo_set_line_width(cr, 0.5);
// meridians
for (int intLon = MAX (-180, dispZone->lonLeft); intLon < MIN (180, dispZone->lonRight); intLon += step) {
cairo_move_to (cr, getX (intLon), getY (MAX_LAT));
cairo_line_to (cr, getX (intLon), getY (-MAX_LAT));
cairo_stroke(cr);
}
// parallels
for (int intLat = MAX (-MAX_LAT, dispZone->latMin); intLat <= MIN (MAX_LAT, dispZone->latMax); intLat += MIN (step, MAX_LAT)) {
cairo_move_to (cr, dispZone->xR, getY (intLat));
cairo_line_to (cr, dispZone->xL, getY (intLat));
cairo_stroke(cr);
}
}
/*! exit when timeout expire */
static gboolean exitOnTimeOut (gpointer data) {
printf ("exit on time out\n");
exit (EXIT_SUCCESS);
}
/* draw barbules or arrows */
static void drawBarbulesArrows (cairo_t *cr) {
double u, v, gust, w, twd, tws, uCurr, vCurr, currTwd, currTws, head_x, head_y, lat, lon;
double tDeltaCurrent = zoneTimeDiff (¤tZone, &zone);
int nCall = 0;
lat = dispZone.latMin;
while (lat <= dispZone.latMax) {
lon = dispZone.lonLeft;
while (lon <= dispZone.lonRight) {
u = 0; v = 0; w = 0; uCurr = 0; vCurr = 0;
if (isInZone (lat, lon, &zone) || (par.constWindTws > 0)) {
findWindGrib (lat, lon, theTime, &u, &v, &gust, &w, &twd, &tws);
nCall ++;
if (par.windDisp == BARBULE) {
double val = (par.averageOrGustDisp == 0) ? tws : MAX (tws, MS_TO_KN * gust);
barbule (cr, lat, lon, u, v, val, WIND);
}
else if (par.windDisp == ARROW) {
head_x = getX (lon);
head_y = getY (lat);
arrow (cr, head_x, head_y, u, v, twd, tws, WIND);
}
if (par.waveDisp) showWaves (cr, lat, lon, w);
if (par.currentDisp) {
findCurrentGrib (lat, lon, theTime - tDeltaCurrent, &uCurr, &vCurr, &currTwd, &currTws);
barbule (cr, lat, lon, uCurr, vCurr, currTws, CURRENT);
}
}
lon += (dispZone.lonStep) / 2;
}
lat += (dispZone.latStep) / 2;
}
// printf ("nCall in drawBarbulesArrows to findWind: %d\n", nCall);
}
/*! draw the main window */
static void drawGribCallback (GtkDrawingArea *area, cairo_t *cr, \
int width, int height, gpointer user_data) {
guint8 r, g, b;
int iSurface = (int) theTime;
if (iSurface > MAX_N_SURFACE) {
fprintf (stderr, "In drawGribCallBack: MAX_N_SURFACE exceeded: %d\n", MAX_N_SURFACE);
exit (EXIT_FAILURE);
}
dispZone.xL = 0; // right
dispZone.xR = width; // left
dispZone.yT = 0; // top
dispZone.yB = height; // bottom
CAIRO_SET_SOURCE_RGB_WHITE (cr);
cairo_paint (cr); // clear all
if (par.showColors != 0) {
if (par.constWindTws != 0) { // const Wind
mapColors (par.constWindTws, &r, &g, &b);
cairo_set_source_rgba (cr, r/255.0, g/255.0, b/255.0, 0.5);
cairo_rectangle (cr, 1, 1, width, height);
cairo_fill(cr);
}
else {
if (!existSurface [iSurface])
createWindSurface (cr, iSurface, width, height);
cairo_set_source_surface (cr, surface[iSurface], 0, 0);
cairo_paint(cr);
}
}
// paintDayNight (cr, width, height);
drawShpMap (cr);
drawGrid (cr, &dispZone, (par.gridDisp) ? 1: 90); // if gridDisp, every degree. Else only every 90°
drawScale (cr, &dispZone);
drawBarbulesArrows (cr);
calculateOrthoRoute ();
drawOrthoRoute (cr, ORTHO_ROUTE_PARAM);
drawLoxoRoute (cr);
if ((route.n != 0) && (isfinite(route.totDist)) && (route.totDist > 0)) {
drawAllIsochrones (cr, par.style);
drawAllRoutes (cr);
//Pp selectedPt = isocArray [nIsoc - 1][selectedPointInLastIsochrone]; // selected point in last isochrone
//circle (cr, selectedPt.lon, selectedPt.lat, 1.0, 0.0, 1.1);
}
focusOnPointInRoute (cr);
if (destPressed) {
showUnicode (cr, DESTINATION_UNICODE, getX (par.pDest.lon), getY (par.pDest.lat) - 20);
circle (cr, par.pDest.lon, par.pDest.lat, 0.0, 0.0, 1.0);
}
circle (cr, par.pOr.lon, par.pOr.lat, 0.0, 1.0, 0.0);
if (my_gps_data.OK)
circle (cr, my_gps_data.lon, my_gps_data.lat , 1.0, 0.0, 0.0);
if (polygonStarted) {
for (int i = 0; i < forbidZones [par.nForbidZone].n ; i++) {
// printf ("polygonStart i = %d\n", i);
circle (cr, forbidZones [par.nForbidZone].points [i].lon, forbidZones [par.nForbidZone].points [i].lat, 1.0, 0, 0);
}
// cairo_fill_preserve(cr);
}
drawPoi (cr);
// Dessin egalement le rectangle de selection si en cours de selection
if (selecting) {
CAIRO_SET_SOURCE_RGBA_SELECTION(cr);
cairo_rectangle (cr, whereWasMouse.x, whereWasMouse.y, whereIsMouse.x - whereWasMouse.x, whereIsMouse.y - whereWasMouse.y);
cairo_fill(cr);
}
drawForbidArea (cr);
if (par.special) {
onRunButtonClicked ();
g_timeout_add (QUIT_TIME_OUT, exitOnTimeOut, NULL);
}
drawTrace (cr);
if (par.infoDisp)
drawInfo (cr, width, height);
//printf ("Time drawGribCallback: %.4f ms\n", (1000 * (double) (clock () - debut)) / CLOCKS_PER_SEC);
}
/*! draw the polar circles and scales */
static void polarTarget (cairo_t *cr, int type, double width, double height, double rStep) {
PolMat *ptMat = (type == WAVE_POLAR) ? &wavePolMat : &polMat;
double nStep = ceil (maxValInPol (ptMat));
char str [MAX_SIZE_NUMBER];
if (type == WAVE_POLAR) {
nStep = nStep/10;
rStep = rStep *10;
}
int rMax = rStep * nStep;
double centerX = width / 2;
double centerY = height / 2;
const int MIN_R_STEP_SHOW = 12;
CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr);
for (int i = 1; i <= nStep; i++)
cairo_arc (cr, centerX, centerY, i * rStep, -G_PI/2, G_PI/2); //trace cercle
for (double angle = -90; angle <= 90; angle += 22.5) { // segments
cairo_move_to (cr, centerX, centerY);
cairo_rel_line_to (cr, rMax * cos (DEG_TO_RAD * angle),
rMax * sin (DEG_TO_RAD * angle));
}
cairo_stroke(cr);
CAIRO_SET_SOURCE_RGB_DARK_GRAY(cr);
// libelles vitesses
for (int i = 1; i <= nStep; i++) {
cairo_move_to (cr, centerX - 40, centerY - i * rStep);
if (type == WAVE_POLAR) {
if ((i % 2) == 0) {// only pair values
snprintf (str, MAX_SIZE_NUMBER, "%2d %%", i * 10);
cairo_show_text (cr, str);
cairo_move_to (cr, centerX - 40, centerY + i * rStep);
cairo_show_text (cr, str);
}
}
else {
if ((rStep > MIN_R_STEP_SHOW) || ((i % 2) == 0)) { // only pair values if too close
snprintf (str, MAX_SIZE_NUMBER, "%2d kn", i);
cairo_show_text (cr, str);
cairo_move_to (cr, centerX - 40, centerY + i * rStep);
cairo_show_text (cr, str);
}
}
}
// libelles angles
for (double angle = -90; angle <= 90; angle += 22.5) {
cairo_move_to (cr, centerX + rMax * cos (DEG_TO_RAD * angle) * 1.05,
centerY + rMax * sin (DEG_TO_RAD * angle) * 1.05);
snprintf (str, MAX_SIZE_NUMBER, "%.2f°", angle + 90);
cairo_show_text (cr, str);
}
cairo_stroke(cr);
}
/*! draw the polar legends */
static void polarLegend (cairo_t *cr, int type) {
double xLeft = 100;
double y = 5;
double hSpace = 18;
char line [MAX_SIZE_LINE];
GdkRGBA color;
PolMat *ptMat = (type == WAVE_POLAR) ? &wavePolMat : &polMat;
cairo_set_line_width (cr, 1);
CAIRO_SET_SOURCE_RGB_GRAY(cr);
cairo_rectangle (cr, xLeft, y, 120, ptMat->nCol * hSpace);
cairo_stroke(cr);
cairo_set_line_width (cr, 1);
xLeft += 20;
y += hSpace;
for (int c = 1; c < ptMat->nCol; c++) {
color = colors [c % nColors];
cairo_set_source_rgba (cr, color.red, color.green, color.blue, color.alpha);
cairo_move_to (cr, xLeft, y);
snprintf (line, MAX_SIZE_LINE, (type == WAVE_POLAR) ? "Height at %.2lf m" : "Wind at %.2lf kn", ptMat->t [0][c]);
cairo_show_text (cr, line);
y += hSpace;
}
cairo_stroke(cr);
}
/*! return x and y in polar */
static void getPolarXYbyValue (int type, int l, double w, double width, \
double height, double radiusFactor, double *x, double *y) {
PolMat *ptMat = (type == WAVE_POLAR) ? &wavePolMat : &polMat;
double angle = (90 - ptMat->t [l][0]) * DEG_TO_RAD; // convert to Radius
double val = findPolar (ptMat->t [l][0], w, *ptMat);
double radius = val * radiusFactor;
*x = width / 2 + radius * cos(angle);
*y = height / 2 - radius * sin(angle);
}
/*! return x and y in polar */
static void getPolarXYbyCol (int type, int l, int c, double width, \
double height, double radiusFactor, double *x, double *y) {
PolMat *ptMat = (type == WAVE_POLAR) ? &wavePolMat : &polMat;
double angle = (90 - ptMat->t [l][0]) * DEG_TO_RAD; // Convert to Radius
double radius = ptMat->t [l][c] * radiusFactor;
*x = width / 2 + radius * cos(angle);
*y = height / 2 - radius * sin(angle);
}
/*! Draw polar from polar matrix */
static void drawPolarBySelectedTws (cairo_t *cr, int polarType, PolMat *ptMat,
double selectedTws, double width, double height, double radiusFactor) {
char line [MAX_SIZE_LINE];
double x, y, x1, x2, y1, y2, vmgAngle, vmgSpeed;
cairo_set_line_width (cr, 5);
CAIRO_SET_SOURCE_RGBA_POLAR_TWS (cr);
getPolarXYbyValue (polarType, 1, selectedTws, width, height, radiusFactor, &x, &y);
cairo_move_to (cr, x, y);
// segments
if (segmentOrBezier == SEGMENT) {
for (int l = 2; l < ptMat->nLine; l += 1) {
getPolarXYbyValue (polarType, l, selectedTws, width, height, radiusFactor, &x, &y);
cairo_line_to (cr, x, y);
}
}
// draw Bezier if number of points exceed threshold
else {
for (int l = 2; l < ptMat->nLine - 2; l += 3) {
getPolarXYbyValue (polarType, l, selectedTws, width, height, radiusFactor, &x, &y);
getPolarXYbyValue (polarType, l+1, selectedTws, width, height, radiusFactor, &x1, &y1);
getPolarXYbyValue (polarType, l+2, selectedTws, width, height, radiusFactor, &x2, &y2);
cairo_curve_to(cr, x, y, x1, y1, x2, y2);
}
getPolarXYbyValue (polarType, ptMat->nLine -1, selectedTws, width, height, radiusFactor, &x, &y);
cairo_line_to(cr, x, y);
}
cairo_stroke(cr);
if (polarType == POLAR) {
bestVmg (selectedTws, &polMat, &vmgAngle, &vmgSpeed);
double ceilSpeed = ceil (maxValInPol (&polMat));
if (vmgSpeed > 0) {
cairo_set_line_width (cr, 0.5);
cairo_move_to (cr, width/2, height/2);
cairo_line_to (cr, width/2, height/2 - vmgSpeed * radiusFactor);
cairo_line_to (cr, width/2 + radiusFactor * ceilSpeed, height/2 - vmgSpeed * radiusFactor);
cairo_stroke(cr);
cairo_move_to (cr, width/2 + 50 + radiusFactor * ceilSpeed, height/2 - vmgSpeed * radiusFactor);
snprintf (line, MAX_SIZE_LINE, "Best VMG at %3.0lf°: %5.2lf Kn", vmgAngle, vmgSpeed);
cairo_show_text (cr, line);
}
bestVmgBack (selectedTws, &polMat, &vmgAngle, &vmgSpeed);
if (vmgSpeed > 0) {
cairo_set_line_width (cr, 0.5);
cairo_move_to (cr, width/2, height/2);
cairo_line_to (cr, width/2, height/2 + vmgSpeed * radiusFactor);
cairo_line_to (cr, width/2 + radiusFactor * ceilSpeed, height/2 + vmgSpeed * radiusFactor);
cairo_stroke(cr);
cairo_move_to (cr, width/2 + 50 + radiusFactor * ceilSpeed, height/2 + vmgSpeed * radiusFactor);
snprintf (line, MAX_SIZE_LINE, "Best Back VMG at %3.0lf°: %5.2lf Kn", vmgAngle, vmgSpeed);
cairo_show_text (cr, line);
}
}
}
/*! Draw polar from polar matrix */
static void drawPolarAll (cairo_t *cr, int polarType, PolMat ptMat,
double width, double height, double radiusFactor) {
double x, y, x1, x2, y1, y2;
cairo_set_line_width (cr, 1);
int minCol = (selectedPol == 0) ? 1 : selectedPol;
int maxCol = (selectedPol == 0) ? ptMat.nCol : selectedPol + 1;
for (int c = minCol; c < maxCol; c++) {
GdkRGBA color = colors [c % nColors];
cairo_set_source_rgba (cr, color.red, color.green, color.blue, color.alpha);
getPolarXYbyCol (polarType, 1, c, width, height, radiusFactor, &x, &y);
cairo_move_to (cr, x, y);
// segments
if (segmentOrBezier == SEGMENT) {
for (int l = 2; l < ptMat.nLine; l += 1) {
getPolarXYbyCol (polarType, l, c, width, height, radiusFactor, &x, &y);
cairo_line_to(cr, x, y);
}
}
// draw Bezier if number of points exceed threshold
else {
for (int l = 2; l < ptMat.nLine - 2; l += 3) {
getPolarXYbyCol (polarType, l, c, width, height, radiusFactor, &x, &y);
getPolarXYbyCol (polarType, l+1, c, width, height, radiusFactor, &x1, &y1);
getPolarXYbyCol (polarType, l+2, c, width, height, radiusFactor, &x2, &y2);
cairo_curve_to(cr, x, y, x1, y1, x2, y2);
}
getPolarXYbyCol (polarType, ptMat.nLine -1, c, width, height, radiusFactor, &x, &y);
cairo_line_to(cr, x, y);
}
cairo_stroke(cr);
}
}
/*! Draw polar from polar matrix */
static void onDrawPolarEvent (GtkDrawingArea *area, cairo_t *cr, \
int width, int height, gpointer user_data) {
PolMat *ptMat = (polarType == WAVE_POLAR) ? &wavePolMat : &polMat;
//double radiusFactor = (polarType == WAVE_POLAR) ? width / 40 : width / (maxValInPol (ptMat) * 5); // Ajustez la taille de la courbe
double radiusFactor;
radiusFactor = width / (maxValInPol (ptMat) * 6); // Ajust size of drawing
polarTarget (cr, polarType, width, height, radiusFactor);
polarLegend (cr, polarType);
drawPolarAll (cr, polarType, *ptMat, width, height, radiusFactor);
drawPolarBySelectedTws (cr, polarType, ptMat, selectedTws, width, height, radiusFactor);
if (polarDrawingArea != NULL)
gtk_widget_queue_draw (polarDrawingArea);
}
/*! callback DropDown to find index in polar to draw */
static void cbPolarFilterDropDown (GObject *dropDown, GParamSpec *pspec, gpointer user_data) {
selectedPol = gtk_drop_down_get_selected (GTK_DROP_DOWN(dropDown));
if (polarDrawingArea != NULL)
gtk_widget_queue_draw (polarDrawingArea);
}
/*! combo filter zone for polar */
static GtkWidget *create_filter_combo (int type) {
PolMat *ptMat = (type == WAVE_POLAR) ? &wavePolMat : &polMat;
char str [MAX_SIZE_LINE];
// Create GlistStore to store strings
GtkStringList *string_list = gtk_string_list_new (NULL);
gtk_string_list_append (string_list, "All");
for (int c = 1; c < ptMat->nCol; c++) {
snprintf (str, sizeof (str), "%.2lf %s", ptMat->t [0][c], (type == WAVE_POLAR) ? "m. Wave Height" : "Knots. Wind Speed.");
gtk_string_list_append (string_list, str);
}
// Create dropdown
GtkWidget *dropDown = gtk_drop_down_new(G_LIST_MODEL(string_list), NULL);
gtk_drop_down_set_selected(GTK_DROP_DOWN(dropDown), 0);
g_signal_connect(dropDown, "notify::selected", G_CALLBACK(cbPolarFilterDropDown), NULL);
return dropDown;
}
/*! display polar matrix */
static void polarDump () {
PolMat *ptMat = (polarType == WAVE_POLAR) ? &wavePolMat : &polMat;
GtkWidget *label;
char str [MAX_SIZE_LINE] = "Polar Grid: ";
GtkWidget *dumpWindow = gtk_application_window_new (app);
g_strlcat (str, (polarType == WAVE_POLAR) ? par.wavePolFileName : par.polarFileName, MAX_SIZE_LINE);
gtk_window_set_title(GTK_WINDOW(dumpWindow), str);
g_signal_connect (window, "destroy", G_CALLBACK (onParentDestroy), dumpWindow);
// g_signal_connect (G_OBJECT(dumpWindow), "destroy", G_CALLBACK (gtk_window_destroy), NULL);
// Scroll
GtkWidget *scrolled_window = gtk_scrolled_window_new ();
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_window_set_child (GTK_WINDOW (dumpWindow), (GtkWidget *) scrolled_window);
gtk_widget_set_size_request (scrolled_window, 800, 400);
// grid creation
GtkWidget *grid = gtk_grid_new();
gtk_scrolled_window_set_child (GTK_SCROLLED_WINDOW (scrolled_window), (GtkWidget *) grid);
if ((ptMat->nCol == 0) || (ptMat->nLine == 0)) {
infoMessage ("No polar information", GTK_MESSAGE_ERROR);
return;
}
for (int line = 0; line < ptMat->nLine; line++) {
for (int col = 0; col < ptMat->nCol; col++) {
if ((col == 0) && (line == 0)) strcpy (str, (polarType == WAVE_POLAR) ? "Angle/Height" : "TWA/TWS");
else snprintf (str, sizeof (str), "%6.2f", ptMat->t [line][col]);
label = gtk_label_new (str);
gtk_grid_attach(GTK_GRID (grid), label, col, line, 1, 1);
gtk_widget_set_size_request (label, MAX_TEXT_LENGTH * 10, -1);
// Add distinct proportes for first line and first column
if (line == 0 || col == 0) {
// set in bold
PangoAttrList *attrs = pango_attr_list_new();
PangoAttribute *attr = pango_attr_weight_new(PANGO_WEIGHT_BOLD);
pango_attr_list_insert (attrs, attr);
gtk_label_set_attributes (GTK_LABEL(label), attrs);
pango_attr_list_unref (attrs);
}
}
}
gtk_window_present (GTK_WINDOW (dumpWindow));
}
/*! launch system command in a thread */
void* editPolarRun (void *data) {
FILE *fs;
char fileName [MAX_SIZE_FILE_NAME] = "";
char line [MAX_SIZE_LINE] = "";
strncpy (fileName, (polarType == WAVE_POLAR) ? par.wavePolFileName : par.polarFileName, sizeof (fileName));
snprintf (line, sizeof (line), "%s %s \n", par.spreadsheet, fileName);
printf ("editPolarRun: %s\n", line);
if ((fs = popen (line, "r")) == NULL)
fprintf (stderr, "Error in editPolarRun: popen call: %s\n", line);
else {
pclose (fs);
readPolar (fileName, (polarType == WAVE_POLAR) ? &wavePolMat : &polMat);
gtk_widget_queue_draw (polarDrawingArea);
}
return NULL;
}
/*! callback function in polar for edit */
static void onEditButtonPolarClicked (GtkWidget *widget, gpointer data) {
g_thread_new ("editPolar", editPolarRun, NULL);
}
/*! Callback radio button selecting provider for segment or bezier */
static void segmentOrBezierButtonToggled (GtkToggleButton *button, gpointer user_data) {
segmentOrBezier = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "index"));
if (polarDrawingArea != NULL)
gtk_widget_queue_draw (polarDrawingArea);
}
/*! Callback for polar to change scale calue */
static void onScaleValueChanged (GtkScale *scale) {
char str [MAX_SIZE_LINE];
snprintf (str, sizeof (str), (polarType == WAVE_POLAR) ? "%.2lf Meters" : "%.2lf Kn", selectedTws);
gtk_label_set_text (GTK_LABEL(scaleLabel), str);
selectedTws = gtk_range_get_value(GTK_RANGE(scale));
if (polarDrawingArea != NULL)
gtk_widget_queue_draw (polarDrawingArea);
}
/*! Draw polar from polar file */
static void polarDraw () {
char line [MAX_SIZE_LINE] = "Polar: ";
char sStatus [MAX_SIZE_LINE], str [MAX_SIZE_LINE];
PolMat *ptMat = (polarType == WAVE_POLAR) ? &wavePolMat : &polMat;
selectedTws = 0;
if ((ptMat->nCol == 0) || (ptMat->nLine == 0)) {
infoMessage ("No polar information", GTK_MESSAGE_ERROR);
return;
}
// Main window creation
GtkWidget *polWindow = gtk_application_window_new (app);
gtk_window_set_default_size(GTK_WINDOW (polWindow), POLAR_WIDTH, POLAR_HEIGHT);
g_strlcat (line, (polarType == WAVE_POLAR) ? par.wavePolFileName : par.polarFileName, MAX_SIZE_LINE);
gtk_window_set_title (GTK_WINDOW (polWindow), line);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), polWindow);
// g_signal_connect (polWindow, "destroy", G_CALLBACK(gtk_window_destroy), NULL);
// vertical box container creation
GtkWidget *vBox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (polWindow), vBox);
// drawing area creation
polarDrawingArea = gtk_drawing_area_new ();
gtk_widget_set_hexpand (polarDrawingArea, TRUE);
gtk_widget_set_vexpand (polarDrawingArea, TRUE);
gtk_widget_set_size_request (polarDrawingArea, POLAR_WIDTH, POLAR_HEIGHT - 100);
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (polarDrawingArea), onDrawPolarEvent, NULL, NULL);
// create zone for combo box
GtkWidget *filter_combo = create_filter_combo (polarType);
GtkWidget *dumpButton = gtk_button_new_from_icon_name ("x-office-spreadsheet-symbolic");
g_signal_connect(G_OBJECT(dumpButton), "clicked", G_CALLBACK (polarDump), NULL);
GtkWidget *editButton = gtk_button_new_from_icon_name ("document-edit-symbolic");
g_signal_connect(G_OBJECT(editButton), "clicked", G_CALLBACK (onEditButtonPolarClicked), NULL);
// radio button for bezier or segment choice
GtkWidget *segmentRadio = gtk_check_button_new_with_label ("Segment");
GtkWidget *bezierRadio = gtk_check_button_new_with_label ("Bézier");
gtk_check_button_set_group ((GtkCheckButton *) segmentRadio, (GtkCheckButton *)bezierRadio);
g_object_set_data (G_OBJECT(segmentRadio), "index", GINT_TO_POINTER (SEGMENT));
g_object_set_data (G_OBJECT(bezierRadio), "index", GINT_TO_POINTER (BEZIER));
g_signal_connect (segmentRadio, "toggled", G_CALLBACK (segmentOrBezierButtonToggled), NULL);
g_signal_connect (bezierRadio, "toggled", G_CALLBACK (segmentOrBezierButtonToggled), NULL);
segmentOrBezier = (ptMat->nLine < MIN_POINT_FOR_BEZIER) ? SEGMENT : BEZIER;
gtk_check_button_set_active ((GtkCheckButton *) ((segmentOrBezier == SEGMENT) ? segmentRadio : bezierRadio), TRUE);
// GtkScale widget creation
int maxScale = ptMat->t[0][ptMat->nCol-1]; // max value of wind or waves
// printf ("maxScale: %d\n", maxScale);
GtkWidget *scale = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, 0, maxScale, 1);
gtk_scale_set_value_pos(GTK_SCALE(scale), GTK_POS_TOP);
gtk_range_set_value(GTK_RANGE(scale), selectedTws);
gtk_widget_set_size_request (scale, 300, -1); // Adjust GtkScale size
g_signal_connect (scale, "value-changed", G_CALLBACK (onScaleValueChanged), NULL);
snprintf (str, sizeof (str), (polarType == WAVE_POLAR) ? "%.2lf Meters": "%.2f Kn", selectedTws);
scaleLabel = gtk_label_new (str);
GtkWidget *hBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
gtk_box_append (GTK_BOX (hBox), filter_combo);
gtk_box_append (GTK_BOX (hBox), segmentRadio);
gtk_box_append (GTK_BOX (hBox), bezierRadio);
gtk_box_append (GTK_BOX (hBox), dumpButton);
gtk_box_append (GTK_BOX (hBox), editButton);
gtk_box_append (GTK_BOX (hBox), scale);
gtk_box_append (GTK_BOX (hBox), scaleLabel);
GtkWidget *separator = gtk_separator_new (GTK_ORIENTATION_HORIZONTAL);
// status bar creation
snprintf (sStatus, sizeof (sStatus), "nCol: %2d nLig: %2d max: %2.2lf", \
ptMat->nCol, ptMat->nLine, maxValInPol (ptMat));
GtkWidget *polStatusbar = gtk_label_new (sStatus);
gtk_box_append (GTK_BOX (vBox), hBox);
gtk_box_append (GTK_BOX (vBox), polarDrawingArea);
gtk_box_append (GTK_BOX (vBox), separator);
gtk_box_append (GTK_BOX (vBox), polStatusbar);
if (polarDrawingArea != NULL)
gtk_widget_queue_draw (polarDrawingArea);
gtk_window_present (GTK_WINDOW (polWindow));
}
/*! time management init */
static void initStart (struct tm *start) {
long intDate = zone.dataDate [0];
long intTime = zone.dataTime [0];
start->tm_year = (intDate / 10000) - 1900;
start->tm_mon = ((intDate % 10000) / 100) - 1;
start->tm_mday = intDate % 100;
start->tm_hour = intTime / 100;
start->tm_min = intTime % 100;
start->tm_isdst = -1; // avoid adjustments with hours summer winter
start->tm_sec += 3600 * par.startTimeInHours; // add seconds
mktime (start);
}
/*! calculate difference in hours between departure time and time 0 */
static double getDepartureTimeInHour (struct tm *start) {
time_t theTime0 = gribDateTimeToEpoch (zone.dataDate [0], zone.dataTime [0]);
start->tm_isdst = -1; // avoid adjustments with hours summer winter
time_t startTime = mktime (start);
return (startTime - theTime0)/3600.0; // calculated in hours
}
/*! when OK in calendar is clicked */
static void onOkButtonCalClicked(GtkWidget *widget, gpointer window) {
gtk_window_destroy(GTK_WINDOW(window));
// printf ("startInfo before: %s, startTime: %lf\n", asctime (&startInfo), par.startTimeInHours);
par.startTimeInHours = getDepartureTimeInHour (&startInfo);
// printf ("startInfo after: %s, startTime: %lf\n", asctime (&startInfo), par.startTimeInHours);
if ((par.startTimeInHours < 0) || (par.startTimeInHours > zone.timeStamp [zone.nTimeStamp -1])) {
gtk_window_destroy (GTK_WINDOW (window));
infoMessage ("start time should be within grib window time !", GTK_MESSAGE_WARNING);
}
else {
route.ret = 0; // mean routing not terminated
g_thread_new ("routingLaunch", routingLaunch, NULL); // launch routing
routingTimeout = g_timeout_add (ROUTING_TIME_OUT, routingCheck, NULL);
spinner ("Isochrone building", " ");
}
}
/*! when now in calendar is clicked */
static void onNowButtonCalClicked (GtkWidget *widget, gpointer window) {
time_t currentTime = time (NULL);
struct tm *gmtTime = gmtime (¤tTime);
startInfo = *gmtTime;
gtk_window_destroy (GTK_WINDOW(window));
onOkButtonCalClicked (widget, window);
}
/*! year month date for fCalendar */
static void dateUpdate (GtkCalendar *calendar, gpointer user_data) {
GDateTime *date = gtk_calendar_get_date (calendar);
startInfo.tm_sec = 0;
startInfo.tm_sec = 0;
startInfo.tm_isdst = -1; // avoid adjustments with hours summer winter
startInfo.tm_mday = g_date_time_get_day_of_month (date);
startInfo.tm_mon = g_date_time_get_month (date) - 1;
startInfo.tm_year = g_date_time_get_year (date) - 1900;
}
/*! get start date and time for routing. Returns true if OK Response */
static void fCalendar (struct tm *start) {
char str [MAX_SIZE_LINE];
time_t currentTime = time (NULL);
struct tm *gmtTime = gmtime(¤tTime);
snprintf (str, sizeof (str), "%d/%02d/%02d %02d:%02d UTC", gmtTime->tm_year + 1900, gmtTime->tm_mon + 1,
gmtTime->tm_mday, gmtTime->tm_hour, gmtTime->tm_min);
GtkWidget *calWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (calWindow), "Pick a Date");
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), calWindow);
GtkWidget *vBox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (calWindow), (GtkWidget *) vBox);
GtkWidget *calendar = gtk_calendar_new();
GDateTime *date = g_date_time_new_utc (start->tm_year + 1900, start->tm_mon + 1, start->tm_mday, 0, 0, 0);
gtk_calendar_select_day (GTK_CALENDAR(calendar), date);
g_signal_connect(calendar, "day-selected", G_CALLBACK (dateUpdate), NULL);
g_date_time_unref (date);
// Create labels and selection buttons
GtkWidget *labelHour = gtk_label_new("Hour");
GtkWidget *spinHour = gtk_spin_button_new_with_range(0, 23, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinHour), start->tm_hour);
g_signal_connect (spinHour, "value-changed", G_CALLBACK (intSpinUpdate), &start->tm_hour);
GtkWidget *labelMinutes = gtk_label_new("Minutes");
GtkWidget *spinMinutes = gtk_spin_button_new_with_range(0, 59, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinMinutes), start->tm_min);
g_signal_connect (spinMinutes, "value_changed", G_CALLBACK (intSpinUpdate), &start->tm_min);
// Create horizontal box
GtkWidget *hBox0 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5);
gtk_box_append (GTK_BOX (hBox0), labelHour);
gtk_box_append (GTK_BOX (hBox0), spinHour);
gtk_box_append (GTK_BOX (hBox0), labelMinutes);
gtk_box_append (GTK_BOX (hBox0), spinMinutes);
// Create last horizontal box
GtkWidget *hBox1 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
GtkWidget *nowButton = gtk_button_new_with_label (str);
GtkWidget *OKbutton = gtk_button_new_with_label ("OK");
GtkWidget *cancelButton = gtk_button_new_with_label ("Cancel");
gtk_box_append (GTK_BOX(hBox1), nowButton);
gtk_box_append (GTK_BOX(hBox1), OKbutton);
gtk_box_append (GTK_BOX(hBox1), cancelButton);
gtk_box_append (GTK_BOX (vBox), calendar);
gtk_box_append (GTK_BOX (vBox), hBox0);
gtk_box_append (GTK_BOX (vBox), hBox1);
g_signal_connect (nowButton, "clicked", G_CALLBACK (onNowButtonCalClicked), calWindow);
g_signal_connect (OKbutton, "clicked", G_CALLBACK (onOkButtonCalClicked), calWindow);
g_signal_connect (cancelButton, "clicked", G_CALLBACK (onCancelButtonClicked), calWindow);
gtk_window_present (GTK_WINDOW (calWindow));
}
/*! one line for niceReport () */
static void lineReport (GtkWidget *grid, int l, const char* iconName, const char *libelle, const char *value) {
GtkWidget *icon = gtk_button_new_from_icon_name (iconName);
GtkWidget *label = gtk_label_new (libelle);
gtk_grid_attach(GTK_GRID (grid), icon, 0, l, 1, 1);
gtk_label_set_yalign(GTK_LABEL(label), 0);
gtk_label_set_xalign(GTK_LABEL(label), 0);
gtk_grid_attach(GTK_GRID (grid), label,1, l, 1, 1);
GtkWidget *labelValue = gtk_label_new (value);
gtk_label_set_yalign(GTK_LABEL(labelValue), 0);
gtk_label_set_xalign(GTK_LABEL(labelValue), 1);
GtkWidget *separator = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
// add separator to grid
gtk_grid_attach (GTK_GRID (grid), labelValue, 2, l, 1, 1);
gtk_grid_attach(GTK_GRID(grid), separator, 0, l + 1, 3, 1);
gtk_widget_set_margin_end(GTK_WIDGET(labelValue), 20);
}
/*! draw legend */
static void drawLegend (cairo_t *cr, guint leftX, guint topY, double colors [][3], char *libelle [], size_t maxColors) {
const int DELTA = 12;
const int RECTANGLE_WIDTH = 55;
CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr);
cairo_rectangle (cr, leftX, topY, RECTANGLE_WIDTH, (maxColors + 1) * DELTA);
cairo_stroke (cr);
cairo_set_font_size (cr, 12);
for (int i = 0; i < maxColors; i++) {
cairo_set_source_rgb (cr, colors[i][0], colors[i][1], colors[i][2]);
cairo_move_to (cr, leftX + DELTA /2, topY + (i + 1) * DELTA);
cairo_show_text (cr, libelle [i]);
}
}
/*! call back to draw statistics */
static void onStatEvent (GtkDrawingArea *drawing_area, cairo_t *cr, int width, int height, gpointer user_data) {
#define MAX_VAL 3
width *= 0.9;
height *= 0.9;
const int LEGEND_X_LEFT = width - 35;
const int LEGEND_Y_TOP = 10;
double statValues [MAX_VAL];
statValues [0] = route.motorDist;
statValues [1] = route.tribordDist;
statValues [2] = route.babordDist;
const double EPSILON_DASHBOARD = 1.0;
double total = 0;
for (int i = 0; i < MAX_VAL; i++) {
total += statValues[i];
}
if (total < 1.0)
return;
// Legend
char *libelle [MAX_VAL] = {"Motor", "Tribord", "Babord"};
double colors[MAX_VAL][3] = {{1, 0, 0}, {0.5, 0.5, 0.5}, {0, 0, 0}}; // Red Gray Black
drawLegend (cr, LEGEND_X_LEFT, LEGEND_Y_TOP, colors, libelle, MAX_VAL);
double start_angle = 0;
for (int i = 0; i < MAX_VAL; i++) {
double slice_angle = (statValues[i] / total) * 360.0;
if (slice_angle < EPSILON_DASHBOARD) continue;
// Define segment color and draw segment
cairo_set_source_rgb(cr, colors[i][0], colors[i][1], colors[i][2]);
cairo_move_to(cr, width / 2, height / 2);
cairo_arc(cr, width / 2, height / 2, MIN(width, height) / 2, start_angle * DEG_TO_RAD, (start_angle + slice_angle) * DEG_TO_RAD);
cairo_close_path(cr);
cairo_fill(cr);
start_angle += slice_angle;
}
// percentage and libelle
CAIRO_SET_SOURCE_RGB_WHITE(cr);
start_angle = 0;
for (int i = 0; i < MAX_VAL; i++) {
double slice_angle = (statValues[i] / total) * 360.0;
if (slice_angle < EPSILON_DASHBOARD) continue;
// update percentage text position
double mid_angle = start_angle + slice_angle / 2;
double x = (width / 2) + (MIN(width, height) / 4) * cos(mid_angle * DEG_TO_RAD);
double y = (height / 2) + (MIN(width, height) / 4) * sin(mid_angle * DEG_TO_RAD);
char percentage [MAX_SIZE_LINE];
if (statValues [i] > 0) {
snprintf(percentage, sizeof(percentage), "%.0f%%", (statValues[i] / total) * 100);
cairo_move_to(cr, x, y);
cairo_show_text(cr, percentage);
}
start_angle += slice_angle;
}
}
/*! call back to draw allure statistics */
static void onAllureEvent (GtkDrawingArea *drawing_area, cairo_t *cr, int width, int height, gpointer user_data) {
#define MAX_ALLURES 3
width *= 0.9;
height *= 0.9;
const int LEGEND_X_LEFT = width - 35;
const int LEGEND_Y_TOP = 10;
double twa;
double statValues [MAX_ALLURES] = {0};
const int threshold [MAX_ALLURES] = {60, 120, 180};
const double EPSILON_DASHBOARD = 1.0;
double total = 0;
// calculate stat on allures
for (int i = 0; i < route.n; i++) {
if (route.t[i].motor) continue;
twa = fTwa (route.t[i].lCap, route.t[i].twd);
for (int k = 0; k < MAX_ALLURES; k++) {
if (fabs (twa) < threshold [k]) {
statValues [k] += route.t[i].od;
break;
}
}
}
for (int i = 0; i < MAX_VAL; i++) {
total += statValues[i];
}
if (total < 1.0)
return;
// legend
double colors[MAX_VAL][3] = {{1, 0, 1}, {1, 165.0/255.0, 0}, {0, 1, 1}}; // Orange in the middle
char *libelle [MAX_ALLURES] = {"Près", "Travers", "Portant"};
drawLegend (cr, LEGEND_X_LEFT, LEGEND_Y_TOP, colors, libelle, MAX_ALLURES);
double start_angle = 0;
for (int i = 0; i < MAX_VAL; i++) {
double slice_angle = (statValues[i] / total) * 360.0;
if (slice_angle < EPSILON_DASHBOARD) continue;
// Define segment color and draw segment
cairo_set_source_rgb(cr, colors[i][0], colors[i][1], colors[i][2]);
cairo_move_to(cr, width / 2, height / 2);
cairo_arc(cr, width / 2, height / 2, MIN(width, height) / 2, start_angle * DEG_TO_RAD, (start_angle + slice_angle) * DEG_TO_RAD);
cairo_close_path(cr);
cairo_fill(cr);
start_angle += slice_angle;
}
// percentage and libelle
CAIRO_SET_SOURCE_RGB_BLACK(cr);
start_angle = 0;
for (int i = 0; i < MAX_VAL; i++) {
double slice_angle = (statValues[i] / total) * 360.0;
if (slice_angle < EPSILON_DASHBOARD) continue;
// update percentage text position
double mid_angle = start_angle + slice_angle / 2;
double x = (width / 2) + (MIN(width, height) / 4) * cos(mid_angle * DEG_TO_RAD);
double y = (height / 2) + (MIN(width, height) / 4) * sin(mid_angle * DEG_TO_RAD);
char percentage [MAX_SIZE_LINE];
if (statValues [i] > 0) {
snprintf(percentage, sizeof(percentage), "%.0f%%", (statValues[i] / total) * 100);
cairo_move_to(cr, x, y);
cairo_show_text(cr, percentage);
}
start_angle += slice_angle;
}
}
/*! display nice report */
static void niceReport (SailRoute *route, double computeTime) {
char str [MAX_SIZE_LINE];
char totalDate [MAX_SIZE_DATE];
char line [MAX_SIZE_LINE];
char strLat [MAX_SIZE_LINE];
char strLon [MAX_SIZE_LINE];
const int WIDTH = 500;
if (computeTime > 0)
snprintf (line, sizeof (line), "%s Compute Time:%.2lf sec.", (route->destinationReached) ?
"Destination reached" : "Destination unreached", computeTime);
else
snprintf (line,sizeof (line), "%s", (route->destinationReached) ? "Destination reached" : "Destination unreached");
GtkWidget *reportWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW(reportWindow), line);
gtk_widget_set_size_request(reportWindow, WIDTH, -1);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), niceReport);
GtkWidget *vBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (reportWindow), (GtkWidget *) vBox);
GtkWidget *grid = gtk_grid_new();
gtk_grid_set_column_spacing(GTK_GRID(grid), 10);
gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
gtk_grid_set_row_homogeneous(GTK_GRID(grid), FALSE);
gtk_grid_set_column_homogeneous(GTK_GRID(grid), FALSE);
snprintf (line, sizeof (line), "%4d/%02d/%02d %02d:%02d\n",
startInfo.tm_year + 1900, startInfo.tm_mon+1, startInfo.tm_mday, startInfo.tm_hour, startInfo.tm_min);
lineReport (grid, 0, "document-open-recent", "Departure Date and Time", line);
snprintf (line, sizeof (line), "%02d:%02d\n", (int) par.startTimeInHours, (int) (60 * fmod (par.startTimeInHours, 1.0)));
lineReport (grid, 2, "dialog-information-symbolic", "Nb hours:minutes after origin of grib", line);
snprintf (line, sizeof (line), "%d\n", route->nIsoc);
lineReport (grid, 4, "accessories-text-editor-symbolic", "Nb of isochrones", line);
snprintf (line, sizeof (line), "%s %s\n", latToStr (lastClosest.lat, par.dispDms, strLat), lonToStr (lastClosest.lon, par.dispDms, strLon));
lineReport (grid, 6, "emblem-ok-symbolic", "Best Point Reached", line);
snprintf (line, sizeof (line), "%.2lf\n", (route->destinationReached) ? 0 : orthoDist (lastClosest.lat, lastClosest.lon,\
par.pDest.lat, par.pDest.lon));
lineReport (grid, 8, "mail-forward-symbolic", "Distance To Destination", line);
snprintf (line, sizeof (line), "%s\n",\
newDate (zone.dataDate [0], zone.dataTime [0]/100 + par.startTimeInHours + route->duration, totalDate));
lineReport (grid, 10, "alarm-symbolic", "Arrival Date and Time", line);
snprintf (line, sizeof (line), "%.2lf\n", route->totDist);
lineReport (grid, 12, "emblem-important-symbolic", "Total Distance in Nautical Miles", line);
snprintf (line, sizeof (line), "%.2lf\n", route->motorDist);
lineReport (grid, 14, "emblem-important-symbolic", "Motor Distance in Nautical Miles", line);
snprintf (line, sizeof (line), "%s\n", durationToStr (route->duration, str, sizeof (str)));
lineReport (grid, 16, "user-away", "Duration", line);
snprintf (line, sizeof (line), "%s\n", durationToStr (route->motorDuration, str, sizeof (str)));
lineReport (grid, 18, "user-away", "Motor Duration", line);
snprintf (line, sizeof (line), "%.2lf\n", route->totDist/route->duration);
lineReport (grid, 20, "utilities-system-monitor-symbolic", "Mean Speed Over Ground", line);
// setup drawing area for stat
GtkWidget *hBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
GtkWidget *stat_drawing_area = gtk_drawing_area_new ();
gtk_widget_set_size_request (stat_drawing_area, WIDTH/2, 150);
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (stat_drawing_area), onStatEvent, NULL, NULL);
GtkWidget *allure_drawing_area = gtk_drawing_area_new ();
gtk_widget_set_size_request (allure_drawing_area, WIDTH/2, 150);
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (allure_drawing_area), onAllureEvent, NULL, NULL);
gtk_box_append (GTK_BOX (hBox), stat_drawing_area);
gtk_box_append (GTK_BOX (hBox), allure_drawing_area);
gtk_box_append (GTK_BOX (vBox), grid);
gtk_box_append (GTK_BOX (vBox), hBox);
gtk_window_present (GTK_WINDOW (reportWindow));
}
/*! check if routing is terminated */
static gboolean routingCheck (gpointer data) {
if (route.ret == 0) { // not terminated
gtk_widget_queue_draw(drawing_area); // affiche le tout
return TRUE;
}
g_source_remove (routingTimeout); // timer stopped
spinnerWindowDestroy ();
if (route.ret == -1) {
infoMessage ("Stopped", GTK_MESSAGE_ERROR);
return TRUE;
}
if (! isfinite (route.totDist) || (route.totDist <= 1)) {
infoMessage ("No route calculated. Check if wind !", GTK_MESSAGE_WARNING);
}
niceReport (&route, route.calculationTime);
selectedPointInLastIsochrone = (nIsoc <= 1) ? 0 : isoDesc [nIsoc -1].closest;
gtk_widget_queue_draw (drawing_area);
return TRUE;
}
/*! launch routing */
static void onRunButtonClicked () {
if (! gpsTrace)
if (addTraceGPS (par.traceFileName))
gpsTrace = true; // only one GPS trace per session
if (! isInZone (par.pOr.lat, par.pOr.lon, &zone) && (par.constWindTws == 0)) {
infoMessage ("Origin point not in wind zone", GTK_MESSAGE_WARNING);
return;
}
if (! isInZone (par.pDest.lat, par.pDest.lon, &zone) && (par.constWindTws == 0)) {
infoMessage ("Destination point not in wind zone", GTK_MESSAGE_WARNING);
return;
}
initStart (&startInfo);
if (par.special == 0)
fCalendar (&startInfo);
}
/*! check if bestDepartureTime is terminated */
static gboolean bestDepartureCheck (gpointer data) {
char str [MAX_SIZE_LINE];
snprintf (str, MAX_SIZE_LINE, "Evaluation count: %d", chooseDeparture.count);
switch (chooseDeparture.ret) {
case RUNNING: // not terminated
snprintf (str, MAX_SIZE_LINE, "Evaluation count: %d", chooseDeparture.count);
gtk_window_set_title(GTK_WINDOW(spinnerWindow), str);
break;;
case NO_SOLUTION:
g_source_remove (routingTimeout); // timer stopped
spinnerWindowDestroy ();
infoMessage ("No solution", GTK_MESSAGE_WARNING);
break;
case STOPPED:
g_source_remove (routingTimeout); // timer stopped
spinnerWindowDestroy ();
infoMessage ("Stopped", GTK_MESSAGE_WARNING);
break;
case EXIST_SOLUTION:
simulationReportExist = true;
g_source_remove (routingTimeout); // timer stopped
spinnerWindowDestroy ();
snprintf (str, MAX_SIZE_LINE, "The quickest trip lasts %.2lf hours, start time: %d hours after beginning of Grib\nSee simulation Report for details",
chooseDeparture.minDuration, chooseDeparture.bestTime);
infoMessage (str, GTK_MESSAGE_WARNING);
initStart (&startInfo);
selectedPointInLastIsochrone = (nIsoc <= 1) ? 0 : isoDesc [nIsoc -1].closest;
niceReport (&route, route.calculationTime);
gtk_widget_queue_draw (drawing_area);
break;
default:
fprintf (stderr, "Error in bestDepartureCheck: Unknown chooseDeparture.ret: %d\n", chooseDeparture.ret);
break;
}
return TRUE;
}
/*! when OK in departure box is clicked */
static void onOkButtonDepClicked (GtkWidget *widget, gpointer theWindow) {
printf ("Response departurep\n");;
chooseDeparture.ret = RUNNING; // mean not terminated
simulationReportExist = false;
g_thread_new ("chooseDepartureLaunch", bestTimeDeparture, NULL); // launch routing
routingTimeout = g_timeout_add (ROUTING_TIME_OUT, bestDepartureCheck, NULL);
spinner ("Simulation Running", "It can take a while !!! ");
gtk_window_destroy(GTK_WINDOW (theWindow));
}
/*! launch all routing in order to choose best departure time */
static void onChooseDepartureButtonClicked (GtkWidget *widget, gpointer data) {
if (! isInZone (par.pOr.lat, par.pOr.lon, &zone) && (par.constWindTws == 0)) {
infoMessage ("Origin point not in wind zone", GTK_MESSAGE_WARNING);
return;
}
if (! isInZone (par.pDest.lat, par.pDest.lon, &zone) && (par.constWindTws == 0)) {
infoMessage ("Destination point not in wind zone", GTK_MESSAGE_WARNING);
return;
}
chooseDeparture.tStep = 1;
chooseDeparture.tBegin = 0;
chooseDeparture.tEnd = zone.timeStamp [zone.nTimeStamp - 1];
GtkWidget *depWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (depWindow), "Simulation");
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), depWindow);
GtkWidget *vBox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (depWindow), (GtkWidget *) vBox);
GtkWidget *grid = gtk_grid_new ();
gtk_grid_set_column_spacing (GTK_GRID(grid), 10);
gtk_grid_set_row_spacing (GTK_GRID(grid), 5);
GtkWidget *label_time_step = gtk_label_new("Time Step");
GtkWidget *spin_button_time_step = gtk_spin_button_new_with_range (1, 12, 1);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_button_time_step), chooseDeparture.tStep);
g_signal_connect (spin_button_time_step, "value-changed", G_CALLBACK (intSpinUpdate), &chooseDeparture.tStep);
gtk_label_set_xalign(GTK_LABEL (label_time_step), 0);
gtk_grid_attach(GTK_GRID (grid), label_time_step, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID (grid), spin_button_time_step, 1, 0, 1, 1);
GtkWidget *label_mini = gtk_label_new("Min Start After Grib");
GtkWidget *spin_button_mini = gtk_spin_button_new_with_range (0, zone.timeStamp [zone.nTimeStamp - 1], 1);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_button_mini), chooseDeparture.tBegin);
g_signal_connect (spin_button_mini, "value-changed", G_CALLBACK (intSpinUpdate), &chooseDeparture.tBegin);
gtk_label_set_xalign(GTK_LABEL (label_mini), 0);
gtk_grid_attach(GTK_GRID (grid), label_mini, 0, 1, 1, 1);
gtk_grid_attach(GTK_GRID (grid), spin_button_mini, 1, 1, 1, 1);
GtkWidget *label_maxi = gtk_label_new("Max Start After Grib");
GtkWidget *spin_button_maxi = gtk_spin_button_new_with_range (1, zone.timeStamp [zone.nTimeStamp - 1], 1);
gtk_spin_button_set_value (GTK_SPIN_BUTTON (spin_button_maxi), chooseDeparture.tEnd);
g_signal_connect (spin_button_maxi, "value-changed", G_CALLBACK (intSpinUpdate), &chooseDeparture.tEnd);
gtk_label_set_xalign(GTK_LABEL (label_maxi), 0);
gtk_grid_attach(GTK_GRID (grid), label_maxi, 0, 2, 1, 1);
gtk_grid_attach(GTK_GRID (grid), spin_button_maxi, 1, 2, 1, 1);
GtkWidget *hBox = OKCancelLine (onOkButtonDepClicked, depWindow);
gtk_box_append (GTK_BOX (vBox), grid);
gtk_box_append (GTK_BOX (vBox), hBox);
gtk_window_present (GTK_WINDOW (depWindow));
}
/*! Callback for stop button */
static void onStopButtonClicked (GtkWidget *widget, gpointer data) {
animation.active = NO_ANIMATION;
if (animation.timer > 0)
g_source_remove (animation.timer);
animation.timer = 0;
}
/*! Callback for animation update */
static gboolean onPlayTimeout (gpointer user_data) {
theTime += par.tStep;
if (theTime > zone.timeStamp [zone.nTimeStamp - 1]) {
theTime = zone.timeStamp [zone.nTimeStamp - 1];
if (animation.timer > 0)
g_source_remove (animation.timer);
animation.active = NO_ANIMATION;
animation.timer = 0;
}
gtk_widget_queue_draw(drawing_area);
statusBarUpdate ();
return animation.active;
}
/*! Callback for animation update */
static gboolean onLoopTimeout (gpointer user_data) {
theTime += par.tStep;
if ((theTime > zone.timeStamp [zone.nTimeStamp - 1]) || (theTime > par.startTimeInHours + route.duration))
theTime = par.startTimeInHours;
gtk_widget_queue_draw(drawing_area);
statusBarUpdate ();
return animation.active;
}
/*! Callback for play button (animation) */
static void onPlayButtonClicked (GtkWidget *widget, gpointer user_data) {
if (animation.active == NO_ANIMATION) {
animation.active = PLAY;
animation.timer = g_timeout_add (animation.tempo [par.speedDisp], (GSourceFunc)onPlayTimeout, NULL);
}
}
/*! Callback for loop button (animation) */
static void onLoopButtonClicked (GtkWidget *widget, gpointer user_data) {
if (route.n == 0) {
infoMessage ("No route !", GTK_MESSAGE_WARNING);
return;
}
if (animation.active == NO_ANIMATION) {
animation.active = LOOP;
if ((theTime < par.startTimeInHours) || (theTime > par.startTimeInHours + route.duration))
theTime = par.startTimeInHours;
gtk_widget_queue_draw (drawing_area);
statusBarUpdate ();
animation.timer = g_timeout_add (animation.tempo [par.speedDisp], (GSourceFunc)onLoopTimeout, NULL);
}
}
/*! change animation timer */
static void changeAnimation () {
if (animation.timer > 0 && animation.active != NO_ANIMATION) {
g_source_remove (animation.timer);
}
if (animation.active == PLAY)
animation.timer = g_timeout_add (animation.tempo [par.speedDisp], (GSourceFunc)onPlayTimeout, NULL);
else
animation.timer = g_timeout_add (animation.tempo [par.speedDisp], (GSourceFunc)onLoopTimeout, NULL);
}
/*! Callback for to start button */
static void onToStartButtonClicked (GtkWidget *widget, gpointer data) {
theTime = 0;
gtk_widget_queue_draw(drawing_area);
statusBarUpdate ();
}
static void onToEndButtonClicked (GtkWidget *widget, gpointer data) {
theTime = zone.timeStamp [zone.nTimeStamp - 1];
gtk_widget_queue_draw(drawing_area);
statusBarUpdate (route.n -1);
}
/*! Callback for reward button */
static void onRewardButtonClicked (GtkWidget *widget, gpointer data) {
// theTime -= zone.timeStamp [1]-zone.timeStamp [0];
theTime -= par.tStep;
if (theTime < 0) theTime = 0;
gtk_widget_queue_draw(drawing_area);
statusBarUpdate ();
}
/*! Callback for Forward button */
static void onForwardButtonClicked (GtkWidget *widget, gpointer data) {
//theTime += zone.timeStamp [1]-zone.timeStamp [0];
theTime += par.tStep;
if (theTime > zone.timeStamp [zone.nTimeStamp - 1])
theTime = zone.timeStamp [zone.nTimeStamp - 1];
gtk_widget_queue_draw(drawing_area);
statusBarUpdate ();
}
/*! display isochrones */
static void isocDump () {
char *buffer = NULL;
const int N_POINT_FACTOR = 1000;
if (nIsoc == 0)
infoMessage ("No isochrone", GTK_MESSAGE_INFO);
else {
if ((buffer = (char *) malloc (nIsoc * MAX_SIZE_LINE * N_POINT_FACTOR)) == NULL)
infoMessage ("Not enough memory", GTK_MESSAGE_ERROR);
else {
allIsocToStr (buffer, nIsoc * MAX_SIZE_LINE * N_POINT_FACTOR);
displayText (750, 400, buffer, "Isochrones");
free (buffer);
}
}
}
/*! display isochrone descriptors */
static void isocDescDump () {
char *buffer = NULL;
if (route.n <= 0)
infoMessage ("No route calculated", GTK_MESSAGE_INFO);
else {
if ((buffer = (char *) malloc (nIsoc * MAX_SIZE_LINE)) == NULL)
infoMessage ("Not enough memory", GTK_MESSAGE_ERROR);
else {
if (isoDescToStr (buffer, nIsoc * MAX_SIZE_LINE))
displayText (750, 400, buffer, "Isochrone Descriptor");
else infoMessage ("Not enough space", GTK_MESSAGE_ERROR);
}
}
}
/*! display Points of Interest information */
static void historyReset () {
route.n = 0;
historyRoute.n = 0;
gtk_widget_queue_draw(drawing_area);
}
/*! Response for new Trace OK */
static void newTraceResponse (GtkWidget *widget, gpointer entryWindow) {
FILE *f;
printf ("Trace name OK: %s\n", traceName);
if ((f = fopen (traceName, "r")) != NULL) {// check if file already exist
infoMessage ("In newTraceResponse: This name already exist ! Retry...", GTK_MESSAGE_ERROR );
fclose (f);
}
else {
strncpy (par.traceFileName, traceName, MAX_SIZE_FILE_NAME);
if ((f = fopen (traceName, "w")) == NULL)
infoMessage ("In NewTraceResponse: Impossible to Write", GTK_MESSAGE_ERROR );
else
fclose (f);
}
gtk_window_destroy (GTK_WINDOW (entryWindow));
gtk_widget_queue_draw (drawing_area);
}
/*! new Trace */
static void newTrace () {
strncpy (traceName, par.traceFileName, MAX_SIZE_FILE_NAME);
entryBox ("New Trace", "Trace: ", traceName, newTraceResponse);
}
/*! Edit trace */
static void editTrace () {
char line [MAX_SIZE_LINE] = "";
snprintf (line, sizeof (line), "%s %s\n", par.editor, par.traceFileName);
g_thread_new ("editTrace", commandRun, line);
}
/*! add POR to current trace */
static void traceAdd () {
char fileName [MAX_SIZE_FILE_NAME];
buildRootName (par.traceFileName, fileName);
addTracePt (fileName, par.pOr.lat, par.pOr.lon);
gtk_widget_queue_draw (drawing_area);
}
/*! display trace report */
static void traceReport () {
char fileName [MAX_SIZE_FILE_NAME];
double od, ld, rd, sog;
char str [MAX_SIZE_LINE];
char line [MAX_SIZE_LINE];
char strLat [MAX_SIZE_LINE];
char strLon [MAX_SIZE_LINE];
double lat, lon, time;
GtkWidget *traceWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW(traceWindow), "Trace Report");
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), traceWindow);
GtkWidget *grid = gtk_grid_new();
gtk_window_set_child (GTK_WINDOW (traceWindow), (GtkWidget *) grid);
gtk_grid_set_column_spacing(GTK_GRID(grid), 10);
gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
gtk_grid_set_row_homogeneous(GTK_GRID(grid), FALSE);
gtk_grid_set_column_homogeneous(GTK_GRID(grid), FALSE);
buildRootName (par.traceFileName, fileName);
if (! distanceTraceDone (fileName, &od, &ld, &rd, &sog)) {
infoMessage ("Error in distance trace calculation", GTK_MESSAGE_ERROR);
return;
}
snprintf (line, sizeof (line), "%.2lf", od);
lineReport (grid, 0, "mail-forward-symbolic", "Trace Ortho Dist", line);
snprintf (line, sizeof (line), "%.2lf", ld);
lineReport (grid, 2, "mail-forward-symbolic", "Trace Loxo Dist", line);
snprintf (line, sizeof (line), "%.2lf", rd);
lineReport (grid, 4, "emblem-important-symbolic", "Trace Real Dist", line);
snprintf (line, sizeof (line), "%.2lf", sog);
lineReport (grid, 6, "emblem-important-symbolic", "Average SOG", line);
if (findLastTracePoint (fileName, &lat, &lon, &time)) {
snprintf (line, sizeof (line), "%s %s", latToStr (par.pOr.lat, par.dispDms, strLat), lonToStr (par.pOr.lon, par.dispDms, strLon));
lineReport (grid, 8, "preferences-desktop-locale-symbolic", "Last Position", line);
snprintf (line, sizeof (line), "%s", epochToStr (time, false, str, sizeof (str)));
lineReport (grid, 10, "document-open-recent", "Last Time", line);
}
gtk_window_present (GTK_WINDOW (traceWindow));
}
/*! display trace information */
static void traceDump () {
FILE *f = NULL;
char line [MAX_SIZE_LINE], strLat [MAX_SIZE_LINE], strLon [MAX_SIZE_LINE];
int count = 0, l = 2;
char fileName [MAX_SIZE_FILE_NAME];
buildRootName (par.traceFileName, fileName);
char *latToken, *lonToken, *timeToken, *cogToken, *sogToken;
if ((f = fopen (fileName, "r")) == NULL) {
infoMessage ("Error in tracePoint: cannot read", GTK_MESSAGE_ERROR);
return;
}
GtkWidget *separator = gtk_separator_new (GTK_ORIENTATION_HORIZONTAL);
GtkWidget *label = NULL;
GtkWidget *traceWindow = gtk_application_window_new (app);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), traceWindow);
gtk_window_set_default_size(GTK_WINDOW (traceWindow), 600, 450);
// g_signal_connect(G_OBJECT(traceWindow), "destroy", G_CALLBACK(gtk_window_destroy), NULL);
GtkWidget *scrolled_window = gtk_scrolled_window_new ();
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
gtk_window_set_child (GTK_WINDOW (traceWindow), (GtkWidget *) scrolled_window);
GtkWidget *grid = gtk_grid_new();
gtk_scrolled_window_set_child (GTK_SCROLLED_WINDOW (scrolled_window), grid);
gtk_grid_set_column_spacing (GTK_GRID(grid), 20);
//gtk_grid_set_row_spacing (GTK_GRID(grid), 5);
//gtk_grid_set_row_homogeneous (GTK_GRID(grid), FALSE);
//gtk_grid_set_column_homogeneous (GTK_GRID(grid), FALSE);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Lat."), 0, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Lon."), 1, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Dat-Time"), 2, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("COG"), 3, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("SOG"), 4, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), separator, 0, 1, 5, 1);
while ((fgets (line, MAX_SIZE_LINE, f) != NULL )) {
if ((latToken = strtok (line, CSV_SEP)) != NULL) { // Lat
label = strToLabel (latToStr (strtod (latToken, NULL), par.dispDms, strLat), -1);
gtk_grid_attach(GTK_GRID (grid), label, 0, l, 1, 1);
}
if ((lonToken = strtok (NULL, CSV_SEP)) != NULL) { // Lon
label = strToLabel (lonToStr (strtod (lonToken, NULL), par.dispDms, strLon), -1);
gtk_grid_attach (GTK_GRID (grid), label, 1, l, 1, 1);
}
if ((timeToken = strtok (NULL, CSV_SEP))!= NULL ); // epoch not cpnsidered
if ((timeToken = strtok (NULL, CSV_SEP))!= NULL ) { // time
label = strToLabel (timeToken, -1);
gtk_grid_attach (GTK_GRID (grid), label, 2, l, 1, 1);
}
if ((cogToken = strtok (NULL, CSV_SEP))!= NULL ) { // cog
label = strToLabel (cogToken, -1);
gtk_grid_attach (GTK_GRID (grid), label, 3, l, 1, 1);
}
if ((sogToken = strtok (NULL, CSV_SEP))!= NULL ) { // sog
label = strToLabel (sogToken, -1);
gtk_grid_attach (GTK_GRID (grid), label, 4, l, 1, 1);
}
gtk_widget_set_margin_end (GTK_WIDGET(label), 20);
l += 1;
count += 1;
}
fclose (f);
snprintf (line, sizeof (line), "%s (Number: %d)", strrchr (fileName, '/' + 1), count);
gtk_window_set_title (GTK_WINDOW (traceWindow), line);
gtk_window_present (GTK_WINDOW (traceWindow));
}
/* call back for openSecnario */
void cbOpenTrace (GObject* source_object, GAsyncResult* res, gpointer data) {
GFile* file = gtk_file_dialog_open_finish ((GtkFileDialog *) source_object, res, NULL);
if (file != NULL) {
gchar *fileName = g_file_get_path(file);
printf ("File selected: %s\n", fileName);
if (fileName != NULL) {
strncpy (par.traceFileName, fileName, MAX_SIZE_FILE_NAME);
g_free(fileName);
traceReport ();
gtk_widget_queue_draw (drawing_area);
}
}
}
/*! Select trace file and read trace file */
static void openTrace () {
GtkFileDialog* fileDialog = selectFile ("Open Trace", "trace", "Trace Files", "*.csv", "*.csv");
gtk_file_dialog_open (fileDialog, GTK_WINDOW (window), NULL, cbOpenTrace, NULL);
}
/*! display Points of Interest information */
static void poiDump () {
char line [MAX_SIZE_LINE];
char strLat [MAX_SIZE_LINE];
char strLon [MAX_SIZE_LINE];
int count = 0;
int l = 2;
GtkWidget *separator = gtk_separator_new (GTK_ORIENTATION_HORIZONTAL);
GtkWidget *label;
GtkWidget *poiWindow = gtk_application_window_new (app);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), poiWindow);
GtkWidget *grid = gtk_grid_new();
gtk_window_set_child (GTK_WINDOW (poiWindow), (GtkWidget *) grid);
gtk_grid_set_column_spacing (GTK_GRID(grid), 20);
gtk_grid_set_row_spacing (GTK_GRID(grid), 5);
gtk_grid_set_row_homogeneous (GTK_GRID(grid), FALSE);
gtk_grid_set_column_homogeneous (GTK_GRID(grid), FALSE);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Lat."), 0, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Lon."), 1, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Type"), 2, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Level"), 3, 0, 1, 1);
gtk_grid_attach (GTK_GRID (grid), strToLabelBold("Name"), 4, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), separator, 0, 1, 5, 1);
for (int i = 0; i < nPoi; i++) {
if ((tPoi [i].type != UNVISIBLE) && (tPoi [i].type != PORT)) {
label = gtk_label_new (latToStr (tPoi[i].lat, par.dispDms, strLat));
gtk_grid_attach(GTK_GRID (grid), label, 0, l, 1, 1);
label = gtk_label_new (lonToStr (tPoi[i].lon, par.dispDms, strLon));
gtk_grid_attach (GTK_GRID (grid), label, 1, l, 1, 1);
snprintf (line, sizeof (line), "%d", tPoi [i].type);
label = gtk_label_new (line);
gtk_grid_attach (GTK_GRID (grid), label, 2, l, 1, 1);
snprintf (line, sizeof (line), "%d", tPoi [i].level);
label = gtk_label_new (line);
gtk_grid_attach (GTK_GRID (grid), label, 3, l, 1, 1);
label = gtk_label_new (tPoi [i].name);
gtk_grid_attach (GTK_GRID (grid), label, 4, l, 1, 1);
separator = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
gtk_grid_attach (GTK_GRID(grid), separator, 0, l + 1, 5, 1);
gtk_widget_set_margin_end (GTK_WIDGET(label), 20);
gtk_label_set_yalign(GTK_LABEL(label), 0);
gtk_label_set_xalign(GTK_LABEL(label), 0);
l += 2;
count += 1;
}
}
snprintf (line, sizeof (line), "Points of Interest (Number: %d)", count);
gtk_window_set_title (GTK_WINDOW (poiWindow), line);
gtk_window_present (GTK_WINDOW (poiWindow));
}
/*! print the route from origin to destination or best point */
static void historyRteDump (gpointer user_data) {
int k = GPOINTER_TO_INT (user_data);
char buffer [MAX_SIZE_BUFFER];
char title [MAX_SIZE_LINE];
if (historyRoute.r[k].n <= 0)
infoMessage ("No route calteculated", GTK_MESSAGE_INFO);
else {
routeToStr (&historyRoute.r[k], buffer, MAX_SIZE_BUFFER);
snprintf (title, MAX_SIZE_LINE, "History: %2d", k);
displayText (1400, 400, buffer, title);
}
}
/*! display history of routes */
static void rteHistory () {
char str [MAX_SIZE_LINE];
GtkWidget *itemHist;
GtkWidget *box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
if (historyRoute.n <= 1) {
infoMessage ("No History", GTK_MESSAGE_INFO);
return;
}
else if (historyRoute.n == 2) {
historyRteDump (GINT_TO_POINTER (0));
return;
}
for (int i = 0; i < historyRoute.n - 1; i++) {
snprintf (str, sizeof (str), "History: %d", i);
itemHist = gtk_button_new_with_label (str);
g_signal_connect_swapped (itemHist, "clicked", G_CALLBACK (historyRteDump), GINT_TO_POINTER (i));
gtk_box_append (GTK_BOX (box), itemHist);
}
menuHist = gtk_popover_new ();
gtk_widget_set_parent (menuHist, window);
g_signal_connect(window, "destroy", G_CALLBACK (onParentWindowDestroy), menuHist);
gtk_popover_set_child ((GtkPopover*) menuHist, (GtkWidget *) box);
gtk_popover_set_has_arrow ((GtkPopover*) menuHist, false);
GdkRectangle rect = {200, 100, 1, 1};
gtk_popover_set_pointing_to ((GtkPopover*) menuHist, &rect);
gtk_widget_set_visible (menuHist, true);
}
/*! display the report of route calculation */
static void rteReport () {
if (route.n <= 0)
infoMessage ("No route calculated", GTK_MESSAGE_INFO);
else {
niceReport (&route, 0);
}
}
/*! Draw simulation */
static void cbSimulationReport (GtkDrawingArea *area, cairo_t *cr, int width, int height, gpointer user_data) {
char str [MAX_SIZE_NUMBER];
int x, y;
cairo_set_line_width (cr, 1);
const int X_LEFT = 30;
const int X_RIGHT = width - 20;
const int Y_TOP = 10;
const int Y_BOTTOM = height - 25;
const int XK = (X_RIGHT - X_LEFT) / (chooseDeparture.tStop -chooseDeparture.tBegin);
const int YK = (Y_BOTTOM - Y_TOP) / (int) chooseDeparture.maxDuration;
const int DELTA = 5;
const int RECTANGLE_WIDTH = CLAMP (XK, 1, 20); // between 1 and 20
// Draw horizontal line wirh arrow
CAIRO_SET_SOURCE_RGB_BLACK(cr);
cairo_move_to (cr, X_LEFT, Y_BOTTOM );
cairo_line_to (cr, X_RIGHT, Y_BOTTOM);
cairo_line_to (cr, X_RIGHT - DELTA, Y_BOTTOM + DELTA); // for arrow
cairo_stroke (cr);
cairo_move_to (cr, X_RIGHT, Y_BOTTOM );
cairo_line_to (cr, X_RIGHT - DELTA, Y_BOTTOM - DELTA);
cairo_stroke (cr);
// Draw vertical line wirh arrow
cairo_move_to (cr, X_LEFT, Y_BOTTOM);
cairo_line_to (cr, X_LEFT, Y_TOP);
cairo_line_to (cr, X_LEFT - DELTA, Y_TOP + DELTA);
cairo_stroke (cr);
cairo_move_to (cr, X_LEFT, Y_TOP);
cairo_line_to (cr, X_LEFT + DELTA, Y_TOP + DELTA);
cairo_stroke (cr);
int h;
CAIRO_SET_SOURCE_RGB_GRAY(cr);
for (int t = chooseDeparture.tBegin; t < chooseDeparture.tStop; t += chooseDeparture.tStep) {
if (t != chooseDeparture.bestTime) {
h = (int) chooseDeparture.t [t] * YK;
cairo_rectangle (cr, X_LEFT + t * XK, Y_BOTTOM - h, RECTANGLE_WIDTH, h);
}
}
cairo_fill (cr);
CAIRO_SET_SOURCE_RGB_GREEN(cr);
h = (int) chooseDeparture.t [chooseDeparture.bestTime] * YK;
cairo_rectangle (cr, X_LEFT + chooseDeparture.bestTime * XK, Y_BOTTOM - h, RECTANGLE_WIDTH, h);
cairo_fill (cr);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
// Draw time labels
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size (cr, 10);
const int displayStep = MAX (1, (chooseDeparture.tStop - chooseDeparture.tBegin) / 20);
for (int t = chooseDeparture.tBegin; t < chooseDeparture.tStop; t += displayStep) {
x = X_LEFT + (RECTANGLE_WIDTH/2) + XK * t;
cairo_move_to (cr, x, Y_BOTTOM + 10);
snprintf (str, MAX_SIZE_NUMBER,"%d", t);
cairo_show_text (cr, str);
}
cairo_stroke(cr);
// Draw duration labels;
const int durationStep = (int) (chooseDeparture.maxDuration) / 10;
for (int duration = 0; duration < chooseDeparture.maxDuration ; duration += durationStep) {
y = Y_BOTTOM - duration * YK;
cairo_move_to (cr, X_LEFT - 20, y);
snprintf (str, MAX_SIZE_NUMBER,"%2d", duration);
cairo_show_text (cr, str);
CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr); // Horizontal lines
cairo_move_to (cr, X_LEFT, y);
cairo_line_to (cr, X_RIGHT, y);
cairo_stroke (cr);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
}
cairo_stroke(cr);
}
/*! display the report of simulation for best time departure */
static void simulationReport () {
char line [MAX_SIZE_LINE];
if (! simulationReportExist) {
printf ("no simulation available\n");
infoMessage ("No simulation available", GTK_MESSAGE_INFO);
return;
}
snprintf (line, sizeof (line), "Simulation Report. Min Duration: %.2lf hours, Best Departure Time: %d hours after beginning of Grib",
chooseDeparture.minDuration, chooseDeparture.bestTime);
GtkWidget *simulationWindow = gtk_application_window_new (GTK_APPLICATION (app));
gtk_window_set_title (GTK_WINDOW(simulationWindow), line);
gtk_window_set_default_size (GTK_WINDOW(simulationWindow), 1200, 400);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), simulationWindow);
GtkWidget *drawing_area = gtk_drawing_area_new ();
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (drawing_area), cbSimulationReport, NULL, NULL);
gtk_window_set_child (GTK_WINDOW (simulationWindow), drawing_area);
gtk_window_present (GTK_WINDOW (simulationWindow));
}
/*! Draw routegram */
static void onRoutegramEvent (GtkDrawingArea *area, cairo_t *cr, int width, int height, gpointer user_data) {
#define MAX_VAL_ROUTE 3
int x, y;
char str [MAX_SIZE_LINE], strDate [MAX_SIZE_LINE];
const int LEGEND_X_LEFT = width - 80;
const int LEGEND_Y_TOP = 10;
const int X_LEFT = 30;
const int X_RIGHT = width - 100;
const int Y_TOP = 20;
const int Y_BOTTOM = height - 25;
const int HEAD_Y = 10;
const int DELTA = 5;
const int DAY_LG = 10;
const int XK = (X_RIGHT - X_LEFT) / (route.duration + par.tStep);
double u, v, head_x;
cairo_set_line_width (cr, 1);
cairo_set_font_size (cr, 12);
char *libelle [MAX_VAL_ROUTE] = {"Wind", "Gust", "Waves"};
double colors[MAX_VAL_ROUTE][3] = {{0, 0, 1}, {1, 0, 0}, {0, 1, 0}}; // blue red blue
drawLegend (cr, LEGEND_X_LEFT, LEGEND_Y_TOP, colors, libelle, MAX_VAL_ROUTE);
// Draw horizontal line wirh arrow
CAIRO_SET_SOURCE_RGB_BLACK(cr);
cairo_move_to (cr, X_LEFT, Y_BOTTOM);
cairo_line_to (cr, X_RIGHT, Y_BOTTOM);
cairo_line_to (cr, X_RIGHT - DELTA, Y_BOTTOM + DELTA); // for arrow
cairo_stroke (cr);
cairo_move_to (cr, X_RIGHT, Y_BOTTOM );
cairo_line_to (cr, X_RIGHT - DELTA, Y_BOTTOM - DELTA);
cairo_stroke (cr);
// Draw verical line wirh arrow
cairo_move_to (cr, X_LEFT, Y_BOTTOM);
cairo_line_to (cr, X_LEFT, Y_TOP);
cairo_line_to (cr, X_LEFT - DELTA, Y_TOP + DELTA);
cairo_stroke (cr);
cairo_move_to (cr, X_LEFT, Y_TOP);
cairo_line_to (cr, X_LEFT + DELTA, Y_TOP + DELTA);
cairo_stroke (cr);
// Draw time labels and vertical lines
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size (cr, 10);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
struct tm tmTime;
memcpy (&tmTime, &startInfo, sizeof (tmTime));
double timeStep = (route.duration <= 120) ? 6 : 12;
int lastDay = -1;
for (double i = 0; i <= route.duration; i+= timeStep) {
x = X_LEFT + XK * i;
cairo_move_to (cr, x, Y_BOTTOM + 10);
snprintf (strDate, sizeof (strDate), "%4d/%02d/%02d %02d:%02d", tmTime.tm_year + 1900, tmTime.tm_mon+1, tmTime.tm_mday, tmTime.tm_hour, tmTime.tm_min);
cairo_show_text (cr, strrchr (strDate, ' ') + 1); // hour is after space
if (tmTime.tm_mday != lastDay) { // change day
cairo_move_to (cr, x, Y_BOTTOM + 20);
strDate [DAY_LG] = '\0'; // only date
cairo_show_text (cr, strDate);
CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr);
cairo_move_to (cr, x, Y_BOTTOM);
cairo_line_to (cr, x, Y_TOP);
cairo_stroke (cr);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
}
lastDay = tmTime.tm_mday;
tmTime.tm_min += timeStep * 60;
mktime (&tmTime);
}
cairo_stroke(cr);
// vertical arrival line
CAIRO_SET_SOURCE_RGB_BLACK(cr);
double lastX = X_LEFT + XK * route.duration;
cairo_move_to (cr, lastX, Y_BOTTOM);
cairo_line_to (cr, lastX, Y_TOP);
cairo_stroke(cr);
showUnicode (cr, DESTINATION_UNICODE, lastX, Y_TOP + 50);
// arrival date
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size (cr, 16);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
newDate (zone.dataDate [0], zone.dataTime [0]/100 + par.startTimeInHours + route.duration, strDate);
cairo_move_to (cr, lastX, Y_TOP + 100);
char *ptHour = strchr (strDate, ' ');
*ptHour = '\0'; // cut strdate with date and hour
cairo_show_text (cr, strDate); // the date
cairo_move_to (cr, lastX , Y_TOP + 120);
cairo_show_text (cr, ptHour + 1); // the time
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size (cr, 10);
// Draw speeds labels and horizontal lines
cairo_set_font_size (cr, 10);
const double step = 5;
double maxMax = MAX (MS_TO_KN * route.maxGust, route.maxTws);
const int YK = (Y_BOTTOM - Y_TOP) / maxMax;
for (double speed = step; speed <= maxMax + step; speed += step) {
y = Y_BOTTOM - YK * speed;
cairo_move_to (cr, X_LEFT - 20, y);
snprintf (str, MAX_SIZE_LINE, "%02.0lf", speed);
cairo_show_text (cr, str);
CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr); // Horizontal lines
cairo_move_to (cr, X_LEFT, y);
cairo_line_to (cr, lastX, y);
cairo_stroke (cr);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
}
cairo_stroke(cr);
double lastU, lastV, lastG, lastW, lastTwd, lastTws;
// find last values at destination
if (route.destinationReached) {
findWindGrib (par.pDest.lat, par.pDest.lon, route.t[route.n - 1].time + route.lastStepDuration,\
&lastU, &lastV, &lastG, &lastW, &lastTwd, &lastTws);
}
// draw tws arrows
int arrowStep = (route.n / 24) + 1;
for (int i = 0; i < route.n; i += arrowStep) {
head_x = X_LEFT + XK * i * par.tStep;
u = -sin (DEG_TO_RAD * route.t[i].twd) * route.t[i].tws / MS_TO_KN;
v = -cos (DEG_TO_RAD * route.t[i].twd) * route.t[i].tws / MS_TO_KN;
arrow (cr, head_x, HEAD_Y, u, v, route.t [i].twd, route.t[i].tws, WIND);
}
// draw gust
if (route.maxGust > 0) {
CAIRO_SET_SOURCE_RGB_RED(cr);
for (int i = 0; i < route.n; i ++) {
x = X_LEFT + XK * i * par.tStep;
y = Y_BOTTOM - YK * MAX (MS_TO_KN * route.t[i].g, route.t[i].tws);
if (i == 0) cairo_move_to (cr, x, y);
else cairo_line_to (cr, x, y);
}
if (route.destinationReached)
cairo_line_to (cr, lastX, Y_BOTTOM - YK * MAX (MS_TO_KN * lastG, lastTws));
cairo_stroke(cr);
}
// draw tws
CAIRO_SET_SOURCE_RGB_BLUE(cr);
for (int i = 0; i < route.n; i++) {
x = X_LEFT + XK * i * par.tStep;
y = Y_BOTTOM - YK * route.t[i].tws;
if (i == 0) cairo_move_to (cr, x, y);
else cairo_line_to (cr, x, y);
}
if (route.destinationReached)
cairo_line_to (cr, lastX, Y_BOTTOM - YK * lastTws);
cairo_stroke(cr);
//draw Waves
if (route.maxWave > 0) {
CAIRO_SET_SOURCE_RGB_GREEN(cr);
for (int i = 0; i < route.n; i ++) {
x = X_LEFT + XK * i * par.tStep;
y = Y_BOTTOM - YK * route.t[i].w;
if (i == 0) cairo_move_to (cr, x, y);
else cairo_line_to (cr, x, y);
}
if (route.destinationReached)
cairo_line_to (cr, lastX, Y_BOTTOM - YK * lastW);
cairo_stroke(cr);
}
//draw SOG
cairo_set_line_width (cr, 5);
x = X_LEFT;
y = Y_BOTTOM - YK * route.t[0].sog;
int motor = route.t[0].motor;
int amure = route.t[0].amure;
routeColor (cr, motor, amure);
cairo_move_to (cr, x, y);
for (int i = 1; i < route.n; i++) {
x = X_LEFT + XK * i * par.tStep;
y = Y_BOTTOM - YK * route.t[i].sog;
cairo_line_to (cr, x, y);
if ((route.t[i].motor != motor) || (route.t[i].amure != amure)) {
cairo_stroke (cr);
amure = route.t[i].amure;
motor = route.t[i].motor;
routeColor (cr, motor, amure);
cairo_move_to (cr, x, y);
}
}
// last SOG segment to destination
cairo_line_to (cr, lastX, y);
cairo_stroke(cr);
}
/*! represent routegram */
static void routeGram () {
char line [MAX_SIZE_LINE];
if (route.n <= 0) {
infoMessage ("No route calculated", GTK_MESSAGE_INFO);
return;
}
snprintf (line, MAX_SIZE_LINE, "Routegram max TWS: %.2lf, max Gust: %.2lf, max Waves: %.2lf, miles: %.2lf",\
route.maxTws, MAX (route.maxTws, MS_TO_KN * route.maxGust), route.maxWave, route.totDist);
GtkWidget *routeWindow = gtk_application_window_new (GTK_APPLICATION (app));
gtk_window_set_title (GTK_WINDOW(routeWindow), line);
gtk_window_set_default_size (GTK_WINDOW(routeWindow), 1400, 400);
g_signal_connect(window, "destroy", G_CALLBACK(onParentDestroy), routeWindow);
GtkWidget *route_drawing_area = gtk_drawing_area_new ();
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (route_drawing_area), onRoutegramEvent, NULL, NULL);
gtk_window_set_child (GTK_WINDOW (routeWindow), route_drawing_area);
gtk_window_present (GTK_WINDOW (routeWindow));
}
/*! print the route from origin to destination or best point */
static void routeDump () {
char buffer [MAX_SIZE_BUFFER];
if (route.n <= 0)
infoMessage ("No route calculated", GTK_MESSAGE_INFO);
else {
routeToStr (&route, buffer, MAX_SIZE_BUFFER);
displayText (1400, 400, buffer, (route.destinationReached) ? "Destination reached" :\
"Destination unreached. Route to best point");
}
}
/*! show parameters information */
static void parDump () {
char str [MAX_SIZE_FILE_NAME];
writeParam (buildRootName (TEMP_FILE_NAME, str), true, false);
displayFile (buildRootName (TEMP_FILE_NAME, str), "Parameter Dump", true);
}
/*! show parameters information */
static void parInfo () {
char str [MAX_SIZE_FILE_NAME];
displayFile (buildRootName (par.parInfoFileName, str), "Parameter Info", true);
}
/*! launch system command in a thread */
void *poiEditRun (void *data) {
FILE *fs;
int comportement = GPOINTER_TO_INT (data);
char line [MAX_SIZE_LINE] = "";
snprintf (line, sizeof (line), "%s %s\n", par.spreadsheet, (comportement == POI_SEL) ? par.poiFileName: par.portFileName);
if ((fs = popen (line, "r")) == NULL) {
fprintf (stderr, "Error in poiEditRun: system call: %s\n", line);
}
else {
pclose (fs);
nPoi = 0;
nPoi = readPoi (par.poiFileName);
nPoi += readPoi (par.portFileName);
gtk_widget_queue_draw (drawing_area);
}
return NULL;
}
/*! edit poi or port */
static void poiEdit (GSimpleAction *action, GVariant *parameter, gpointer *data) {
g_thread_new ("poiEdit", poiEditRun, data);
}
/*! Function to draw the speedometer */
static void drawSpeedometer(GtkDrawingArea *area, cairo_t *cr, int width, int height, gpointer data) {
MyGpsData *dashboard = (MyGpsData *)data;
double sog = (dashboard->OK) ? dashboard->sog : 0;
if (isnan (sog)) sog = 0;
double xc = width / 2.0;
double yc = height / 2.0;
CAIRO_SET_SOURCE_RGB_BLACK(cr);
cairo_arc(cr, xc, yc, DASHBOARD_RADIUS, 0, 2 * G_PI);
cairo_stroke(cr);
// Draw the speed inside a rectangle at the center
char speed_str[10];
cairo_set_font_size (cr, 10);
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
snprintf(speed_str, sizeof(speed_str), "%.2lfKn", sog);
cairo_rectangle(cr, xc - 25, yc + 15, 60, 20);
cairo_fill(cr);
CAIRO_SET_SOURCE_RGB_WHITE(cr);
cairo_move_to(cr, xc - 15, yc + 30);
cairo_show_text(cr, speed_str);
// Draw speed marks
CAIRO_SET_SOURCE_RGB_BLACK(cr);
cairo_set_line_width(cr, 2);
for (int i = DASHBOARD_MIN_SPEED; i <= DASHBOARD_MAX_SPEED; ++i) {
double angle = (i - DASHBOARD_MIN_SPEED) * (G_PI / (DASHBOARD_MAX_SPEED - DASHBOARD_MIN_SPEED)) - G_PI;
double x1 = xc + (DASHBOARD_RADIUS - 10) * cos(angle);
double y1 = yc + (DASHBOARD_RADIUS - 10) * sin(angle);
double x2 = xc + DASHBOARD_RADIUS * cos(angle);
double y2 = yc + DASHBOARD_RADIUS * sin(angle);
cairo_move_to(cr, x1, y1);
cairo_line_to(cr, x2, y2);
cairo_stroke(cr);
// Draw the speed numbers
char speed_text[4];
snprintf(speed_text, sizeof(speed_text), "%d", i);
cairo_text_extents_t extents;
cairo_text_extents(cr, speed_text, &extents);
double tx = xc + (DASHBOARD_RADIUS - 20) * cos(angle) - extents.width / 2;
double ty = yc + (DASHBOARD_RADIUS - 20) * sin(angle) + extents.height / 2;
cairo_move_to(cr, tx, ty);
cairo_show_text(cr, speed_text);
}
// Draw the needle
CAIRO_SET_SOURCE_RGB_RED(cr);
cairo_set_line_width(cr, 3);
double needle_angle = (sog - DASHBOARD_MIN_SPEED) * (G_PI / (DASHBOARD_MAX_SPEED - DASHBOARD_MIN_SPEED)) - G_PI;
double needle_x = xc + (DASHBOARD_RADIUS - 20) * cos(needle_angle);
double needle_y = yc + (DASHBOARD_RADIUS - 20) * sin(needle_angle);
cairo_move_to(cr, xc, yc);
cairo_line_to(cr, needle_x, needle_y);
cairo_stroke(cr);
}
/*! Function to draw the compass */
static void drawCompass (GtkDrawingArea *area, cairo_t *cr, int width, int height, gpointer data) {
MyGpsData *dashboard = (MyGpsData *)data;
double cog = (dashboard->OK) ? dashboard->cog : 0;
if (isnan (cog)) cog = 0;
double angle_rad = cog * DEG_TO_RAD;
cairo_set_line_width(cr, 2.0);
double xc = width / 2.0;
double yc = height / 2.0;
// Draw exterior circle for compass
cairo_arc(cr, xc, yc, DASHBOARD_RADIUS, 0, 2 * G_PI);
cairo_stroke(cr);
// Draw main directions (N, E, S, W) and secondary (NE, SE, SW, NW)
cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
cairo_set_font_size(cr, 20);
struct {
const char *label;
double angle;
} directions[] = {
{"N", 0}, {"NE", 45}, {"E", 90}, {"SE", 135},
{"S", 180}, {"SW", 225}, {"W", 270}, {"NW", 315}
};
for (int i = 0; i < 8; i++) {
double direction_angle = directions[i].angle * DEG_TO_RAD;
double label_x = xc + (DASHBOARD_RADIUS - 30) * sin(direction_angle) - 10;
double label_y = yc - (DASHBOARD_RADIUS - 30) * cos(direction_angle) + 10;
cairo_move_to(cr, label_x, label_y);
cairo_show_text(cr, directions[i].label);
}
// Draw graduations
cairo_set_line_width(cr, 1.0);
for (int i = 0; i < 360; i += 10) {
double tick_angle = i * DEG_TO_RAD;
double inner_radius = DASHBOARD_RADIUS - (i % 30 == 0 ? 20 : 10);
double tick_x1 = xc + DASHBOARD_RADIUS * sin(tick_angle);
double tick_y1 = yc - DASHBOARD_RADIUS * cos(tick_angle);
double tick_x2 = xc + inner_radius * sin(tick_angle);
double tick_y2 = yc - inner_radius * cos(tick_angle);
cairo_move_to(cr, tick_x1, tick_y1);
cairo_line_to(cr, tick_x2, tick_y2);
cairo_stroke(cr);
}
// Draw the speed inside a rectangle at the center
char cog_str[10];
cairo_set_font_size (cr, 10);
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
snprintf(cog_str, sizeof(cog_str), "%.0lf°", cog);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
cairo_rectangle(cr, xc - 25, yc + 15, 60, 20);
cairo_fill(cr);
CAIRO_SET_SOURCE_RGB_WHITE(cr);
cairo_move_to(cr, xc - 15, yc + 30);
cairo_show_text(cr, cog_str);
double needle_length = DASHBOARD_RADIUS * 0.8;
double needle_x = xc + needle_length * sin(angle_rad);
double needle_y = yc - needle_length * cos(angle_rad);
// Draw basis for arrow
cairo_set_source_rgb(cr, 0, 0, 0);
cairo_arc(cr, xc, yc, 10, 0, 2 * G_PI);
cairo_fill(cr);
// Draw line for arrow
CAIRO_SET_SOURCE_RGB_RED(cr);
cairo_set_line_width(cr, 4.0);
cairo_move_to(cr, xc, yc);
cairo_line_to(cr, needle_x, needle_y);
cairo_stroke(cr);
// Draw opposite side of arrow
double opposite_x = xc - needle_length * sin(angle_rad);
double opposite_y = yc + needle_length * cos(angle_rad);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
cairo_move_to(cr, xc, yc);
cairo_line_to(cr, opposite_x, opposite_y);
cairo_stroke(cr);
}
/*! draw hour */
static void drawHourPos (GtkDrawingArea *area, cairo_t *cr, int width, int height, gpointer data) {
char strLat [MAX_SIZE_LINE], strLon [MAX_SIZE_LINE];
char strDate [MAX_SIZE_DATE], str [MAX_SIZE_LINE];
PangoLayout *layout;
PangoFontDescription *font_desc;
double xc = width / 2.0;
double yc = height / 2.0;
//time_t now = time(NULL);
//struct tm *utc_time = gmtime(&now);
//strftime(strDate, sizeof(strDate), "%Y-%m-%d %H:%M:%S UTC", utc_time);*/
epochToStr (my_gps_data.time, true, strDate, sizeof (strDate));
CAIRO_SET_SOURCE_RGB_BLACK (cr);
cairo_arc(cr, xc, yc, DASHBOARD_RADIUS * 0.8, 0, 2 * G_PI);
cairo_fill(cr);
CAIRO_SET_SOURCE_RGB_WHITE (cr);
cairo_arc(cr, xc, yc, DASHBOARD_RADIUS * 0.8 - 2, 0, 2 * G_PI);
cairo_stroke (cr);
layout = pango_cairo_create_layout(cr);
pango_layout_set_text(layout, strchr (strDate, ' ') + 1, -1);
// Set font description
font_desc = pango_font_description_from_string("DSEG7 Classic 12");
pango_layout_set_font_description(layout, font_desc);
pango_font_description_free(font_desc);
CAIRO_SET_SOURCE_RGB_GREEN (cr);
cairo_move_to (cr, xc-40, yc - 20);
pango_cairo_update_layout(cr, layout);
pango_cairo_show_layout(cr, layout);
g_object_unref(layout);
// position
CAIRO_SET_SOURCE_RGB_WHITE (cr);
cairo_set_font_size (cr, 12);
cairo_move_to (cr, xc-38, yc + 25);
snprintf (str, sizeof (str), "%s", latToStr (my_gps_data.lat, par.dispDms, strLat));
cairo_show_text (cr, str);
cairo_move_to (cr, xc-38, yc + 40);
snprintf (str, sizeof (str), "%s", lonToStr (my_gps_data.lon, par.dispDms, strLon));
cairo_show_text (cr, str);
}
/*! Function to draw the text zone */
static void drawTextZone (GtkDrawingArea *area, cairo_t *cr, int width, int height, gpointer data) {
char str [MAX_SIZE_LINE];
double nextLat, nextLon;
int nextWp = (wayPoints.n == 0) ? -1 : 0; // to be revaluated
double xc = width / 2.0;
double yc = height / 2.0;
CAIRO_SET_SOURCE_RGB_BLACK (cr);
cairo_arc(cr, xc, yc, DASHBOARD_RADIUS * 0.8, 0, 2 * G_PI);
cairo_fill(cr);
CAIRO_SET_SOURCE_RGB_WHITE (cr);
cairo_arc(cr, xc, yc, DASHBOARD_RADIUS * 0.8 - 2, 0, 2 * G_PI);
cairo_stroke (cr);
cairo_move_to (cr, xc, yc);
cairo_set_font_size (cr, 12);
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
CAIRO_SET_SOURCE_RGB_WHITE(cr);
if (! my_gps_data.OK) return;
// calculate route to Way Point
cairo_move_to (cr, xc-50, yc - 15);
nextLat = (nextWp == -1) ? par.pDest.lat : wayPoints.t [nextWp].lat;
nextLon = (nextWp == -1) ? par.pDest.lon : wayPoints.t [nextWp].lon;
snprintf (str, sizeof (str), "Ortho Route: %.0lf°",
// directCap (my_gps_data.lat, my_gps_data.lon, nextLat, nextLon),
orthoCap (my_gps_data.lat, my_gps_data.lon, nextLat, nextLon));
cairo_show_text (cr, str);
// calculate route to SailRoute
if (route.n > 0) {
int i = findIndexInRouteNow ();
cairo_move_to (cr, xc-50, yc + 15);
if (i < 0)
snprintf (str, sizeof (str), "Sail Route: NA");
else if (i >= route.n)
snprintf (str, sizeof (str), "Sail Route: N/A");
else
snprintf (str, sizeof (str), "Sail Route: %.0lf°", route.t[i].oCap);
cairo_show_text (cr, str);
}
}
/*! update on timeout */
static gboolean updateDashboard(gpointer label) {
if (window == NULL) return FALSE;
gtk_widget_queue_draw (widgetDashboard.hourPosZone);
gtk_widget_queue_draw (widgetDashboard.speedometer);
gtk_widget_queue_draw (widgetDashboard.compass);
gtk_widget_queue_draw (widgetDashboard.textZone);
return TRUE;
}
/*! callback destroy dashboard */
static void onDashboardWindowDestroy (GtkWidget *widget, gpointer data) {
if (widgetDashboard.timeoutId != 0) {
g_source_remove (widgetDashboard.timeoutId);
widgetDashboard.timeoutId = 0;
}
}
/*! show Dashboard */
static void dashboard () {
const int D_WIDTH = 250;
const int D_HEIGHT = 250;
const int D_TIMER = 1;
GtkWidget *dashboardWindow = gtk_application_window_new (GTK_APPLICATION (app));
gtk_window_set_title(GTK_WINDOW(dashboardWindow), "");
gtk_window_set_default_size (GTK_WINDOW(dashboardWindow), 4 * D_WIDTH, D_HEIGHT);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), dashboardWindow);
g_signal_connect (dashboardWindow, "destroy", G_CALLBACK (onDashboardWindowDestroy), NULL);
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 5);
gtk_window_set_child(GTK_WINDOW(dashboardWindow), box);
// Hour Zone
widgetDashboard.hourPosZone = gtk_drawing_area_new();
gtk_widget_set_size_request (widgetDashboard.hourPosZone, D_WIDTH, D_HEIGHT);
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA(widgetDashboard.hourPosZone), drawHourPos, &my_gps_data, NULL);
gtk_box_append (GTK_BOX(box), widgetDashboard.hourPosZone);
// Speedometer
widgetDashboard.speedometer = gtk_drawing_area_new();
gtk_widget_set_size_request(widgetDashboard.speedometer, D_WIDTH, D_HEIGHT);
gtk_drawing_area_set_draw_func(GTK_DRAWING_AREA (widgetDashboard.speedometer), drawSpeedometer, &my_gps_data, NULL);
gtk_box_append(GTK_BOX(box), widgetDashboard.speedometer);
// Compass
widgetDashboard.compass = gtk_drawing_area_new();
gtk_widget_set_size_request (widgetDashboard.compass, D_WIDTH, D_HEIGHT);
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA(widgetDashboard.compass), drawCompass, &my_gps_data, NULL);
gtk_box_append (GTK_BOX(box), widgetDashboard.compass);
// text Zone
widgetDashboard.textZone = gtk_drawing_area_new();
gtk_widget_set_size_request (widgetDashboard.textZone, D_WIDTH, D_HEIGHT);
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA(widgetDashboard.textZone), drawTextZone, &my_gps_data, NULL);
gtk_box_append (GTK_BOX(box), widgetDashboard.textZone);
// UTC Time
widgetDashboard.timeoutId = g_timeout_add_seconds (D_TIMER, updateDashboard, NULL); // Update every second
gtk_window_present (GTK_WINDOW (dashboardWindow));
}
/*! show GPS information */
static void gpsDump () {
char line [MAX_SIZE_LINE], strLat [MAX_SIZE_LINE], strLon [MAX_SIZE_LINE], str [MAX_SIZE_LINE];
GtkWidget *gpsWindow = gtk_application_window_new (GTK_APPLICATION (app));
gtk_window_set_title (GTK_WINDOW(gpsWindow), "GPS Information");
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), gpsWindow);
GtkWidget *grid = gtk_grid_new();
/*if (!my_gps_data.OK) {
infoMessage ("No GPS position available", GTK_MESSAGE_WARNING);
return;
}*/
gtk_window_set_child (GTK_WINDOW (gpsWindow), (GtkWidget *) grid);
gtk_grid_set_column_spacing(GTK_GRID(grid), 10);
gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
gtk_grid_set_row_homogeneous(GTK_GRID(grid), FALSE);
gtk_grid_set_column_homogeneous(GTK_GRID(grid), FALSE);
snprintf (line, sizeof (line), "%s", (my_gps_data.OK) ? "YES" : "NO");
lineReport (grid, 0, "audio-input-microphone-symbolic", "GPS Available", line);
snprintf (line, sizeof (line), "%s %s\n", \
latToStr (my_gps_data.lat, par.dispDms, strLat), lonToStr (my_gps_data.lon, par.dispDms, strLon));
lineReport (grid, 2, "network-workgroup-symbolic", "Position", line);
snprintf (line, sizeof (line), "%.2f°\n", my_gps_data.cog);
lineReport (grid, 4, "view-refresh-symbolic", "COG", line);
snprintf (line, sizeof (line), "%.2f Knots\n", my_gps_data.sog);
lineReport (grid, 6, "media-playlist-consecutive-symbolic", "SOG", line);
snprintf (line, sizeof (line), "%.2f meters\n", my_gps_data.alt);
lineReport (grid, 8, "airplane-mode-symbolic", "Altitude", line);
snprintf (line, sizeof (line), "%d\n", my_gps_data.status);
lineReport (grid, 10, "dialog-information-symbolic", "Status", line);
snprintf (line, sizeof (line), "%d\n", my_gps_data.nSat);
lineReport (grid, 12, "preferences-system-network-symbolic", "Number of satellites", line);
snprintf (line, sizeof (line), "%s\n", epochToStr (my_gps_data.time, true, str, sizeof (str)));
lineReport (grid, 14, "alarm-symbolic", "UTC", line);
gtk_window_present (GTK_WINDOW (gpsWindow));
}
/*! launch help HTML file */
static void help () {
char command [MAX_SIZE_LINE ];
snprintf (command, MAX_SIZE_LINE, "%s %s", par.webkit, par.helpFileName);
g_thread_new ("help", commandRun, command);
}
/*! display info on the program */
static void helpInfo () {
const char *authors[2] = {PROG_AUTHOR, NULL};
char str [MAX_SIZE_LINE];
char strVersion [MAX_SIZE_LINE];
char strGps [MAX_SIZE_LINE];
snprintf (strVersion, sizeof (strVersion), "%s\nGTK version: %d.%d.%d\nGlib version: %d.%d.%d\nCairo Version:%s\n \
GPS %s\nECCODES version from ECMWF: %s\n Curl version: %s\n Shapefil version: %s\n Compilation date: %s\n",
PROG_VERSION,
gtk_get_major_version(), gtk_get_minor_version(), gtk_get_micro_version(),
// webkit_get_major_version (), webkit_get_minor_version (),webkit_get_micro_version (), // ATT GTK4 CHANGE
GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION,
CAIRO_VERSION_STRING,
gpsInfo (par.gpsType, strGps, MAX_SIZE_LINE),
ECCODES_VERSION_STR, LIBCURL_VERSION, "1.56",
__DATE__);
GtkWidget *p_about_dialog = gtk_about_dialog_new ();
gtk_about_dialog_set_version (GTK_ABOUT_DIALOG (p_about_dialog), strVersion);
gtk_about_dialog_set_program_name (GTK_ABOUT_DIALOG (p_about_dialog), PROG_NAME);
gtk_about_dialog_set_authors (GTK_ABOUT_DIALOG (p_about_dialog), authors);
gtk_about_dialog_set_website (GTK_ABOUT_DIALOG (p_about_dialog), PROG_WEB_SITE);
GdkPixbuf *p_logo = gdk_pixbuf_new_from_file (buildRootName (PROG_LOGO, str), NULL);
GdkTexture *texture_logo = gdk_texture_new_for_pixbuf (p_logo);
gtk_about_dialog_set_logo (GTK_ABOUT_DIALOG (p_about_dialog), (GdkPaintable *) texture_logo); // ATT GTK4 CHANGE
gtk_about_dialog_set_comments(GTK_ABOUT_DIALOG (p_about_dialog), DESCRIPTION);
gtk_window_set_modal (GTK_WINDOW(p_about_dialog), true); // ATT GTK4 CHANGE
gtk_window_present (GTK_WINDOW (p_about_dialog)); // ATT GTK4 CHANGE
}
/*! check if readGrib is terminated (wind) */
static gboolean readGribCheck (gpointer data) {
// printf ("readGribCheck\n");
if (readGribRet == -1) { // not terminated
return TRUE;
}
g_source_remove (gribReadTimeout); // timer stopped
spinnerWindowDestroy ();
if (readGribRet == 0) {
infoMessage ("Error in readGribCheck (wind)", GTK_MESSAGE_ERROR);
}
else {
theTime = 0;
par.constWindTws = 0;
initDispZone ();
updatedColors = false;
titleUpdate ();
}
gtk_widget_queue_draw (drawing_area);
destroySurface ();
return TRUE;
}
/*! check if readGrib is terminated (current) */
static gboolean readCurrentGribCheck (gpointer data) {
gtk_widget_queue_draw (drawing_area);
if (readCurrentGribRet == -1) { // not terminated
return TRUE;
}
g_source_remove (currentGribReadTimeout); // timer stopped
spinnerWindowDestroy ();
if (readCurrentGribRet == 0) {
infoMessage ("Error in readCurrentGribCheck (current)", GTK_MESSAGE_ERROR);
}
return TRUE;
}
/*! open selected file */
static void loadGribFile (int type, char *fileName) {
iFlow = type;
if (type == WIND) { // wind
printf ("loadGribFile Wind: %s\n", fileName);
strncpy (par.gribFileName, fileName, MAX_SIZE_FILE_NAME - 1);
readGribRet = -1; // Global variable
//readGribAll (par.gribFileName, &zone, WIND);
g_thread_new("readGribThread", readGrib, &iFlow);
spinner ("Grib File decoding", " ");
gribReadTimeout = g_timeout_add (READ_GRIB_TIME_OUT, readGribCheck, NULL);
}
else {
strncpy (par.currentGribFileName, fileName, MAX_SIZE_FILE_NAME - 1);
readCurrentGribRet = -1; // Global variable
g_thread_new("readCurrentGribThread", readGrib, &iFlow);
spinner ("Current Grib File decoding", " ");
currentGribReadTimeout = g_timeout_add (READ_GRIB_TIME_OUT, readCurrentGribCheck, NULL);
}
}
/*! getMeteoConsult */
void *getMeteoConsult (void *data) {
if (! curlGet (urlRequest.url, urlRequest.outputFileName)) {
readGribRet = 0;
return NULL;
}
strncpy (par.gribFileName, urlRequest.outputFileName, MAX_SIZE_FILE_NAME - 1);
if (readGribAll (par.gribFileName, &zone, WIND))
readGribRet = 1;
else readGribRet = 0;
return NULL;
}
/*! Response for URL change */
static void urlResponse (GtkWidget *widget, gpointer entryWindow) {
printf ("urlRequest.url: %s\n", urlRequest.url);
printf ("urlRequest.outputFileName: %s\n", urlRequest.outputFileName);
g_strlcat (urlRequest.outputFileName, strrchr (urlRequest.url, '/'), MAX_SIZE_LINE);
printf ("urlRequest.outputFileName: %s\n", urlRequest.outputFileName);
readGribRet = -1; // Global variable
g_thread_new("readGribThread", getMeteoConsult, NULL);
spinner ("Grib meteoConsultDownload and decoding", " ");
gribReadTimeout = g_timeout_add (READ_GRIB_TIME_OUT, readGribCheck, NULL);
gtk_window_destroy (GTK_WINDOW (entryWindow));
}
/*! build meteoconsult url then download it and load the grib file */
static void urlDownloadGrib (gpointer user_data) {
int index = GPOINTER_TO_INT(user_data);
if (menuGrib != NULL) popoverFinish (menuGrib);
urlRequest.urlType = typeFlow;
snprintf (urlRequest.outputFileName, sizeof (urlRequest.outputFileName), (typeFlow == WIND) ? "%sgrib": "%scurrentgrib", par.workingDir);
buildMeteoUrl (urlRequest.urlType, index, urlRequest.url);
printf ("url: %s\n", urlRequest.url);
entryBox ("MeteoConsult", "URL: ", urlRequest.url, urlResponse);
}
/*! update NOAA URL */
static void updateNoaaUrl(GtkSpinButton *spin_button, gpointer user_data) {
DialogData *data = (DialogData *)user_data;
data->bottomLat = gtk_spin_button_get_value_as_int(data->bottomLatSpin);
data->leftLon = gtk_spin_button_get_value_as_int(data->leftLonSpin);
data->topLat = gtk_spin_button_get_value_as_int(data->topLatSpin);
data->rightLon = gtk_spin_button_get_value_as_int(data->rightLonSpin);
data->timeStep = gtk_spin_button_get_value_as_int(data->timeStepSpin);
data->timeMax = gtk_spin_button_get_value_as_int(data->timeMaxSpin);
buildNoaaUrl (data->url, data->topLat, data->leftLon, data->bottomLat, data->rightLon, 0);
gtk_text_buffer_set_text (data->urlBuffer, data->url, -1);
}
/*! Download all NOOA files,concat them in a bigFile and load it */
static void *getGribNoaaAll (void *user_data) {
DialogData *data = (DialogData *)user_data;
time_t now = time (NULL);
struct tm *pTime = gmtime (&now);
char fileName [MAX_SIZE_URL], bigFile [MAX_SIZE_LINE], prefix [MAX_SIZE_LINE];
char strDate [MAX_SIZE_DATE];
strftime (strDate, MAX_SIZE_DATE, "%F", pTime);
snprintf (prefix, sizeof (prefix), "%sgrib/interNoaa-", par.workingDir);
printf ("Step: %d\n", data->timeStep);
for (int i = 0; i <= (data->timeMax) * 24; i += (data->timeStep)) {
buildNoaaUrl (data->url, data->topLat, data->leftLon, data->bottomLat, data->rightLon, i);
printf ("URL is: %s\n", data->url);
snprintf (fileName, sizeof (fileName), "%s%03d", prefix, i);
printf ("outputFileName: %s\n\n", fileName);
if (! curlGet (data->url, fileName)) {
readGribRet = 0;
return NULL;
}
}
snprintf (bigFile, sizeof (bigFile), "%sgrib/NOAA-%s-%02d-%03d.grb", par.workingDir, strDate, data->timeStep, data->timeMax * 24);
if (concat (prefix, data->timeStep, data->timeMax * 24, bigFile)) {
printf ("bigFile: %s\n", bigFile);
strncpy (par.gribFileName, bigFile, MAX_SIZE_FILE_NAME - 1);
if (readGribAll (par.gribFileName, &zone, WIND))
readGribRet = 1;
else readGribRet = 0;
}
else
readGribRet = 0;
return NULL;
}
/*! Manage response to NOAA dialog box */
static void onOkButtonNoaaClicked (GtkWidget *widget, gpointer theWindow) {
readGribRet = -1; // Global variable
g_thread_new("readGribThread", getGribNoaaAll, &noaaData);
spinner ("Grib NOAA Download and decoding", " ");
gribReadTimeout = g_timeout_add (READ_GRIB_TIME_OUT, readGribCheck, NULL);
gtk_window_destroy (GTK_WINDOW (theWindow));
}
/*! Dialog box to Manage NOAA URL and lauch downloadinf*/
static void gribNoaa (GSimpleAction *action, GVariant *parameter, gpointer *userData) {
GtkWidget *label;
DialogData *data = &noaaData;
const int TIME_STEP = 3, TIME_MAX = 2;
data->bottomLat = zone.latMin, data->topLat = zone.latMax, data->leftLon = zone.lonLeft, data->rightLon = zone.lonRight;
data->timeStep = TIME_STEP, data->timeMax = TIME_MAX;
GtkWidget *noaaWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (noaaWindow), "NOAA");
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), noaaWindow);
GtkWidget *vBox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (noaaWindow), (GtkWidget *) vBox);
GtkWidget *grid = gtk_grid_new();
buildNoaaUrl (data->url, data->topLat, data->leftLon, data->bottomLat, data->rightLon, 0);
gtk_grid_set_column_spacing(GTK_GRID(grid), 10);
gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
gtk_grid_set_row_homogeneous(GTK_GRID(grid), FALSE);
gtk_grid_set_column_homogeneous(GTK_GRID(grid), FALSE);
// Two firts lines : bottomLat, leftLon, topLat, rightLon
label = gtk_label_new ("Bottom Lat");
gtk_label_set_xalign(GTK_LABEL(label), 0.0);
data->bottomLatSpin = GTK_SPIN_BUTTON(gtk_spin_button_new_with_range(-90, 90, 1));
gtk_spin_button_set_value(GTK_SPIN_BUTTON(data->bottomLatSpin), data->bottomLat);
gtk_grid_attach(GTK_GRID(grid), label, 0, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(data->bottomLatSpin), 1, 0, 1, 1);
label = gtk_label_new("Top Lat");
gtk_label_set_xalign(GTK_LABEL(label), 0.0);
data->topLatSpin = GTK_SPIN_BUTTON(gtk_spin_button_new_with_range(-90, 90, 1));
gtk_spin_button_set_value(GTK_SPIN_BUTTON(data->topLatSpin), data->topLat);
gtk_grid_attach(GTK_GRID(grid), label, 2, 0, 1, 1);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(data->topLatSpin), 3, 0, 1, 1);
label = gtk_label_new("Left Lon");
gtk_label_set_xalign(GTK_LABEL(label), 0.0);
data->leftLonSpin = GTK_SPIN_BUTTON(gtk_spin_button_new_with_range(-180, 180, 1));
gtk_spin_button_set_value(GTK_SPIN_BUTTON(data->leftLonSpin), data->leftLon);
gtk_grid_attach(GTK_GRID(grid), label, 0, 1, 1, 1);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(data->leftLonSpin), 1, 1, 1, 1);
label = gtk_label_new("Right Lon");
gtk_label_set_xalign(GTK_LABEL(label), 0.0);
data->rightLonSpin = GTK_SPIN_BUTTON(gtk_spin_button_new_with_range(-180, 180, 1));
gtk_spin_button_set_value(GTK_SPIN_BUTTON(data->rightLonSpin), data->rightLon);
gtk_grid_attach(GTK_GRID(grid), label, 2, 1, 1, 1);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(data->rightLonSpin), 3, 1, 1, 1);
// Third line: timeStep, timeMax
label = gtk_label_new("Time Step");
gtk_label_set_xalign(GTK_LABEL(label), 0.0);
data->timeStepSpin = GTK_SPIN_BUTTON(gtk_spin_button_new_with_range(0, 24, 1));
gtk_spin_button_set_value(GTK_SPIN_BUTTON(data->timeStepSpin), TIME_STEP);
gtk_grid_attach(GTK_GRID(grid), label, 0, 2, 1, 1);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(data->timeStepSpin), 1, 2, 1, 1);
label = gtk_label_new("Forecat Time in Days");
gtk_label_set_xalign(GTK_LABEL(label), 0.0);
data->timeMaxSpin = GTK_SPIN_BUTTON(gtk_spin_button_new_with_range(0, MAX_N_DAYS_WEATHER, 1));
gtk_spin_button_set_value(GTK_SPIN_BUTTON(data->timeMaxSpin), TIME_MAX);
gtk_grid_attach(GTK_GRID(grid), label, 2, 2, 1, 1);
gtk_grid_attach(GTK_GRID(grid), GTK_WIDGET(data->timeMaxSpin), 3, 2, 1, 1);
// Multi-line zone to display URL
label = gtk_label_new("NOAA URL");
gtk_label_set_xalign(GTK_LABEL(label), 0.0);
gtk_grid_attach(GTK_GRID(grid), label, 0, 3, 1, 1);
GtkWidget *text_view = gtk_text_view_new();
gtk_text_view_set_editable(GTK_TEXT_VIEW(text_view), FALSE);
gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(text_view), GTK_WRAP_WORD_CHAR);
data->urlBuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view));
gtk_text_buffer_set_text(data->urlBuffer, data->url, -1);
gtk_grid_attach(GTK_GRID(grid), text_view, 1, 3, 3, 2);
// spin button connection
g_signal_connect(data->bottomLatSpin, "value-changed", G_CALLBACK (updateNoaaUrl), data);
g_signal_connect(data->leftLonSpin, "value-changed", G_CALLBACK (updateNoaaUrl), data);
g_signal_connect(data->topLatSpin, "value-changed", G_CALLBACK (updateNoaaUrl), data);
g_signal_connect(data->rightLonSpin, "value-changed", G_CALLBACK (updateNoaaUrl), data);
g_signal_connect(data->timeStepSpin, "value-changed", G_CALLBACK (updateNoaaUrl), data);
g_signal_connect(data->timeMaxSpin, "value-changed", G_CALLBACK (updateNoaaUrl), data);
GtkWidget *hBox = OKCancelLine (onOkButtonNoaaClicked, noaaWindow);
gtk_box_append (GTK_BOX (vBox), grid);
gtk_box_append (GTK_BOX (vBox), hBox);
gtk_window_present (GTK_WINDOW (noaaWindow));
}
/*! callback for openPolar */
void cbOpenGrib (GObject* source_object, GAsyncResult* res, gpointer data) {
GFile* file = gtk_file_dialog_open_finish ((GtkFileDialog *) source_object, res, NULL);
if (file != NULL) {
gchar *fileName = g_file_get_path(file);
printf ("File selected: %s\n", fileName);
if (fileName != NULL) {
loadGribFile (typeFlow, fileName);
g_free(fileName);
}
}
}
/*! Select grib file and read grib file, fill gribData */
static void openGrib (GSimpleAction *action, GVariant *parameter, gpointer *data) {
typeFlow = GPOINTER_TO_INT (data);
GtkFileDialog* fileDialog;
if (typeFlow == WIND)
fileDialog = selectFile ("Open Grib", "grib", "Grib Files", "*.gr*", ".*gr*");
else
fileDialog = selectFile ("Open Current Grib", "currentgrib", "Current GribFiles", "*.gr*", "*.gr");
gtk_file_dialog_open (fileDialog, GTK_WINDOW (window), NULL, cbOpenGrib, NULL);
}
/*! callback for openPolar */
void cbOpenPolar (GObject* source_object, GAsyncResult* res, gpointer data) {
GFile* file = gtk_file_dialog_open_finish ((GtkFileDialog *) source_object, res, NULL);
if (file != NULL) {
gchar *fileName = g_file_get_path(file);
printf ("File selected: %s\n", fileName);
if (fileName != NULL) {
if (strstr (fileName, "polwave.csv") == NULL) {
readPolar (fileName, &polMat);
strncpy (par.polarFileName, fileName, sizeof (par.polarFileName) - 1);
polarType = POLAR;
polarDraw ();
}
else {
readPolar (fileName, &wavePolMat);
strncpy (par.wavePolFileName, fileName, sizeof (par.wavePolFileName) - 1);
polarType = WAVE_POLAR;
polarDraw ();
}
g_free(fileName);
}
}
}
/*! Select polar file and read polar file, fill polMat */
static void openPolar () {
GtkFileDialog* fileDialog = selectFile ("Open Polar", "pol", "Polar Files", "*.csv", "*.pol");
gtk_file_dialog_open (fileDialog, GTK_WINDOW (window), NULL, cbOpenPolar, NULL);
}
/*! callback for openPolar */
void cbSaveScenario (GObject* source_object, GAsyncResult* res, gpointer data) {
GFile* file = gtk_file_dialog_save_finish ((GtkFileDialog *) source_object, res, NULL);
if (file != NULL) {
gchar *fileName = g_file_get_path(file);
if (fileName != NULL) {
printf ("File: %s\n", fileName);
printf ("Mail Pw Exist: %d\n", par.storeMailPw);
writeParam (fileName, false, par.storeMailPw);
g_free(fileName);
}
}
}
/*! Select polar file and read polar file, fill polMat */
static void saveScenario () {
GtkFileDialog *fileDialog = selectFile ("Save as", "par", "Parameter Files", "*.par", "*.par");
gtk_file_dialog_save (fileDialog, GTK_WINDOW (window), NULL, cbSaveScenario, NULL);
}
/*! Make initialization following parameter file load */
static void initScenario () {
char str [MAX_SIZE_LINE];
int poiIndex = -1;
double unusedTime;
if (par.gribFileName [0] != '\0') {
iFlow = WIND;
readGrib (&iFlow);
if (readGribRet == 0) {
fprintf (stderr, "Error in initScenario: Unable to read grib file: %s\n ", par.gribFileName);
return;
}
printf ("Grib loaded : %s\n", par.gribFileName);
printf ("Grib DateTime0 : %s\n", gribDateTimeToStr (zone.dataDate [0], zone.dataTime [0], str, sizeof (str)));
theTime = zone.timeStamp [0];
updatedColors = false;
initDispZone ();
}
if (par.currentGribFileName [0] != '\0') {
iFlow = CURRENT;
readGrib (&iFlow);
printf ("Cur grib loaded: %s\n", par.currentGribFileName);
printf ("Grib DateTime0 : %s\n", gribDateTimeToStr (currentZone.dataDate [0], currentZone.dataTime [0], str, sizeof (str)));
}
if (readPolar (par.polarFileName, &polMat))
printf ("Polar loaded : %s\n", par.polarFileName);
if (readPolar (par.wavePolFileName, &wavePolMat))
printf ("Polar loaded : %s\n", par.wavePolFileName);
nPoi = 0;
if (par.poiFileName [0] != '\0')
nPoi += readPoi (par.poiFileName);
if (par.portFileName [0] != '\0')
nPoi += readPoi (par.portFileName);
if ((poiIndex = findPoiByName (par.pOrName, &par.pOr.lat, &par.pOr.lon)) != -1)
strncpy (par.pOrName, tPoi [poiIndex].name, sizeof (par.pOrName) - 1);
else par.pOrName [0] = '\0';
if ((poiIndex = findPoiByName (par.pDestName, &par.pDest.lat, &par.pDest.lon)) != -1)
strncpy (par.pDestName, tPoi [poiIndex].name, sizeof (par.pDestName) - 1);
else par.pDestName [0] = '\0';
if (par.pOr.id != -1) // not initialized
findLastTracePoint (par.traceFileName, &par.pOr.lat, &par.pOr.lon, &unusedTime);
nIsoc = 0;
route.n = 0;
route.destinationReached = false;
initWayPoints ();
}
/*! launch system command in a thread */
void* scenarioEditRun (void *data) {
FILE *fs;
char line [MAX_SIZE_LINE] = "";
snprintf (line, sizeof (line), "%s %s\n", par.editor, parameterFileName);
if ((fs = popen (line, "r")) == NULL) {
fprintf (stderr, "Error in scenarioEditRun: system call: %s\n", line);
}
else {
pclose (fs);
readParam (parameterFileName);
initScenario ();
if (readGribRet == 0) {
infoMessage ("Error in readgrib", GTK_MESSAGE_ERROR);
}
gtk_widget_queue_draw (drawing_area);
}
return NULL;
}
/*! Edit parameter file */
static void editScenario () {
g_thread_new ("editScenario", scenarioEditRun, NULL);
}
/* call back for openScenario */
void cbOpenScenario (GObject* source_object, GAsyncResult* res, gpointer data) {
GFile* file = gtk_file_dialog_open_finish ((GtkFileDialog *) source_object, res, NULL);
if (file != NULL) {
gchar *fileName = g_file_get_path(file);
printf ("File selected: %s\n", fileName);
if (fileName != NULL) {
strncpy (parameterFileName, fileName, MAX_SIZE_FILE_NAME);
readParam (fileName);
initScenario ();
if (readGribRet == 0)
infoMessage ("Error in readgrib", GTK_MESSAGE_ERROR);
g_free(fileName);
gtk_widget_queue_draw (drawing_area);
}
}
}
/*! Read parameter file and initialize context */
static void openScenario () {
GtkFileDialog* fileDialog =selectFile ("Open Parameters", "par", "Parameter Files", "*.par", "*.par");
gtk_file_dialog_open (fileDialog, GTK_WINDOW (window), NULL, cbOpenScenario, NULL);
}
/*! provides meta information about grib file, called by gribInfo */
static void gribInfoDisplay (const char *fileName, Zone *zone) {
const size_t MAX_VISIBLE_SHORTNAME = 10;
char buffer [MAX_SIZE_BUFFER];
char line [MAX_SIZE_LINE] = "";
char str [MAX_SIZE_NAME] = "";
char str1 [MAX_SIZE_NAME] = "";
char strTmp [MAX_SIZE_LINE] = "";
char strLat0 [MAX_SIZE_NAME] = "", strLon0 [MAX_SIZE_NAME] = "";
char strLat1 [MAX_SIZE_NAME] = "", strLon1 [MAX_SIZE_NAME] = "";
char centreName [MAX_SIZE_NAME] = "";
int l = 0;
long timeStep;
bool isTimeStepOK = true;
// for (size_t i = 0; i < sizeof(dicTab) / sizeof(dicTab[0]); i++) // search name of center
for (size_t i = 0; i < 4; i++) // search name of center
if (dicTab [i].id == zone->centreId)
strncpy (centreName, dicTab [i].name, sizeof (centreName) - 1);
snprintf (line, sizeof (line), "Centre ID: %ld %s Ed. number: %ld", zone->centreId, centreName, zone->editionNumber);
GtkWidget *gribWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (gribWindow), line);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), gribWindow);
GtkWidget *grid = gtk_grid_new();
gtk_window_set_child (GTK_WINDOW (gribWindow), (GtkWidget *) grid);
gtk_grid_set_column_spacing(GTK_GRID(grid), 10);
gtk_grid_set_row_spacing(GTK_GRID(grid), 5);
gtk_grid_set_row_homogeneous(GTK_GRID(grid), FALSE);
gtk_grid_set_column_homogeneous(GTK_GRID(grid), FALSE);
newDate (zone->dataDate [0], zone->dataTime [0]/100, strTmp);
lineReport (grid, 0, "document-open-recent", "Date From", strTmp);
newDate (zone->dataDate [0], zone->dataTime [0]/100 + zone->timeStamp [zone->nTimeStamp -1], strTmp);
lineReport (grid, l+=2, "document-open-recent", "Date To", strTmp);
snprintf (line, sizeof (line), "%d", zone->nMessage);
lineReport (grid, l+=2, "zoom-original-symbolic", "Nb. Messages", line);
snprintf (line, sizeof (line), "%ld", zone->stepUnits);
lineReport (grid, l+=2, "document-page-setup", "Step Unit", line);
snprintf (line, sizeof (line), "%ld", zone->numberOfValues);
lineReport (grid, l+=2, "document-page-setup-symbolic", "Nb. of Values", line);
snprintf (line, sizeof (line), "From: %s, %s To: %s %s", latToStr (zone->latMax, par.dispDms, strLat0), lonToStr (zone->lonLeft, par.dispDms, strLon0),
latToStr (zone->latMin, par.dispDms, strLat1), lonToStr (zone->lonRight, par.dispDms, strLon1));
lineReport (grid, l+=2, "network-workgroup-symbolic", "Zone ", line);
snprintf (line, sizeof (line), "%.3f° - %.3f°\n", zone->latStep, zone->lonStep);
lineReport (grid, l+=2, "dialog-information-symbolic", "Lat Step - Lon Step", line);
snprintf (line, sizeof (line), "%ld - %ld\n", zone->nbLat, zone->nbLon);
lineReport (grid, l+=2 , "preferences-desktop-locale-symbolic", "Nb. Lat - Nb. Lon", line);
timeStep = zone->timeStamp [1] - zone->timeStamp [0];
// check if regular
for (size_t i = 1; i < zone->nTimeStamp - 1; i++)
if ((zone->timeStamp [i] - zone->timeStamp [i-1]) != timeStep) {
isTimeStepOK = false;
// printf ("timeStep: %ld other timeStep: %ld\n", timeStep, zone->timeStamp [i] - zone->timeStamp [i-1]);
}
snprintf (strTmp, sizeof (strTmp), "TimeStamp List of %s %zu", (isTimeStepOK)? "regular" : "UNREGULAR", zone->nTimeStamp);
if (zone->nTimeStamp < 8 || ! isTimeStepOK) {
strcpy (buffer, "[ ");
for (size_t k = 0; k < zone->nTimeStamp; k++) {
if ((k > 0) && ((k % 20) == 0))
g_strlcat (buffer, "\n", MAX_SIZE_BUFFER);
snprintf (str, sizeof (str), "%ld ", zone->timeStamp [k]);
if (strlen (buffer) > MAX_SIZE_BUFFER - 10)
break;
g_strlcat (buffer, str, MAX_SIZE_BUFFER);
}
g_strlcat (buffer, "]\n", MAX_SIZE_BUFFER);
}
else {
snprintf (buffer, sizeof (buffer), "[%ld, %ld, ..%ld]\n", zone->timeStamp [0], zone->timeStamp [1], zone->timeStamp [zone->nTimeStamp - 1]);
}
lineReport (grid, l+=2, "view-list-symbolic", strTmp, buffer);
strcpy (line, "[ ");
for (size_t k = 0; k < MIN (zone->nShortName -1, MAX_VISIBLE_SHORTNAME); k++) {
snprintf (str, sizeof (str), "%s ", zone->shortName [k]);
g_strlcat (line, str, MAX_SIZE_LINE);
}
if (zone->nShortName > 0) {
if (zone->nShortName -1 < MAX_VISIBLE_SHORTNAME) {
snprintf (str, sizeof (str), "%s ]\n", zone->shortName [zone->nShortName -1]);
g_strlcat (line, str, MAX_SIZE_LINE);
}
else
strcat (line, ", ...]");
}
snprintf (strTmp, sizeof (strTmp), "List of %zu shortnames", zone->nShortName);
lineReport (grid, l+=2, "non-starred-symbolic", strTmp, line);
snprintf (line, sizeof (line), "%s\n", (zone->wellDefined) ? (zone->allTimeStepOK) ? "Well defined" : "All TimeSteps are not defined" : "Undefined");
lineReport (grid, l+=2 , (zone->wellDefined) ? "weather-clear" : "weather-showers", "Zone is", line);
lineReport (grid, l+=2 , "mail-attachment-symbolic", "Grib File Name", fileName);
formatThousandSep (str1, getFileSize (fileName));
lineReport (grid, l+=2, "document-properties-symbolic", "Grib File size", str1);
if ((zone->nDataDate > 1) || (zone->nDataTime > 1)) {
snprintf (line, sizeof (line), "Date: %zu, Time: %zu\n", zone->nDataDate, zone->nDataTime);
lineReport (grid, l+=2, "software-update-urgent-symbolic", "Warning number of", line);
}
gtk_window_present (GTK_WINDOW (gribWindow));
}
/*! provides meta information about grib file */
static void gribInfo (GSimpleAction *action, GVariant *parameter, gpointer *data) {
typeFlow = GPOINTER_TO_INT (data);
if (typeFlow == WIND) {
if (zone.nbLat == 0)
infoMessage ("No wind data grib available", GTK_MESSAGE_ERROR);
else
gribInfoDisplay (par.gribFileName, &zone);
}
else { // current
if (currentZone.nbLat == 0)
infoMessage ("No current data grib available", GTK_MESSAGE_ERROR);
else
gribInfoDisplay (par.currentGribFileName, ¤tZone);
}
}
/*! read mail grib received from provider */
static gboolean mailGribRead (gpointer data) {
FILE *fp;
char command [MAX_SIZE_LINE * 2];
if (! gribRequestRunning) {
return TRUE;
}
char line[MAX_SIZE_LINE] = "";
char buffer[MAX_SIZE_BUFFER] = "\n";
int n = 0;
char *fileName, *end;
char newPw [MAX_SIZE_NAME];
dollarSubstitute (par.mailPw, newPw, MAX_SIZE_NAME);
snprintf (command, sizeof (command), "%s %s%s %s", par.imapScript, par.workingDir, (provider == SAILDOCS_CURR) ? "currentgrib" : "grib", newPw);
if ((fp = popen (command, "r")) == NULL) {
fprintf (stderr, "Error in mailGribRead. popen command: %s\n", command);
gribRequestRunning = false;
spinnerWindowDestroy ();
return TRUE;
}
while (fgets (line, sizeof(line)-1, fp) != NULL) {
n += 1;
printf ("line: %s\n", line);
g_strlcat (buffer, line, MAX_SIZE_BUFFER);
}
pclose(fp);
if (n > 0) {
g_source_remove (gribMailTimeout); // timer stopped
if (((fileName = strstr (buffer, "File: /") + 6) != NULL) && (n > 2)) {
printf ("Mail Response: %s\n", buffer);
while (isspace (*fileName)) fileName += 1;
if ((end = strstr (fileName, " ")) != NULL)
*(end) = '\0';
spinnerWindowDestroy ();
loadGribFile ((provider == SAILDOCS_CURR) ? CURRENT: WIND, fileName);
}
else infoMessage ("Grib File not found", GTK_MESSAGE_ERROR);
spinnerWindowDestroy ();
gribRequestRunning = false;
}
return TRUE;
}
/*! return maxTimeRange of GFS model based on timeStep and resolution */
static int maxTimeRange () {
switch (provider) {
case SAILDOCS_GFS: case MAILASAIL:
if (par.gribResolution <= 0.25)
return 120;
else if (par.gribResolution < 1.0)
return (par.gribTimeStep < 6) ? 192 : 240;
else return (par.gribTimeStep < 6) ? 192 : (par.gribTimeStep < 12) ? 240 : 384;
case SAILDOCS_ECMWF:
return (par.gribTimeStep < 6) ? 144 : 240;
case SAILDOCS_ICON:
return 120;
case SAILDOCS_ARPEGE:
return 96;
case SAILDOCS_AROME:
return 48;
case SAILDOCS_CURR:
return 192;
default:
fprintf (stderr, "Error in maxTimeRange: provider not supported: %d\n", provider);
return 120;
}
}
/*! return number of values x n message wich give an evaluation
of grib file size in bytes */
static int evalSize (int nShortName) {
int nValue = ((abs (mailRequestPar.lat2-mailRequestPar.lat1) / par.gribResolution) + 1) * \
((abs (mailRequestPar.lon2-mailRequestPar.lon1) / par.gribResolution) + 1);
int nMessage = nShortName * (1 + (par.gribTimeMax / par.gribTimeStep));
return nMessage * nValue;
}
/* update timemax and size value of the mail request box */
static void updateMailRequestBox () {
char str [MAX_SIZE_LINE] = "";
if (spinButtonTimeMax != NULL) {
gtk_spin_button_set_value(GTK_SPIN_BUTTON (spinButtonTimeMax), par.gribTimeMax / 24);
formatThousandSep (str, evalSize (6));
gtk_label_set_text(GTK_LABEL (valSizeEval), str);
}
}
/*! Callback Time Step value */
static void timeStepChanged (GtkSpinButton *spin_button, gpointer user_data) {
par.gribTimeStep = gtk_spin_button_get_value_as_int(spin_button);
par.gribTimeMax = maxTimeRange ();
updateMailRequestBox ();
}
/*! Callback Time Max value */
static void timeMaxChanged (GtkSpinButton *spin_button, gpointer user_data) {
par.gribTimeMax = gtk_spin_button_get_value_as_int(spin_button) * 24;
par.gribTimeMax = MIN (par.gribTimeMax, maxTimeRange ());
updateMailRequestBox ();
}
/*! Callback resolution */
static void resolutionChanged (GtkSpinButton *spin_button, gpointer user_data) {
par.gribResolution = gtk_spin_button_get_value (spin_button);
par.gribTimeMax = maxTimeRange ();
updateMailRequestBox ();
}
/*! Callback change mail provider */
static void cbMailDropDown (GObject *dropDown, GParamSpec *pspec, gpointer user_data) {
provider = gtk_drop_down_get_selected (GTK_DROP_DOWN(dropDown));
g_print ("Selected provider: %d\n", provider);
par.gribTimeMax = maxTimeRange ();
updateMailRequestBox ();
}
/*! Callback to set up mail password */
static void passwordEntryChanged (GtkEditable *editable, gpointer user_data) {
const gchar *text = gtk_editable_get_text (editable);
g_strlcpy (par.mailPw, text, MAX_SIZE_NAME);
}
/*! action when closing mail request box */
static void onOkButtonMailClicked (GtkWidget *widget, gpointer theWindow) {
//static void mailRequestBoxResponse (GtkDialog *dialog, gint response_id, gpointer user_data) {
FILE *fs;
char buffer [MAX_SIZE_BUFFER] = "";
char *ptBuffer, *ptBuffer1;
char command [MAX_SIZE_LINE * 2] = "";
char newPw [MAX_SIZE_NAME];
dollarSubstitute (par.mailPw, newPw, MAX_SIZE_NAME);
//if (response_id == GTK_RESPONSE_ACCEPT) {
if (smtpGribRequestPython (provider, mailRequestPar.lat1, mailRequestPar.lon1, mailRequestPar.lat2, mailRequestPar.lon2, buffer, MAX_SIZE_BUFFER)) {
ptBuffer = strchr (buffer, ' '); // delete first words
ptBuffer1 = strchr (ptBuffer + 1, ' '); // delete second word
spinner ("Waiting for grib Mail response", ptBuffer1);
snprintf (command, sizeof (command), "%s %s", par.imapToSeen, newPw);
if ((fs = popen (command, "r")) == NULL) {
infoMessage ("Error running imapToSeen script", GTK_MESSAGE_ERROR);;
return;
}
pclose (fs);
// printf ("ImapToSeen: command:%s\n", command);
gribRequestRunning = true;
gribMailTimeout = g_timeout_add (GRIB_TIME_OUT, mailGribRead, NULL);
}
else {
infoMessage ("Error SMTP request Python, check connectivity and mail Password", GTK_MESSAGE_ERROR);
}
//}
gtk_window_destroy (GTK_WINDOW (theWindow));
}
/*! mail request dialog box */
static void mailRequestBox (double lat1, double lon1, double lat2, double lon2) {
char strLat1 [MAX_SIZE_NAME] = "", strLon1 [MAX_SIZE_NAME] = "";
char strLat2 [MAX_SIZE_NAME] = "", strLon2 [MAX_SIZE_NAME] = "";
char str [MAX_SIZE_LINE] = "", str1 [MAX_SIZE_LINE] = "";
mailRequestPar.lat1 = lat1;
mailRequestPar.lon1 = lon1;
mailRequestPar.lat2 = lat2;
mailRequestPar.lon2 = lon2;
snprintf (str, sizeof (str), "%s, %s to %s, %s", latToStr (lat1, par.dispDms, strLat1), lonToStr (lon1, par.dispDms, strLon1),
latToStr (lat2, par.dispDms, strLat2), lonToStr (lon2, par.dispDms, strLon2));
GtkWidget *separator = gtk_separator_new (GTK_ORIENTATION_HORIZONTAL);
GtkWidget *mailWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW (mailWindow), "Launch Mail Grib Request");
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), mailWindow);
GtkWidget *vBox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (mailWindow), (GtkWidget *) vBox);
gtk_widget_set_size_request (mailWindow, 400, -1);
GtkWidget *grid = gtk_grid_new();
gtk_grid_set_column_spacing (GTK_GRID(grid), 10);
gtk_grid_set_row_spacing (GTK_GRID(grid), 5);
GtkWidget *label_zone = gtk_label_new ("Zone");
gtk_label_set_xalign(GTK_LABEL(label_zone), 0);
gtk_grid_attach(GTK_GRID (grid), label_zone, 0, 0, 1, 1);
GtkWidget *label_buffer = gtk_label_new (str);
gtk_grid_attach(GTK_GRID (grid), label_buffer, 1, 0, 3, 1);
GtkWidget *label_model = gtk_label_new ("Model");
/* Create GlistStore to store strings */
GtkStringList *string_list = gtk_string_list_new (NULL);
for (int i = 0; i < N_PROVIDERS; i++) {
snprintf (str, sizeof (str), "%s", providerTab [i].libelle);
gtk_string_list_append (string_list, str);
}
// GtkWidget *dropDown = gtk_drop_down_new_from_strings (providerArray);
GtkWidget *dropDown = gtk_drop_down_new (G_LIST_MODEL(string_list), NULL);
gtk_drop_down_set_selected ((GtkDropDown *) dropDown, 0);
g_signal_connect (dropDown, "notify::selected", G_CALLBACK (cbMailDropDown), NULL);
gtk_label_set_xalign(GTK_LABEL(label_model), 0);
gtk_grid_attach(GTK_GRID(grid), label_model, 0, 1, 1, 1);
gtk_grid_attach(GTK_GRID(grid), dropDown, 1, 1, 3, 1);
// Create Time Step and Time Max
GtkWidget *label_resolution = gtk_label_new("Resolution");
// gtk_adjustment_new(gdouble value, gdouble lower, gdouble upper, gdouble step_increment, gdouble page_increment, gdouble page_size);
GtkAdjustment *adjustment = gtk_adjustment_new (0.5, 0.25, 1.0, 0.25, 1.0, 0.0);
// Crete GtkSpinButton with GtkAdjustment
GtkWidget *spin_button_resolution = gtk_spin_button_new(adjustment, 0.25, 2); // 0.25 resolution, 2 nombre de chiffres après la virgule
gtk_spin_button_set_value(GTK_SPIN_BUTTON (spin_button_resolution), par.gribResolution);
g_signal_connect (spin_button_resolution, "value-changed", G_CALLBACK (resolutionChanged), NULL);
gtk_label_set_xalign(GTK_LABEL (label_resolution), 0);
gtk_grid_attach(GTK_GRID (grid), label_resolution, 0, 2, 1, 1);
gtk_grid_attach(GTK_GRID (grid), spin_button_resolution, 1, 2, 1, 1);
GtkWidget *label_time_step = gtk_label_new("Time Step");
GtkWidget *spin_button_time_step = gtk_spin_button_new_with_range(3, 24, 3);
gtk_spin_button_set_value(GTK_SPIN_BUTTON (spin_button_time_step), par.gribTimeStep);
g_signal_connect (spin_button_time_step, "value-changed", G_CALLBACK (timeStepChanged), NULL);
gtk_label_set_xalign(GTK_LABEL (label_time_step), 0);
gtk_grid_attach(GTK_GRID (grid), label_time_step, 0, 3, 1, 1);
gtk_grid_attach(GTK_GRID (grid), spin_button_time_step, 1, 3, 1, 1);
strcpy (str, "Forecast time in days");
GtkWidget *label_time_max = gtk_label_new (str);
spinButtonTimeMax = gtk_spin_button_new_with_range (1, MAX_N_DAYS_WEATHER, 1); // ATT : Global variable
gtk_spin_button_set_value(GTK_SPIN_BUTTON (spinButtonTimeMax), par.gribTimeMax / 24);
g_signal_connect (spinButtonTimeMax, "value-changed", G_CALLBACK (timeMaxChanged), NULL);
gtk_label_set_xalign(GTK_LABEL (label_time_max), 0);
gtk_grid_attach(GTK_GRID (grid), label_time_max, 0, 4, 1, 1);
gtk_grid_attach(GTK_GRID (grid), spinButtonTimeMax, 1, 4, 1, 1);
GtkWidget *label_size_eval = gtk_label_new ("Number of values ");
gtk_label_set_xalign(GTK_LABEL (label_size_eval), 0);
formatThousandSep (str1, evalSize (6));
valSizeEval = gtk_label_new (str1);
gtk_widget_set_halign (valSizeEval, GTK_ALIGN_START);
gtk_grid_attach(GTK_GRID (grid), label_size_eval, 0, 5, 1, 1);
gtk_grid_attach(GTK_GRID (grid), valSizeEval, 1, 5, 1, 1);
gtk_grid_attach(GTK_GRID (grid), separator, 0, 6, 3, 1);
if (par.mailPw [0] == '\0') { // password needed if does no exist
GtkWidget *password_label = gtk_label_new ("Mail Password");
gtk_label_set_xalign(GTK_LABEL (password_label), 0);
GtkWidget *password_entry = gtk_entry_new ();
gtk_entry_set_visibility (GTK_ENTRY (password_entry), FALSE);
gtk_entry_set_invisible_char (GTK_ENTRY (password_entry), '*');
g_signal_connect (password_entry, "changed", G_CALLBACK (passwordEntryChanged), par.mailPw);
gtk_grid_attach (GTK_GRID (grid), password_label, 0, 7, 1, 1);
gtk_grid_attach (GTK_GRID (grid), password_entry, 1, 7, 1, 1);
}
GtkWidget *hBox = OKCancelLine (onOkButtonMailClicked, mailWindow);
gtk_box_append (GTK_BOX (vBox), grid);
gtk_box_append (GTK_BOX (vBox), hBox);
// g_object_unref (string_list);
gtk_window_present (GTK_WINDOW (mailWindow));
}
/*! For testing */
static void testFunction () {
char buffer [MAX_SIZE_BUFFER];
printf ("test\n");
checkGribToStr (buffer, MAX_SIZE_BUFFER);
displayText (750, 400, buffer, "Grib Wind Check");
// printGrib (&zone, tGribData [WIND]);
}
/*! Display label in col c and ligne l of tab */
static void labelCreate (GtkWidget *tab, char *name, int c, int l) {
GtkWidget *label = gtk_label_new (name);
gtk_grid_attach(GTK_GRID(tab), label, c, l, 1, 1);
gtk_widget_set_margin_start(label, 10);
gtk_label_set_xalign(GTK_LABEL(label), 0.0);
}
/*! Lat update for change */
static void onLatChange (GtkWidget *widget, gpointer data) {
double *x_ptr = (double *) data;
*x_ptr = getCoord (gtk_editable_get_text (GTK_EDITABLE (widget)));
gtk_widget_queue_draw (drawing_area);
}
/*! Origin Lon update for change */
static void onLonChange (GtkWidget *widget, gpointer data) {
double *x_ptr = (double *) data;
*x_ptr = getCoord (gtk_editable_get_text (GTK_EDITABLE (widget)));
*x_ptr = lonCanonize (*x_ptr);
gtk_widget_queue_draw (drawing_area);
}
/*! Callback Radio button for Wind colors */
static void radioButtonColors (GtkToggleButton *button, gpointer user_data) {
par.showColors = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "index"));
gtk_widget_queue_draw (drawing_area); // affiche le tout
destroySurface ();
}
/*! Radio button for Wind Colar */
static GtkWidget *createRadioButtonColors (char *name, GtkWidget *tabDisplay, GtkWidget *from, int i) {
GtkWidget *choice = gtk_check_button_new_with_label (name);
g_object_set_data (G_OBJECT(choice), "index", GINT_TO_POINTER(i));
g_signal_connect (choice, "toggled", G_CALLBACK (radioButtonColors), NULL);
gtk_grid_attach (GTK_GRID(tabDisplay), choice, i+1, 1, 1, 1);
if (from != NULL)
gtk_check_button_set_group ((GtkCheckButton *) choice, (GtkCheckButton *) from);
if (i == par.showColors)
gtk_check_button_set_active ((GtkCheckButton *) choice, TRUE);
return choice;
}
/*! Callback wind representation */
static void radioButtonWindDisp (GtkToggleButton *button, gpointer user_data) {
par.windDisp = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(button), "index"));
gtk_widget_queue_draw (drawing_area);
}
/*! Radio button for Wind disp */
static GtkWidget *createRadioButtonWindDisp (char *name, GtkWidget *tabDisplay, GtkWidget *from, int i) {
GtkWidget *choice = gtk_check_button_new_with_label (name);
g_object_set_data (G_OBJECT(choice), "index", GINT_TO_POINTER(i));
g_signal_connect (choice, "toggled", G_CALLBACK (radioButtonWindDisp), NULL);
gtk_grid_attach (GTK_GRID(tabDisplay), choice, i+1, 2, 1, 1);
if (from != NULL)
gtk_check_button_set_group ((GtkCheckButton *) choice, (GtkCheckButton *) from);
if (i == par.windDisp)
gtk_check_button_set_active ((GtkCheckButton *) choice, TRUE);
return choice;
}
/*! CallBack for disp choice Avr or Gust or Rain or Pressure */
static void cbDropDownDisp (GObject *dropDown, GParamSpec *pspec, gpointer user_data) {
par.averageOrGustDisp = gtk_drop_down_get_selected (GTK_DROP_DOWN (dropDown));
gtk_widget_queue_draw (drawing_area); // Draw all
destroySurface ();
}
/*! CallBack for Isochrone choice */
static void cbDropDownIsoc (GObject *dropDown, GParamSpec *pspec, gpointer user_data) {
par.style = gtk_drop_down_get_selected (GTK_DROP_DOWN (dropDown));
gtk_widget_queue_draw (drawing_area); // Draw all
}
/*! CallBack for DMS choice */
static void cbDropDownDMS (GObject *dropDown, GParamSpec *pspec, gpointer user_data) {
par.dispDms = gtk_drop_down_get_selected (GTK_DROP_DOWN (dropDown));
statusBarUpdate ();
}
/*! Callback activated or not */
static void onCheckBoxToggled (GtkWidget *checkbox, gpointer user_data) {
gboolean *flag = (gboolean *)user_data;
*flag = gtk_check_button_get_active ((GtkCheckButton *) checkbox);
gtk_widget_queue_draw (drawing_area);
}
/*! Callback for poi visibility change level */
static void onLevelPoiVisibleChanged (GtkScale *scale, gpointer label) {
par.maxPoiVisible = gtk_range_get_value(GTK_RANGE(scale));
gchar *value_str = g_strdup_printf("POI: %d", par.maxPoiVisible);
gtk_label_set_text(GTK_LABEL(label), value_str);
g_free(value_str);
gtk_widget_queue_draw (drawing_area);
}
/*! Callback for speed display change */
static void onTempoDisplayChanged (GtkScale *scale, gpointer label) {
par.speedDisp = gtk_range_get_value(GTK_RANGE(scale)) ;
gchar *value_str = g_strdup_printf("Display Speed: %d", par.speedDisp);
gtk_label_set_text(GTK_LABEL(label), value_str);
g_free(value_str);
changeAnimation ();
}
/*! Translate double to entry */
static GtkWidget *doubleToEntry (double x) {
char str [MAX_SIZE_NAME];
snprintf (str, sizeof (str), "%.2lf", x);
return gtk_entry_new_with_buffer(gtk_entry_buffer_new(str, -1)); // Create and return the entry with buffer
}
/*! Translate lat to entry */
static GtkWidget *latToEntry (double lat) {
char str [MAX_SIZE_NAME];
latToStr (lat, par.dispDms, str);
return gtk_entry_new_with_buffer(gtk_entry_buffer_new(str, -1)); // Create and return the entry with buffer
}
/*! Translate lon to entry */
static GtkWidget *lonToEntry (double lon) {
char str [MAX_SIZE_NAME];
lonToStr (lon, par.dispDms, str);
return gtk_entry_new_with_buffer(gtk_entry_buffer_new(str, -1)); // Create and return the entry with buffer
}
/*! double update for change */
static void doubleUpdate (GtkWidget *widget, gpointer data) {
double *x_ptr = (double *)data;
*x_ptr = strtod (gtk_editable_get_text(GTK_EDITABLE(widget)), NULL);
}
/*! wind Twd update for change */
static void windTwdUpdate (GtkWidget *widget, gpointer data) {
par.constWindTwd = strtod (gtk_editable_get_text(GTK_EDITABLE(widget)), NULL);
gtk_widget_queue_draw (drawing_area);
}
/*! wind Tws update for change */
static void windTwsUpdate (GtkWidget *widget, gpointer data) {
par.constWindTws = strtod (gtk_editable_get_text(GTK_EDITABLE(widget)), NULL);
if (par.constWindTws != 0)
initZone (&zone);
gtk_widget_queue_draw (drawing_area);
}
/*! Change parameters and pOr and pDest coordinates */
static void change () {
// Create dialog box
GtkWidget *changeWindow = gtk_application_window_new (app);
gtk_window_set_title (GTK_WINDOW(changeWindow), "change");
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), changeWindow);
// Create notebook
GtkWidget *notebook = gtk_notebook_new();
gtk_window_set_child (GTK_WINDOW (changeWindow), notebook);
// "Display" notebook
GtkWidget *tabDisplay = gtk_grid_new();
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tabDisplay, gtk_label_new("Display"));
gtk_widget_set_halign(GTK_WIDGET(tabDisplay), GTK_ALIGN_START);
gtk_widget_set_valign(GTK_WIDGET(tabDisplay), GTK_ALIGN_START);
gtk_grid_set_row_spacing(GTK_GRID(tabDisplay), 20);
gtk_grid_set_column_spacing(GTK_GRID(tabDisplay), 5);
// "Parameter" notebook
GtkWidget *tabParam = gtk_grid_new();
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tabParam, gtk_label_new("Parameter"));
gtk_grid_set_row_spacing(GTK_GRID(tabParam), 5);
gtk_grid_set_column_spacing(GTK_GRID(tabParam), 5);
// "Technical" notebook
GtkWidget *tabTec = gtk_grid_new();
if (par.techno)
gtk_notebook_append_page(GTK_NOTEBOOK(notebook), tabTec, gtk_label_new("Technical"));
gtk_grid_set_row_spacing(GTK_GRID(tabTec), 5);
gtk_grid_set_column_spacing(GTK_GRID(tabTec), 5);
// Create origin
GtkWidget *entryOriginLat = latToEntry (par.pOr.lat);
GtkWidget *entryOriginLon = lonToEntry (par.pOr.lon);
labelCreate (tabParam, "Origin. Lat", 0, 0);
gtk_grid_attach (GTK_GRID(tabParam), entryOriginLat, 1, 0, 1, 1);
labelCreate (tabParam, "Lon", 0, 1);
gtk_grid_attach (GTK_GRID(tabParam), entryOriginLon, 1, 1, 1, 1);
g_signal_connect (entryOriginLat, "changed", G_CALLBACK (onLatChange), &par.pOr.lat);
g_signal_connect (entryOriginLon, "changed", G_CALLBACK (onLonChange), &par.pOr.lon);
// Create destination
GtkWidget *entryDestLat = latToEntry (par.pDest.lat);
GtkWidget *entryDestLon = lonToEntry (par.pDest.lon);
labelCreate (tabParam, "Dest. Lat", 0, 2);
gtk_grid_attach (GTK_GRID(tabParam), entryDestLat, 1, 2, 1, 1);
labelCreate (tabParam, "Lon", 0, 3);
gtk_grid_attach( GTK_GRID(tabParam), entryDestLon, 1, 3, 1, 1);
g_signal_connect (entryDestLat, "changed", G_CALLBACK (onLatChange), &par.pDest.lat);
g_signal_connect (entryDestLon, "changed", G_CALLBACK (onLonChange), &par.pDest.lon);
// Create xWind
labelCreate (tabParam, "xWind", 0, 4);
GtkWidget *entryXWind = doubleToEntry (par.xWind);
gtk_grid_attach (GTK_GRID (tabParam), entryXWind, 1, 4, 1, 1);
g_signal_connect (entryXWind, "changed", G_CALLBACK (doubleUpdate), &par.xWind);
// Create max Wind
labelCreate (tabParam, "Max Wind", 0, 5);
GtkWidget *entryMaxWind = doubleToEntry (par.maxWind);
gtk_grid_attach(GTK_GRID(tabParam), entryMaxWind, 1, 5, 1, 1);
g_signal_connect (entryMaxWind, "changed", G_CALLBACK (doubleUpdate), &par.maxWind);
// Create penalty
labelCreate (tabParam, "Virement de bord", 0, 6);
GtkWidget *spinPenalty0 = gtk_spin_button_new_with_range (0, 60, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinPenalty0), par.penalty0);
gtk_grid_attach(GTK_GRID(tabParam), spinPenalty0, 1, 6, 1, 1);
g_signal_connect (spinPenalty0, "value-changed", G_CALLBACK (intSpinUpdate), &par.penalty0);
labelCreate (tabParam, "Empannage", 0, 7);
GtkWidget *spinPenalty1 = gtk_spin_button_new_with_range (0, 60, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinPenalty1), par.penalty1);
gtk_grid_attach(GTK_GRID(tabParam), spinPenalty1, 1, 7, 1, 1);
g_signal_connect (spinPenalty1, "value-changed", G_CALLBACK (intSpinUpdate), &par.penalty1);
// Create motorSpeed, threshold
labelCreate (tabParam, "Motor Speed ", 0, 8);
GtkWidget *entrySog = doubleToEntry (par.motorSpeed);
gtk_grid_attach(GTK_GRID(tabParam), entrySog, 1, 8, 1, 1);
g_signal_connect (entrySog, "changed", G_CALLBACK (doubleUpdate), &par.motorSpeed);
labelCreate (tabParam, "Threshold for Motor", 0, 9);
GtkWidget *entryThreshold = doubleToEntry (par.threshold);
gtk_grid_attach(GTK_GRID(tabParam), entryThreshold, 1, 9, 1, 1);
g_signal_connect (entryThreshold, "changed", G_CALLBACK (doubleUpdate), &par.threshold);
// Create day_efficiency night_efficiency
labelCreate (tabParam, "Day Efficiency", 0, 10);
GtkWidget *entryDayEfficiency = doubleToEntry (par.dayEfficiency);
gtk_grid_attach (GTK_GRID(tabParam), entryDayEfficiency, 1, 10, 1, 1);
g_signal_connect (entryDayEfficiency, "changed", G_CALLBACK (doubleUpdate), &par.dayEfficiency);
labelCreate (tabParam, "Night Efficiency", 0, 11);
GtkWidget *entryNightEfficiency = doubleToEntry (par.nightEfficiency);
gtk_grid_attach (GTK_GRID(tabParam), entryNightEfficiency, 1, 11, 1, 1);
g_signal_connect (entryNightEfficiency, "changed", G_CALLBACK (doubleUpdate), &par.nightEfficiency);
// create time Step
labelCreate (tabParam, "Time Step", 0, 12);
GtkWidget *spinTStep = gtk_spin_button_new_with_range (1, 24, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinTStep), (int) par.tStep);
gtk_grid_attach (GTK_GRID(tabParam), spinTStep, 1, 12, 1, 1);
g_signal_connect (spinTStep, "value-changed", G_CALLBACK (intSpinUpdate), &par.tStep);
// Create cog step and cog range
labelCreate (tabParam, "Cog Step", 0, 13);
GtkWidget *spinCog = gtk_spin_button_new_with_range (1, 20, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinCog), par.cogStep);
gtk_grid_attach (GTK_GRID(tabParam), spinCog, 1, 13, 1, 1);
g_signal_connect (spinCog, "value-changed", G_CALLBACK (intSpinUpdate), &par.cogStep);
labelCreate (tabParam, "Cog Range", 0, 14);
GtkWidget *spinRange = gtk_spin_button_new_with_range (50, 150, 5);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinRange), par.rangeCog);
gtk_grid_attach (GTK_GRID(tabParam), spinRange, 1, 14, 1, 1);
g_signal_connect (spinRange, "value-changed", G_CALLBACK (intSpinUpdate), &par.rangeCog);
// Create startTime
labelCreate (tabTec, "Start Time in hours", 0, 0);
GtkWidget *entryStartTime = doubleToEntry (par.startTimeInHours);
gtk_grid_attach (GTK_GRID (tabTec), entryStartTime, 1, 0, 1, 1);
g_signal_connect (entryStartTime, "changed", G_CALLBACK (doubleUpdate),&par.startTimeInHours);
// Create Opt
labelCreate (tabTec, "Opt", 0, 1);
GtkWidget *spinOpt = gtk_spin_button_new_with_range (0, 4, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinOpt), par.opt);
gtk_grid_attach (GTK_GRID(tabTec), spinOpt, 1, 1, 1, 1);
g_signal_connect (spinOpt, "value-changed", G_CALLBACK (intSpinUpdate), &par.opt);
// Create Max Isoc
labelCreate (tabTec, "Max Isoc", 0, 2);
GtkWidget *spinMaxIso = gtk_spin_button_new_with_range(0, MAX_N_ISOC, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinMaxIso), par.maxIso);
gtk_grid_attach (GTK_GRID(tabTec), spinMaxIso, 1, 2, 1, 1);
g_signal_connect (spinMaxIso, "value-changed", G_CALLBACK (intSpinUpdate), &par.maxIso);
// Create JFactor
labelCreate (tabTec, "jFactor", 0, 3);
GtkWidget *spinJFactor = gtk_spin_button_new_with_range (0, 1000, 10);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinJFactor), par.jFactor);
gtk_grid_attach (GTK_GRID(tabTec), spinJFactor, 1, 3, 1, 1);
g_signal_connect (spinJFactor, "value-changed", G_CALLBACK (intSpinUpdate), &par.jFactor);
// Create k Factor and N sector
labelCreate (tabTec, "k Factor", 0, 4);
GtkWidget *spinKFactor = gtk_spin_button_new_with_range(0, 4, 1);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinKFactor), par.kFactor);
gtk_grid_attach (GTK_GRID(tabTec), spinKFactor, 1, 4, 1, 1);
g_signal_connect (spinKFactor, "value-changed", G_CALLBACK (intSpinUpdate), &par.kFactor);
labelCreate (tabTec, "N sectors", 0, 5);
GtkWidget *spinNSectors = gtk_spin_button_new_with_range(0, 1000, 10);
gtk_spin_button_set_value(GTK_SPIN_BUTTON(spinNSectors), par.nSectors);
gtk_grid_attach (GTK_GRID(tabTec), spinNSectors, 1, 5, 1, 1);
g_signal_connect (spinNSectors, "value-changed", G_CALLBACK (intSpinUpdate), &par.nSectors);
// Create constWind Twd and Tws
labelCreate (tabTec, "Const Wind Twd", 0, 6);
GtkWidget *entryWindTwd = doubleToEntry (par.constWindTwd);
gtk_grid_attach (GTK_GRID (tabTec), entryWindTwd, 1, 6, 1, 1);
g_signal_connect (entryWindTwd, "changed", G_CALLBACK (windTwdUpdate), NULL);
labelCreate (tabTec, "Const Wind Tws", 0, 7);
GtkWidget *entryWindTws = doubleToEntry (par.constWindTws);
gtk_grid_attach (GTK_GRID(tabTec), entryWindTws, 1, 7, 1, 1);
g_signal_connect (entryWindTws, "changed", G_CALLBACK (windTwsUpdate), NULL);
// Create constCurrent Twd and Tws
labelCreate (tabTec, "Const Current Twd", 0, 8);
GtkWidget *entryCurrentTwd = doubleToEntry (par.constCurrentD);
gtk_grid_attach (GTK_GRID(tabTec), entryCurrentTwd, 1, 8, 1, 1);
g_signal_connect (entryCurrentTwd, "changed", G_CALLBACK (doubleUpdate), &par.constCurrentD);
labelCreate (tabTec, "Const Current Tws", 0, 9);
GtkWidget *entryCurrentTws = doubleToEntry (par.constCurrentS);
gtk_grid_attach (GTK_GRID(tabTec), entryCurrentTws, 1, 9, 1, 1);
g_signal_connect (entryCurrentTws, "changed", G_CALLBACK (doubleUpdate), &par.constCurrentS);
// Create constWave
labelCreate (tabTec, "Const Wave Height", 0, 10);
GtkWidget *entryWave = doubleToEntry (par.constWave);
gtk_grid_attach (GTK_GRID(tabTec), entryWave, 1, 10, 1, 1);
g_signal_connect (entryWave, "changed", G_CALLBACK (doubleUpdate), &par.constWave);
GtkWidget *separator = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
gtk_grid_attach (GTK_GRID(tabTec), separator, 0, 11, 11, 1);
// checkbox: "closest"
GtkWidget *checkboxClosest = gtk_check_button_new_with_label("Closest");
gtk_check_button_set_active ((GtkCheckButton *) checkboxClosest, par.closestDisp);
g_signal_connect (G_OBJECT (checkboxClosest), "toggled", G_CALLBACK (onCheckBoxToggled), &par.closestDisp);
gtk_grid_attach (GTK_GRID (tabTec), checkboxClosest, 0, 12, 1, 1);
// checkbox: "focal point"
GtkWidget *checkboxFocal = gtk_check_button_new_with_label("Focal Point");
gtk_check_button_set_active ((GtkCheckButton *) checkboxFocal, par.focalDisp);
g_signal_connect(G_OBJECT(checkboxFocal), "toggled", G_CALLBACK (onCheckBoxToggled), &par.focalDisp);
gtk_grid_attach(GTK_GRID (tabTec), checkboxFocal, 1, 12, 1, 1);
labelCreate (tabDisplay, "", 0, 0); // just for space on top
// Radio Button Colors
labelCreate (tabDisplay, "Colors", 0, 1);
GtkWidget *choice0 = createRadioButtonColors ("None", tabDisplay, NULL, 0);
GtkWidget *choice1 = createRadioButtonColors ("B.& W.", tabDisplay, choice0, 1);
createRadioButtonColors ("Colored", tabDisplay, choice1, 2);
// Radio Button Wind
labelCreate (tabDisplay, "Wind", 0, 2);
choice0 = createRadioButtonWindDisp ("None", tabDisplay, NULL, 0);
choice1 = createRadioButtonWindDisp ("Arrow", tabDisplay, choice0, 1);
createRadioButtonWindDisp ("Barbule", tabDisplay, choice1, 2);
// Create combo box for Avr/gust/rain/pressure
labelCreate (tabDisplay, "Wind/Gust/Rain/Pressure", 0, 3);
const char *arrayDisp [] = {"Wind", "Gust", "Waves", "Rain", "Pressure", NULL};
GtkWidget *dropDownDisp = gtk_drop_down_new_from_strings (arrayDisp);
gtk_drop_down_set_selected ((GtkDropDown *) dropDownDisp, par.averageOrGustDisp);
gtk_grid_attach (GTK_GRID(tabDisplay), dropDownDisp, 1, 3, 1, 1);
g_signal_connect (dropDownDisp, "notify::selected", G_CALLBACK (cbDropDownDisp), NULL);
// Create combo box for Isochrones
labelCreate (tabDisplay, "Isoc.", 0, 4);
const char *arrayIsoc [] = {"None", "Points", "Segment", "Bezier", NULL};
GtkWidget *dropDownIsoc = gtk_drop_down_new_from_strings (arrayIsoc);
gtk_drop_down_set_selected ((GtkDropDown *) dropDownIsoc, par.style);
gtk_grid_attach (GTK_GRID(tabDisplay), dropDownIsoc, 1, 4, 1, 1);
g_signal_connect (dropDownIsoc, "notify::selected", G_CALLBACK (cbDropDownIsoc), NULL);
// Create combo box for DMS (Degree Minutes Second) representaton
labelCreate (tabDisplay, "DMS", 2, 4);
const char *arrayDMS [] = {"Basic", "DD", "DM", "DMS", NULL};
GtkWidget *dropDownDMS = gtk_drop_down_new_from_strings (arrayDMS);
gtk_drop_down_set_selected ((GtkDropDown *) dropDownDMS, par.dispDms);
gtk_grid_attach (GTK_GRID(tabDisplay), dropDownDMS, 3, 4, 1, 1);
g_signal_connect (dropDownDMS, "notify::selected", G_CALLBACK (cbDropDownDMS), NULL);
// Checkbox: "waves"
GtkWidget *checkboxWave = gtk_check_button_new_with_label("Waves");
gtk_check_button_set_active ((GtkCheckButton *) checkboxWave, par.waveDisp);
g_signal_connect(G_OBJECT (checkboxWave), "toggled", G_CALLBACK (onCheckBoxToggled), &par.waveDisp);
gtk_grid_attach(GTK_GRID(tabDisplay), checkboxWave, 0, 5, 1, 1);
// Checkbox: "current"
GtkWidget *checkboxCurrent = gtk_check_button_new_with_label("Current");
gtk_check_button_set_active ((GtkCheckButton *) checkboxCurrent, par.currentDisp);
g_signal_connect (G_OBJECT(checkboxCurrent), "toggled", G_CALLBACK (onCheckBoxToggled), &par.currentDisp);
gtk_grid_attach(GTK_GRID (tabDisplay), checkboxCurrent, 1, 5, 1, 1);
// Checkbox: "Grid" for parallels and meridians
GtkWidget *checkboxGrid = gtk_check_button_new_with_label("Grid");
gtk_check_button_set_active ((GtkCheckButton *) checkboxGrid, par.gridDisp);
g_signal_connect (G_OBJECT(checkboxGrid), "toggled", G_CALLBACK (onCheckBoxToggled), &par.gridDisp);
gtk_grid_attach(GTK_GRID (tabDisplay), checkboxGrid, 2, 5, 1, 1);
// Checkbox: "info display"
GtkWidget *checkboxInfoDisp = gtk_check_button_new_with_label("Info Display");
gtk_check_button_set_active ((GtkCheckButton *) checkboxInfoDisp, par.infoDisp);
g_signal_connect (G_OBJECT(checkboxInfoDisp), "toggled", G_CALLBACK (onCheckBoxToggled), &par.infoDisp);
gtk_grid_attach (GTK_GRID (tabDisplay), checkboxInfoDisp, 3, 5, 1, 1);
GtkWidget *separator1 = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
gtk_grid_attach (GTK_GRID(tabDisplay), separator1, 0, 6, 10, 1);
// Create GtkScale POI widget
const int MAX_LEVEL_POI_VISIBLE = 5;
GtkWidget *labelNumber = gtk_label_new (g_strdup_printf("POI: %d", par.maxPoiVisible));
gtk_grid_attach(GTK_GRID (tabDisplay), labelNumber, 0, 7, 1, 1);
gtk_widget_set_margin_start (labelNumber, 4);
gtk_label_set_xalign(GTK_LABEL(labelNumber), 0.0);
GtkWidget *levelVisible = gtk_scale_new_with_range (GTK_ORIENTATION_HORIZONTAL, 1, MAX_LEVEL_POI_VISIBLE, 1);
gtk_range_set_value (GTK_RANGE(levelVisible), par.maxPoiVisible);
gtk_scale_set_value_pos (GTK_SCALE(levelVisible), GTK_POS_TOP);
gtk_widget_set_size_request (levelVisible, 200, -1); // Ajuster la largeur du GtkScale
g_signal_connect (levelVisible, "value-changed", G_CALLBACK (onLevelPoiVisibleChanged), labelNumber);
gtk_grid_attach(GTK_GRID(tabDisplay), levelVisible, 1, 7, 2, 1);
// Create GtkScale Display Speed widget
GtkWidget *labelSpeedDisplay = gtk_label_new (g_strdup_printf("Display Speed: %d", par.speedDisp));
gtk_grid_attach(GTK_GRID (tabDisplay), labelSpeedDisplay, 0, 8, 1, 1);
gtk_widget_set_margin_start (labelSpeedDisplay, 4);
gtk_label_set_xalign(GTK_LABEL(labelSpeedDisplay), 0.0);
GtkWidget *levelSpeedDisplay = gtk_scale_new_with_range (GTK_ORIENTATION_HORIZONTAL, 0, MAX_N_ANIMATION - 1, 1);
gtk_range_set_value (GTK_RANGE(levelSpeedDisplay), par.speedDisp);
gtk_scale_set_value_pos (GTK_SCALE(levelSpeedDisplay), GTK_POS_TOP);
gtk_widget_set_size_request (levelSpeedDisplay, 200, -1); // Ajuster la largeur du GtkScale
g_signal_connect (levelSpeedDisplay, "value-changed", G_CALLBACK (onTempoDisplayChanged), labelSpeedDisplay);
gtk_grid_attach(GTK_GRID(tabDisplay), levelSpeedDisplay, 1, 8, 2, 1);
gtk_window_present (GTK_WINDOW (changeWindow));
}
/*! zoom in */
static void onZoomInButtonClicked (GtkWidget *widget, gpointer data) {
dispZoom (0.6);
gtk_widget_queue_draw (drawing_area);
}
/*! zoom out */
static void onZoomOutButtonClicked (GtkWidget *widget, gpointer data) {
dispZoom (1.4);
gtk_widget_queue_draw (drawing_area);
}
/*! zoom original */
static void onZoomOriginalButtonClicked (GtkWidget *widget, gpointer data) {
initDispZone ();
gtk_widget_queue_draw (drawing_area);
}
/*! go up button */
static void onUpButtonClicked (GtkWidget *widget, gpointer data) {
dispTranslate (1.0, 0);
gtk_widget_queue_draw (drawing_area);
}
/*! go down button */
static void onDownButtonClicked (GtkWidget *widget, gpointer data) {
dispTranslate (-1.0, 0);
gtk_widget_queue_draw (drawing_area);
}
/*! go left button */
static void onLeftButtonClicked (GtkWidget *widget, gpointer data) {
dispTranslate (0, -1.0);
gtk_widget_queue_draw (drawing_area);
}
/*! go right button */
static void onRightButtonClicked (GtkWidget *widget, gpointer data) {
dispTranslate (0, 1.0);
gtk_widget_queue_draw (drawing_area);
}
/*! center the map on GPS position */
static void onCenterMap (GtkWidget *widget, gpointer data) {
centerDispZone (par.pOr.lon, par.pOr.lat);
gtk_widget_queue_draw (drawing_area);
}
/*! Response for poi change */
static void poiNameResponse (GtkWidget *widget, gpointer entryWindow) {
if (menuWindow != NULL) popoverFinish (menuWindow);
tPoi [nPoi].lon = xToLon (whereIsPopup.x);
tPoi [nPoi].lat = yToLat (whereIsPopup.y);
tPoi [nPoi].level = 1;
tPoi [nPoi].type = NEW;
nPoi += 1;
gtk_widget_queue_draw (drawing_area);
gtk_window_destroy (GTK_WINDOW (entryWindow));
}
/*! poi name */
static void poiNameChoose () {
strncpy (tPoi [nPoi].name, "example", MAX_SIZE_POI_NAME);
if (nPoi >= MAX_N_POI) {
infoMessage ("Number of poi exceeded", GTK_MESSAGE_ERROR);
return;
}
entryBox ("Poi Name", "Name: ", tPoi [nPoi].name, poiNameResponse);
}
/*! create wayPoint */
static void wayPointSelected () {
if (menuWindow != NULL) popoverFinish (menuWindow);
if (wayPoints.n < MAX_N_WAY_POINT) {
destPressed = false;
wayPoints.t [wayPoints.n].lat = yToLat (whereIsPopup.y);
wayPoints.t [wayPoints.n].lon = xToLon (whereIsPopup.x);
wayPoints.n += 1;
gtk_widget_queue_draw (drawing_area);
}
else (infoMessage ("Number of waypoints exceeded", GTK_MESSAGE_ERROR));
}
/*! update point of origin */
static void originSelected () {
if (menuWindow != NULL) popoverFinish (menuWindow);
destPressed = false;
par.pOr.lat = yToLat (whereIsPopup.y);
par.pOr.lon = xToLon (whereIsPopup.x);
route.n = 0;
wayPoints.n = 0;
wayPoints.totOrthoDist = 0;
wayPoints.totLoxoDist = 0;
par.pOrName [0] = '\0';
gtk_widget_queue_draw (drawing_area);
}
/*! update point of destination */
static void destinationSelected () {
if (menuWindow != NULL) popoverFinish (menuWindow);
destPressed = true;
route.n = 0;
par.pDest.lat = yToLat (whereIsPopup.y);
par.pDest.lon = xToLon (whereIsPopup.x);
wayPoints.t [wayPoints.n].lat = par.pDest.lat;
wayPoints.t [wayPoints.n].lon = par.pDest.lon;
calculateOrthoRoute ();
niceWayPointReport ();
par.pOr.id = -1;
par.pOr.father = -1;
par.pDest.id = 0;
par.pDest.father = 0;
par.pDestName [0] = '\0';
gtk_widget_queue_draw (drawing_area);
}
/*! update start polygon for forbidden zone */
static void startPolygonSelected () {
if (menuWindow != NULL) popoverFinish (menuWindow);
if ((forbidZones [par.nForbidZone].points = (Point *) malloc (MAX_SIZE_FORBID_ZONE * sizeof(Point))) == NULL) {
fprintf (stderr, "Error in on_popup_menu_selection: malloc forbidZones with k = %d\n", par.nForbidZone);
infoMessage ("in on_popup_menu_selection Error malloc forbidZones", GTK_MESSAGE_ERROR);
return;
}
polygonStarted = true;
if (par.nForbidZone < MAX_N_FORBID_ZONE) {
forbidZones [par.nForbidZone].points [0].lat = yToLat (whereIsPopup.y);
forbidZones [par.nForbidZone].points [0].lon = xToLon (whereIsPopup.x);
forbidZones [par.nForbidZone].n = 1;
gtk_widget_queue_draw (drawing_area); // affiche tout
}
}
/*! intermediate vertex polygon for forbidden zone */
static void vertexPolygonSelected () {
if (menuWindow != NULL) popoverFinish (menuWindow);
if (polygonStarted && (forbidZones [par.nForbidZone].n < MAX_SIZE_FORBID_ZONE-1)) {
printf ("vertex polygon %d %d\n", par.nForbidZone, forbidZones [par.nForbidZone].n);
forbidZones [par.nForbidZone].points [forbidZones [par.nForbidZone].n].lat = yToLat (whereIsPopup.y);
forbidZones [par.nForbidZone].points [forbidZones [par.nForbidZone].n].lon = xToLon (whereIsPopup.x);
forbidZones [par.nForbidZone].n += 1;
gtk_widget_queue_draw (drawing_area); // affiche tout
}
}
/*! close polygon for forbidden zone */
static void closePolygonSelected () {
if (menuWindow != NULL) popoverFinish (menuWindow);
if (polygonStarted && (forbidZones [par.nForbidZone].n < MAX_SIZE_FORBID_ZONE) && (forbidZones [par.nForbidZone].n > 2)) {
forbidZones [par.nForbidZone].points [forbidZones [par.nForbidZone].n].lat = forbidZones [par.nForbidZone].points [0].lat;
forbidZones [par.nForbidZone].points [forbidZones [par.nForbidZone].n].lon = forbidZones [par.nForbidZone].points [0].lon;
forbidZones [par.nForbidZone].n += 1;
par.nForbidZone += 1;
updateIsSeaWithForbiddenAreas ();
gtk_widget_queue_draw (drawing_area); // affiche tout
}
polygonStarted = false;
}
/*! callback when mouse move */
static gboolean onMotionEvent (GtkEventControllerMotion *controller, double x, double y, gpointer user_data) {
whereIsMouse.x = x;
whereIsMouse.y = y;
if (selecting) {
// g_print("Déplacement de la souris : x = %f, y = %f\n", x, y);
gtk_widget_queue_draw (drawing_area); // Redessiner pour mettre à jour le rectangle de sélection
}
else statusBarUpdate ();
return TRUE;
}
/*! change the route selecting another point in last isochrone*/
static void changeLastPoint () {
double dXy, xLon, yLat, minDxy = DBL_MAX;
double x = whereIsPopup.x;
double y = whereIsPopup.y;
if (menuWindow != NULL) popoverFinish (menuWindow);
for (int i = 0; i < isoDesc [nIsoc - 1 ].size; i++) {
xLon = getX (isocArray [nIsoc - 1][i].lon);
yLat = getY (isocArray [nIsoc - 1][i].lat);
dXy = (xLon - x)*(xLon -x) + (yLat - y) * (yLat - y);
if (dXy < minDxy) {
minDxy = dXy;
selectedPointInLastIsochrone = i;
}
}
lastClosest = isocArray [nIsoc - 1][selectedPointInLastIsochrone];
storeRoute (&par.pOr, &lastClosest, 0);
niceReport (&route, 0);
}
/*! select action associated to right click */
static void onRightClickEvent (GtkGestureClick *gesture, int n_press, double x, double y, gpointer user_data) {
char str [MAX_SIZE_LINE];
whereIsPopup.x = x;
whereIsPopup.y = y;
GtkWidget *box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
if (route.n != 0 && !route.destinationReached) {
GtkWidget *recalculateButton = gtk_button_new_with_label ("Last Point In Isochrone");
g_signal_connect (recalculateButton, "clicked", G_CALLBACK (changeLastPoint), NULL);
gtk_box_append (GTK_BOX (box), recalculateButton);
}
GtkWidget *meteoGramButton = gtk_button_new_with_label ("Meteogram");
g_signal_connect (meteoGramButton, "clicked", G_CALLBACK (meteogram), NULL);
GtkWidget *originButton = gtk_button_new_with_label ("Point Of Origin");
g_signal_connect (originButton, "clicked", G_CALLBACK (originSelected), NULL);
snprintf (str, sizeof (str), "Waypoint no: %d", wayPoints.n + 1);
GtkWidget *waypointButton = gtk_button_new_with_label (str);
g_signal_connect (waypointButton, "clicked", G_CALLBACK (wayPointSelected), NULL);
GtkWidget *destinationButton = gtk_button_new_with_label ("Point of Destination");
g_signal_connect (destinationButton, "clicked", G_CALLBACK (destinationSelected), NULL);
GtkWidget *poiButton = gtk_button_new_with_label ("Point of Interest");
g_signal_connect (poiButton, "clicked", G_CALLBACK (poiNameChoose), NULL);
GtkWidget *startPolygonButton = gtk_button_new_with_label ("Start Polygon");
g_signal_connect (startPolygonButton, "clicked", G_CALLBACK (startPolygonSelected), NULL);
GtkWidget *vertexPolygonButton = gtk_button_new_with_label ("Vertex Polygon");
g_signal_connect (vertexPolygonButton, "clicked", G_CALLBACK (vertexPolygonSelected), NULL);
GtkWidget *closePolygonButton = gtk_button_new_with_label ("Close Polygon");
g_signal_connect (closePolygonButton, "clicked", G_CALLBACK (closePolygonSelected), NULL);
gtk_box_append (GTK_BOX (box), meteoGramButton);
gtk_box_append (GTK_BOX (box), originButton);
gtk_box_append (GTK_BOX (box), waypointButton);
gtk_box_append (GTK_BOX (box), destinationButton);
gtk_box_append (GTK_BOX (box), poiButton);
gtk_box_append (GTK_BOX (box), startPolygonButton);
gtk_box_append (GTK_BOX (box), vertexPolygonButton);
gtk_box_append (GTK_BOX (box), closePolygonButton);
menuWindow = gtk_popover_new ();
gtk_widget_set_parent (menuWindow, drawing_area);
gtk_popover_set_child ((GtkPopover*) menuWindow, (GtkWidget *) box);
g_signal_connect(drawing_area, "destroy", G_CALLBACK (onParentWindowDestroy), menuWindow);
GdkRectangle rect = {x, y, 1, 1};
//gtk_popover_set_has_arrow ((GtkPopover*) menuWindow, false);
gtk_popover_set_pointing_to ((GtkPopover*) menuWindow, &rect);
//gtk_popover_popup ((GtkPopover *) menuWindow);
//gtk_popover_set_cascade_popdown ((GtkPopover*) menuWindow, TRUE);
//gtk_popover_set_autohide ((GtkPopover*) menuWindow, TRUE);
gtk_widget_set_visible (menuWindow, true);
}
/*! Callback associated to mouse left clic release event
Action after selection. Launch smtp request for grib file */
static void onLeftReleaseEvent (GtkGestureClick *gesture, int n_press, double x, double y, gpointer user_data) {
double lat1, lat2, lon1, lon2;
if (n_press == 1) {
//g_print("Clic gauche relache\n");
if (selecting && \
((whereIsMouse.x - whereWasMouse.x) > MIN_MOVE_FOR_SELECT) && \
((whereIsMouse.x - whereWasMouse.x) > MIN_MOVE_FOR_SELECT)) {
lat1 = yToLat (whereIsMouse.y);
lon1 = xToLon (whereWasMouse.x);
lat2 = yToLat (whereWasMouse.y);
lon2 = xToLon (whereIsMouse.x);
lon1 = lonCanonize (lon1);
lon2 = lonCanonize (lon2);
provider = SAILDOCS_GFS; // default
mailRequestBox (lat1, lon1, lat2, lon2);
}
}
selecting = false;
gtk_widget_queue_draw (drawing_area); // Redessiner pour effacer le rectangle de sélection
}
/*! Callback associated to mouse left clic event */
static void onLeftClickEvent (GtkGestureClick *gesture, int n_press, double x, double y, gpointer user_data) {
selecting = !selecting;
whereWasMouse.x = whereIsMouse.x = x;
whereWasMouse.y = whereIsMouse.y = y;
gtk_widget_queue_draw (drawing_area); // Redessiner pour mettre à jour le rectangle de sélection
}
/*! Zoom associated to mouse scroll event */
static gboolean onScrollEvent (GtkEventController *controller, double delta_x, double delta_y, gpointer user_data) {
if (delta_y > 0) {
dispZoom (1.4);
} else if (delta_y < 0) {
dispZoom (0.6);
}
gtk_widget_queue_draw (drawing_area);
return TRUE;
}
/*! Callback when fullscreen or back */
static void onFullscreenNotify (void) {
destroySurface ();
gtk_widget_queue_draw (drawing_area);
}
/*! Callback when keyboard key pressed */
static gboolean onKeyEvent (GtkEventController *controller, guint keyval, \
guint keycode, GdkModifierType modifiers, gpointer user_data) {
switch (keyval) {
case GDK_KEY_F1:
if (!my_gps_data.OK)
infoMessage ("No GPS position available", GTK_MESSAGE_WARNING);
else {
par.pOr.lat = my_gps_data.lat;
par.pOr.lon = my_gps_data.lon;
infoMessage ("Point of Origin = GPS position", GTK_MESSAGE_WARNING);
gtk_widget_queue_draw (drawing_area);
}
break;
case GDK_KEY_Escape:
printf ("Exit success\n");
exit (EXIT_SUCCESS); // exit if ESC key pressed
case GDK_KEY_Up:
dispTranslate (1.0, 0);
break;
case GDK_KEY_Down:
dispTranslate (-1.0, 0);
break;
case GDK_KEY_Left:
dispTranslate (0, -1.0);
break;
case GDK_KEY_Right:
dispTranslate (0, 1.0);
break;
default:
break;
}
gtk_widget_queue_draw (drawing_area);
return TRUE; // event has been managed with success
}
/*! Draw meteogram */
static void onMeteogramEvent (GtkDrawingArea *area, cairo_t *cr, int width, \
int height, gpointer user_data) {
#define MAX_VAL_MET 4
const int LEGEND_X_LEFT = width - 80;
const int LEGEND_Y_TOP = 10;
char str [MAX_SIZE_LINE];
int x, y;
double u, v, g = 0, w, twd, tws, head_x, maxTws = 0, maxG = 0, maxMax = 0, maxWave = 0;
double uCurr, vCurr, currTwd, currTws, maxCurrTws = 0;// current
long tMax = zone.timeStamp [zone.nTimeStamp -1];
double tDeltaCurrent = zoneTimeDiff (¤tZone, &zone);
double tDeltaNow = 0; // time between beginning of grib and now in hours
double lat, lon;
char totalDate [MAX_SIZE_DATE];
int timeMeteo, initTimeMeteo;
lat = yToLat (whereIsPopup.y);
lon = xToLon (whereIsPopup.x);
lon = lonCanonize (lon);
if (zone.nTimeStamp < 2) return;
cairo_set_line_width (cr, 1);
const int X_LEFT = 30;
const int X_RIGHT = width - 20;
const int Y_TOP = 40;
const int Y_BOTTOM = height - 25;
const int HEAD_Y = 20;
const int XK = (X_RIGHT - X_LEFT) / tMax;
const int DELTA = 5;
const int DAY_LG = 10;
char *libelle [MAX_VAL_MET] = {"Wind", "Gust", "Waves", "Current"};
double colors[MAX_VAL_MET][3] = {{0, 0, 1}, {1, 0, 0}, {0, 1, 0}, {1, 165.0/255.0, 0}}; // blue red blue orange
drawLegend (cr, LEGEND_X_LEFT, LEGEND_Y_TOP, colors, libelle, MAX_VAL_MET);
// graphical difference between up to now and after now
// tDeltaNow is the number of hours between beginning of grib to now */
time_t now = time (NULL);
tDeltaNow = (now - vOffsetLocalUTC)/ 3600.0; // offset between local and UTC in hours
tDeltaNow -= gribDateTimeToEpoch (zone.dataDate [0], zone.dataTime [0]) / 3600.0;
//printf ("tDeltaNow: %.2lf\n", tDeltaNow);
CAIRO_SET_SOURCE_RGB_YELLOW(cr);
if (tDeltaNow > 0) {
x = X_LEFT + XK * tDeltaNow;
x = MIN (x, X_RIGHT);
cairo_rectangle (cr, X_LEFT, Y_TOP, x - X_LEFT, Y_BOTTOM - Y_TOP); // past is gray
cairo_fill (cr);
if (x < X_RIGHT -10) {
CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr); // line for now
cairo_move_to (cr, x, Y_BOTTOM);
cairo_line_to (cr, x, Y_TOP);
cairo_stroke (cr);
}
}
// Draw horizontal line with arrow
CAIRO_SET_SOURCE_RGB_BLACK(cr);
cairo_move_to (cr, X_LEFT, Y_BOTTOM );
cairo_line_to (cr, X_RIGHT, Y_BOTTOM);
cairo_line_to (cr, X_RIGHT - DELTA, Y_BOTTOM + DELTA); // for arrow
cairo_stroke (cr);
cairo_move_to (cr, X_RIGHT, Y_BOTTOM );
cairo_line_to (cr, X_RIGHT - DELTA, Y_BOTTOM - DELTA);
cairo_stroke (cr);
// Draw vertical line with arrow
cairo_move_to (cr, X_LEFT, Y_BOTTOM);
cairo_line_to (cr, X_LEFT, Y_TOP);
cairo_line_to (cr, X_LEFT - DELTA, Y_TOP + DELTA);
cairo_stroke (cr);
cairo_move_to (cr, X_LEFT, Y_TOP);
cairo_line_to (cr, X_LEFT + DELTA, Y_TOP + DELTA);
cairo_stroke (cr);
// find max Tws max gust max waves max current and draw twd arrows
for (int i = 0; i < tMax; i += 1) {
findWindGrib (lat, lon, i, &u, &v, &g, &w, &twd, &tws);
findCurrentGrib (lat, lon, i- tDeltaCurrent, &uCurr, &vCurr, &currTwd, &currTws);
head_x = X_LEFT + XK * i;
if ((i % (tMax / 24)) == 0) {
arrow (cr, head_x, HEAD_Y, u, v, twd, tws, WIND);
arrow (cr, head_x, HEAD_Y + 20, uCurr, vCurr, currTwd, currTws, CURRENT);
}
if (tws > maxTws) maxTws = tws;
if (w > maxWave) maxWave = w;
if (g > maxG) maxG = g;
if (currTws > maxCurrTws) maxCurrTws = currTws;
}
maxG *= MS_TO_KN;
maxMax = ceil (MAX (maxG, MAX (maxTws, MAX (maxWave, (MAX (maxCurrTws, 10))))));
// Draw time label and vertical line
cairo_select_font_face (cr, "Sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size (cr, 10);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
initTimeMeteo = zone.dataTime [0]/100;
for (int i = 0; i <= tMax; i+= (par.gribTimeMax <= 120) ? 6 : 12) {
timeMeteo = (zone.dataTime [0]/100) + i;
x = X_LEFT + XK * i;
cairo_move_to (cr, x, Y_BOTTOM + 10);
newDate (zone.dataDate [0], timeMeteo, totalDate);
cairo_show_text (cr, strrchr (totalDate, ' ') + 1); // hour is after space
if ((timeMeteo % ((par.gribTimeMax <= 240) ? 24 : 48)) == initTimeMeteo) { // only year month day considered
cairo_move_to (cr, x, Y_BOTTOM + 20);
totalDate [DAY_LG] = '\0'; // date
cairo_show_text (cr, totalDate);
CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr);
cairo_move_to (cr, x, Y_BOTTOM);
cairo_line_to (cr, x, Y_TOP);
cairo_stroke (cr);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
}
}
cairo_stroke(cr);
const int YK = (Y_BOTTOM - Y_TOP) / maxMax;
CAIRO_SET_SOURCE_RGB_BLACK(cr);
// Draw speed labels and horizontal lines
cairo_set_font_size (cr, 10);
double step = (maxMax > 50) ? 10 : 5;
for (double speed = step; speed <= maxMax; speed += step) {
y = Y_BOTTOM - YK * speed;
cairo_move_to (cr, X_LEFT - 20, y);
snprintf (str, MAX_SIZE_LINE, "%02.0lf", speed);
cairo_show_text (cr, str);
CAIRO_SET_SOURCE_RGB_ULTRA_LIGHT_GRAY(cr); // horizontal line
cairo_move_to (cr, X_LEFT, y);
cairo_line_to (cr, X_RIGHT, y);
cairo_stroke (cr);
CAIRO_SET_SOURCE_RGB_BLACK(cr);
}
cairo_stroke(cr);
CAIRO_SET_SOURCE_RGB_BLUE(cr);
// draw tws
for (int i = 0; i < tMax; i += 1) {
findWindGrib (lat, lon, i, &u, &v, &g, &w, &twd, &tws);
x = X_LEFT + XK * i;
y = Y_BOTTOM - YK * tws;
if (i == 0) cairo_move_to (cr, x, y);
else cairo_line_to (cr, x, y);
}
cairo_stroke(cr);
// draw gust
if (maxG > 0) {
CAIRO_SET_SOURCE_RGB_RED(cr);
for (int i = 0; i < tMax; i += 1) {
findWindGrib (lat, lon, i, &u, &v, &g, &w, &twd, &tws);
x = X_LEFT + XK * i;
y = Y_BOTTOM - YK * MAX (g * MS_TO_KN, tws);
if (i == 0) cairo_move_to (cr, x, y);
else cairo_line_to (cr, x, y);
}
cairo_stroke(cr);
}
// draw waves
if (maxWave > 0) {
CAIRO_SET_SOURCE_RGB_GREEN(cr);
for (int i = 0; i < tMax; i += 1) {
findWindGrib (lat, lon, i, &u, &v, &g, &w, &twd, &tws);
x = X_LEFT + XK * i;
y = Y_BOTTOM - YK * w;
if (i == 0) cairo_move_to (cr, x, y);
else cairo_line_to (cr, x, y);
}
cairo_stroke(cr);
}
// draw uTws (current)
if (maxCurrTws > 0) {
CAIRO_SET_SOURCE_RGB_ORANGE(cr);
for (int i = 0; i < tMax; i += 1) {
findCurrentGrib (lat, lon, i - tDeltaCurrent, &uCurr, &vCurr, &currTwd, &currTws);
x = X_LEFT + XK * i;
y = Y_BOTTOM - YK * currTws;
if (i == 0) cairo_move_to (cr, x, y);
else cairo_line_to (cr, x, y);
}
cairo_stroke(cr);
}
}
/*! meteogram */
static void meteogram () {
char totalDate [MAX_SIZE_DATE];
char strLat [MAX_SIZE_NAME], strLon [MAX_SIZE_NAME];
char line [MAX_SIZE_LINE];
if (par.constWindTws > 0) {
infoMessage ("Wind is constant !", GTK_MESSAGE_INFO);
return;
}
popoverFinish (menuWindow);
Pp pt;
pt.lat = yToLat (whereIsPopup.y);
pt.lon = xToLon (whereIsPopup.x);
snprintf (line, sizeof (line), "Meteogram for %s %s beginning %s during %ld hours", latToStr (pt.lat, par.dispDms, strLat),
lonToStr (pt.lon, par.dispDms, strLon),
newDate (zone.dataDate [0], (zone.dataTime [0]/100), totalDate),
zone.timeStamp [zone.nTimeStamp -1]);
GtkWidget *meteoWindow = gtk_application_window_new (GTK_APPLICATION (app));
gtk_window_set_title (GTK_WINDOW(meteoWindow), line);
gtk_window_set_default_size (GTK_WINDOW(meteoWindow), 1400, 400);
g_signal_connect (window, "destroy", G_CALLBACK(onParentDestroy), meteoWindow);
GtkWidget *meteogram_drawing_area = gtk_drawing_area_new ();
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (meteogram_drawing_area), onMeteogramEvent, NULL, NULL);
gtk_window_set_child (GTK_WINDOW (meteoWindow), meteogram_drawing_area);
gtk_window_present (GTK_WINDOW (meteoWindow));
}
/*! submenu with label and icon
static void try_subMenu(GMenu *vMenu, const char *str, const char *app, const gchar *iconName) {
GMenuItem *menu_item = g_menu_item_new (str, app);
g_menu_item_set_label(menu_item, str);
if (iconName != NULL) {
GIcon *icon = g_themed_icon_new_with_default_fallbacks(iconName);
g_menu_item_set_icon (menu_item, G_ICON(icon));
g_object_unref(icon);
}
g_menu_append_item(vMenu, menu_item);
g_object_unref(menu_item);
}
*/
/*! submenu with label but no icon */
static void subMenu (GMenu *vMenu, const char *str, const char *app, const gchar *iconName) {
GMenuItem *menu_item = g_menu_item_new (str, app);
g_menu_append_item (vMenu, menu_item);
g_object_unref (menu_item);
}
/*! Grib URL selection for Meteo Consult */
static void gribUrl (GSimpleAction *action, GVariant *parameter, gpointer *data) {
typeFlow = GPOINTER_TO_INT (data);
GtkWidget *itemUrl;
GtkWidget *box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
for (int i = 0; i < N_WIND_URL; i++) {
itemUrl = gtk_button_new_with_label (WIND_URL [i * 2]);
g_signal_connect_swapped (itemUrl, "clicked", G_CALLBACK (urlDownloadGrib), GINT_TO_POINTER (i));
gtk_box_append (GTK_BOX (box), itemUrl);
}
menuGrib = gtk_popover_new ();
gtk_widget_set_parent (menuGrib, window);
g_signal_connect (window, "destroy", G_CALLBACK (onParentWindowDestroy), menuGrib);
gtk_popover_set_child ((GtkPopover*) menuGrib, (GtkWidget *) box);
gtk_popover_set_has_arrow ((GtkPopover*) menuGrib, false);
GdkRectangle rect = {200, 100, 1, 1};
gtk_popover_set_pointing_to ((GtkPopover*) menuGrib, &rect);
gtk_widget_set_visible (menuGrib, true);
}
/*! Callback exit */
static void quitActivated (GSimpleAction *action, GVariant *parameter, GApplication *application) {
exit (EXIT_SUCCESS);
}
/*! Callback polar_draw */
static void polarDrawActivated (GSimpleAction *action, GVariant *parameter, gpointer *data) {
polarType = GPOINTER_TO_INT (data);
polarDraw ();
}
/*! Callback poi (point of interest) save */
static void poiSaveActivated (GSimpleAction *action, GVariant *parameter, GApplication *application) {
writePoi (par.poiFileName);
}
/*! Callback for text read file */
static void cliActivated (GSimpleAction *action, GVariant *parameter, GApplication *application) {
char str [MAX_SIZE_FILE_NAME];
displayFile (buildRootName (par.cliHelpFileName, str), "CLI Info", true);
}
/*! create a button within toolBow, with an icon and a callback function */
static void createButton (GtkWidget *toolBox, char *iconName, void *callBack) {
GtkWidget *button = gtk_button_new_from_icon_name (iconName);
g_signal_connect (button, "clicked", G_CALLBACK (callBack), NULL);
gtk_box_append (GTK_BOX (toolBox), button);
}
/*! Update info GPS */
static gboolean updateGpsCallback (gpointer data) {
char str [MAX_SIZE_LINE], strDate [MAX_SIZE_LINE], strLat [MAX_SIZE_LINE], strLon [MAX_SIZE_LINE];
GtkWidget *label = GTK_WIDGET(data);
if (my_gps_data.OK)
snprintf (str, sizeof (str), "%s UTC Lat: %s Lon: %s COG: %.0lf° SOG: %.2lf Kn",
epochToStr (my_gps_data.time, false, strDate, sizeof (strDate)),
latToStr (my_gps_data.lat, par.dispDms, strLat), lonToStr (my_gps_data.lon, par.dispDms, strLon),
my_gps_data.cog, my_gps_data.sog);
else
snprintf (str, sizeof (str), " No GPS Info");
gtk_label_set_text (GTK_LABEL(label), str);
return G_SOURCE_CONTINUE;
}
/*! Main window set up */
static void appActivate (GApplication *application) {
app = GTK_APPLICATION (application);
window = gtk_application_window_new (app);
titleUpdate ();
gtk_window_set_default_size (GTK_WINDOW (window), MAIN_WINDOW_DEFAULT_WIDTH, MAIN_WINDOW_DEFAULT_HEIGHT);
gtk_window_maximize (GTK_WINDOW (window)); // full screen
gtk_application_window_set_show_menubar (GTK_APPLICATION_WINDOW (window), TRUE);
GtkWidget *vBox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 5);
gtk_window_set_child (GTK_WINDOW (window), vBox);
GtkWidget *toolBox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 5);
createButton (toolBox, "system-run", onRunButtonClicked);
createButton (toolBox, "starred", onChooseDepartureButtonClicked);
createButton (toolBox, "preferences-desktop", change);
createButton (toolBox, "media-playback-pause", onStopButtonClicked);
createButton (toolBox, "media-playback-start", onPlayButtonClicked);
createButton (toolBox, "media-playlist-repeat", onLoopButtonClicked);
createButton (toolBox, "media-skip-backward", onToStartButtonClicked);
createButton (toolBox, "media-seek-backward", onRewardButtonClicked);
createButton (toolBox, "media-seek-forward", onForwardButtonClicked);
createButton (toolBox, "media-skip-forward", onToEndButtonClicked);
createButton (toolBox, "zoom-in", onZoomInButtonClicked);
createButton (toolBox, "zoom-out", onZoomOutButtonClicked);
createButton (toolBox, "zoom-original", onZoomOriginalButtonClicked);
createButton (toolBox, "pan-start-symbolic", onLeftButtonClicked);
createButton (toolBox, "pan-up-symbolic", onUpButtonClicked);
createButton (toolBox, "pan-down-symbolic", onDownButtonClicked);
createButton (toolBox, "pan-end-symbolic", onRightButtonClicked);
createButton (toolBox, "find-location-symbolic", onCenterMap);
createButton (toolBox, "edit-select-all", paletteDraw);
createButton (toolBox, "applications-engineering-symbolic", testFunction);
GtkWidget *gpsInfo = gtk_label_new (" GPS Info coming...");
gtk_box_append (GTK_BOX (toolBox), gpsInfo);
// label line for route info in bold red left jutified (Global Variable)
labelInfoRoute = gtk_label_new ("");
//gtk_label_set_justify (GTK_LABEL(labelInfoRoute), GTK_JUSTIFY_LEFT);
PangoAttrList *attrs = pango_attr_list_new();
PangoAttribute *attr = pango_attr_weight_new(PANGO_WEIGHT_BOLD);
pango_attr_list_insert(attrs, attr);
attr = pango_attr_foreground_new (65535, 0, 0); // red
pango_attr_list_insert(attrs, attr);
gtk_label_set_attributes (GTK_LABEL(labelInfoRoute), attrs);
gtk_label_set_xalign(GTK_LABEL (labelInfoRoute), 0); // left justified
// Create statusbar (Global Variable)
statusbar = gtk_label_new ("Statusbar"); // global variable
// Create drawing area (Global Variable)
drawing_area = gtk_drawing_area_new();
gtk_widget_set_hexpand(drawing_area, TRUE);
gtk_widget_set_vexpand(drawing_area, TRUE);
gtk_drawing_area_set_draw_func (GTK_DRAWING_AREA (drawing_area), drawGribCallback, NULL, NULL);
// Create event controller for mouse motion
GtkEventController *motion_controller = gtk_event_controller_motion_new();
gtk_widget_add_controller (drawing_area, motion_controller);
g_signal_connect(motion_controller, "motion", G_CALLBACK (onMotionEvent), NULL);
// Create left clic manager
GtkGesture *click_gesture_left = gtk_gesture_click_new();
gtk_gesture_single_set_button (GTK_GESTURE_SINGLE(click_gesture_left), GDK_BUTTON_PRIMARY);
gtk_widget_add_controller (drawing_area, GTK_EVENT_CONTROLLER (click_gesture_left));
g_signal_connect(click_gesture_left, "pressed", G_CALLBACK (onLeftClickEvent), NULL);
// Connexion du signal pour le relâchement du clic gauche
g_signal_connect(click_gesture_left, "released", G_CALLBACK (onLeftReleaseEvent), NULL);
// Create rigtt clic manager
GtkGesture *click_gesture_right = gtk_gesture_click_new();
gtk_gesture_single_set_button(GTK_GESTURE_SINGLE(click_gesture_right), GDK_BUTTON_SECONDARY);
GtkEventController *click_controller_right = GTK_EVENT_CONTROLLER (click_gesture_right);
gtk_widget_add_controller (drawing_area, GTK_EVENT_CONTROLLER (click_controller_right));
g_signal_connect(click_gesture_right, "pressed", G_CALLBACK (onRightClickEvent), NULL);
// Create event controller for mouse scroll
GtkEventController *scroll_controller = gtk_event_controller_scroll_new(GTK_EVENT_CONTROLLER_SCROLL_BOTH_AXES);
gtk_widget_add_controller (drawing_area, scroll_controller);
g_signal_connect(scroll_controller, "scroll", G_CALLBACK (onScrollEvent), NULL);
// Create event controller for keyboard keys
GtkEventController *key_controller = gtk_event_controller_key_new();
gtk_widget_add_controller (window, key_controller); // window and not drawing_area required !!!
g_signal_connect(key_controller, "key-pressed", G_CALLBACK (onKeyEvent), NULL);
// Connext signal notiy to detect change in window (e.g. fullsceren)
g_signal_connect(window, "notify", G_CALLBACK(onFullscreenNotify), NULL);
g_timeout_add_seconds (GPS_TIME_INTERVAL, updateGpsCallback, gpsInfo);
GtkWidget *separator = gtk_separator_new(GTK_ORIENTATION_HORIZONTAL);
gtk_box_append (GTK_BOX (vBox), toolBox);
gtk_box_append (GTK_BOX (vBox), labelInfoRoute);
gtk_box_append (GTK_BOX (vBox), drawing_area);
gtk_box_append (GTK_BOX (vBox), separator);
gtk_box_append (GTK_BOX (vBox), statusbar);
gtk_window_present (GTK_WINDOW (window));
}
/*! for app_startup */
static void createAction (char *actionName, void *callBack) {
GSimpleAction *act_item = g_simple_action_new (actionName, NULL);
g_action_map_add_action (G_ACTION_MAP (app), G_ACTION (act_item));
g_signal_connect (act_item, "activate", G_CALLBACK (callBack), NULL);
}
/*! for app_startup */
static void createActionWithParam (char *actionName, void *callBack, int param) {
//static int zero = 0;
//static int one = 1;
GSimpleAction *act_item = g_simple_action_new (actionName, NULL);
g_action_map_add_action (G_ACTION_MAP (app), G_ACTION (act_item));
//g_signal_connect_data (act_item, "activate", G_CALLBACK(callBack), (param == 0) ? &zero : &one, NULL, 0);
g_signal_connect_data (act_item, "activate", G_CALLBACK(callBack), GINT_TO_POINTER (param), NULL, 0);
}
/*! Menu set up */
static void appStartup (GApplication *application) {
if (setlocale (LC_ALL, "C") == NULL) {
fprintf (stderr, "Error in ap_startup: setlocale failed");
return;
}
GtkApplication *app = GTK_APPLICATION (application);
createActionWithParam ("gribOpen", openGrib, WIND);
createActionWithParam ("gribInfo", gribInfo, WIND);
createActionWithParam ("windNOAAselect", gribNoaa, WIND);
createActionWithParam ("windURLselect", gribUrl, WIND);
createActionWithParam ("currentGribOpen", openGrib, CURRENT);
createActionWithParam ("currentGribInfo", gribInfo, CURRENT);
createActionWithParam ("currentURLselect", gribUrl, CURRENT);
createAction ("quit", quitActivated);
createAction ("scenarioOpen", openScenario);
createAction ("scenarioSettings", change);
createAction ("scenarioShow", parDump);
createAction ("scenarioSave", saveScenario);
createAction ("scenarioEdit", editScenario);
createAction ("scenarioInfo", parInfo);
createAction ("polarOpen", openPolar);
createActionWithParam ("polarDraw", polarDrawActivated, POLAR);
createActionWithParam ("wavePolarDraw", polarDrawActivated, WAVE_POLAR);
createAction ("isochrones", isocDump);
createAction ("isochronesDesc", isocDescDump);
createAction ("orthoReport", niceWayPointReport);
createAction ("routeGram", routeGram);
createAction ("sailRoute", routeDump);
createAction ("sailReport", rteReport);
createAction ("simulationReport", simulationReport);
createAction ("dashboard", dashboard);
createAction ("gps", gpsDump);
createAction ("historyReset", historyReset);
createAction ("sailHistory", rteHistory);
createAction ("poiDump", poiDump);
createAction ("poiSave", poiSaveActivated);
createActionWithParam ("poiEdit", poiEdit, POI_SEL);
createActionWithParam ("portsEdit", poiEdit, PORT_SEL);
createAction ("traceAdd", traceAdd);
createAction ("traceReport", traceReport);
createAction ("traceDump", traceDump);
createAction ("openTrace", openTrace);
createAction ("newTrace", newTrace);
createAction ("editTrace", editTrace);
createAction ("help", help);
createActionWithParam ("OSM0", openMap, 0); // open Street Map
createActionWithParam ("OSM1", openMap, 1); // open Sea Map
createAction ("windy", windy);
createAction ("CLI", cliActivated);
createAction ("info", helpInfo);
GMenu *menubar = g_menu_new ();
GMenuItem *file_menu = g_menu_item_new ("_Grib", NULL);
GMenuItem *polar_menu = g_menu_item_new ("_Polar", NULL);
GMenuItem *scenario_menu = g_menu_item_new ("_Scenario", NULL);
GMenuItem *display_menu = g_menu_item_new ("_Display", NULL);
GMenuItem *history_menu = g_menu_item_new ("_History", NULL);
GMenuItem *poi_menu = g_menu_item_new("PO_I", NULL);
GMenuItem *trace_menu = g_menu_item_new("_Trace", NULL);
GMenuItem *help_menu = g_menu_item_new("_Help", NULL);
// Add elements for "Grib" menu
GMenu *file_menu_v = g_menu_new ();
subMenu (file_menu_v, "Wind: Open Grib", "app.gribOpen", "folder");
subMenu (file_menu_v, "Wind: Grib Info", "app.gribInfo", "applications-engineering-symbolic");
subMenu (file_menu_v, "Wind: Meteoconsult", "app.windURLselect", "applications-engineering-symbolic");
subMenu (file_menu_v, "Wind: NOAA", "app.windNOAAselect", "applications-engineering-symbolic");
subMenu (file_menu_v, "Current: Open Grib", "app.currentGribOpen", "folder");
subMenu (file_menu_v, "Current: Grib Info", "app.currentGribInfo", "applications-engineering-symbolic");
subMenu (file_menu_v, "Current: Meteoconsult", "app.currentURLselect", "applications-engineering-symbolic");
subMenu (file_menu_v, "Quit", "app.quit", "application-exit-symbolic");
// Add elements for "Polar" menu
GMenu *polar_menu_v = g_menu_new ();
subMenu (polar_menu_v, "Polar or Wave Polar open", "app.polarOpen", "folder-symbolic");
subMenu (polar_menu_v, "Polar Draw", "app.polarDraw", "utilities-system-monitor-symbolic");
subMenu (polar_menu_v, "Wave Polar Draw", "app.wavePolarDraw", "x-office-spreadsheet-symbolic");
// Add elements for "Scenario" menu
GMenu *scenario_menu_v = g_menu_new ();
subMenu (scenario_menu_v, "Open", "app.scenarioOpen", "folder-symbolic");
subMenu (scenario_menu_v, "Settings", "app.scenarioSettings", "preferences-desktop");
subMenu (scenario_menu_v, "Show", "app.scenarioShow", "document-open-symbolic");
subMenu (scenario_menu_v, "Save", "app.scenarioSave", "media-floppy-symbolic");
subMenu (scenario_menu_v, "Edit", "app.scenarioEdit", "document-edit-symbolic");
subMenu (scenario_menu_v, "Info Parameters", "app.scenarioInfo", "document-properties-symbolic");
// Add elements for "Display" menu
GMenu *display_menu_v = g_menu_new ();
if (par.techno) {
subMenu (display_menu_v, "Isochrones", "app.isochrones", "");
subMenu (display_menu_v, "Isochrones Descriptors", "app.isochronesDesc", "");
}
subMenu (display_menu_v, "Way Points Report", "app.orthoReport", "");
subMenu (display_menu_v, "Routegram", "app.routeGram", "");
subMenu (display_menu_v, "Sail Route", "app.sailRoute", "");
subMenu (display_menu_v, "Sail Report", "app.sailReport", "");
subMenu (display_menu_v, "Simulation Report", "app.simulationReport", "");
subMenu (display_menu_v, "Dashboard", "app.dashboard", "");
subMenu (display_menu_v, "GPS", "app.gps", "");
// Add elements for "History" menu
GMenu *history_menu_v = g_menu_new ();
subMenu (history_menu_v, "Reset", "app.historyReset", "document-open-symbolic");
subMenu (history_menu_v, "Sail History Routes", "app.sailHistory", "");
// Add elements for "Poi" (Points of interest) menu
GMenu *poi_menu_v = g_menu_new ();
subMenu (poi_menu_v, "Report", "app.poiDump", "document-open-symbolic");
subMenu (poi_menu_v, "Save", "app.poiSave", "media-floppy-symbolic-symbolic");
subMenu (poi_menu_v, "Edit PoI", "app.poiEdit", "document-edit-symbolic");
subMenu (poi_menu_v, "Edit Ports", "app.portsEdit", "document-edit-symbolic");
// Add elements for "Trace" menu
GMenu *trace_menu_v = g_menu_new ();
subMenu (trace_menu_v, "Add POR", "app.traceAdd", "");
subMenu (trace_menu_v, "Report", "app.traceReport", "");
subMenu (trace_menu_v, "Dump", "app.traceDump", "");
subMenu (trace_menu_v, "Open", "app.openTrace", "");
subMenu (trace_menu_v, "New", "app.newTrace", "");
subMenu (trace_menu_v, "Edit", "app.editTrace", "");
// Add elements for "Help" menu
GMenu *help_menu_v = g_menu_new ();
subMenu (help_menu_v, "Help", "app.help", "");
subMenu (help_menu_v, "Windy", "app.windy", "");
subMenu (help_menu_v, "Open Street Map", "app.OSM0", "");
subMenu (help_menu_v, "Open Sea Map", "app.OSM1", "");
subMenu (help_menu_v, "CLI mode", "app.CLI", "text-x-generic");
subMenu (help_menu_v, "Info", "app.info", "");
//g_menu_item_set_submenu (menu_item_menu, G_MENU_MODEL (menu));
g_menu_item_set_submenu (file_menu, G_MENU_MODEL (file_menu_v));
g_object_unref (file_menu_v);
g_menu_item_set_submenu (polar_menu, G_MENU_MODEL (polar_menu_v));
g_object_unref (polar_menu_v);
g_menu_item_set_submenu (scenario_menu, G_MENU_MODEL (scenario_menu_v));
g_object_unref (scenario_menu_v);
g_menu_item_set_submenu (display_menu, G_MENU_MODEL (display_menu_v));
g_object_unref (display_menu_v);
g_menu_item_set_submenu (history_menu, G_MENU_MODEL (history_menu_v));
g_object_unref (history_menu_v);
g_menu_item_set_submenu (poi_menu, G_MENU_MODEL (poi_menu_v));
g_object_unref (poi_menu_v);
g_menu_item_set_submenu (trace_menu, G_MENU_MODEL (trace_menu_v));
g_object_unref (trace_menu_v);
g_menu_item_set_submenu (help_menu, G_MENU_MODEL (help_menu_v));
g_object_unref (help_menu_v);
g_menu_append_item (menubar, file_menu);
g_menu_append_item (menubar, polar_menu);
g_menu_append_item (menubar, scenario_menu);
g_menu_append_item (menubar, display_menu);
g_menu_append_item (menubar, history_menu);
g_menu_append_item (menubar, poi_menu);
g_menu_append_item (menubar, trace_menu);
g_menu_append_item (menubar, help_menu);
g_object_unref (file_menu);
g_object_unref (polar_menu);
g_object_unref (scenario_menu);
g_object_unref (display_menu);
g_object_unref (history_menu);
g_object_unref (poi_menu);
g_object_unref (trace_menu);
g_object_unref (help_menu);
gtk_application_set_menubar (GTK_APPLICATION (app), G_MENU_MODEL (menubar));
}
/*! Display main menu and make initializations */
int main (int argc, char *argv[]) {
bool ret = true;
vOffsetLocalUTC = offsetLocalUTC ();
printf ("LocalTime - UTC: %.0lf hours\n", vOffsetLocalUTC / 3600.0);
if (setlocale (LC_ALL, "C") == NULL) { // very important for scanf decimal numbers
fprintf (stderr, "Error in main: setlocale failed");
return EXIT_FAILURE;
}
strncpy (parameterFileName, PARAMETERS_FILE, sizeof (parameterFileName));
switch (argc) {
case 1: // no parameter
ret = readParam (parameterFileName);
break;
case 2: // one parameter
if (argv [1][0] == '-') {
ret = readParam (parameterFileName);
optionManage (argv [1][1]);
exit (EXIT_SUCCESS);
}
else {
ret = readParam (argv [1]);
strncpy (parameterFileName, argv [1], sizeof (parameterFileName) - 1);
}
break;
case 3: // two parameters
if (argv [1][0] == '-') {
ret = readParam (argv [2]);
strncpy (parameterFileName, argv [2], sizeof (parameterFileName) - 1);
optionManage (argv [1][1]);
exit (EXIT_SUCCESS);
}
else {
printf ("Usage: %s [-<option>] [<par file>]\n", argv [0]);
exit (EXIT_FAILURE);
}
break;
default:
printf ("Usage: %s [-<option>] [<par file>]\n", argv [0]);
exit (EXIT_FAILURE);
break;
}
if (!ret) exit (EXIT_FAILURE);
g_thread_new ("GPS", getGPS, &par.gpsType); // launch GPS with gpsType info
initZone (&zone);
initDispZone ();
if (par.mostRecentGrib) // most recent grib will replace existing grib
initWithMostRecentGrib ();
initScenario ();
if (par.isSeaFileName [0] != '\0')
readIsSea (par.isSeaFileName);
printf ("readIsSea done : %s\n", par.isSeaFileName);
updateIsSeaWithForbiddenAreas ();
printf ("update isSea : with Forbid Areas done\n");
for (int i = 0; i < par.nShpFiles; i++) {
initSHP (par.shpFileName [i]);
printf ("SHP file loaded: %s\n", par.shpFileName [i]);
}
printf ("Working dir : %s\n", par.workingDir);
printf ("Editor : %s\n", par.editor);
printf ("Spreadsheet : %s\n", par.spreadsheet);
printf ("poi File Name : %s\n", par.poiFileName);
printf ("poi File Name : %s\n", par.portFileName);
printf ("nPoi : %d\n", nPoi);
app = gtk_application_new (APPLICATION_ID, 0);
g_signal_connect (app, "startup", G_CALLBACK (appStartup), NULL);
g_signal_connect (app, "activate", G_CALLBACK (appActivate), NULL);
//printf ("launching...\n");
ret = g_application_run (G_APPLICATION (app), 0, NULL);
g_object_unref (app);
freeSHP ();
free (tIsSea);
return ret;
}
|
import { ChangeEvent, useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import * as enums from '../../utils/enums/tarefa'
import { remover, editar, alteraStatus } from '../../store/reducers/tarefas'
import * as S from './styles' //usamos para importar tudo, para n ter q importar cada componente estilizado
import TarefaClass from '../../models/Tarefa'
import { Botao, BotaoSalvar } from '../../styles'
type Props = TarefaClass
const Tarefa = ({
titulo,
prioridade,
status,
descricao: descricaoOriginal,
id
}: Props) => {
const [estaEditando, setEstaEditando] = useState(false)
const dispatch = useDispatch()
const [descricao, setDescricao] = useState('')
useEffect(() => {
if (descricaoOriginal.length > 0) {
setDescricao(descricaoOriginal)
}
}, [descricaoOriginal])
const cancelarEdicao = () => {
setEstaEditando(false)
setDescricao(descricaoOriginal)
}
const alteraStatusTarefa = (event: ChangeEvent<HTMLInputElement>) => {
dispatch(alteraStatus({ id, finalizado: event.target.checked }))
}
return (
<S.Card>
<label htmlFor={titulo}>
<input
type="checkbox"
id={titulo}
checked={status === enums.Status.CONCLUIDA}
onChange={alteraStatusTarefa}
/>
<S.Titulo>
{estaEditando && <em>Editando: </em>}
{titulo}
</S.Titulo>
</label>
<S.Tag parametro="prioridade" prioridade={prioridade}>
{prioridade}
</S.Tag>
<S.Tag parametro="status" status={status}>
{status}
</S.Tag>
<S.Descricao
disabled={!estaEditando}
value={descricao}
onChange={(e) => setDescricao(e.target.value)}
/>
<S.BarraAcoes>
{estaEditando ? (
<>
<BotaoSalvar
onClick={() => {
dispatch(editar({ descricao, id, prioridade, status, titulo }))
setEstaEditando(false)
}}
>
Salvar
</BotaoSalvar>
<S.BotaoCancelarRemover onClick={cancelarEdicao}>
Cancelar
</S.BotaoCancelarRemover>
</>
) : (
<>
<Botao onClick={() => setEstaEditando(true)}>Editar</Botao>
<S.BotaoCancelarRemover onClick={() => dispatch(remover(id))}>
Remover
</S.BotaoCancelarRemover>
</>
)}
</S.BarraAcoes>
</S.Card>
)
}
export default Tarefa
|
- - -
***Iron Law of Processor Performance***
- - -
- ***Processor Performance → Latency (time it takes to execute program)***
- *Decompose Time/Program into Components to examine trade-offs*
<br>
$\frac{Time}{Program} = \frac{Instruction}{Program} \times \frac{Cycles}{Instruction} \times \frac{Instructions}{Cycle}$
<br>
***Instructions/Program:*** *depends on source code & compiler technology & ISA*
***CPI:*** *depends on ISA & microarchitecture*
***Time/Cycle:*** *depends on the microarchitecture & base technology*
<br>
- ***single-cycle unpipelined has long cycle time as critical path is long***
- ***pipelined has pipeline latches which shorten critical path** (critical path is longest path of all pipeline stages)*
<br>
- ***CPI → throughput metric***
- ***lower CPI → higher throughput***
- *throughput: number of instructions can execute in a given time*
<br>
- ***different trade-offs between cycles/instruction and time/cycle in microarchitecture***
- - -
|
import { gql, useMutation, useQuery } from "@apollo/client";
import { useState } from "react";
import ToDoListChild from "./ToDoListChild";
// 할 일 조회, 목표 번호를 조건에 사용해서 해당 목표에 맞는 할 일만 불러와줌
const PART_LIST = gql`
query PartList($partListId: Int!) {
partList(id: $partListId) {
toDoListCode
objectiveCode
toDoThing
}
}
`;
// 할 일 추가
const ADD_TO_DO_LIST = gql`
mutation CreateToDoList($createToDoListInput: CreateToDoListInput!) {
createToDoList(createToDoListInput: $createToDoListInput) {
objectiveCode
toDoThing
}
}
`;
export default function ToDoList(props: any) {
// 목표 번호를 props 로 받아옴
// console.log("props", props);
const [thing, setThing] = useState(""); // 할 일 추가용 state
const { data, loading, error } = useQuery(PART_LIST, {
// 할 일 조회 query
// 목표에 맞는 할 일들을 조회 하기 위해 목표 번호를 넣어준다.
variables: {
partListId: props.value,
},
});
// 할 일 추가 mutation
const [addTodoThing] = useMutation(ADD_TO_DO_LIST, {
// 목표 추가 후 전체 할 일 조회를 다시 호출
refetchQueries: [
{
// 할 일 조회 호출 시 해당 목표 번호를 같이 던져줘야 함
query: PART_LIST,
variables: {
partListId: props.value,
},
},
],
});
// 할 일 추가 함수
function addThing(e: any) {
addTodoThing({
variables: {
createToDoListInput: {
objectiveCode: parseInt(e.target.getAttribute("data-key")),
toDoThing: thing,
},
},
});
setThing(""); // input에 값을 서버에 넘겨주고 나서 input를 다시 비워줌
}
// 로딩중
if (loading) return <p>Loading...</p>;
// 에러
if (error) return <p>Error :(</p>;
return (
<div className="bg-slate-500">
<h2>할 일 목록</h2>
<div>
{data?.partList?.map((toDoList: any) => (
// map으로 받아오면 하위 항목을 감쌀 때 key값을 넣어줘야 에러가 안남
// 하위 컴포넌트에 value로 값을 전달해 준다.
<ToDoListChild key={toDoList.toDoListCode} value={toDoList} />
))}
<div>
<label>할 일 추가!</label>
<input className="border-2 border-amber-400 rounded-lg w-[300px] ml-3" name="newToDoThing" onChange={(event) => setThing(event.target.value)} placeholder="새로운 할 일을 추가해주세요." value={thing} />
<button className="mx-3 text-sm bg-sky-800 p-0.5 rounded-lg" onClick={addThing} data-key={props.value}>
추가
</button>
</div>
</div>
</div>
);
}
|
import React, {useEffect,useState} from 'react';
import { Link } from 'react-router-dom';
import {styles} from '../styles';
import {navLinks} from '../constants';
import { logo,menu, close,linkedin,github,leetcode } from "../assets";
const Navbar = () => {
const[active,setActive]=useState("");
const[toggle,setToggle]=useState(false);
return (
<nav
className={`${styles.paddingX} w-full flex items-center py-5 fixed top-0 z-20 bg-primary `}
>
<div className="w-full flex justify-between items-center max-w-7xl mx-auto">
{/* <Link
to="/"
className="flex items-center gap-2"
onClick={() => {
setActive("");
window.scrollTo(0, 0);
}}
>
<img src={logo} alt="logo" className="w-9 h-9 object-contain" />
<p className="text-white text-[18px] font-bold cursor-pointer flex ">
Ankit
<span className="sm:block hidden"> Raj</span>
</p>
</Link> */}
<div className=" flex items-center gap-2 ">
<a href="https://www.linkedin.com/in/rajankit24/" target="blank">
<img src={linkedin} alt="logo" className="w-9 h-9 object-contain" />
</a>
<a href="https://leetcode.com/Ankit75124/" target="blank">
<img src={leetcode} alt="logo" className="w-9 h-9 object-contain" />
</a>
<a href="https://github.com/Ankit75124" target="blank">
<img src={github} alt="logo" className="w-9 h-9 object-contain" />
</a>
</div>
<ul className="list-none hidden sm:flex flex-row gap-10">
{navLinks.map((nav) => (
<li
key={nav.id}
className={`${
active === nav.title ? "text-white" : "text-secondary"
} hover:text-white text-[18px] font-medium cursor-pointer`}
onClick={() => setActive(nav.title)}
>
<a href={`#${nav.id}`}>{nav.title}</a>
</li>
))}
</ul>
<div className="sm:hidden flex flex-1 justify-end items-center">
<img
src={toggle ? close : menu}
alt="menu"
className="w-[28px] h-[28px] object-contain"
onClick={() => setToggle(!toggle)}
/>
<div
className={`${
!toggle ? "hidden" : "flex"
} p-6 black-gradient absolute top-20 right-0 mx-4 my-2 min-w-[140px] z-10 rounded-xl`}
>
<ul className="list-none flex justify-end items-start flex-col gap-4">
{navLinks.map((nav) => (
<li
key={nav.id}
className={`${
active === nav.title ? "text-white" : "text-secondary"
} fonts-poppins font-medium cursor-pointer text-[16px]`}
onClick={() => {
setToggle(!toggle);
setActive(nav.title);
}}
>
<a href={`#${nav.id}`}>{nav.title}</a>
</li>
))}
</ul>
</div>
<img src={logo} alt="logo" className="w-9 h-9 object-contain" />
</div>
</div>
</nav>
);
}
export default Navbar
|
#include <iostream>
#ifndef SINGLE
#define SINGLE 1
using namespace std;
// Patron Singleton empleado para variables globales
class PersonID
{
static PersonID *instance;
int personID;
// Private constructor so that no objects can be created.
PersonID()
{
personID = 1; // Contador de ID
}
public:
static PersonID *getInstance()
{
if (!instance)
instance = new PersonID;
return instance;
}
// Retorna el ID actual
int getID()
{
int resul = this->personID;
this->personID += 1;
return resul;
}
};
#endif
|
package com.sinsra.controller;/*
* ClassName: ArticleController
* Package: com.sinsra.controller
* @Create: 2024/4/23 21:53
*/
import com.sinsra.annotation.mySystemLog;
import com.sinsra.domain.ResponseResult;
import com.sinsra.domain.dto.AddArticleDto;
import com.sinsra.domain.dto.ArticleDto;
import com.sinsra.domain.entity.Article;
import com.sinsra.domain.vo.ArticleByIdVo;
import com.sinsra.domain.vo.ArticleVo;
import com.sinsra.domain.vo.PageVo;
import com.sinsra.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/content/article")
public class ArticleController {
@Autowired
ArticleService articleService;
@PostMapping
public ResponseResult add(@RequestBody AddArticleDto article){
return articleService.add(article);
}
@GetMapping("/list")
public ResponseResult list(Article article, Integer pageNum, Integer pageSize){
PageVo pageVo = articleService.selectArticlePage(article,pageNum,pageSize);
return ResponseResult.okResult(pageVo);
}
@GetMapping(value = "/{id}")
//①先查询根据文章id查询对应的文章
public ResponseResult getInfo(@PathVariable(value = "id")Long id){
ArticleByIdVo article = articleService.getInfo(id);
return ResponseResult.okResult(article);
}
@PutMapping
//②然后才是修改文章
public ResponseResult edit(@RequestBody ArticleDto article){
articleService.edit(article);
return ResponseResult.okResult();
}
@DeleteMapping("/{id}")
public ResponseResult delete(@PathVariable Long id){
//直接使用mybatisplus提供的removeById方法
articleService.removeById(id);
return ResponseResult.okResult();
}
}
|
/************************************************************************************************************************************
Author : Dipak Pawar
Description : This class is used to test RESTAPITourV2
History:
----------------------------------------------------------------------------------------------------------------------------------
VERSION DATE AUTHOR DETAIL ISSUE
1 19 June 2018 Dipak Pawar Initial Developement ST-
**************************************************************************************************************************************/
@isTest
public class RESTAPITourV2Test {
public static User apiUser;
public static Building__c b;
public static Contact nmdContact;
/************************************************************************************************************************************
Author : Krishana Tupe
Description : This setup method will setup the initial test data for verification of Tour and Task creation functionality.
Created Date : 07 June 2018
Issue No : ST-
**************************************************************************************************************************************/
@TestSetup
public static void setupData() {
SalesConsoleSettings.createSettings();
Profile weworkSystemAdmin = [SELECT Id FROM Profile WHERE Name='System Administrator'];
apiUser = new User();
apiUser.Alias = 'APIU';
apiUser.Email='test@example.com';
apiUser.EmailEncodingKey='UTF-8';
apiUser.LastName='APIUser';
apiUser.LanguageLocaleKey='en_US';
apiUser.LocaleSidKey = 'en_US';
apiuser.ProfileId = weworkSystemAdmin.Id;
apiUser.IsActive = true;
apiUser.TimeZoneSidKey='America/Los_Angeles';
apiUser.UserName='tourapiuser@example.com';
apiUser.CommunityNickname = TestingUtility.createUserCommunityName();
insert apiUser;
Map<String, Object> mapCommunitySalesLead = new Map<String, Object>();
mapCommunitySalesLead.put('LastName', 'TestCommunitySalesLead');
mapCommunitySalesLead.put('Username', 'TestCommunitySalesLead@weworkexample.com');
mapCommunitySalesLead.put('Email', 'joinus@wework.com');
User CommunityLead = TestingUtility.insertUserWithAssert(weworkSystemAdmin.Id, mapCommunitySalesLead, true);
nmdContact = new Contact(FirstName='WeWork', LastName='NMD USER',Email='joinus@wework.com');
insert nmdContact;
Setting__c testTourRservableSettings = new Setting__c();
testTourRservableSettings.Name = 'TourRservableSettings';
testTourRservableSettings.Data__c = '{"salesleadprofiles": [{"profilename":"System Administrator", "profileid":"00eF0000000Rfpc"}], "bookedbysalesleadlabel":"Booked By Sales Lead", "apiuseremail":"joinus@wework.com", "apiuserid":"005F0000003KmbwIAC", "apiusercontactid":"'+nmdContact.Id+'"}';
insert testTourRservableSettings;
TestingUtility.getRecords(new Map<String, Object> {'objName'=>'touropenhour','numberOfRecords'=>'1'});
TestingUtility.getRecords(new Map<String, object> {'objName'=>'journey','numberOfRecords'=>'1'});
List<Building__c> lstBuilding = [SELECT Id, City__c, uuid__c, Name FROM Building__c WHERE Name LIKE 'testBuilding%'];
List<Tour_Schedule__c> lstTourSchedule = [SELECT Building__c, Simultaneous_Tours__c, Tour_Spacing__c, Maximum_Tour_Days__c FROM Tour_Schedule__c];
List<Tour_Open_Hour__c> lstTourOpenHour = [SELECT weekday__c, start_time__c, end_time__c, Tour_Schedule__c, Building__c FROM Tour_Open_Hour__c];
}
/************************************************************************************************************************************
Author : Krishana Tupe
Description : This method gives the sample tour payload for tour booking;
Created Date : 07 June 2018
Issue No : ST-
**************************************************************************************************************************************/
public static RESTAPITourModelsV2.Input getTourPayload (){
List<Building__c> lstBuilding = [SELECT Id, City__c, uuid__c, Name FROM Building__c WHERE Name LIKE 'testBuilding%'];
Debug.Log('lstBuilding Data==>'+lstBuilding);
String jsonPayload = '{"desks_interested_min":"2","desks_interested_max":"3","desks_interested_range":"10-20","first_name":"John","last_name":"Smith0706201801","email":"john.smith0706201802@example.com","phone":"8600139164","lead_source":"wework.com","lead_source_detail":"Book A Tour Form","utm_campaign_id":"","utm_campaign":"San Francisco - Modifier","utm_content":"utm contents","utm_medium":"cpc","utm_source":"ads-google","utm_term":"virtual +office +san +francisco","company_name":"John Smith","company_size":"2-5 desks","company_industry":"Education","quick_quote_location":"New York City","notes":"Our Notes for","referral_code":"JetBlue","promo_code":"JetBlue","buildings_interested_uuids":["bdf78b97-f8c9-4062-923d-ed32e251d2ad"],"product_interests":["Office Space"],"product_line":"WeWork","locale":"US","country_code":"US","tour_date":"2018-06-07","tour_time":"08:00AM","tour_uuid":"fdb15bdf-19e2-4abe-bd40-7b7fa9816fb5","tour_building_uuid":"'+lstBuilding[0].UUID__c+'","tour_notes":"Currently at Manhattan, Relocate","contact_uuid":"dsp18593-3239-45cc-b690-5bccc15a27c3","original_tour":"","original_tour_uuid":"","sf_journey_uuid":"","booked_by_contact_id":"0033D00000Ou6FA","tour_completed_by":"","t_and_cs_consent":"False","marketing_consent":"False","affiliates_consent":"False","referral_fail_reason":"No Show","booked_by_sales_lead":true}';
RESTAPITourModelsV2.Input tourPayload = (RESTAPITourModelsV2.Input)JSON.deserialize(jsonPayload, RESTAPITourModelsV2.Input.class);
return tourPayload;
}
/************************************************************************************************************************************
Author : Krishana Tupe
Description : This method verifies the task creation functionality for tour booking When Account is Consumer and Booked By Contact Id is null.
Created Date : 07 June 2018
Issue No : ST-
**************************************************************************************************************************************/
public static testMethod void verifyCreateTaskForTourConsumer() {
User apiUser = [SELECT Id FROM User WHERE UserName = 'tourapiuser@example.com'];
List<Account> lstAccount = new List<Account>([SELECT Id, OwnerId, UUID__c, RecordTypeId FROM Account]);
List<Contact> lstContact = new List<Contact>([SELECT Id, FirstName, LastName, UUID__c, Email FROM Contact]);
System.runAs(apiUser){
lstAccount[0].UUID__c = 'account-uuid';
lstAccount[0].OwnerId = apiUser.Id;
TestingUtility.updateListWithAssert(lstAccount);
}
RESTAPITourModelsV2.Input tourPayload = getTourPayload();
tourPayload.contact_uuid = lstContact[0].UUID__c;
tourPayload.booked_by_contact_id =null;
tourPayload.booked_by_sales_lead = false;
tourPayload.email = lstContact[0].Email;
tourPayload.first_name = lstContact[0].FirstName;
tourPayload.last_name = lstContact[0].LastName;
Test.startTest();
//submit post
RESTAPIResult response = new RESTAPIResult();
response.setSuccess(RESTAPITourV2.bookTour(tourPayload));
system.assertEquals(true, response.success, 'Response msg: ' + response.message);
List<Opportunity>lstOpps = [SELECT Id, OwnerId ,Primary_Member__c, RecordType.Name,AccountId,Account.OwnerId,Account.RecordType.Name FROM Opportunity WHERE Primary_Member__r.email = :lstContact[0].email];
System.assert(lstOpps.size() > 0,'An opportunity should be created');
User SusuieRomero = [SELECT Id, Name FROM User WHERE Id = '005F0000003KmbwIAC'];
System.assertEquals(lstOpps[0].RecordType.Name, lstOpps[0].Account.RecordType.Name,'Opportunity Record Type should be same as Account Record Type.');
System.assertEquals(lstOpps[0].Account.OwnerId,lstOpps[0].OwnerId,'Opportunity owner should be same as Account owner as Account of Opportunity is mid market.');
List<Tour_Outcome__c> lstTours = [SELECT id, Opportunity__c, tour_completed_by__c, tour_completed_by_UUID__c, tour_completed_by_Name__c, tour_completed_by_SFID__c,
Booked_By_Sales_Lead__c, Hosted_By__c, Assigned_Host__c, OwnerId, booked_by_contact_id__c FROM Tour_Outcome__c WHERE tour_date__c = :tourPayload.tour_date ];
System.assert(lstTours.size() > 0,'A tour for the specified date should be created:' + tourPayload.tour_date);
System.assertEquals(SusuieRomero.Id, lstTours[0].OwnerId);
System.assertEquals(false, lstTours[0].Booked_By_Sales_Lead__c);
System.assertEquals(lstTours[0].booked_by_contact_id__c, lstTours[0].Assigned_Host__c);
RESTAPITourModelsV2.Response res = (RESTAPITourModelsV2.Response)JSON.deserialize(JSON.serialize(response.result), RESTAPITourModelsV2.Response.class);
System.assert(response.success != null && response.success && String.valueOf(res.tour_sfid).equals(lstTours[0].Id),'The tour id should be provided as response; ' + lstTours[0].Id);
System.assert(response.success != null && response.success && String.valueOf(res.contact_sfid).equals(lstContact[0].Id),'The Contact Id which tour should booked should be provided as response; ' + lstContact[0].Id);
Test.stopTest();
}
/************************************************************************************************************************************
Author : Krishana Tupe
Description : This method verifies the task creation functionality for tour booking When Account is Mid Market and Booked By Contact Id is null.
Created Date : 11 June 2018
Issue No : ST-
**************************************************************************************************************************************/
public static testMethod void verifyCreateTaskForTourMidMarket() {
User apiUser = [SELECT Id FROM User WHERE UserName = 'tourapiuser@example.com'];
List<Account> lstAccount = new List<Account>([SELECT Id, OwnerId, UUID__c, RecordTypeId FROM Account]);
List<Contact> lstContact = new List<Contact>([SELECT Id, FirstName, LastName, UUID__c, Email FROM Contact]);
System.runAs(apiUser){
lstAccount[0].UUID__c = 'account-uuid';
lstAccount[0].OwnerId = apiUser.Id;
lstAccount[0].RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Mid Market').getRecordTypeId();
TestingUtility.updateWithAssert(lstAccount[0]);
}
lstContact[0].UUID__c = 'contact-uuid';
TestingUtility.updateWithAssert(lstContact[0]);
RESTAPITourModelsV2.Input tourPayload = getTourPayload();
tourPayload.contact_uuid = lstContact[0].UUID__c;
tourPayload.booked_by_contact_id = null;
tourPayload.booked_by_sales_lead = false;
tourPayload.email = lstContact[0].Email;
tourPayload.first_name = lstContact[0].FirstName;
tourPayload.last_name = lstContact[0].LastName;
Test.startTest();
RESTAPIResult response = new RESTAPIResult();
response.setSuccess(RESTAPITourV2.bookTour(tourPayload));
system.assertEquals(true, response.success, 'Response msg: ' + response.message);
List<Opportunity>lstOpps = [SELECT Id, OwnerId ,Primary_Member__c, RecordType.Name,AccountId,Account.OwnerId,Account.RecordType.Name FROM Opportunity WHERE Primary_Member__r.email = :lstContact[0].email];
System.assert(lstOpps.size() > 0,'An opportunity should be created');
System.assertEquals(lstOpps[0].RecordType.Name, lstOpps[0].Account.RecordType.Name,'Opportunity Record Type should be same as Account Record Type.');
System.assertEquals(lstOpps[0].Account.OwnerId,lstOpps[0].OwnerId,'Opportunity owner should be same as Account owner as Account of Opportunity is mid market.');
List<Tour_Outcome__c> lstTours = [SELECT id, Opportunity__c, tour_completed_by__c, tour_completed_by_UUID__c, tour_completed_by_Name__c, tour_completed_by_SFID__c,
Booked_By_Sales_Lead__c, Hosted_By__c, Assigned_Host__c, OwnerId, booked_by_contact_id__c FROM Tour_Outcome__c WHERE tour_date__c = :tourPayload.tour_date ];
System.assert(lstTours.size() > 0,'A tour for the specified date should be created:' + tourPayload.tour_date);
System.assertEquals(false, lstTours[0].Booked_By_Sales_Lead__c);
System.assertEquals(lstTours[0].booked_by_contact_id__c, lstTours[0].Assigned_Host__c);
RESTAPITourModelsV2.Response res = (RESTAPITourModelsV2.Response)JSON.deserialize(JSON.serialize(response.result), RESTAPITourModelsV2.Response.class);
System.assert(response.success != null && response.success && String.valueOf(res.tour_sfid).equals(lstTours[0].Id),'The tour id should be provided as response; ' + lstTours[0].Id);
System.assert(response.success != null && response.success && String.valueOf(res.contact_sfid).equals(lstContact[0].Id),'The Contact Id which tour should booked should be provided as response; ' + lstContact[0].Id);
Test.stopTest();
}
/************************************************************************************************************************************
Author : Krishana Tupe
Description : This method verifies the task creation functionality for tour booking When Account is Mid Market and Booked By Contact Id is given.
Created Date : 11 June 2018
Issue No :
**************************************************************************************************************************************/
public static testMethod void verifyCreateTaskForTourMidMarketWithBookedByConId() {
User apiUser = [SELECT Id FROM User WHERE UserName = 'tourapiuser@example.com'];
List<Account> lstAccount = new List<Account>([SELECT Id, OwnerId, UUID__c, RecordTypeId FROM Account]);
List<Contact> lstContact = new List<Contact>([SELECT Id, FirstName, LastName, UUID__c, Email FROM Contact]);
System.runAs(apiUser){
lstAccount[0].Name = 'A Company';
lstAccount[0].UUID__c = 'account-uuid';
lstAccount[0].OwnerId = apiUser.Id;
lstAccount[0].RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Mid Market').getRecordTypeId();
TestingUtility.updateWithAssert(lstAccount[0]);
}
lstContact[0].UUID__c = 'contact-uuid';
lstContact[0].Email = 'testtourcompletedbycontact@example.com';
TestingUtility.updateWithAssert(lstContact[0]);
RESTAPITourModelsV2.Input tourPayload = getTourPayload();
tourPayload.contact_uuid = lstContact[0].UUID__c;
tourPayload.booked_by_contact_id = lstContact[0].Id;
tourPayload.booked_by_sales_lead = false;
tourPayload.email = lstContact[0].Email;
tourPayload.first_name = lstContact[0].FirstName;
tourPayload.last_name = lstContact[0].LastName;
Test.startTest();
RESTAPI.PayloadDetails payload = new RESTAPI.PayloadDetails();
payload.Input = tourPayload;
RESTAPIResult response = new RESTAPITourV2().executePost(payload);
System.assertEquals(true, response.success, 'Response msg: ' + response.message);
List<Opportunity> lstOpps = [SELECT Id, OwnerId, Primary_Member__c, RecordType.Name, AccountId, Account.OwnerId, Account.RecordType.Name FROM Opportunity WHERE Primary_Member__r.email = :lstContact[0].email];
System.assert(lstOpps.size() > 0,'An opportunity should be created');
System.assertEquals(lstOpps[0].RecordType.Name, lstOpps[0].Account.RecordType.Name, 'Opportunity Record Type should be same as Account Record Type.');
System.assertEquals(lstOpps[0].Account.OwnerId, lstOpps[0].OwnerId, 'Opportunity owner should be same as Account owner as Account of Opportunity is mid market.');
List<Tour_Outcome__c> lstTours = [SELECT Id, Opportunity__c, tour_completed_by__c, tour_completed_by_UUID__c, tour_completed_by_Name__c, tour_completed_by_SFID__c,
Booked_By_Sales_Lead__c, Hosted_By__c, Assigned_Host__c, OwnerId, booked_by_contact_id__c FROM Tour_Outcome__c WHERE tour_date__c = :tourPayload.tour_date];
System.debug('lstTours[0].Assigned_Host__c-->'+lstTours[0].Assigned_Host__c);
System.assert(lstTours.size() > 0, 'A tour for the specified date should be created:' + tourPayload.tour_date);
User susuieRomero = [SELECT Id, Name FROM User WHERE Id = '005F0000003KmbwIAC'];
System.assertEquals(susuieRomero.Id, lstTours[0].OwnerId);
System.assertEquals(false, lstTours[0].Booked_By_Sales_Lead__c);
System.assertEquals(lstTours[0].booked_by_contact_id__c, lstContact[0].Id);
RESTAPITourModelsV2.Response res = (RESTAPITourModelsV2.Response)JSON.deserialize(JSON.serialize(response.result), RESTAPITourModelsV2.Response.class);
System.assert(response.success != null && response.success && String.valueOf(res.tour_sfid).equals(lstTours[0].Id),'The tour id should be provided as response; ' + lstTours[0].Id);
System.assert(response.success != null && response.success && String.valueOf(res.contact_sfid).equals(lstContact[0].Id),'The Contact Id which tour should booked should be provided as response; ' + lstContact[0].Id);
Test.stopTest();
}
/************************************************************************************************************************************
Author : Dipak Pawar
Description :
Created Date : 12 June 2018
Issue No : ST-2482
**************************************************************************************************************************************/
public static testMethod void verifyCreateTaskForTourReschedule(){
User apiUser = [SELECT Id FROM User WHERE UserName = 'tourapiuser@example.com'];
List<Account> lstAccount = new List<Account>([SELECT Id, OwnerId, UUID__c, RecordTypeId FROM Account]);
List<Contact> lstContact = new List<Contact>([SELECT Id, FirstName, LastName, UUID__c, Email FROM Contact]);
List<Building__c> lstBuilding = [SELECT Id, City__c, uuid__c, Name FROM Building__c WHERE Name LIKE 'testBuilding%'];
System.runAs(apiUser){
lstAccount[0].UUID__c = 'account-uuid';
lstAccount[0].OwnerId = apiUser.Id;
TestingUtility.updateListWithAssert(lstAccount);
}
lstContact[0].UUID__c = 'contact-uuid';
lstContact[0].Email = 'testtourcompletedbycontact@example.com';
TestingUtility.updateWithAssert(lstContact[0]);
RESTAPITourModelsV2.Input tourPayload = getTourPayload();
tourPayload.contact_uuid = lstContact[0].UUID__c;
tourPayload.booked_by_contact_id = null;
tourPayload.booked_by_sales_lead = false;
tourPayload.email = lstContact[0].Email;
tourPayload.first_name = lstContact[0].FirstName;
tourPayload.last_name = lstContact[0].LastName;
Test.startTest();
RESTAPIResult result = new RESTAPIResult();
result.setSuccess(RESTAPITourV2.bookTour(tourPayload));
System.assertEquals(true, result.success, 'Response msg: ' + result.message);
List<Opportunity>lstOpps = [SELECT Id, OwnerId ,Primary_Member__c, RecordType.Name,AccountId,Account.OwnerId,Account.RecordType.Name FROM Opportunity WHERE Primary_Member__r.email = :lstContact[0].email];
System.assert(lstOpps.size() > 0,'An opportunity should be created');
System.assertEquals(lstOpps[0].RecordType.Name, lstOpps[0].Account.RecordType.Name,'Opportunity Record Type should be same as Account Record Type.');
System.assertEquals(apiUser.Id, lstOpps[0].OwnerId);
List<Tour_Outcome__c> lstTours = [SELECT id, Status__c, Opportunity__c, tour_completed_by__c, tour_completed_by_UUID__c, tour_completed_by_Name__c, tour_completed_by_SFID__c,
Booked_By_Sales_Lead__c, Hosted_By__c, Assigned_Host__c, OwnerId, booked_by_contact_id__c, uuid__c, Original_Tour__c, Original_Tour__r.uuid__c FROM Tour_Outcome__c WHERE tour_date__c = :tourPayload.tour_date ];
System.assert(lstTours.size() > 0, 'A tour for the specified date should be created:' + tourPayload.tour_date);
System.assertEquals(1, lstTours.size());
System.assertEquals('Scheduled', lstTours[0].Status__c);
System.assertEquals('fdb15bdf-19e2-4abe-bd40-7b7fa9816fb5', lstTours[0].uuid__c);
tourPayload.original_tour_uuid = 'fdb15bdf-19e2-4abe-bd40-7b7fa9816fb5';
tourPayload.tour_uuid = 'fdb15bdf-19e2-4abe-bd40-7b7fa9812345';
List<Journey__c> lstJourney1 = new List<Journey__c>([SELECT Id, Status__c, Name FROM Journey__c WHERE Primary_Contact__c =: lstContact[0].Id]);
lstJourney1[0].Status__c = 'Started';
TestingUtility.updateWithAssert(lstJourney1[0]);
result = new RESTAPIResult();
result.setSuccess(RESTAPITourV2.bookTour(tourPayload));
system.assertEquals(true, result.success, 'Response msg: ' + result.message);
lstTours = [SELECT id, Status__c, Opportunity__c, tour_completed_by__c, tour_completed_by_UUID__c, tour_completed_by_Name__c, tour_completed_by_SFID__c,
Booked_By_Sales_Lead__c, Hosted_By__c, Assigned_Host__c, OwnerId, booked_by_contact_id__c, uuid__c, Original_Tour__c, Original_Tour__r.uuid__c FROM Tour_Outcome__c WHERE tour_date__c = :tourPayload.tour_date ];
System.assert(lstTours.size() > 0,'A tour for the specified date should be created:' + tourPayload.tour_date);
System.assertEquals(2, lstTours.size());
for(Tour_Outcome__c tour : lstTours){
if(tour.uuid__c == 'fdb15bdf-19e2-4abe-bd40-7b7fa9816fb5'){
System.assertEquals('Scheduled', tour.Status__c);
} else if(tour.uuid__c == 'fdb15bdf-19e2-4abe-bd40-7b7fa9812345'){
System.assertEquals('Scheduled', tour.Status__c);
System.assertNotEquals(null, tour.Original_Tour__c);
System.assertEquals('fdb15bdf-19e2-4abe-bd40-7b7fa9816fb5', tour.Original_Tour__r.uuid__c);
}
}
Test.stopTest();
}
}
|
import axios from 'axios'
const baseUrl = '/api/blogs'
let token = null
const setToken = (newToken) => {
token = `bearer ${newToken}`
}
const getAll = () => {
const request = axios.get(baseUrl)
return request.then((response) => response.data)
}
const getById = async (id) => {
const response = await axios.get(`${baseUrl}/${id}`)
return response.data
}
const create = async (newObject) => {
const config = {
headers: { Authorization: token }
}
const response = await axios.post(baseUrl, newObject, config)
return response.data
}
const update = async (id, newObject) => {
const response = await axios.put(`${baseUrl}/${id}`, newObject)
return response.data
}
const remove = async (id) => {
const config = {
headers: { Authorization: token }
}
const response = await axios.delete(`${baseUrl}/${id}`, config)
return response
}
const comment = async (id, newObject) => {
const config = {
headers: { Authorization: token }
}
const response = await axios.post(
`${baseUrl}/${id}/comments`,
newObject,
config
)
return response.data
}
const blogService = {
getAll,
getById,
create,
setToken,
update,
remove,
comment
}
export default blogService
|
/*
* Calvin Neo
* Copyright (C) 2016 Calvin Neo <calvinneo@calvinneo.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "gen_common.h"
#include <boost/algorithm/string.hpp>
std::string gen_rights(std::string filename, std::string author) {
using namespace std;
using namespace boost;
string line_filename = " File: " + filename + " \n";
string line_author = " Author: " + filename + " \n";
string line_cfor = " This codes is generated by CFortranTranslator \n CFortranTranslator is published under GPL license \n refer to https://github.com/CalvinNeo/CFortranTranslator/ for more ";
string all_lines = line_filename + line_author + line_cfor;
vector<string> splitvec;
split(splitvec, all_lines, is_any_of("\n"), token_compress_on);
string content;
int longest = 0;
for (int i = 0; i < splitvec.size(); i++)
{
longest = max(longest, (int)splitvec[i].size());
}
for (int i = 0; i < splitvec.size(); i++)
{
content += "/*";
content += splitvec[i];
content += string(longest - splitvec[i].size(), ' ');
content += "*/\n";
}
sprintf(codegen_buf, "/*%s*/\n%s/*%s*/\n", string(longest , '*').c_str(), content.c_str(), string(longest, '*').c_str());
return string(codegen_buf);
}
ParseNode gen_header() {
std::string x = gen_rights(" ", " ");
x += "#include \"../for90std/for90std.h\" \n";
if (get_context().parse_config.usefor) {
x += "#define USE_FORARRAY \n";
}
else {
x += "#define USE_CARRAY \n";
}
ParseNode newnode = gen_token(Term{TokenMeta::META_ANY, x.c_str()});
return newnode;
}
ParseNode gen_comment(std::string comment, bool line_comment) {
if (line_comment)
{
return gen_token(Term{ TokenMeta::Comments, "//" + comment });
}
else {
return gen_token(Term{ TokenMeta::Comments, "/*" + comment + "*/" });
}
}
void insert_comments(ParseNode & newnode) {
for (const std::string & comment : get_tokenizer_context().comments)
{
newnode.addchild(gen_comment(comment, false));
}
get_tokenizer_context().comments.clear();
}
|
using System.Numerics;
using Raylib_cs;
public class Simulation
{
public readonly int Width;
public readonly int Height;
public readonly string Title;
public readonly int Iterations;
public List<Ball> Balls;
public List<Line> Lines;
private readonly System.Timers.Timer timer;
private readonly List<Ball> ballQueue;
private readonly List<Line> lineQueue;
public Simulation(int width, int height, string title, int iterations = 10)
{
Width = width;
Height = height;
Title = title;
Iterations = iterations;
Balls = new();
Lines = new();
timer = new(3000);
ballQueue = new();
lineQueue = new();
}
private void CallBalls(Action<Ball> act)
{
for (int i = 0; i < Balls.Count; i++)
{
act(Balls[i]);
}
}
private void CallLines(Action<Line> act)
{
for (int i = 0; i < Lines.Count; i++)
{
act(Lines[i]);
}
}
public void Run()
{
Raylib.SetTraceLogLevel(TraceLogLevel.LOG_ERROR);
Raylib.InitWindow(Width, Height, Title);
Random rand = new Random();
timer.AutoReset = true;
timer.Elapsed += new((_, _) => ballQueue.Add(
new(Utils.RandomRange(rand, 0.1f, 0.5f), 1.5f, 0f)
));
timer.Start();
while (!Raylib.WindowShouldClose())
{
Raylib.BeginDrawing();
Raylib.ClearBackground(Color.WHITE);
Simulate();
Draw();
Raylib.DrawText($"FPS: {Math.Round(1 / Const.DeltaTime, 1)}", 10, 10, 16, Color.BLACK);
Raylib.EndDrawing();
}
Raylib.CloseWindow();
}
public void Simulate()
{
Const.DeltaTime = Raylib.GetFrameTime() / Iterations;
for (int i = 0; i < Iterations; i++)
{
CallBalls(ball =>
{
ball.Update();
});
CallBalls(ball =>
{
// TODO: Check for collisions first, and only include them
CallBalls(b =>
{
if (ball == b)
{
return;
}
ball.Collide(b);
});
});
CallBalls(ball =>
{
CallLines(line =>
{
ball.Collide(line);
});
});
CallBalls(ball =>
{
ball.Step();
});
CallBalls(ball =>
{
if (Ball.Invalid(ball) || ball.Position.Y >= 30) Balls.Remove(ball);
});
}
foreach (Ball ball in ballQueue.ToList())
{
Balls.Add(ball);
}
foreach (Line line in lineQueue.ToList())
{
Lines.Add(line);
}
ballQueue.Clear();
lineQueue.Clear();
}
public void Draw()
{
CallLines(line =>
{
line.Draw();
});
CallBalls(ball =>
{
ball.Draw();
});
}
}
|
<script>
import { notifCenter } from "./notifications";
// Max number of displayed messages.
export let maxToShow = 4;
// The open-close state.
let show = false;
// The list of displayed messages, based on the `maxToShow` prop.
$: messages = $notifCenter.slice(0, maxToShow);
const doDismiss = message => {
notifCenter.dismiss(message);
// Close popup when there are no more messages.
if ($notifCenter.length === 0) {
show = false;
}
};
const doPopup = () => {
// Don't show popup when there are no messages.
if ($notifCenter.length === 0) {
show = false;
} else {
show = !show;
}
};
const doClearAll = () => {
notifCenter.clear();
show = false; // close the popup
};
</script>
<style>
/* unread message count */
.badge {
display: inline-block;
position: absolute;
top: 0;
background-color: #4285f4;
color: #d7e6fd;
right: 0;
border-radius: 9999px;
font-size: 12px;
min-width: 18px;
line-height: 18px;
min-height: 18px;
text-align: center;
}
/* custom width for message popup */
.messages {
min-width: 400px;
}
</style>
<!-- the UI markup -->
<!-- notification center -->
<button class="relative p-1" on:click={doPopup}>
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
class="w-6 h-6">
<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
</svg>
<!-- Show number of messages or hide if zero. -->
{#if $notifCenter.length}
<span class="badge">{$notifCenter.length}</span>
{/if}
</button>
<!-- Show only if there are messages. -->
{#if show && $notifCenter.length}
<!-- Clicking anywhere on the page will close the popup, that's why this button. -->
<button
tabindex="-1"
class="fixed inset-0 w-full h-full cursor-default focus:outline-none"
on:click|preventDefault={() => (show = false)} />
<div
class="absolute right-0 p-3 mt-1 text-gray-600 bg-gray-100 rounded shadow-xl
messages">
<ul class="space-y-3">
{#each messages as message}
<li class="p-3 border rounded">
<p>{message}</p>
<div class="mt-1">
<button
class="px-2 text-sm text-gray-100 bg-gray-600 rounded-sm"
on:click={() => doDismiss(message)}>
dismiss
</button>
</div>
</li>
{/each}
</ul>
<div class="flex justify-end mt-3">
<button
class="px-2 text-sm text-gray-100 bg-gray-600 rounded-sm"
on:click={doClearAll}>
clear all
</button>
</div>
</div>
{/if}
|
"use client";
import NewServiceSchema from "@/lib/form/new-service-schema";
import { Service } from "@prisma/client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import axios, { AxiosError } from "axios";
import { useState } from "react";
import * as z from "zod";
import { CaptureForm } from "../CaptureForm";
import { useToast } from "../ui/use-toast";
type NewServiceSchemaType = z.infer<typeof NewServiceSchema>;
const UpdateServiceForm = ({ service }: { service: Service }) => {
const { toast } = useToast();
const [isLoading, setIsLoading] = useState(false);
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: (payload: NewServiceSchemaType) => {
return axios.put("/api/service/updateService", payload);
},
onMutate: () => {
setIsLoading(true);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["service"] });
},
onSettled: (data, variables, context) => {
setIsLoading(false);
},
onError: (data: AxiosError) => {
return data.response?.data;
},
});
const onSubmit = async (values: NewServiceSchemaType) => {
const payload = { ...values, id: service.id };
try {
await mutation.mutateAsync(payload);
toast({
title: "Successfully updated service",
description: "Customers will now be able to see the new service.",
});
} catch (err) {
return (err as AxiosError).response?.data;
}
};
// Convert the seconds stored in database to the input foramt (HH:MM:SS) for defaultValue
const estimatedTimeToFormat = new Date(service.estimatedTime * 1000)
.toISOString()
.slice(11, 19);
const captureFormProps = {
isLoading,
schema: NewServiceSchema,
formFields: [
{
name: "name",
label: "Service Name",
placeholder: "Haircut + Beard",
defaultValue: service.name,
},
{
name: "description",
label: "Description",
placeholder: "Cut both hair and beard",
defaultValue: service.description,
},
{
name: "price",
label: "Price",
placeholder: "30.00",
defaultValue: service.price,
},
{
name: "estimatedTime",
label: "Estimated time (HH:MM:SS)",
defaultValue: estimatedTimeToFormat,
},
],
submitButtonText: "Update",
submitButtonClassNames: "w-full",
onSubmit,
};
return (
<>
<CaptureForm {...captureFormProps} />
</>
);
};
export default UpdateServiceForm;
|
----------------------------------------------------------------------------------
-- Company: Department of Electrical and Computer Engineering, University of Alberta
-- Engineer: Shyama Gandhi and Bruce Cockburn
-- Create Date: 10/29/2020 07:18:24 PM
-- Description: CPU LAB 3 - ECE 410 (2021)
-- Revision:
-- Revision 0.01 - File Created
-- Revision 1.01 - File Modified by Raju Machupalli (October 31, 2021)
-- Revision 2.01 - File Modified by Shyama Gandhi (November 2, 2021)
-- Revision 3.01 - File Modified by Antonio Andara (October 31, 2023)
-- Additional Comments:
--
----------------------------------------------------------------------------------
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
ENTITY cpu_core_tb IS
END cpu_core_tb;
ARCHITECTURE behavior OF cpu_core_tb IS
SIGNAL clock : STD_LOGIC := '0';
SIGNAL reset : STD_LOGIC := '0';
SIGNAL user_input : STD_LOGIC_VECTOR(7 DOWNTO 0);
SIGNAL OPCODE_output : STD_LOGIC_VECTOR(3 DOWNTO 0);
SIGNAL PC_output : STD_LOGIC_VECTOR(4 DOWNTO 0);
SIGNAL CPU_output : STD_LOGIC_VECTOR(7 DOWNTO 0);
SIGNAL enter : STD_LOGIC;
SIGNAL done : STD_LOGIC;
-- Clock period definitions
CONSTANT clock_period : TIME := 8 ns;
BEGIN
--*********************************
-- Instantiate the Unit Under Test (UUT)
UUT : ENTITY WORK.cpu_core(Structural)
port map(
clock => clock
, reset => reset
, enter => enter
, user_input => user_input
, CPU_output => CPU_output
, PC_output => PC_output
, OPCODE_output => OPCODE_output
, done => done
);
-----------------------------------
-- Clock process definition
clock_process : PROCESS
BEGIN
clock <= '0';
WAIT FOR clock_period/2;
clock <= '1';
WAIT FOR clock_period/2;
END PROCESS;
-- Stimulus process
stim_proc : PROCESS
BEGIN
reset <= '1';
WAIT FOR 10 ns;
reset <= '0';
--*********************************
-- provide the required input stimulus here for the design under test
user_input <= "10101010";
enter <= '1';
-----------------------------------
WAIT;
END PROCESS;
END behavior;
|
#include <bits/stdc++.h>
using namespace std;
#define M 3
struct Node
{
Node* parent;
int mat[M][M];
int a, b;
int cost;
int level;
};
int printMatrix(int mat[M][M])
{
for (int i = 0; i < M; i++)
{
for (int j = 0; j < M; j++)
printf("%d ", mat[i][j]);
printf("\n");
}
}
Node* newNode(int mat[M][M], int a, int b, int newA,
int newB, int level, Node* parent)
{
Node* node = new Node;
node->parent = parent;
memcpy(node->mat, mat, sizeof node->mat);
swap(node->mat[a][b], node->mat[newA][newB]);
node->cost = INT_MAX;
node->level = level;
node->a = newA;
node->b = newB;
return node;
}
int row[] = { 1, 0, -1, 0 };
int col[] = { 0, -1, 0, 1 };
int calculateCost(int initial[M][M], int final[M][M])
{
int count = 0;
for (int i = 0; i < M; i++)
for (int j = 0; j < M; j++)
if (initial[i][j] && initial[i][j] != final[i][j])
count++;
return count;
}
int isSafe(int a, int b)
{
return (a >= 0 && a < M && b >= 0 && b < M);
}
void printPath(Node* root)
{
if (root == NULL)
return;
printPath(root->parent);
printMatrix(root->mat);
printf("\n");
}
struct comp
{
bool operator()(const Node* lhs, const Node* rhs) const
{
return (lhs->cost + lhs->level) > (rhs->cost + rhs->level);
}
};
void solve(int initial[M][M], int a, int b,
int final[M][M])
{
priority_queue<Node*, std::vector<Node*>, comp> pq;
Node* root = newNode(initial, a, b, a, b, 0, NULL);
root->cost = calculateCost(initial, final);
pq.push(root);
while (!pq.empty())
{
Node* min = pq.top();
pq.pop();
if (min->cost == 0)
{
printPath(min);
return;
}
for (int i = 0; i < 4; i++)
{
if (isSafe(min->a + row[i], min->b + col[i]))
{
Node* child = newNode(min->mat, min->a,
min->b, min->a + row[i],
min->b + col[i],
min->level + 1, min);
child->cost = calculateCost(child->mat, final);
pq.push(child);
}
}
}
}
int main()
{
int initial[M][M] =
{
{1, 2, 3},
{5, 6, 0},
{7, 8, 4}
};
int final[M][M] =
{
{1, 2, 3},
{5, 8, 6},
{0, 7, 4}
};
int a = 1, b = 2;
solve(initial, a, b, final);
return 0;
}
|
import { Icon } from "@iconify/react";
import style from "../../styles/css/SecurityPwInput.module.css";
import { useEffect, useState } from "react";
import { QuestionModal } from "../common/AlertModals";
const SecurityPwInput = ({ setIsInput, setAccountPw }: any) => {
const closeModal = () => {
setIsInput(false);
};
const keyList = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
const [shuffledKeyList, setSuffledKeyList] = useState<string[]>(keyList);
useEffect(() => {
// 버튼 리스트 랜덤조합
function shuffleArray(array: string[]) {
for (let i = array.length - 1; i > 0; i--) {
// 0부터 i 사이의 무작위 인덱스를 선택합니다.
const j = Math.floor(Math.random() * (i + 1));
// 배열의 요소 i와 j를 교환합니다.
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const shuffle = shuffleArray([...keyList]);
setSuffledKeyList(shuffle);
}, []);
const [display, setDisplay] = useState<string[]>([]);
const inputKey = (event: any) => {
const { id } = event.target;
setDisplay((prev: any) => {
if (prev.length !== 4) {
return [...prev, id];
} else return prev;
});
};
const deleteInput = () => {
if (display.length) {
setDisplay((prev) => prev.slice(0, -1));
}
};
const confirmation = () => {
if (display.length === 4) {
setAccountPw(display.join(""));
setIsInput(false);
} else {
QuestionModal({
title: "비밀번호",
text: "비밀번호 4자리를 입력해주세요!",
});
}
};
return (
<div className={style.wrapper}>
<button className={style.xButton} onClick={closeModal}>
X
</button>
<div className={style.inputBox}>
<div className={style.box} id="1">
{display[0] && "*"}
</div>
<div className={style.box} id="2">
{display[1] && "*"}
</div>
<div className={style.box} id="3">
{display[2] && "*"}
</div>
<div className={style.box} id="4">
{display[3] && "*"}
</div>
</div>
<div className={style.keypad}>
{shuffledKeyList.map((key, index) => (
<div key={index} id={key} className={style.key} onClick={inputKey}>
{key}
</div>
))}
<div className={style.k1} onClick={confirmation}>
입력
</div>
<div className={style.k2} id="backSpace" onClick={deleteInput}>
<Icon icon={"bi-backspace-fill"} id="backSpace" />
</div>
</div>
</div>
);
};
export default SecurityPwInput;
|
package com.ccooy.gameframe.framework.impl
class Pool<T>(private val factory: PoolObjectFactory<T>, private val maxSize: Int) {
private val freeObjects: MutableList<T>
interface PoolObjectFactory<T> {
fun createObject(): T
}
init {
this.freeObjects = ArrayList(maxSize)
}
fun newObject(): T? {
return if (freeObjects.isEmpty())
factory.createObject()
else
freeObjects.removeAt(freeObjects.size - 1)
}
fun free(mObject: T) {
if (freeObjects.size < maxSize)
freeObjects.add(mObject)
}
}
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="css/bootstrap.css">
</head>
<body>
<!-- NavBar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand text-warning" href="#">Morito</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Html</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Css</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Js</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Php</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Python</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Tracks
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">FrontEnd</a>
<a class="dropdown-item" href="#">BackEnd</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Full Stack Developer</a>
</div>
</li>
</ul>
</div>
</nav>
<!-- First Section -->
<div class="container m-1">
<div class="row">
<div class="col-lg-8">
<div class="jumbotron bg-light">
<h1 class="display-4 text-warning">Morito</h1>
<p class="lead">This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p>
<hr class="my-4">
<p>It uses utility classes for typography and spacing to space content out within the larger container.</p>
<p class="lead">
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-warning my-2 my-sm-0" type="submit">Search</button>
</form>
</p>
</div>
</div>
<div class="col-lg-4">
<div class="list-group">
<a data-toggle="collapse" href="#x" class="list-group-item list-group-item-action bg-warning">
Category
</a>
<div class="collapse-show" id="x">
<a href="#" class="list-group-item list-group-item-action">html</a>
<a href="#" class="list-group-item list-group-item-action">css</a>
<a href="#" class="list-group-item list-group-item-action">js</a>
<a href="#" class="list-group-item list-group-item-action">php</a>
<a href="#" class="list-group-item list-group-item-action">python</a>
</div>
</div>
</div>
</div>
</div>
<!-- Cards -->
<div class="container">
<div class="text-center m-5">
<h3 class="text-danger">My City ❤️🥰</h3>
</div>
<div class="row">
<div class="col-lg-4 p-1 col-md-6 col-12">
<div class="card">
<img class="card-img-top" src="image/2.webp" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-warning">Go somewhere</a>
</div>
</div>
</div>
<div class="col-lg-4 p-1 col-md-6 col-12">
<div class="card">
<img class="card-img-top" src="image/2.webp" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-warning">Go somewhere</a>
</div>
</div>
</div>
<div class="col-lg-4 p-1 col-md-6 col-12">
<div class="card">
<img class="card-img-top" src="image/2.webp" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-warning">Go somewhere</a>
</div>
</div>
</div>
<div class="col-lg-4 p-1 col-md-6 col-12">
<div class="card">
<img class="card-img-top" src="image/2.webp" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-warning">Go somewhere</a>
</div>
</div>
</div>
<div class="col-lg-4 p-1 col-md-6 col-12">
<div class="card">
<img class="card-img-top" src="image/2.webp" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-warning">Go somewhere</a>
</div>
</div>
</div>
<div class="col-lg-4 p-1 col-md-6 col-12">
<div class="card">
<img class="card-img-top" src="image/2.webp" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
<a href="#" class="btn btn-warning">Go somewhere</a>
</div>
</div>
</div>
</div>
</div>
<!-- Slide -->
<div class="container">
<div class="text-center m-5">
<h3 class="text-danger">My Second Country ❤️🥰</h3>
</div>
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
<li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="1"></li>
<li data-target="#carouselExampleIndicators" data-slide-to="2"></li>
</ol>
<div class="carousel-inner">
<div class="carousel-item active">
<img style="border-radius: 10px;" class="d-block w-100" src="image/4.webp" alt="First slide">
</div>
<div class="carousel-item">
<img style="border-radius: 10px;" class="d-block w-100" src="image/4.webp" alt="Second slide">
</div>
<div class="carousel-item">
<img style="border-radius: 10px;" class="d-block w-100" src="image/4.webp" alt="Third slide">
</div>
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
<!-- Contact -->
<div class="container">
<div class="text-center m-5">
<h3 class="text-danger">Welcome To DUBAI 🤩</h3>
</div>
<div class="card mb-3">
<div class="row no-gutters">
<div class="col">
<div class="card-body">
<h5 class="card-title">اهلا بكم</h5>
<p class="card-text">This is a wider card text below longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
<form>
<div class="form-group">
<label for="exampleInputEmail1">البريد الالكتروني</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">اترك رساله لدبي</label>
<textarea class="form-control"></textarea>
</div>
<div class="form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-warning">Send</button>
</form>
</div>
</div>
<div class="col">
<img src="image/8.jpg" class="card-img" alt="...">
</div>
</div>
</div>
</div>
<!-- footer -->
<footer class="bg-light text-center bg-dark text-light text-lg-start" style="border-top: 10px solid #ffc107;">
<!-- Grid container -->
<div class="container p-4">
<!--Grid row-->
<div class="row">
<!--Grid column-->
<div class="col-lg-6 col-md-12 mb-4 mb-md-0">
<h5 class="text-uppercase text-warning">Morito</h5>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Iste atque ea quis
molestias. Fugiat pariatur maxime quis culpa corporis vitae repudiandae
aliquam voluptatem veniam, est atque cumque eum delectus sint!
</p>
</div>
<!--Grid column-->
<!--Grid column-->
<div class="col-lg-6 col-md-12 mb-4 mb-md-0">
<h5 class="text-uppercase text-warning">Morito</h5>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Iste atque ea quis
molestias. Fugiat pariatur maxime quis culpa corporis vitae repudiandae
aliquam voluptatem veniam, est atque cumque eum delectus sint!
</p>
</div>
<!--Grid column-->
</div>
<!--Grid row-->
</div>
<!-- Grid container -->
<!-- Copyright -->
<div class="text-center p-3" style="background-color: rgba(0, 0, 0, 0.2);">
© 2020 Copyright Morito.
</div>
<!-- Copyright -->
</footer>
<script src="js/popper.min.js"></script>
<script src="js/jquery-3.6.0.min.js"></script>
<script src="js/bootstrap.js"></script>
</body>
</html>
|
import {
CommandInteraction,
InteractionReplyOptions,
MessageActionRow,
MessageButton,
} from "discord.js";
import { oauth, patreon } from "patreon";
import { readFileSync, writeFileSync } from "fs";
import { app } from "../webserver/express";
import config from "../../../config/config.json";
import url from "url";
var redirectURL = config.redirectUrl;
export const getPatreonData = async (token: string, url = "/current_user") => {
const apiClient = patreon(token);
return apiClient(url);
};
const funcBuffer: {
[key: string]: () => Promise<void>;
} = {};
app.get("/patreonlogin", (req, res) => {
const { code, state } = req.query;
if (!code) {
return res.send("error loading patreon bot");
}
let token;
return oauth(config.CLIENT_ID, config.CLIENT_SECRET)
.getTokens(code, "https://" + redirectURL + "/patreonlogin")
.then(({ access_token }) => {
token = access_token; // eslint-disable-line camelcase
const apiClient = patreon(token);
return Promise.all([apiClient("/current_user")]);
})
.then(async ([{ store, rawJson }]) => {
const { id } = rawJson.data;
const patreonInfo = JSON.parse(
readFileSync("./patreonConfig.json").toString()
);
patreonInfo[state as any] = {
token,
};
writeFileSync("./patreonConfig.json", JSON.stringify(patreonInfo));
console.log(
`Saved user ${store.find("user", id).full_name} to the funcBuffer`
);
await funcBuffer[state as any]();
funcBuffer[state as any] = null;
return res.send(
"you are logged in, thanks!, you can close this tab, and return to discord"
);
})
.catch((err) => {
console.log(err);
return res.send("error loading patreon bot");
});
});
export const generateLoginButton = async (interaction: CommandInteraction) => {
const loginUrl = url.format({
protocol: "https",
host: "patreon.com",
pathname: "/oauth2/authorize",
query: {
response_type: "code",
client_id: config.CLIENT_ID,
redirect_uri: "https://" + redirectURL + "/patreonlogin",
state: interaction.user.id,
},
});
funcBuffer[interaction.user.id] = async () => {
await interaction.editReply(`You are now logged in!`);
};
const row = new MessageActionRow().addComponents(
new MessageButton().setLabel("Login").setURL(loginUrl).setStyle("LINK")
);
await interaction.reply({
ephemeral: true,
content: `Please login to patreon by clicking the button below.`,
components: [row],
});
};
export const getPatreonEmails = async (
token: string,
campaign: string,
award?: string,
count = "10",
page = ""
) => {
const url =
"/campaigns/" +
campaign +
"/pledges?page%5Bcount%5D=" +
count +
"&sort=created";
const data = await getPatreonData(token, url + page);
return [
...data.rawJson.data
.map(
(d) =>
data.rawJson.included.find(
(pledge) =>
d.relationships.patron.data.id == pledge.id &&
(!award || award == d.relationships.reward?.data.id)
)?.attributes.email
)
.filter((d) => d),
...(data.rawJson.links.next
? await getPatreonEmails(
token,
count,
data.rawJson.links.next.split(url)[1]
)
: []),
];
};
export const getPatreonDiscordIDs = async (
token: string,
campaign: string,
count = "10",
page = ""
) => {
const url =
"/campaigns/" +
campaign +
"/pledges?page%5Bcount%5D=" +
count +
"&sort=created";
const data = await getPatreonData(token, url + page);
return [
...data.rawJson.data
.map(
(d) =>
data.rawJson.included.find(
(pledge) => d.relationships.patron.data.id == pledge.id
)?.attributes
)
.filter((d) => d),
...(data.rawJson.links.next
? await getPatreonDiscordIDs(
token,
count,
data.rawJson.links.next.split(url)[1]
)
: []),
];
};
|
import java.util.Scanner;
public class CaesarCipher {
// Method to encrypt plaintext using Caesar Cipher
public static String encrypt(String plaintext, int shift) {
StringBuilder encryptedText = new StringBuilder();
// Iterate through each character in the plaintext
for (char c : plaintext.toCharArray()) {
if (Character.isLetter(c)) {
char base = Character.isLowerCase(c) ? 'a' : 'A';
// Apply the Caesar Cipher shift to each letter
char encryptedChar = (char) (base + (c - base + shift) % 26);
encryptedText.append(encryptedChar);
} else {
// Keep non-letter characters unchanged
encryptedText.append(c);
}
}
// Convert StringBuilder to String and return the encrypted text
return encryptedText.toString();
}
// Method to decrypt Caesar Cipher encrypted text
public static String decrypt(String encryptedText, int shift) {
// Decrypting is essentially encrypting with the opposite (negative) shift
return encrypt(encryptedText, 26 - shift);
}
// Main method to take user input and demonstrate Caesar Cipher
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get user input for plaintext
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine();
// Get user input for the shift value (key)
System.out.print("Enter the shift value (key): ");
int shift = scanner.nextInt();
// Encrypt the plaintext using the provided shift
String encryptedText = encrypt(plaintext, shift);
System.out.println("Encrypted text: " + encryptedText);
// Decrypt the encrypted text using the same shift
String decryptedText = decrypt(encryptedText, shift);
System.out.println("Decrypted text: " + decryptedText);
// Close the Scanner to prevent resource leaks
scanner.close();
}
}
|
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_location/flutter_location.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await FlutterLocation.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: ListView(
children: <Widget>[
Center(
child: Text('Running on: $_platformVersion\n'),
),
FlatButton(
onPressed: () async {
LocationData location;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
location = await FlutterLocation.getLocation();
} on PlatformException {
print('Failed to get platform version.');
}
print(location.toString());
setState(() {
_platformVersion = location.toString();
});
},
child: Text('获取经纬度'),
)
],
)),
);
}
}
|
<template>
<div>
<h2>New Post</h2>
<form @submit.prevent="onSubmit">
<textarea cols="30" rows="10" :value="inputTxt"
@input="handleInput" :disabled="disabled">
</textarea>
<br />
<input type="submit" :value="btnTxt" :disabled="disabled" />
</form>
</div>
</template>
<script setup>
import { ref, computed } from "vue";
import { useRouter } from "vue-router"
import { usePostListStore } from '@/stores/usePostStore'
const store = usePostListStore()
const router = useRouter()
const isSaving = ref(false)
const inputTxt = ref('')
const emit = defineEmits(["input:post"])
const btnTxt = computed(() => isSaving.value ? 'Saving...' : 'Save')
const disabled = computed(() => isSaving.value)
const handleInput = (event) => {
const value = event.target.value
if (!value) return
emit("input:post", value)
inputTxt.value = value
}
const onSubmit = () => {
isSaving.value = true
const postObj = { text: inputTxt.value };
store.addPost(postObj).then(() => {
isSaving.value = false;
inputTxt.value = '';
router.push('/posts');
});
}
</script>
<style scoped>
input {
margin: 1rem 0;
}
</style>
|
package cz.cvut.fit.niadp.mvcgame;
import java.util.List;
import cz.cvut.fit.niadp.config.MvcGameConfig;
import cz.cvut.fit.niadp.mvcgame.bridge.IGameGraphics;
import cz.cvut.fit.niadp.mvcgame.controller.GameController;
import cz.cvut.fit.niadp.mvcgame.memento.CareTaker;
import cz.cvut.fit.niadp.mvcgame.model.GameModel;
import cz.cvut.fit.niadp.mvcgame.model.IGameModel;
import cz.cvut.fit.niadp.mvcgame.proxy.GameModelProxy;
import cz.cvut.fit.niadp.mvcgame.view.GameInfoView;
import cz.cvut.fit.niadp.mvcgame.view.GameView;
public class MvcGame {
private IGameModel model;
private GameView view;
private GameController controller;
private GameInfoView gameInfoView;
public void init() {
this.model = new GameModelProxy(new GameModel());
this.view = new GameView(model);
this.gameInfoView = new GameInfoView(model);
this.controller = this.view.getController();
CareTaker.getInstance().setModel(this.model);
}
public void processPressedKeys(List<String> pressedKeysCodes) {
this.controller.processPressedKeys(pressedKeysCodes);
}
public void processUnpressedKeys(String code) {
this.controller.processUnpressedKeys(code);
}
public String getWindowTitle() {
return MvcGameConfig.GAME_TITLE;
}
public int getWindowWidth() {
return MvcGameConfig.MAX_X;
}
public int getWindowHeight() {
return MvcGameConfig.MAX_Y;
}
public void setGraphicsContext(IGameGraphics gameGraphics) {
this.view.setGraphicsContext(gameGraphics);
}
public void setInfoGraphicsContext(IGameGraphics gameGraphics) {
this.gameInfoView.setGraphicsContext(gameGraphics);
}
public void selectLevel(int level){
this.controller.selectedLevel(level);
}
}
|
package online.caltuli.consumer.api.abuseipdb;
import online.caltuli.consumer.api.abuseipdb.exception.ConfigurationLoadException;
import org.apache.http.client.fluent.Request;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.util.Properties;
import java.io.InputStream;
import java.util.function.Supplier;
public class AbuseIpDbClient {
private final static String PROPERTIES_FILE = "config.abuse-ip-db.properties";
private static Properties properties = new Properties();
private static volatile AbuseIpDbClient instance;
private String baseUrl;
private String apiKey;
private Supplier<InputStream> inputStreamSupplier; // make tests easier
private AbuseIpDbClient() throws ConfigurationLoadException {
this.inputStreamSupplier = () ->
AbuseIpDbClient.class.getClassLoader().getResourceAsStream(PROPERTIES_FILE);
loadProperties(this.inputStreamSupplier);
this.baseUrl = properties.getProperty("abuseipdb.api.url");
this.apiKey = properties.getProperty("abuseipdb.api.key");
}
private static void loadProperties(Supplier<InputStream> inputStreamSupplier) throws ConfigurationLoadException {
Logger logger = LogManager.getLogger(AbuseIpDbClient.class);
try (InputStream inputStream = inputStreamSupplier.get()) {
if (inputStream != null) {
properties.load(inputStream);
} else {
logger.info("Property file '" + PROPERTIES_FILE + "' not found in the classpath");
throw new ConfigurationLoadException("Property file '" + PROPERTIES_FILE + "' not found in the classpath");
}
} catch (IOException e) {
logger.info("Error loading properties file");
throw new ConfigurationLoadException("Error loading properties file");
}
// Afficher les propriétés chargées
/*
System.out.println("Properties loaded:");
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + "=" + value);
}
*/
}
public static AbuseIpDbClient getInstance() throws ConfigurationLoadException {
if (instance == null) {
instance = new AbuseIpDbClient();
}
return instance;
}
/*
send HTTP request :
GET /api/v2/check?ipAddress=[ip parameter value]&maxAgeInDays=90 HTTP/1.1
Host: api.abuseipdb.com
Key: [Authentication token from AbuseIpDb company]
Accept: application/json
return related HTTP response in JSON format
*/
protected String fetchIpDetailsAsJson(String ip) throws IOException {
String response =
Request.Get(
baseUrl
+ "?ipAddress="
+ ip
+ "&maxAgeInDays=90"
)
.addHeader("Key", apiKey)
.addHeader("Accept", "application/json")
.execute().returnContent().asString();
return response;
}
}
/*
{"data":{"ipAddress":"82.65.137.201","isPublic":true,"ipVersion":4,"isWhitelisted":null,"abuseConfidenceScore":0,"countryCode":"FR","usageType":"Fixed Line ISP","isp":"Free SAS","domain":"free.fr","hostnames":["82-65-137-201.subs.proxad.net"],"isTor":false,"totalReports":0,"numDistinctUsers":0,"lastReportedAt":null}}
*/
|
import play, { SpotifyAlbum, SpotifyPlaylist, SpotifyTrack } from 'play-dl';
import { sanitizeUrl } from '@/helpers/helpers';
import { StreamInfo } from '@/sources/source-stream';
import { PlayDlSourceStream } from '../play-dl-source';
import { IStrategy } from './strategy';
export class SpotifyTrackStrategy implements IStrategy {
constructor(private playDlSourceStream: PlayDlSourceStream) {}
async getStreamInfo(url: string): Promise<StreamInfo[]> {
const spotifyInfo = (await play.spotify(sanitizeUrl(url))) as SpotifyTrack;
const searched = (
await this.playDlSourceStream.search(
`${spotifyInfo.name} - ${spotifyInfo?.artists.shift()?.name}`,
{
limit: 1,
}
)
).shift();
return [
{
title: spotifyInfo.name,
url: searched.url,
source: {
url: spotifyInfo.url,
},
artist: spotifyInfo?.artists.shift()?.name ?? searched.artist,
thumbnail: {
url: spotifyInfo.thumbnail.url,
},
},
];
}
}
export class SpotifyPlaylistStrategy implements IStrategy {
async getStreamInfo(url: string): Promise<StreamInfo[]> {
const playlist = (await play.spotify(sanitizeUrl(url))) as SpotifyPlaylist;
const tracks = await playlist.all_tracks();
const spotifyTracks = tracks.map((track) => ({
title: track.name,
url: undefined,
artist: track?.artists.shift().name,
}));
return spotifyTracks;
}
}
export class SpotifyAlbumStrategy implements IStrategy {
async getStreamInfo(url: string): Promise<StreamInfo[]> {
const album = (await play.spotify(sanitizeUrl(url))) as SpotifyAlbum;
const tracks = await album.all_tracks();
const spotifyTracks = tracks.map((track) => ({
title: track.name,
url: undefined,
artist: track?.artists.shift().name,
}));
return spotifyTracks;
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import ItemFactory from 'components/CV/Item';
import ListTitle from 'components/CV/Block/ListTitle';
import styles from './cv__list_block.scss';
const ListBlock = ({ icon, title, items, color }) => (
<div className={styles.container}>
<ListTitle
icon={icon}
title={title}
color={color}
/>
<div>
{
items.map((item) => (
<ItemFactory
key={item.slug}
item={item}
color={color}
/>
))
}
</div>
</div>
);
ListBlock.propTypes = {
icon: PropTypes.string,
title: PropTypes.string,
color: PropTypes.string,
items: PropTypes.array
};
export default ListBlock;
|
package it.pagopa.selfcare.mscore.connector.email;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import it.pagopa.selfcare.mscore.api.FileStorageConnector;
import it.pagopa.selfcare.mscore.config.CoreConfig;
import it.pagopa.selfcare.mscore.exception.MsCoreException;
import it.pagopa.selfcare.mscore.model.onboarding.MailTemplate;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.*;
@ExtendWith(SpringExtension.class)
class EmailConnectorImplTest {
@InjectMocks
private EmailConnectorImpl emailConnector;
@Mock
private ObjectMapper mapper;
@Mock
private FileStorageConnector fileStorageConnector;
@Mock
private JavaMailSender javaMailSender;
@Mock
private CoreConfig coreConfig;
@Test
void testSendMail() throws IOException {
when(fileStorageConnector.getTemplateFile(any())).thenReturn("templateFile");
MailTemplate mailTemplate = new MailTemplate();
Path path = Files.createTempFile("contratto", ".pdf");
File pdf = new File(path.toUri());
String fileName = "text.pdf";
byte [] bytes = emailConnector.zipBytes(fileName, pdf);
assertNotNull(bytes);
mailTemplate.setBody("body");
mailTemplate.setSubject("subject");
when(mapper.readValue("templateFile", MailTemplate.class)).thenReturn(mailTemplate);
MimeMessage mimeMessage = mock(MimeMessage.class);
when(javaMailSender.createMimeMessage()).thenReturn(mimeMessage);
when(coreConfig.getSenderMail()).thenReturn("senderMail");
ArrayList<String> destinationMail = new ArrayList<>();
Assertions.assertDoesNotThrow(() -> emailConnector.sendMail("Template Name", destinationMail, pdf, "Product Name", new HashMap<>(), "foo.txt"));
}
@Test
void testSendMailWithoutAttachment() throws JsonProcessingException {
when(fileStorageConnector.getTemplateFile(any())).thenReturn("templateFile");
MailTemplate mailTemplate = new MailTemplate();
mailTemplate.setBody("body");
mailTemplate.setSubject("subject");
when(mapper.readValue("templateFile", MailTemplate.class)).thenReturn(mailTemplate);
MimeMessage mimeMessage = mock(MimeMessage.class);
when(javaMailSender.createMimeMessage()).thenReturn(mimeMessage);
when(coreConfig.getSenderMail()).thenReturn("senderMail");
ArrayList<String> destinationMail = new ArrayList<>();
Assertions.assertDoesNotThrow(() -> emailConnector.sendMail("Template Name", destinationMail, null, "Product Name", new HashMap<>(), null));
}
@Test
void testSendMail2() {
FileStorageConnector fileStorageConnector = mock(FileStorageConnector.class);
when(fileStorageConnector.getTemplateFile(any())).thenReturn("Template File");
ObjectMapper mapper = new ObjectMapper();
EmailConnectorImpl emailConnectorImpl = new EmailConnectorImpl(null, fileStorageConnector, mapper,
new CoreConfig());
ArrayList<String> destinationMail = new ArrayList<>();
File pdf = Paths.get(System.getProperty("java.io.tmpdir"), "test.txt").toFile();
assertThrows(MsCoreException.class, () -> emailConnectorImpl.sendMail("Template Name", destinationMail, pdf,
"Product Name", new HashMap<>(), "foo.txt"));
verify(fileStorageConnector).getTemplateFile(any());
}
}
|
import React from 'react';
import tw, { styled } from 'twin.macro';
import {
ToolbarBoldIcon,
ToolbarCodeIcon,
ToolbarItalicIcon,
ToolbarLinkIcon,
ToolbarPhotoIcon,
ToolbarQuoteIcon,
ToolbarStrikeThroughIcon,
} from '../../static/svg';
export type ToolbarMode =
| 'heading1'
| 'heading2'
| 'heading3'
| 'heading4'
| 'bold'
| 'italic'
| 'strike'
| 'quote'
| 'link'
| 'photo'
| 'code';
interface ToolbarProps {
onClick?: (mode: ToolbarMode) => void;
}
export default function Toolbar({ onClick }: ToolbarProps) {
return (
<ToolbarBlock>
<ToolbarItem onClick={() => onClick?.('heading1')}>
H<span>1</span>
</ToolbarItem>
<ToolbarItem onClick={() => onClick?.('heading2')}>
H<span>2</span>
</ToolbarItem>
<ToolbarItem onClick={() => onClick?.('heading3')}>
H<span>3</span>
</ToolbarItem>
<ToolbarItem onClick={() => onClick?.('heading4')}>
H<span>4</span>
</ToolbarItem>
<Seperator />
<ToolbarItem onClick={() => onClick?.('bold')}>
<ToolbarBoldIcon />
</ToolbarItem>
<ToolbarItem onClick={() => onClick?.('italic')}>
<ToolbarItalicIcon />
</ToolbarItem>
<ToolbarItem onClick={() => onClick?.('strike')}>
<ToolbarStrikeThroughIcon />
</ToolbarItem>
<Seperator />
<ToolbarItem onClick={() => onClick?.('quote')}>
<ToolbarQuoteIcon />
</ToolbarItem>
<ToolbarItem onClick={() => onClick?.('link')}>
<ToolbarLinkIcon />
</ToolbarItem>
<ToolbarItem onClick={() => onClick?.('photo')}>
<ToolbarPhotoIcon />
</ToolbarItem>
<ToolbarItem onClick={() => onClick?.('code')}>
<ToolbarCodeIcon />
</ToolbarItem>
</ToolbarBlock>
);
}
const ToolbarBlock = tw.div`flex flex-wrap items-center mb-4 px-6`;
const ToolbarItem = styled.button`
width: 3rem;
height: 3rem;
flex-shrink: 0;
font-family: 'Fira Mono', sans-serif;
font-weight: 500;
font-size: 1.125rem;
color: #8f8f8f;
&:hover {
color: #333;
background: #e8e8e8;
}
span {
font-size: 0.875rem;
}
svg {
width: 1.5rem;
height: 1.5rem;
margin: 0 auto;
}
`;
const Seperator = tw.div`w-[1px] h-5 mx-2 bg-gray-300`;
|
<?php
namespace backend\controllers;
use Yii;
use backend\models\ScholarisMecV2MallaArea;
use backend\models\ScholarisMecV2MallaAreaSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
/**
* ScholarisMecV2MallaAreaController implements the CRUD actions for ScholarisMecV2MallaArea model.
*/
class ScholarisMecV2MallaAreaController extends Controller
{
/**
* {@inheritdoc}
*/
public function behaviors() {
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'allow' => true,
'roles' => ['@'],
]
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
public function beforeAction($action) {
if (!parent::beforeAction($action)) {
return false;
}
if (Yii::$app->user->identity) {
//OBTENGO LA OPERACION ACTUAL
list($controlador, $action) = explode("/", Yii::$app->controller->route);
$operacion_actual = $controlador . "-" . $action;
//SI NO TIENE PERMISO EL USUARIO CON LA OPERACION ACTUAL
if(!Yii::$app->user->identity->tienePermiso($operacion_actual)){
echo $this->render('/site/error',[
'message' => "Acceso denegado. No puede ingresar a este sitio !!!",
'name' => 'Acceso denegado!!',
]);
}
} else {
header("Location:" . \yii\helpers\Url::to(['site/login']));
exit();
}
return true;
}
/**
* Lists all ScholarisMecV2MallaArea models.
* @return mixed
*/
public function actionIndex1()
{
$mallaId = $_GET['id'];
$model = ScholarisMecV2MallaArea::find()->where(['malla_id' => $mallaId])->orderBy('orden')->all();
$modelMalla = \backend\models\ScholarisMecV2Malla::findOne($mallaId);
return $this->render('index', [
'modelMalla' => $modelMalla,
'model' => $model
]);
}
/**
* Displays a single ScholarisMecV2MallaArea model.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
$model = $this->findModel($id);
$modelMalla = \backend\models\ScholarisMecV2Malla::findOne($model->malla_id);
return $this->render('view', [
'model' => $this->findModel($id),
'modelMalla' => $modelMalla,
]);
}
/**
* Creates a new ScholarisMecV2MallaArea model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$mallaId = $_GET['mallaId'];
$model = new ScholarisMecV2MallaArea();
$modelMalla = \backend\models\ScholarisMecV2Malla::findOne($mallaId);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index1', 'id' => $mallaId]);
}
return $this->render('create', [
'model' => $model,
'modelMalla' => $modelMalla,
]);
}
/**
* Updates an existing ScholarisMecV2MallaArea model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelMalla = \backend\models\ScholarisMecV2Malla::findOne($model->malla_id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
return $this->render('update', [
'model' => $model,
'modelMalla' => $modelMalla
]);
}
/**
* Deletes an existing ScholarisMecV2MallaArea model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
* @throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
$model = $this->findModel($id);
$this->findModel($id)->delete();
//
return $this->redirect(['index1','id' => $model->malla_id]);
}
/**
* Finds the ScholarisMecV2MallaArea model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return ScholarisMecV2MallaArea the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = ScholarisMecV2MallaArea::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
}
|
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Post extends Model
{
use HasFactory;
protected $table = self::TABLE;
public $timestamps = false;
const TABLE = 'posts';
const _ID = 'id';
const _TITLE = 'title';
const _SLUG = 'slug';
const _CONTENT = 'content';
const _CATEGORY_ID = 'category_id';
const _IS_PUBLISHED = 'is_published';
const _CREATED_AT = 'created_at';
const _UPDATED_AT = 'updated_at';
protected $fillable = [
self::_ID,
self::_TITLE,
self::_SLUG,
self::_CONTENT,
self::_CATEGORY_ID,
self::_IS_PUBLISHED,
self::_CREATED_AT,
self::_UPDATED_AT,
];
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}
|
import React, { useCallback, useRef } from 'react';
import { FormHandles } from '@unform/core';
import { Form } from '@unform/web';
import * as Yup from 'yup';
import { Link, useHistory } from 'react-router-dom';
import { FaUserPlus } from 'react-icons/fa';
import { TiArrowRightThick } from 'react-icons/ti';
import { FiMail, FiLock, FiUser } from 'react-icons/fi';
import api from '../../services/api';
import { useToast } from '../../hooks/toast';
import getValidationErros from '../../utils/getValidationErros';
import logo from '../../assets/logo.png';
import Input from '../../Components/Input';
import Button from '../../Components/Button';
import { Container, Content, AnimationContainer, Header } from './styles';
interface SignUpFormaData {
name: string;
email: string;
password: string;
}
const SignUp: React.FC = () => {
const formRef = useRef<FormHandles>(null);
const { addToast } = useToast();
const history = useHistory();
const handleSubmit = useCallback(
async (data: SignUpFormaData) => {
try {
formRef.current?.setErrors({});
const schema = Yup.object().shape({
name: Yup.string().required('Nome obrigatório'),
email: Yup.string()
.required('E-mail obrigatório')
.email('Digite um e-mail válido'),
password: Yup.string().min(6, 'No mínimo 6 dígitos'),
});
await schema.validate(data, {
abortEarly: false,
});
await api.post('/users', data);
addToast({
type: 'success',
title: 'Cadastro readlizado com sucesso!',
description: 'Você já pode fazer seu login no GoBarber.',
});
history.push('/');
} catch (err) {
if (err instanceof Yup.ValidationError) {
const errors = getValidationErros(err);
formRef.current?.setErrors(errors);
} else {
addToast({
type: 'error',
title: 'Erro no cadastro',
description:
'Ocorreu um erro ao fazer o cadastro, tente novamente.',
});
}
}
},
[addToast, history],
);
return (
<Container>
<Header>
<div>
<img src={logo} alt="GoBarber" />
<Link to="/">
Fazer login
<TiArrowRightThick />
</Link>
</div>
</Header>
<Content>
<AnimationContainer>
<Form ref={formRef} initialData={{}} onSubmit={handleSubmit}>
<h2>Faça seu cadastro</h2>
<Input name="name" icon={FiUser} placeholder="Nome" />
<Input name="email" icon={FiMail} placeholder="E-mail" />
<Input
name="password"
icon={FiLock}
type="password"
placeholder="Senha"
/>
<Button type="submit">
Cadastrar
<FaUserPlus />
</Button>
</Form>
</AnimationContainer>
</Content>
</Container>
);
};
export default SignUp;
|
#include <WiFi.h>
#include "time.h"
#include "sntp.h"
const char* ssid = "your_ssid";
const char* password = "your_passwd";
const char* ntpServer1 = "pool.ntp.org";
const char* ntpServer2 = "time.nist.gov";
const long gmtOffset_sec = 25200; // UTC+7
const int daylightOffset_sec = 0; // No daylight saving time in UTC+7
// Thai day names
const char* th_dayNames[] = {"อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัสบดี", "ศุกร์", "เสาร์"};
// Thai month names
const char* th_monthNames[] = {"มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"};
void printLocalTime()
{
struct tm timeinfo;
if(!getLocalTime(&timeinfo)){
Serial.println("No time available (yet)");
return;
}
// Adjust to Thai timezone
time_t thai_time;
thai_time = mktime(&timeinfo) + gmtOffset_sec; // Adjust for timezone
// Calculate Thai day of the week
int thai_day = (timeinfo.tm_wday) % 7; // Adjust for Thai day index
// Print Thai local time with year + 543
Serial.printf("วัน%s, %02d %s %04d %02d:%02d:%02d\n", th_dayNames[thai_day], timeinfo.tm_mday, th_monthNames[timeinfo.tm_mon], timeinfo.tm_year + 1900 + 543, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
}
// Callback function (get's called when time adjusts via NTP)
void timeavailable(struct timeval *t)
{
Serial.println("Got time adjustment from NTP!");
printLocalTime();
}
void setup()
{
Serial.begin(115200);
// Set notification call-back function
sntp_set_time_sync_notification_cb(timeavailable);
// Set NTP server mode to acquire via DHCP
sntp_servermode_dhcp(1);
// Configure NTP servers and time zone
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer1, ntpServer2);
// Connect to WiFi
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
}
void loop()
{
delay(5000);
printLocalTime(); // It will take some time to sync time :)
}
|
#Libro: Crear las clases Libro y Libreria. La clase Libro debe incluir
#atributos como titulo, autor y precio. La clase Libreria debe contener una
#lista de objetos Libro y métodos para calcular el precio total de todos
#los libros en la librería.
import abc
class Libreria(abc.ABC):
def __init__(self):
self.listadelibros =[]
@abc.abstractmethod
def agregas_libro(self, libro: None):
pass
@abc.abstractmethod
def calcular_precio_total(self):
pass
class GuardarLibreria(Libreria):
def agregar_libro(self, libro: None):
self.listadelibros.append(libro)
def calcular_precio_total(self):
precio_total = 0
for libro in self.listadelibros:
precio_total += libro.precio
return precio_total
class Libro():
def __init__(self, titulo: str, autor:str , precio: float):
self.titulo = titulo
self.autor = autor
self.precio = precio
libro1 = Libro("Rayuela","Julio Cortázar", 4999.99)
libro2 = Libro("Drácula","Bram Stoker", 7000)
guardar_libro = GuardarLibreria()
guardar_libro.agregar_libro(libro1)
guardar_libro.agregar_libro(libro2)
print(f"El precio total de los libros en la Libreria es de $: "+ str(guardar_libro.calcular_precio_total()))
#Code made by Emma Ledesma
|
/* eslint-disable jsx-a11y/anchor-is-valid */
import React from 'react';
import { NavLink } from 'react-router-dom';
import { IoHome, IoCashOutline } from "react-icons/io5";
import { useSelector } from 'react-redux';
import { BsBook } from 'react-icons/bs';
import { HiOutlineTranslate } from 'react-icons/hi';
import { AiOutlineTranslation } from 'react-icons/ai';
import { BiPackage, BiBookAlt, BiBook } from 'react-icons/bi';
import { GrReactjs, GrUserAdmin, GrWorkshop } from 'react-icons/gr';
import { TfiCommentsSmiley } from 'react-icons/tfi';
import { FaUsers } from 'react-icons/fa'
import { TbBooks } from 'react-icons/tb'
const Sidebar = () => {
const { user } = useSelector((state)=>state.auth);
return (
<div>
<aside className="menu pl-1 is-fixed">
<p className='menu-label'>a</p>
<p className='menu-label'>a</p>
<p className="menu-label">
General
</p>
<ul className="menu-list">
<li><NavLink to={"/dashboard"}>
<span className="icon-text">
<span className="icon">
<IoHome/>
</span>
<span>Dashboard</span>
</span>
</NavLink></li>
</ul>
<ul className="menu-list">
<li><NavLink to={"/pembayaran"}>
<span className="icon-text">
<span className="icon">
<IoCashOutline/>
</span>
<span>Pembayaran</span>
</span>
</NavLink></li>
</ul>
{user && user.role === "admin" && (
<div>
<p className="menu-label">
Users
</p>
<ul className="menu-list">
<li><NavLink to={"/users"}><span className="icon-text">
<span className="icon">
<GrUserAdmin/>
</span>
<span>Administrasi</span>
</span></NavLink></li>
<li><NavLink to={"/kenshusei"}><span className="icon-text">
<span className="icon">
<FaUsers/>
</span>
<span>Kenshusei</span>
</span></NavLink></li>
</ul>
</div>
)}
<p className="menu-label">
Pengenalan Huruf
</p>
<ul className="menu-list">
<li><NavLink to={"/hirakata"}>
<span className="icon-text">
<span className="icon">
<HiOutlineTranslate/>
</span>
<span>Hirakata</span>
</span>
</NavLink></li>
<li><NavLink to={"/kanjin5"}>
<span className="icon-text">
<span className="icon">
<AiOutlineTranslation/>
</span>
<span>Kanji N5</span>
</span>
</NavLink></li>
</ul>
<p className="menu-label">
Kosakata Dasar
</p>
<ul className="menu-list">
<li><NavLink to={"/katabenda"}>
<span className="icon-text">
<span className="icon">
<BiPackage/>
</span>
<span>Kata Benda</span>
</span>
</NavLink></li>
<li><NavLink to={"/katakerja"}>
<span className="icon-text">
<span className="icon">
<GrWorkshop/>
</span>
<span>Kata Kerja</span>
</span>
</NavLink></li>
<li><NavLink to={"/katasifat"}>
<span className="icon-text">
<span className="icon">
<TfiCommentsSmiley/>
</span>
<span>Kata Sifat</span>
</span>
</NavLink></li>
</ul>
<p className="menu-label">
Tata Bahasa Jepang
</p>
<ul className="menu-list">
<li><NavLink to={"/partikel"}>
<span className="icon-text">
<span className="icon">
<GrReactjs/>
</span>
<span>Partikel Dasar</span>
</span>
</NavLink></li>
<li><NavLink to={"/pengertian"}>
<span className="icon-text">
<span className="icon">
<BsBook/>
</span>
<span>Pola Kalimat</span>
</span>
</NavLink>
</li>
<li><NavLink to={"/suru"}>
<span className="icon-text">
<span className="icon">
<TbBooks/>
</span>
<span>Bentuk Kamus</span>
</span>
</NavLink></li>
<li><NavLink to={"/bentuk1"}>
<span className="icon-text">
<span className="icon">
<BiBookAlt/>
</span>
<span>Bentuk Sopan</span>
</span>
</NavLink></li>
<li><NavLink to={"/nai"}>
<span className="icon-text">
<span className="icon">
<BiBook/>
</span>
<span>Bentuk Negatif</span>
</span>
</NavLink></li>
</ul>
{/* <button className='button is-while'>Log Out</button> */}
</aside>
</div>
)
}
export default Sidebar
|
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django import forms
from .models import Profile
class ProfileCreationForm(UserCreationForm):
email = forms.EmailField(label="Email", max_length=255)
# phone = forms.CharField(label="Phone", max_length=14)
receive_email_alerts = forms.BooleanField(label="Receive email alerts", required=False)
error_messages = {
'password_mismatch': 'The provided passwords do not match',
}
class Meta:
model = Profile
fields = ("email", "password1", "password2", "receive_email_alerts") # , "phone"
error_messages = {
'email': {
'invalid': 'Invalid email address',
},
}
def clean_email(self):
email = self.cleaned_data["email"].lower()
try:
user = Profile.objects.get(email=email)
except Exception as e:
return email
raise forms.ValidationError(f"Email {email} already exists")
# def clean_phone(self):
# phone = self.cleaned_data["phone"]
# phone = ''.join(c for c in phone if c.isdigit()) # remove all extra characters (parenthesis, dashes, etc)
#
# if len(phone) != 10:
# raise forms.ValidationError(f"Phone number {phone} is invalid")
#
# try:
# user = Profile.objects.get(phone=phone)
# except Exception as e:
# return phone
# raise forms.ValidationError(f"Phone number {phone} already exists")
class ProfileChangeForm(UserChangeForm):
class Meta:
model = Profile
fields = ("email",) # , "phone"
|
import React, { useState } from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { FaPlusCircle } from "react-icons/fa";
import NewGroup from "../components/NewGroup.jsx";
const Groups = () => {
const navigate = useNavigate();
const location = useLocation();
const [isReload, setReload] = useState(false);
return (
<div>
<div className={`flex justify-between`}>
<div className="join join-horizontal">
<button
className={`btn btn-sm join-item normal-case ${
location.pathname.includes("my") ? "btn-disabled" : ""
}`}
onClick={(_) => navigate("my")}
>
My Groups
</button>
<button
className={`btn btn-sm join-item normal-case ${
location.pathname.includes("other") ? "btn-disabled" : ""
}`}
onClick={(_) => navigate("other")}
>
Other Groups
</button>
</div>
{location.pathname.includes("my") ? (
<button
className={`btn btn-sm normal-case -space-x-1`}
onClick={() => window.new_group.showModal()}
>
<FaPlusCircle />
<span>New</span>
</button>
) : null}
</div>
<Outlet context={{ isReload, setReload }} />
<dialog id="new_group" className="modal">
<NewGroup isReload={isReload} setReload={setReload} />
</dialog>
</div>
);
};
export default Groups;
|
//
// PetDetailViewController.swift
// PawPaw
//
// Created by Eric Ziegler on 11/1/17.
// Copyright © 2017 zigabytes. All rights reserved.
//
import UIKit
import MessageUI
import MapKit
import WebKit
// MARK: Constants
let PetDetailViewId = "PetDetailViewId"
class PetDetailViewController: BaseViewController {
// MARK: Properties
@IBOutlet var petTable: UITableView!
var pet: Pet!
var loadingPetDetails = false
var loadingView: LoadingView?
// MARK: Init
class func createControllerFor(pet: Pet) -> PetDetailViewController {
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let viewController: PetDetailViewController = storyboard.instantiateViewController(withIdentifier: PetDetailViewId) as! PetDetailViewController
viewController.pet = pet
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
petTable.rowHeight = UITableView.automaticDimension
petTable.estimatedRowHeight = 45.5
loadPetDescriptionFromSite()
}
private func loadPetDescriptionFromSite() {
if let petURL = URL(string: pet.petfinderURL) {
loadingView = LoadingView.displayIn(parentView: self.view, animated: true)
loadingPetDetails = true
let petfinderView = WKWebView(frame: CGRect(x: 0, y: 0, width: 0.5, height: 0.5))
petfinderView.navigationDelegate = self
self.view.addSubview(petfinderView)
petfinderView.load(URLRequest(url: petURL))
}
}
// MARK: Actions
@IBAction func backTapped(_ sender: AnyObject) {
self.navigationController?.popViewController(animated: true)
}
// MARK: Convenience Methods
func performCall() {
if self.pet.shelterPhone.count > 0 {
if let url = URL(string: "tel://\(self.pet.shelterPhone)"), UIApplication.shared.canOpenURL(url) {
let alert = UIAlertController(title: "Would you like to call about \(self.pet.shelterFormattedPhone)?", message: "This will call about \(self.pet.name)", preferredStyle: .alert)
let yesAction = UIAlertAction(title: "Yes", style: .default) { (action) in
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
alert.addAction(UIAlertAction(title: "No Thanks", style: .cancel, handler: nil))
alert.addAction(yesAction)
self.present(alert, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "Cannot Make Phone Call", message: "Either this device cannot make phone calls, or the phone number is invalid.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
func performEmail() {
if MFMailComposeViewController.canSendMail(), self.pet.shelterEmail.count > 0 {
let mailVC = MFMailComposeViewController()
mailVC.mailComposeDelegate = self
mailVC.setToRecipients([self.pet.shelterEmail])
mailVC.setSubject("Interest in a Pet: \(self.pet.name)")
self.present(mailVC, animated: true, completion: nil)
} else {
let alert = UIAlertController(title: "Cannot Send Mail", message: "This device is not able to send emails.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
}
extension PetDetailViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
if loadingPetDetails == false {
return 4
}
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 1
}
else if section == 1 {
return 2
}
else if section == 2 {
return 8
} else {
return 2
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: PetPhotoCellId, for: indexPath) as! PetPhotoCell
cell.layoutFor(pet: self.pet)
cell.delegate = self
return cell
}
else if indexPath.section == 1 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: PetContactHeaderCellId, for: indexPath) as! PetContactHeaderCell
cell.headerLabel.text = "My Story"
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: PetStoryCellId, for: indexPath) as! PetStoryCell
cell.layoutFor(story: self.pet.story)
return cell
}
}
else if indexPath.section == 2 {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: PetContactHeaderCellId, for: indexPath) as! PetContactHeaderCell
cell.headerLabel.text = "More About Me"
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: PetDetailCellId, for: indexPath) as! PetDetailCell
var value = "Unknown"
if indexPath.row == 1 {
if self.pet.breed.count > 0 {
value = self.pet.breed
}
cell.layoutFor(infoType: "Breed", value: value)
}
else if indexPath.row == 2 {
cell.layoutFor(infoType: "Gender", value: self.pet.gender.formattedValue)
}
else if indexPath.row == 3 {
cell.layoutFor(infoType: "Size", value: self.pet.size.formattedValue)
}
else if indexPath.row == 4 {
if self.pet.petType == .dog {
cell.layoutFor(infoType: "Age", value: self.pet.age.formattedValueForDog)
} else {
cell.layoutFor(infoType: "Age", value: self.pet.age.formattedValueForCat)
}
}
else if indexPath.row == 5 {
if self.pet.hasShots {
value = "Yes"
}
cell.layoutFor(infoType: "Has Shots", value: value)
}
else if indexPath.row == 6 {
cell.layoutFor(infoType: pet.alteredDisplayText, value: value)
} else {
if self.pet.isHouseTrained {
value = "Yes"
}
cell.layoutFor(infoType: "House Trained", value: value)
}
return cell
}
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: ShelterInfoCellId, for: indexPath) as! ShelterInfoCell
var contactInfo = "N/A"
if indexPath.row == 0 {
var formattedPhone = self.pet.shelterPhone
if let prettyFormattedPhone = self.pet.formatPhone(source: formattedPhone) {
formattedPhone = prettyFormattedPhone
}
contactInfo = formattedPhone
cell.layoutFor(heading: "Call about me", value: contactInfo)
} else {
if self.pet.shelterEmail.count > 0 {
contactInfo = self.pet.shelterEmail
}
cell.layoutFor(heading: "Email about me", value: contactInfo)
}
return cell
}
}
}
extension PetDetailViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 3 {
if indexPath.row == 0 {
self.performCall()
} else {
self.performEmail()
}
}
}
}
extension PetDetailViewController: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
self.dismiss(animated: true, completion: nil)
}
}
extension PetDetailViewController: PetPhotoCellDelegate {
func favoriteTappedFor(cell: PetPhotoCell, isFavorited: Bool) {
self.pet.isFavorited = isFavorited
let petList = PetList()
petList.loadFavorites()
if isFavorited {
petList.addFavorite(pet: pet)
} else {
petList.removeFavorite(pet: pet)
}
}
func photosTappedFor(cell: PetPhotoCell) {
let photoVC = PhotoViewController.createControllerFor(photos: self.pet.photoURLs, title: self.pet.name)
photoVC.modalPresentationStyle = .fullScreen
self.present(photoVC, animated: true, completion: nil)
}
}
extension PetDetailViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { webView.evaluateJavaScript("document.documentElement.outerHTML.toString()", completionHandler: { (html: Any?, error: Error?) in
self.loadingPetDetails = false
self.loadingView?.dismissWith(animation: false)
if let htmlString = html as? String {
let htmlComponents = htmlString.components(separatedBy: PetFinderDescriptionSeparator)
for curComponent in htmlComponents {
if let stringStart = curComponent.substring(start: 0, offsetBy: 9), stringStart == "\n " {
let storyComponents = curComponent.components(separatedBy: "</div>")
if let firstComponent = storyComponents.first {
if firstComponent.contains("<html") == false && firstComponent.contains("<label") == false {
self.pet.story = firstComponent.replacingOccurrences(of:stringStart, with: "").replacingOccurrences(of: "<br>\n", with: "\n")
break
}
}
}
}
}
self.petTable.reloadData()
})
}
}
|
import React, { useState } from "react";
import { useState as useTodoState } from "../context/state";
import { ActionTypes } from "../context/reduce";
const TodoApp = () => {
const { todos, dispatch } = useTodoState();
const [newTodo, setNewTodo] = useState("");
const [editTodoId, setEditTodoId] = useState(null);
const handleAddTodo = () => {
if (newTodo.trim() !== "") {
if (editTodoId !== null) {
// If editTodoId is not null, update the existing todo
dispatch({
type: ActionTypes.UPDATE_TODO,
payload: {
id: editTodoId,
text: newTodo,
completed: todos.find((todo) => todo.id === editTodoId).completed,
},
});
setEditTodoId(null);
} else {
// If editTodoId is null, add a new todo
dispatch({
type: ActionTypes.ADD_TODO,
payload: {
id: Date.now(),
text: newTodo,
completed: false,
},
});
}
setNewTodo("");
}
};
const handleToggleTodo = (id) => {
dispatch({
type: ActionTypes.UPDATE_TODO,
payload: {
id,
text: todos.find((todo) => todo.id === id).text,
completed: !todos.find((todo) => todo.id === id).completed,
},
});
};
const handleDeleteTodo = (id) => {
dispatch({
type: ActionTypes.DELETE_TODO,
payload: id,
});
};
const handleEditTodo = (id) => {
const todoToEdit = todos.find((todo) => todo.id === id);
setNewTodo(todoToEdit.text);
setEditTodoId(id);
};
return (
<div className="mainbox">
<div className="inputbox">
<h1>Todo App</h1>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
/>
<button onClick={handleAddTodo}>
{editTodoId !== null ? "Update Todo" : "Add Todo"}
</button>
</div>
<ul>
{todos.map((todo) => (
<li
key={todo.id}
style={{
textDecoration: todo.completed ? "line-through" : "none",
}}
>
<input
type="checkbox"
checked={todo.completed}
onChange={() => handleToggleTodo(todo.id)}
/>
{todo.text}
<button onClick={() => handleEditTodo(todo.id)}>Edit</button>
<button onClick={() => handleDeleteTodo(todo.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default TodoApp;
|
import React from 'react';
import PropTypes from 'prop-types';
import {Col, ControlLabel, FormControl, FormGroup, HelpBlock} from "react-bootstrap";
const FormElement = props => {
let componentClass,
formControlChildren;
if (props.type === 'textarea') {
componentClass = 'textarea';
}
if (props.type === 'select') {
componentClass = 'select';
// props.options.unshift({id: '', title: props.title + ' ...'});
formControlChildren = props.options.map(element => (
<option key={element.id} value={element.id}>{element.title}</option>
))
}
return (
<FormGroup
bsSize={props.size}
controlId={props.propertyName}
validationState={props.error && 'error'}
>
<Col componentClass={ControlLabel} sm={props.titleLength || 2}>
{props.title}
</Col>
<Col sm={props.inputLength || 10}>
<FormControl
className={props.className}
type={props.type}
componentClass={componentClass}
required={props.required}
placeholder={props.placeholder}
name={props.propertyName}
value={props.value}
onChange={props.changeHandler}
autoComplete={props.autoComplete}
>
{formControlChildren}
</FormControl>
{props.error &&
<HelpBlock>{props.error}</HelpBlock>
}
</Col>
</FormGroup>
);
};
FormElement.propTypes = {
propertyName: PropTypes.string.isRequired,
error: PropTypes.string,
size: PropTypes.string,
title: PropTypes.string,
type: PropTypes.string.isRequired,
required: PropTypes.bool,
placeholder: PropTypes.string,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.object]),
changeHandler: PropTypes.func.isRequired,
autoComplete: PropTypes.string,
options: PropTypes.arrayOf(PropTypes.object),
inputLength: PropTypes.number,
titleLength: PropTypes.number,
className: PropTypes.string
};
export default FormElement;
|
import { useEffect, useState } from "react";
import i18n from "i18next";
import { useTranslation } from "react-i18next";
import { Club, ClubManager } from "../../../../interfaces/common.interface";
import {
get_clubMember_count_from_ID,
get_teacher_name_from_ID,
get_teacher_name_thai_from_ID,
} from "../../../../functions/getFromID.function";
import Table_button from "../../../table/Table_button.component";
import Clubs_modal_update from "../modal/Clubs_modal_update.component";
import Clubs_modal_delete from "../modal/Clubs_modal_delete.component";
import {
Major_Name_Abbreviation,
Major_To_Background_Color,
} from "../../../../constants/Majors.constant";
import { table_content_style } from "../../../../constants/styles/tables.style";
// Contexts //
import { useContext_Clubs } from "../../../../context/Clubs.context";
import { useContext_Teachers } from "../../../../context/Teachers.context";
interface CurrentComponentProp {
club: Club;
index: number;
}
const Clubs_table_row = (props: CurrentComponentProp) => {
const { club, index } = props;
const {
clubMemberships,
fetchClubMemberships,
clubManagers,
fetchClubManagers,
} = useContext_Clubs();
const { teachers, fetchTeachers } = useContext_Teachers();
const { t } = useTranslation();
useEffect(() => {
if (clubMemberships.length === 0) {
fetchClubMemberships();
}
if (clubManagers.length === 0) {
fetchClubManagers();
}
if (teachers.length === 0) {
fetchTeachers();
}
}, []);
const [updateModalOpen, setUpdateModalOpen] = useState(false);
const onUpdateModalClose = () => {
setUpdateModalOpen(false);
};
const [deleteModalOpen, setDeleteModalOpen] = useState(false);
const onDeleteModalClose = () => {
setDeleteModalOpen(false);
};
const club_member_count = get_clubMember_count_from_ID(
club.club_ID,
clubMemberships
);
const clubTeachers = clubManagers.filter(
(clubManager: ClubManager) =>
clubManager.club_manager_club_ID === club.club_ID
);
return (
<tr className={index % 2 === 1 ? "bg-gray-200" : ""}>
{/* Club name */}
<td className={table_content_style}>{club.club_name}</td>
{/* Club major */}
<td className={`${table_content_style} | hidden md:table-cell`}>
{Major_Name_Abbreviation[club.club_major]}
</td>
{/* Club teachers */}
<td className={`${table_content_style} | hidden sm:table-cell`}>
{clubTeachers.length !== 0 ? (
clubTeachers.map(
(clubManager: ClubManager, index: number, array: number[]) => (
<h1 key={clubManager.club_manager_teacher_ID}>
{i18n.language === "th"
? get_teacher_name_thai_from_ID(
clubManager.club_manager_teacher_ID,
teachers
)
: get_teacher_name_from_ID(
clubManager.club_manager_teacher_ID,
teachers
)}
{index === array.length - 1 ? null : ", "}
</h1>
)
)
) : (
<h1 className="opacity-50">
{t("Clubs_table_content_teachers_noTeachers_message")}
</h1>
)}
</td>
{/* Club member count */}
<td
className={`${table_content_style} font-family-monospace | hidden md:table-cell`}>
{club_member_count}/{club.club_capacity}
</td>
{/* Buttons */}
<td className={table_content_style}>
<div className="flex gap-x-2">
{/* Update button */}
<Clubs_modal_update
club={club}
open={updateModalOpen}
onModalClose={onUpdateModalClose}
/>
<Table_button
icon="fa-solid fa-pencil"
color={Major_To_Background_Color[club.club_major]}
functionToRun={() => {
setUpdateModalOpen(true);
}}
/>
{/* Delete button */}
<Clubs_modal_delete
club={club}
club_member_count={club_member_count}
open={deleteModalOpen}
onModalClose={onDeleteModalClose}
/>
<Table_button
icon="fa-solid fa-trash-can"
color="bg-red-500"
functionToRun={() => {
setDeleteModalOpen(true);
}}
/>
</div>
</td>
</tr>
);
};
export default Clubs_table_row;
|
import {
IController,
IHttpRequest, IHttpResponse,
IAuthentication,
IValidation,
IDefineProperties
} from './sign-in-controller-protocols'
import {
SuperClassSignInAndSignUpController
} from '../super/super-class-controller'
import {
MissingParamError, InvalidParamError
} from './sign-in-controller-errors'
import {
ok, badRequest, unauthorized, serverError
} from './sign-in-controller-helpers'
import {
informationsOfSignInHttpRequestBodyFields
} from './sign-in-controller-utils'
/**
* @implements {Controller}
*
* @method `handle`
* validates the user entries for apply the sign in
*/
export class SignInController extends SuperClassSignInAndSignUpController implements IController {
/**
* @param {IValidation} validationComposite
* implementation of the validation
* @param {IAuthentication} authentication
* implementation of the Authenticator
*/
constructor (
private readonly validationComposite: IValidation,
private readonly authentication: IAuthentication
) {
super()
this.content = {
fields: informationsOfSignInHttpRequestBodyFields,
checkThisType: 'string',
validationTypes: ['required_fields', 'verify_types', 'validate_fields']
}
}
async handle (httpRequest: IHttpRequest): Promise<IHttpResponse> {
try {
let { personal, generateTypes, generatedType, validation } = await this.defineProperties(httpRequest)
do {
validation.content = await this.handleValidate({ type: generatedType.value })
if (validation.content.length > 0) {
if (generatedType.value === this.content.validationTypes[0]) {
validation.error = badRequest(undefined, undefined, new MissingParamError(validation.content.join(' ')), validation.content)
} else {
validation.error = badRequest(undefined, undefined, new InvalidParamError(validation.content.join(' ')), validation.content)
}
break
}
generatedType = generateTypes.next()
} while (!(generatedType.done))
if (validation.error) {
return validation.error
}
const authorization = await this.authentication.auth({
email: personal.email,
password: personal.password
})
if (!authorization) {
return unauthorized()
}
return ok({
accessToken: authorization
})
} catch (error) {
return serverError(error)
}
}
async defineProperties (httpRequest: IHttpRequest): Promise<IDefineProperties> {
const { body: { user: { informations: { personal } } } } = httpRequest
const generateTypes: Generator<string> = (this.generateTypes(this.content.validationTypes, 0))()
this.handleValidate = async (content: { type: string }) => {
return await this.validationComposite.validate({
type: content.type,
fields: this.content.fields,
body: personal,
checkThisType: this.content.checkThisType,
checkTheTypeOfThis: personal
})
}
return {
personal,
generateTypes: generateTypes,
generatedType: generateTypes.next(),
validation: {
content: [],
error: null
}
}
}
}
|
# Array(배열)
- [참고 자료(poiemaweb)](https://poiemaweb.com/js-array)
배열(array)은 1개의 변수에 여러 개의 값을 순차적으로 저장할 때 사용한다. 자바스크립트의 배열은 객체이며 유용한 내장 메소드를 포함하고 있다.
배열은 Array 생성자로 생성된 Array 타입의 객체이며 프로토타입 객체는 Array.prototype이다.
0개 이상의 값을 쉼표로 구분하여 대괄호([])로 묶는다. 첫번째 값은 인덱스 ‘0’으로 읽을 수 있다. 존재하지 않는 요소에 접근하면 undefined를 반환한다.
배열 리터럴은 객체 리터럴과 달리 프로퍼티명이 없고 각 요소의 값만이 존재한다. 객체는 프로퍼티 값에 접근하기 위해 대괄호 표기법 또는 마침표 표기법을 사용하며 프로퍼티명을 키로 사용한다. 배열은 요소에 접근하기 위해 대괄호 표기법만을 사용하며 대괄호 내에 접근하고자 하는 요소의 인덱스를 넣어준다. 인덱스는 0부터 시작한다.
두 객체의 근본적 차이는 배열 리터럴 arr의 프로토타입 객체는 Array.prototype이지만 객체 리터럴 obj의 프로토타입 객체는 Object.prototype이라는 것이다.
## 배열 요소의 추가와 삭제
- 배열 요소의 추가
객체가 동적으로 프로퍼티를 추가할 수 있는 것처럼 배열도 동적으로 요소를 추가할 수 있다. 이때 순서에 맞게 값을 할당할 필요는 없고 인덱스를 사용하여 필요한 위치에 값을 할당한다. 배열의 길이(length)는 마지막 인덱스를 기준으로 산정된다.
값이 할당되지 않은 인덱스 위치의 요소는 생성되지 않는다는 것에 주의하자. 단, 존재하지 않는 요소를 참조하면 undefined가 반환된다.
```js
arr[1] = 1;
arr[3] = 3;
```
- 배열 요소의 삭제
배열은 객체이기 때문에 배열의 요소를 삭제하기 위해 delete 연산자를 사용할 수 있다. 이때 length에는 변함이 없다. 해당 요소를 완전히 삭제하여 length에도 반영되게 하기 위해서는 Array.prototype.splice 메소드를 사용한다.
```js
// 요소의 값만 삭제된다
delete arr[2]; // (4) ["zero", "one", empty, "three"]
// 요소 값만이 아니라 요소를 완전히 삭제한다
// splice(시작 인덱스, 삭제할 요소수)
arr.splice(2, 1); // (3) ["zero", "one", "three"]
```
- 배열의 순회
객체의 프로퍼티를 순회할 때 for…in 문을 사용한다. 배열 역시 객체이므로 for…in 문을 사용할 수 있다. 그러나 배열은 객체이기 때문에 프로퍼티를 가질 수 있다. for…in 문을 사용하면 배열 요소뿐만 아니라 불필요한 프로퍼티까지 출력될 수 있고 요소들의 순서를 보장하지 않으므로 배열을 순회하는데 적합하지 않다.
따라서 배열의 순회에는 forEach 메소드, for 문, for…of 문을 사용하는 것이 좋다.
```js
for (const key in arr) {
console.log("key: " + key, "value: " + arr[key]);
}
arr.forEach((item, index) => console.log(index, item));
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]);
}
for (const item of arr) {
console.log(item);
}
```
<br/><br/>
---
<br/><br/>
## Array Property
- Array.length
<br/><br/>
---
<br/><br/>
## Array Method
- Array.isArray(arg: any): boolean (ES5)
- Array.from (ES6)
- Array.of (ES6)
- Array.prototype.indexOf(searchElement: T, fromIndex?: number): number (ES5)
- Array.prototype.concat(`…items: Array<T[] | T>`): T[] (ES3)
- Array.prototype.join(`separator?: string`): string (ES1)
- Array.prototype.push(`…items: T[]`): number (ES3)
- Array.prototype.pop(): T | undefined (ES3)
- Array.prototype.reverse(): this (ES1)
- Array.prototype.shift(): T | undefined (ES3)
- Array.prototype.slice(start=0, end=this.length): T[] (ES3)
- Array.prototype.splice(start: number, deleteCount=this.length-start, …items: T[]): T[] (ES3)
<br/><br/>
---
<br/><br/>
## sparse array
자바스크립트의 배열은 지금까지 살펴본 일반적인 의미의 배열과 다르다. 즉, 배열의 요소를 위한 각각의 메모리 공간은 동일한 크기를 갖지 않아도 되며 연속적으로 이어져 있지 않을 수도 있다. 배열의 요소가 연속적으로 이어져 있지 않는 배열을 희소 배열(sparse array)이라 한다.
이처럼 자바스크립트의 배열은 엄밀히 말해 일반적 의미의 배열이 아니다. 자바스크립트의 배열은 일반적인 배열의 동작을 흉내낸 특수한 객체이다.
```js
console.log(Object.getOwnPropertyDescriptors([1, 2, 3]));
/*
{
'0': { value: 1, writable: true, enumerable: true, configurable: true },
'1': { value: 2, writable: true, enumerable: true, configurable: true },
'2': { value: 3, writable: true, enumerable: true, configurable: true },
length: { value: 3, writable: true, enumerable: false, configurable: false }
}
인덱스를 프로퍼티 키로 가지며 length 프로퍼티를 갖는 특수한 객체이다.
자바스크립트 배열의 요소는 사실 프로퍼티 값이다. 자바스크립트에서 사용할 수 있는 모든 값은 객체의 프로퍼티 값이 될 수 있으므로 어떤 타입의 값이라도 배열의 요소가 될 수 있다.
*/
const arr = ["string", 10, true, null, undefined, NaN, Infinity, [], {}, function () {}];
```
- 자바스크립트 배열은 인덱스로 배열 요소에 접근하는 경우에는 일반적인 배열보다 느리지만 특정 요소를 탐색하거나 요소를 삽입 또는 삭제하는 경우에는 일반적인 배열보다 빠르다. 자바스크립트 배열은 인덱스로 접근하는 경우의 성능 대신 특정 요소를 탐색하거나 배열 요소를 삽입 또는 삭제하는 경우의 성능을 선택한 것이다.
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>手写bind</title>
</head>
<body>
<script>
Function.prototype.myBind = function (context) {
if (typeof this != "function") {
throw TypeError("must be Function")
}
let args = [...arguments].slice(1), fn = this;
return function () {
fn.apply(
this instanceof fn ? this : context,
args.concat(...arguments)
)
}
}
var value = 1;
var obj = {
value: 100,
};
function Person(name, age) {
this.name = name;
this.age = age;
console.log(this.value); // undefined
console.log(name); // jack
console.log(age); // 35
}
var bindPerson = Person.myBind(obj, "jack");
var bp = new bindPerson(35);
</script>
</body>
</html>
|
import styled from "styled-components";
import { space } from "../../styles/space";
import { Image, ImageSizeType } from "../Image";
import heartPng from "../../images/heart.png";
const Layout = styled.div`
display: flex;
> :not(:first-child) {
margin-left: ${space(2)};
}
`;
interface PropsType {
health: number;
}
export const Health = ({ health }: PropsType) => (
<Layout>
{Array(health)
.fill(null)
.map((_, index) => (
<Image
src={heartPng}
alt={`heart ${index + 1}`}
key={index}
size={ImageSizeType.Small}
/>
))}
</Layout>
);
|
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { goToHomePage } from "../../routes/coordinator";
import useUnprotectedPage from "../../hooks/useUnprotectedPage";
import { loginUser } from "../../services/user";
import useForm from "../../hooks/useForm";
import { CircularProgress, InputAdornment, TextField } from "@mui/material";
import { InputsContainer, LockStyled, AccountCircleStyled } from "./styled";
import { Button } from "@material-ui/core";
const LoginForm = (props) => {
useUnprotectedPage();
const [form, onChange, clear] = useForm({ email: "", password: "" });
const [isLoading, setIsLoading] = useState(false);
const { setRightButtonText } = props;
let navigate = useNavigate();
const onSubmitForm = (e) => {
e.preventDefault();
loginUser(form, clear, navigate, setIsLoading, setRightButtonText);
};
return (
<div>
<InputsContainer>
<form onSubmit={onSubmitForm}>
<TextField
InputLabelProps={{
style: { color: "#a89a3b" },
}}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<AccountCircleStyled />
</InputAdornment>
),
style: { color: "#a89a3b" },
}}
name={"email"}
value={form.email}
onChange={onChange}
label={"Email"}
variant={"outlined"}
fullWidth
margin="normal"
required
type={"email"}
/>
<TextField
InputLabelProps={{
style: { color: "#a89a3b" },
}}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<LockStyled />
</InputAdornment>
),
style: { marginBottom: 18, color: "#a89a3b" },
}}
name={"password"}
value={form.password}
onChange={onChange}
label={"Senha"}
variant={"outlined"}
fullWidth
margin="normal"
required
type={"password"}
/>
<Button type="submit" fullWidth color="primary" variant="contained">
{isLoading ? (
<CircularProgress color={"inherit"} size={24} />
) : (
<>Fazer Login</>
)}
</Button>
</form>
</InputsContainer>
</div>
);
};
export default LoginForm;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.