text
stringlengths 184
4.48M
|
---|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<!-- import the d3 library -->
<script type='text/javascript' src='../lib/d3.v5.min.js'></script>
<!-- Style sheet -->
<style>
#chart-container {
width: 70%;
float: left;
position: relative;
}
#legend-container {
float: left;
width: 30%;
height: 100%;
position: relative;
z-index: 9999;
}
#menu {
clear: both;
}
#legend {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 9999;
}
#tooltip {
position: absolute;
text-align: center;
width: auto;
height: auto;
padding: 5px;
background: rgb(218, 223, 232);
border: 1px solid #4b5d6d;
border-radius: 5px;
pointer-events: none;
font-size: 12px;
font-family: Arial, Helvetica, sans-serif;
}
#tooltip.hidden {
display: none;
}
</style>
</head>
<body>
<h1>Line Chart</h1>
<p>Author: Yana RAGOZINA</p>
<div id="tooltip" class="hidden">
<p id="country-name"></p>
</div>
<div id="legend-container">
<div id="legend">
</div>
</div>
<div id="chart-container">
<div id="chart"></div>
</div>
<script>
let chart = d3.select("#chart"),
originalData = null,
data = null,
selected = {};
// convert all the years from the dataset to an array
// manual assignment to resolve errors
let years = [1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, 1959, 1960, 1961,
1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979,
1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997,
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015,
2016, 2017]
// convert the song counts from the dataset to an array
// manual assignment to avoid errors
var song_count_per_year = new Set();
// define window sizes
var margin = {top: 40, right: 30, bottom: 30, left: 60},
width = 1000 - margin.left - margin.right,
height = 600 - margin.top - margin.bottom;
// append the svg objects to the body of the page
//line chart svg
var svg = d3.select("#chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
//legend svg
var svg_leg = d3.select("#legend")
.append("svg")
.attr("width", width + margin.left + margin.right+ 200)
.attr("height", height + margin.top + margin.bottom + 200)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
//load dataset
d3.csv("../src/dataset_song_count.csv").then(file =>{
originalData = file
data = originalData
preprocessData()
});
// color palette of 40 colors to fit all the countries
var colors = [
"#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c", "#98df8a", "#d62728", "#ff9896",
"#9467bd", "#c5b0d5", "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f", "#c7c7c7",
"#bcbd22", "#dbdb8d", "#17becf", "#9edae5", "#393b79", "#5254a3", "#6b6ecf", "#9c9ede",
"#637939", "#8ca252", "#b5cf6b", "#8c6d31", "#bd9e39", "#e7ba52", "#843c39", "#ad494a",
"#d6616b", "#e7969c", "#7b4173", "#a55194", "#ce6dbd", "#de9ed6"
];
var color = d3.scaleOrdinal(colors);
//prepare the data before displaying the chart
function preprocessData(){
// format numerical values
var parseDate = d3.timeFormat("%Y");
data.forEach(function(d) {
d.year = +d.year;
d.rank = +d.rank;
song_count_per_year.add(+d.song_count_per_year);
});
//retrieve the counts and convert to array
song_count_per_year = Array.from(song_count_per_year);
//group data (song data) by their country of origin
data = d3.nest()
.key(function(d) {
return d['location.country'];
})
.entries(data);
//sort the entire dataset by year in chronological order for correct point placement and linking
data.forEach(function(d) {
d.values.sort(function(a, b) {
return a.year - b.year;
});
});
//initial chart setup and draw
time = 'year';
count = 'song_count_per_year';
displayChart(data, 'year', 'song_count_per_year');
}
//update chart when called with the necessary data
function updateChart() {
//filter the data based on the selected countries
var selectedData = data.filter(function(d) {
return selected[d.key];
});
//clean up the chart
svg.selectAll("*").remove();
//redraw with the new data and parameters
displayChart(selectedData, time, count);
}
// draw chart
function displayChart(selectedData, time, count) {
//set up axis scales
var xMin = d3.min(selectedData, function(d) {
return d3.min(d.values, function(item) {
return item.year;
});
});
var xMax = d3.max(selectedData, function(d) {
return d3.max(d.values, function(item) {
return item.year;
});
});
var yMax = d3.max(selectedData, function(d) {
return d3.max(d.values, function(item) {
return +item.song_count_per_year;
});
});
var x = d3.scaleLinear()
.domain([xMin, xMax])
.range([0, width]);
var y = d3.scaleLinear()
.domain([0, yMax])
.range([height, 0]);
var xAxis = svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(15).tickFormat(d3.format("d")));
svg.append("g")
.call(d3.axisLeft(y));
// display lines on the chart
selectedData.forEach(function(countryData) {
svg.selectAll(".line")
.data([countryData])
.enter()
.append("path")
.attr("fill", "none")
.attr("stroke", function (d) { return color(d.key); })
.attr("stroke-width", 1.5)
.attr("d", function (d) {
return d3.line()
.x(function (d) {
return x(d.year);
})
.y(function (d) { return y(d.song_count_per_year); })
(d.values);
});
//create point class
//necessary to append points for each line representing one country's songs
var pointClass = "point-" + countryData.key;
//tooltip element for data display on hover
var tooltip = d3.select("#chart-container")
.append("div")
.attr("id", "tooltip")
.style("opacity", 0);
//retrieve the top-3 songs for the selected country and year
function getTop3(country, year, period) {
// get the ungrouped data for accurate processing and sort
return originalData.filter(function(d) {
return d["location.country"] === country && d.period == period;
}).sort(function(a, b) {
return a.rank - b.rank;
}).slice(0, 3); //get 3 highest ranking songs
}
//append points for the data mapped on the lines
svg.selectAll("." + pointClass) // for each country line
.data(countryData.values)
.enter()
.append("circle")
.attr("class", pointClass) // unique class for each country
.attr("cx", function (d) {
return x(d.year); // retrieve the year
})
.attr("cy", function (d) {
return y(d.song_count_per_year); // retrieve the song count
})
.attr("r", 3) //set the radius
.style("fill", function (d) { return color(countryData.key)}) //retrieve the corresponding line color
.on("mouseover", function(d) {
// display the tooltip with top-3 songs for this country and time period
var country = countryData.key;
var year = d3.format(".0f")(d.year);
var period = d.period;
var top3Songs = getTop3(country, year, period);
var i = 0;
var content = `<b>${country}<br><br>${year}<br><br>Top-3 Songs (${period}):<br></b><br>`;
top3Songs.forEach(song => {
i += 1;
content += `${i}. ${song.title} - ${song.name}<br>`;
});
tooltip.html(content)
.style("left", (d3.event.pageX + 10) + "px")
.style("top", (d3.event.pageY - 40) + "px")
.style("opacity", 0.9);
})
.on("mouseout", function(d) {
tooltip.style("opacity", 0);
});
});
//add the chart title
svg.append("text")
.attr("class", "chart-title")
.attr("x", width / 2)
.attr("y", -5)
.style("text-anchor", "middle")
.style("font-family", "Arial, sans-serif")
.style("font-size", "16px")
.style("font-family", "Arial, sans-serif")
.style("font-weight", "bold")
.style("fill", "steelblue")
.text("Number of songs written in english yearly by different countries");
//add x-axis label
svg.append("text")
.attr("class", "x-label")
.attr("text-anchor", "middle")
.attr("x", width / 2)
.attr("y", height + 30)
.style("font-family", "Arial, sans-serif")
.style("font-size", "12px")
.text("Year");
//a y-axis label
svg.append("text")
.attr("class", "y-label")
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90)")
.attr("x", -height / 2)
.attr("y", -40)
.style("font-family", "Arial, sans-serif")
.style("font-size", "12px")
.text("Song Count");
//add the legend
var legend = svg_leg.selectAll(".legend")
.data(data)
.enter()
.append("g")
.attr("class", "legend")
.attr("transform", function(d, i) {
return "translate(0," + (i * 20) + ")"; // item spacing
});
// colored rectangle
legend.append("rect")
.attr("x", width + 25)
.attr("y", 0)
.attr("width", 15)
.attr("height", 15)
.style("fill", function(d) { return color(d.key); })
.on("click", function(selectedCountry) {
//add interactivity on click
var isSelected = !selected[selectedCountry.key];
selected[selectedCountry.key] = isSelected;
//update opacity on selection
d3.select(this).style("opacity", isSelected ? 0.5 : 1);
//update the chart to display selected countries' data
updateChart();
});
// country names
legend.append("text")
.attr("x", width + 50)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "start")
.style("font-family", "Arial, sans-serif")
.style("font-size", "12px")
.text(function(d) { return d.key; });
}
</script>
</body>
</html> |
const dotenv = require("dotenv");
const playwright = require("playwright");
dotenv.config();
(async () => {
const browser = await playwright.chromium.launch({ headless: true });
console.log("Initiating browser.")
const page = await (await browser.newContext()).newPage();
console.log("Visitting ", process.env.WEBSITE)
await page.goto(process.env.WEBSITE);
console.log("Going to signin page.")
await page.click("#topnav li:first-child");
await page.waitForLoadState('networkidle') // wait for the page to be loaded
console.log("Logging in...")
await page.fill('#username', process.env.USERNAME)
await page.fill('#password', process.env.PASSWORD)
await page.click("#clogs-captcha-button");
console.log("Logged in.")
console.log("Checking for expiry warning...")
let dangerDiv
try {
dangerDiv = await page.$$(".host-data-widget .text-danger")
}
catch (e) {
console.log("Expiry warning not found. All good.", new Date())
}
if (dangerDiv.length > 0) {
const dangerContent = await dangerDiv.textContent()
console.log("Warning: Expiry warning exists!", dangerContent)
await dangerDiv.click()
await page.waitForLoadState('networkidle') // wait for the page to be loaded
const tableRows = await page.locator("tr")
const rowCount = await tableRows.count()
let domainFound = false
let domainRenewed = false
for (let i = 0; i < rowCount; ++i) {
const tableRow = await tableRows.nth(i)
const textContent = await tableRow.textContent()
if (textContent.indexOf(process.env.DOMAIN) > -1) {
console.log("Found domain listing.")
foundDomain = true
const confirmButton = await tableRow.locator(".btn-success")
const confirmButtonText = await confirmButton.textContent()
if (confirmButtonText.indexOf("Confirm") > -1) {
console.log("Renewing domain.", new Date())
await confirmButton.click()
await page.waitForLoadState('networkidle') // wait for the page to be loaded
domainRenewed = true
} else {
console.error("Error parsing confirm button! Did not renew domain.")
process.exit(1)
}
}
}
if (domainFound === false || domainRenewed === false) {
console.error("Domain not renewed.")
process.exit(1)
}
}
else {
console.log("Expiry warning not found. All good.", new Date())
}
await browser.close();
console.log("Closing browser.")
})();
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time);
});
} |
/**
* 将通过的百分比与十六进制颜色的R、G或B相加
* @param {string} color 要更改的颜色
* @param {number} amount 改变颜色的量
* @returns {string} 颜色的处理部分
*/
function addLight(color: string, amount: number) {
const cc = parseInt(color, 16) + amount
const c = cc > 255 ? 255 : cc
return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`
}
/**
* 根据通过的百分比点亮6个字符的十六进制颜色
* @param {string} color 要更改的颜色
* @param {number} amount 改变颜色的量
* @returns {string} 已处理的颜色,表示为十六进制
*/
export function lighten(color: string, amount: number) {
color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color
amount = Math.trunc((255 * amount) / 100)
return `#${addLight(color.substring(0, 2), amount)}${addLight(
color.substring(2, 4),
amount
)}${addLight(color.substring(4, 6), amount)}`
}
/**
* 判断是否 url
*/
export function isUrl(url: string) {
return /^(http|https):\/\//g.test(url)
} |
require "rails_helper"
RSpec.describe "Posts with authentication", type: :request do
let!(:user) {create(:user)}
let!(:other_user) {create(:user)}
let!(:user_post) {create(:post, user_id: user.id)}
let!(:other_user_post) {create(:post, user_id: other_user.id, published: true )}
let!(:other_user_post_draft) {create(:post, user_id: other_user.id, published: false )}
let!(:auth_headers) { {'Authorization' => "Bearer #{user.auth_token}"} }
let!(:other_auth_headers) { { 'Authorization' => "Bearer #{other_user.auth_token}"} }
let!(:create_params) { {"post" => {"title" => "title", "content" => "content", "published" => true} } }
let!(:update_params) { {"post" => {"title" => "title", "content" => "content", "published" => true} } }
describe "GET /posts/{id}" do
context "with valid auth" do
context "when requisting others author post" do
context "when post is public" do
before { get "/posts/#{other_user_post.id}", headers: auth_headers }
context "payload" do
subject { payload }
it { is_expected.to include(:id) }
end
context "response" do
subject { response }
it { is_expected.to have_http_status(:ok) }
end
end
context "when post is draft" do
before { get "/posts/#{other_user_post_draft.id}", headers: auth_headers }
context "payload" do
subject { payload }
it { is_expected.to include(:error) }
end
context "response" do
subject { response }
it { is_expected.to have_http_status(:not_found) }
end
end
end
context "when requisting users post" do
end
end
end
describe "POST /posts" do
context "with valid auth" do
before { post "/posts", params: create_params, headers: auth_headers }
context "payload" do
subject { payload }
it { is_expected.to include(:id, :title, :content, :published, :author)}
end
context "response" do
subject { response }
it { is_expected.to have_http_status(:created) }
end
end
context "without auth" do
before { post "/posts", params: create_params }
context "payload" do
subject { payload }
it { is_expected.to include(:error) }
end
context "response" do
subject { response }
it { is_expected.to have_http_status(:unauthorized)}
end
end
end
describe "PUT /posts" do
context "with valid auth" do
context "when updating users post" do
before { put "/posts/#{user_post.id}", params: update_params, headers: auth_headers }
context "payload" do
subject { payload }
it { is_expected.to include(:id, :title, :content, :published, :author)}
it { expect(payload[:id]).to eq(user_post.id) }
end
context "response" do
subject { response }
it { is_expected.to have_http_status(:ok) }
end
end
context "when updating others users post" do
before { put "/posts/#{other_user_post.id}", params: update_params, headers: auth_headers }
context "payload" do
subject { payload }
it { is_expected.to include(:error)}
end
context "response" do
subject { response }
it { is_expected.to have_http_status(:not_found) }
end
end
end
end
private
def payload
JSON.parse(response.body).with_indifferent_access
end
end |
package com.solidPrinciples;
import com.solidPrinciples.dependencyInversion.DependencyInversionTester;
import com.solidPrinciples.interfaceSegregation.InterfaceSegregationTester;
import com.solidPrinciples.liskovSubstitution.LiskovSubstitutionTester;
import com.solidPrinciples.liskovSubstitution.exception.PaymentFailedException;
import com.solidPrinciples.liskovSubstitution.exception.PaymentInstrumentInvalidException;
import com.solidPrinciples.openClosed.OpenClosedTester;
import com.solidPrinciples.openClosed.model.Item;
import com.solidPrinciples.openClosed.model.Money;
import com.solidPrinciples.openClosed.model.Receipt;
import java.lang.reflect.Array;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
System.out.println("DIP Test");
DependencyInversionTester.test();
System.out.println("ISP Test");
InterfaceSegregationTester.test();
System.out.println("LSP Test");
try {
LiskovSubstitutionTester.test();
} catch (PaymentInstrumentInvalidException e) {
throw new RuntimeException(e);
} catch (PaymentFailedException e) {
throw new RuntimeException(e);
}
System.out.println("OCP Test");
Receipt receipt = new Receipt();
receipt.setItems(
Arrays.asList(
new Item.Builder().price(new Money.Builder().value(20.0).build()).build(),
new Item.Builder().price(new Money.Builder().value(20.0).build()).build())
);
OpenClosedTester.checkOut_fixed(receipt);
}
} |
<!DOCTYPE html>
<html lang="es">
<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">
<script>
/* 4. Escribe un bucle while que:
- Recorra del 1 al 20
- Si el número es divisible por 3 que muestre "Divisible por 3"
- Si el número es divisible por 5 que muestre "Divisible por 5"
- Si es divisible por 3 y 5 que muestre "Divisible por 3 y 5"
- Si no es dividible ni por 3 ni por 5 que muestre el número
*/
function divisibles(n) {
let resultado = document.getElementById('resultado');
let respuesta = '<p>';
for (let i = 1; i <= n; i++) {
if (i % 3 == 0 && i % 5 == 0) {
respuesta += `${i} es divisible por 3 y 5.`;
} else if (i % 3 == 0) {
respuesta += `${i} es divisible por 3.`;
} else if (i % 5 == 0) {
respuesta += `${i} es divisible por 5.`;
} else {
respuesta += `${i}`;
}
respuesta += '</p>';
}
resultado.innerHTML = respuesta;
}
function divisiblesTernario(n) {
let resultado = document.getElementById('resultado');
let respuesta = '<p>';
for (let i = 1; i <= n; i++) {
i % 3 == 0 && i % 5 == 0 ? respuesta += `${i} es divisible por 3 y 5.`
: i % 3 == 0 ? respuesta += `${i} es divisible por 3.`
: i % 5 == 0 ? respuesta += `${i} es divisible por 5.`
: respuesta += `${i}`;
respuesta += '</p>';
}
resultado.innerHTML = respuesta;
}
</script>
<title>u2r4</title>
</head>
<body>
<h1>4. Divisibles por 3 y 5.</h1>
<div>
<a href="index.html">Volver</a>
</div>
<div id="resultado">
<script>
let n = prompt('Introduce número:', '20');
divisibles(n);
</script>
</div>
</body>
</html> |
import { Component, OnInit, Injector, ViewChild, ElementRef, Renderer2, OnDestroy } from '@angular/core';
import { Location as NgLocation } from '@angular/common';
import { AppComponentBase } from '@shared/common/app-component-base';
import { ActivatedRoute, Router } from '@angular/router';
import { VideoCallServiceProxy, VideoAppointmentDto } from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { CameraComponent } from './camera/camera.component';
import { LocalTrack, RemoteTrack } from 'twilio-video/tsdef/types';
import { Room, connect, createLocalAudioTrack, RemoteParticipant, LocalAudioTrack, LocalVideoTrack, RemoteAudioTrack, RemoteVideoTrack, RemoteTrackPublication } from 'twilio-video';
import { ConnectOptions } from 'twilio-video';
import { VideoSettingsModalComponent } from './video-settings/video-settings-modal.component';
import { from, zip } from 'rxjs';
import { LocalVideoTrackService } from '../local-video-track.service';
import { CanDeactivateComponentBase } from '@shared/common/can-deactivate-component-base';
class RemoteHelpers {
static detachRemoteTrack(track: RemoteTrack) {
if (this.isDetachable(track)) {
track.detach().forEach(el => el.remove());
return true;
}
return false;
}
static isAttachable(track: RemoteTrack): track is RemoteAudioTrack | RemoteVideoTrack {
return !!track &&
((track as RemoteAudioTrack).attach !== undefined ||
(track as RemoteVideoTrack).attach !== undefined);
}
static isDetachable(track: RemoteTrack): track is RemoteAudioTrack | RemoteVideoTrack {
return !!track &&
((track as RemoteAudioTrack).detach !== undefined ||
(track as RemoteVideoTrack).detach !== undefined);
}
}
class LocalHelpers {
static detachLocalTrack(track: LocalTrack) {
if (LocalHelpers.isDetachable(track)) {
track.detach().forEach(el => el.remove());
}
}
static isDetachable(track: LocalTrack): track is LocalAudioTrack | LocalVideoTrack {
return !!track
&& ((track as LocalAudioTrack).detach !== undefined
|| (track as LocalVideoTrack).detach !== undefined);
}
}
@Component({
templateUrl: './appointment.component.html',
styleUrls: ['./appointment.component.less']
})
export class AppointmentComponent extends CanDeactivateComponentBase implements OnInit, OnDestroy {
@ViewChild('camera') camera: CameraComponent;
@ViewChild('settingsModal') settings: VideoSettingsModalComponent;
@ViewChild('participant') participantContainer: ElementRef;
activeRoom: Room;
appointment: VideoAppointmentDto = null;
isMuted = false;
private jwtToken: string = null;
private remoteParticipant: RemoteParticipant = null;
constructor(
injector: Injector,
private readonly location: NgLocation,
private readonly activatedRoute: ActivatedRoute,
private readonly router: Router,
private readonly renderer: Renderer2,
private readonly videoCallService: VideoCallServiceProxy,
private readonly localVideoTrackService: LocalVideoTrackService) {
super(injector);
}
get hasParticipant() {
return this.remoteParticipant != null;
}
get participantName() {
if (!this.appointment) {
return '';
}
return this.getFullName(this.appointment.therapist.id == this.appSession.userId
? this.appointment.patient
: this.appointment.therapist);
}
ngOnInit(): void {
const appointmentIdStr = this.activatedRoute.snapshot.params['id'];
const appointmentId = Number.parseInt(appointmentIdStr);
this.isLoading = true;
this.videoCallService.getAppointment(appointmentId)
.pipe(finalize(() => this.isLoading = false))
.subscribe(async appointment => {
this.appointment = appointment;
if (!appointment.isActive) { // skip for dev
if (!appointment.hasStarted) {
this.message.error(this.l('Appointment.HasNotStarted'));
}
else if (!appointment.hasEnded) {
this.message.error(this.l('Appointment.HasEnded'));
}
this.location.back();
} else {
this.joinCall();
}
this.isLoading = false;
});
this.addSubscriptionToClear(
this.localVideoTrackService.localVideoTrack.subscribe(async track => {
if (this.activeRoom) {
const localParticipant = this.activeRoom.localParticipant;
localParticipant.videoTracks.forEach(publication => publication.unpublish());
await localParticipant.publishTrack(track);
}
}));
}
ngOnDestroy(): void {
if (this.activeRoom) {
this.activeRoom?.localParticipant?.tracks?.forEach(x => {
x.unpublish();
})
this.activeRoom.disconnect();
}
this.clearSubscriptions();
this.localVideoTrackService.disposeCurrentTrack();
}
canDeactivate(): boolean {
//TODO: check the proper way to see if the video call is still running. If so, implement the check here
return false;
}
joinCall() {
zip(
this.videoCallService.getTwilioJwtToken(this.appointment.id),
this.localVideoTrackService.localVideoTrack,
from(createLocalAudioTrack())
).subscribe(async ([token, videoTrack, audioTrack]) => {
this.jwtToken = token;
this.activeRoom = await this.joinOrCreateRoom(`AP_${this.appointment.id}`, [audioTrack, videoTrack]);
this.registerRoomEvents();
});
}
toggleMute() {
this.isMuted = !this.isMuted;
this.activeRoom.localParticipant.audioTracks.forEach(track => {
if (this.isMuted) {
track.track.disable();
}
else {
track.track.enable();
}
});
}
async joinOrCreateRoom(name: string, tracks: LocalTrack[]) {
let room: Room = null;
room = await connect(this.jwtToken, { name, tracks, dominantSpeaker: true } as ConnectOptions);
// try {
// room = await connect(this.jwtToken, { name, tracks, dominantSpeaker: true } as ConnectOptions);
// } catch (error) {
// console.error(`Unable to connect to Room: ${error.message}`);
// }
return room;
}
private registerRoomEvents() {
this.activeRoom
.on('disconnected',
(room: Room) => room.localParticipant.tracks.forEach(publication => LocalHelpers.detachLocalTrack(publication.track)))
.on('participantConnected',
(participant: RemoteParticipant) => this.setRemoteParticipant(participant))
.on('participantDisconnected',
(participant: RemoteParticipant) => this.remoteParticipant = null);
// .on('dominantSpeakerChanged',
// (dominantSpeaker: RemoteParticipant) => this.participants.loudest(dominantSpeaker));
if (this.activeRoom.participants && this.activeRoom.participants.size > 0) {
const participant = this.activeRoom.participants.values()?.next()?.value;
this.setRemoteParticipant(participant);
}
}
private setRemoteParticipant(participant: RemoteParticipant) {
this.remoteParticipant = participant;
if (participant) {
this.registerParticipantEvents(participant);
}
}
private registerParticipantEvents(participant: RemoteParticipant) {
if (participant) {
participant.tracks.forEach(publication => this.subscribe(publication));
participant.on('trackPublished', publication => this.subscribe(publication));
participant.on('trackUnpublished',
publication => {
if (publication && publication.track) {
this.detachRemoteTrack(publication.track);
}
});
}
}
private subscribe(publication: RemoteTrackPublication | any) {
if (publication && publication.on) {
publication.on('subscribed', track => this.attachRemoteTrack(track));
publication.on('unsubscribed', track => this.detachRemoteTrack(track));
}
}
private attachRemoteTrack(track: RemoteTrack) {
if (RemoteHelpers.isAttachable(track)) {
const element = track.attach();
this.renderer.data.id = track.sid;
this.renderer.setStyle(element, 'width', '100%');
this.renderer.appendChild(this.participantContainer.nativeElement, element);
}
}
private detachRemoteTrack(track: RemoteTrack) {
if (RemoteHelpers.isDetachable(track)) {
track.detach().forEach(el => el.remove());
}
}
} |
#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(vector<vector<int>> triangle) {
vector<vector<int>> temp;
temp.assign(triangle.size(), vector<int>());
int answer = 0;
temp[0].push_back(triangle[0][0]);
for (int y = 1; y < triangle.size(); y++)
{
temp[y].assign(triangle[y].size(), 0);
for (int x = 0; x < triangle[y].size(); x++)
{
if (x == 0)
{
temp[y][x] = triangle[y][x] + temp[y - 1][x];
}
else if (x == triangle[y].size() - 1)
{
temp[y][x] = triangle[y][x] + temp[y - 1][x - 1];
}
else
{
int left = temp[y - 1][x - 1];
int right = temp[y - 1][x];
temp[y][x] = triangle[y][x] + (left > right ? left : right);
}
}
}
sort(temp[triangle.size() - 1].begin(), temp[triangle.size() - 1].end(), greater<int>());
return temp[triangle.size() - 1][0];
}
int main()
{
vector<vector<int>> triangle;
triangle.assign(5, vector<int>());
triangle[0].push_back(7);
triangle[1].push_back(3);
triangle[1].push_back(8);
triangle[2].push_back(8);
triangle[2].push_back(1);
triangle[2].push_back(0);
triangle[3].push_back(2);
triangle[3].push_back(7);
triangle[3].push_back(4);
triangle[3].push_back(4);
triangle[4].push_back(4);
triangle[4].push_back(5);
triangle[4].push_back(2);
triangle[4].push_back(6);
triangle[4].push_back(5);
cout << solution(triangle) << endl;;
return 0;
} |
from nicegui import ui
from nicegui.element import Element
class Circle(Element, component='circle.js'):
def __init__(self, x, y, radius, **kwargs):
super().__init__()
self.x = x
self.y = y
self.radius = radius
self.fill = kwargs.get('fill', 'black')
self.stroke = kwargs.get('stroke', 'black')
self.stroke_width = kwargs.get('stroke_width', 1)
self.x_scale_factor = kwargs.get('x_scale_factor', 1)
self.y_scale_factor = kwargs.get('y_scale_factor', 1)
self.rotate_angle = kwargs.get('rotate_angle', 0)
self.rotate_x = self.rotate_angle
self.rotate_y = self.rotate_angle
self.skew_angle_x = kwargs.get('skew_angle_x', 0)
self.skew_angle_y = kwargs.get('skew_angle_y', 0)
self.flip_x = kwargs.get('flip_x', False)
self.flip_y = kwargs.get('flip_y', False)
self._props['r'] = self.radius
self._props['cx'] = self.x
self._props['cy'] = self.y
self._props['fill'] = self.fill
self._props['outline_color'] = self.stroke
self._props['outline_width'] = self.stroke_width
self._props['x_scale_factor'] = self.x_scale_factor
self._props['y_scale_factor'] = self.y_scale_factor
self._props['rotate_angle'] = self.rotate_angle
self._props['x_skew_factor'] = self.skew_angle_x
self._props['y_skew_factor'] = self.skew_angle_y
def set_outline_color(self, color):
self.stroke = color
self._props['outline_color'] = self.stroke
self.update()
def set_color(self, color):
self.fill = color
self._props['fill'] = self.fill
self.update()
def set_radius(self, radius):
self.radius = radius
self._props['radius'] = self.radius
self.update()
def set_position(self, x, y):
self.x = x
self.y = y
self._props['cx'] = self.x
self._props['cy'] = self.y
self.update()
def move(self, dx, dy):
self.x += dx
self.y += dy
self._props['cx'] = self.x
self._props['cy'] = self.y
self.update()
def scaleX(self, factor):
self.radius *= factor
self._props['radius'] = self.radius
self.update()
def skewX(self, angle):
self.skew_angle_x = angle
self._props['x_skew_factor'] = self.skew_angle_x
self.update()
def skewY(self, angle):
self.skew_angle_y = angle
self._props['y_skew_factor'] = self.skew_angle_y
self.update()
def rotate(self, angle):
self.rotate_angle = angle
self.rotate_x = angle
self.rotate_y = angle
self._props['rotate_angle'] = self.rotate_angle
self._props['rotate_x'] = self.rotate_x
self._props['rotate_y'] = self.rotate_y
self.update()
def flipX(self):
pass
def flipY(self):
pass
def __str__(self, indent: int = 0) -> str:
return " " * indent + "Circle(x={}, y={}, radius={}, fill='{}', stroke='{}', stroke_width={}, x_scale_factor={}, y_scale_factor={}, rotate_angle={}, skew_angle_x={}, skew_angle_y={}, flip_x={}, flip_y={})\n".format(self.x, self.y, self.radius, self.fill, self.stroke, self.stroke_width, self.x_scale_factor, self.y_scale_factor, self.rotate_angle, self.skew_angle_x, self.skew_angle_y, self.flip_x, self.flip_y) |
import React, { useEffect, useRef, useState } from 'react';
import { IoSettingsOutline } from "react-icons/io5";
import Post from '../components/Post.jsx';
import CreatePost from '../components/CreatePost.jsx';
import { fetchFeeds, fetchFollowingPosts } from "../services/postService.js";
import TransparencySpinner from '../components/common/TransparencySpinner.jsx';
import PostSkeleton from '../components/common/PostSkeleton.jsx';
import { MdOutlineAdd } from "react-icons/md";
import { MdOutlineClose } from "react-icons/md";
import logo from "/logo.png"
import { useSelector } from "react-redux"
import Sidebar from "../components/common/FeaturSidebar.jsx"
import { RxCross1 } from "react-icons/rx";
const navLinks = [
"For you",
"Following",
];
const Home = () => {
const [isLoading, setIsLoading] = useState(false);
const [allPosts, setAllPosts] = useState([]);
const [isSkeleton, setIsSkeleton] = useState(false);
const scrollDiv = useRef(null);
const [openCreatePost, setOpenCreatePost] = useState(false);
const [showSidebar, setShowSidebar] = useState(false);
const userState = useSelector(state => state.auth.user);
const [option, setOption] = useState(navLinks[0]);
async function fetchMoreData(currIndex) {
setIsSkeleton(true);
let func;
switch (option) {
case "For you":
func = fetchFeeds;
break;
case "Following":
func = fetchFollowingPosts;
break;
default:
func = fetchFeeds;
break;
}
func(currIndex)
.then(({ data }) => {
setAllPosts((prevItems) => [...prevItems, ...data.data]);
setIndex(currIndex + 1);
data?.data?.length === 10 ? setHasMore(true) : setHasMore(false);
})
.catch((err) => console.log(err))
.finally(() => setIsSkeleton(false));
}
useEffect(() => {
// setIndex(0);
setAllPosts([]);
// setHasMore(true);
fetchMoreData(0);
}, [option]);
return (
<div className='w-full'>
<div className='flex w-full relative flex-col justify-start items-center bg-black'>
{/* Spinner */}
{
isLoading &&
<TransparencySpinner />
}
{
openCreatePost && (
<div className='absolute z-10 bg-black/[0.6] w-screen h-screen flex justify-center items-center'>
<div className='relative max-w-[350px] sm:max-w-[500px]'>
<span onClick={() => setOpenCreatePost(false)} className='text-white absolute right-2 top-1 text-2xl'>
<MdOutlineClose />
</span>
<CreatePost type={"Post"} setIsLoading={setIsLoading} />
</div>
</div>
)
}
{
showSidebar && (
<div className='w-full z-[100] bg-black/[0.3] absolute justify-start items-start flex'>
<div className='w-[300px] relative pl-5 bg-black transition-transform duration-1000 transform translate-x-0'>
<Sidebar />
<span
onClick={() => setShowSidebar(false)}
className='text-white transition-all duration-200 ease-in-out cursor-pointer hover:bg-white/[0.3] p-2 rounded-full text-2xl right-5 absolute top-5'
>
<RxCross1 />
</span>
</div>
</div>
)
}
{/* navbar */}
<div className={`sticky top-0 w-full backdrop-blur-2xl border-b-2 border-[white]/[0.19] `}>
{/* mobile navbar */}
<div className='w-full lg:hidden px-4 pt-2 flex flex-row justify-between items-center'>
<div onClick={() => setShowSidebar(true)} className='w-10 cursor-pointer h-10 overflow-hidden'>
<img
src={userState.profileImg}
alt="profile"
className='w-full h-full object-contain rounded-full'
/>
</div>
<div className='h-6 overflow-hidden'>
<img
src={logo}
alt="logo"
className='object-contain h-full w-auto'
/>
</div>
<div className='cursor-pointer p-2 hover:bg-white/[0.2] rounded-full transition-all duration-200 ease-in-out'>
<span className='text-white text-2xl'>
<IoSettingsOutline />
</span>
</div>
</div>
{/* follow and following */}
<div className='flex flex-row justify-between w-full '>
{
navLinks?.map((navlink, index) => (
<div
key={index}
className='flex w-full hover:bg-[white]/[0.1] pt-3 transition-all duration-200 ease-in-out cursor-pointer justify-center items-center flex-row gap-2'
onClick={() => {
setOption(navlink)
}}
>
<div className='flex flex-col gap-2 justify-center items-center'>
<p className={` transition-all duration-300 ease-in-out ${option === navlink ? "text-white font-bold" : "text-[white]/[0.4] font-semibold"} `}>{navlink}</p>
<span className={`bg-blue-400 transition-all duration-200 ease-in-out w-full h-1 rounded-full ${option === navlink ? "block" : "hidden"} `} />
</div>
</div >
))
}
<div className='hover:bg-[white]/[0.1] lg:flex hidden transition-all duration-300 ease-in-out text-xl mx-2 text-white px-3 rounded-full justify-center items-center cursor-pointer '>
<IoSettingsOutline />
</div>
</div >
</div >
{/* Feeds */}
<div ref={scrollDiv} className='h-[calc(100vh-100px)] w-full bg-black overflow-y-auto' >
{
isSkeleton ? (
<div className='flex flex-col justify-start gap-5 items-center' >
<PostSkeleton />
<PostSkeleton />
<PostSkeleton />
<PostSkeleton />
<PostSkeleton />
</div>
) : (
<>
{
option === "For you" &&
<div>
<CreatePost type={"Post"} setIsLoading={setIsLoading} />
</div>
}
<div className='w-full flex pb-14 mt-5 flex-col gap-5 justify-start items-start'>
{
allPosts.length > 0 ? (
allPosts.map((post) => (
<Post key={post?._id} post={post} />
))
) : (
<div className='w-full mt-10'>
<p className='text-white text-center text-4xl font-bold'>No post found</p>
</div>
)
}
</div>
</>
)
}
</div >
{/* Create post button */}
<button onClick={() => { setOpenCreatePost(true) }} className='fixed lg:hidden right-5 bottom-16 rounded-full bg-blue-500 p-2 sm:p-4 shadow-md shadow-black ' >
<span className=' text-white text-4xl '>
<MdOutlineAdd />
</span>
</button >
</div >
</div >
);
}
export default Home; |
# Inpainting canvas
canvas_html = """
<style>
.button {
background-color: #4CAF50;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
}
</style>
<canvas1 width=%d height=%d>
</canvas1>
<canvas width=%d height=%d>
</canvas>
<button>Finish</button>
<script>
var canvas = document.querySelector('canvas')
var ctx = canvas.getContext('2d')
var canvas1 = document.querySelector('canvas1')
var ctx1 = canvas.getContext('2d')
ctx.strokeStyle = 'red';
var img = new Image();
img.src = "data:image/%s;charset=utf-8;base64,%s";
console.log(img)
img.onload = function() {
ctx1.drawImage(img, 0, 0);
};
img.crossOrigin = 'Anonymous';
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.lineWidth = %d
var button = document.querySelector('button')
var mouse = {x: 0, y: 0}
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft
mouse.y = e.pageY - this.offsetTop
})
canvas.onmousedown = ()=>{
ctx.beginPath()
ctx.moveTo(mouse.x, mouse.y)
canvas.addEventListener('mousemove', onPaint)
}
canvas.onmouseup = ()=>{
canvas.removeEventListener('mousemove', onPaint)
}
var onPaint = ()=>{
ctx.lineTo(mouse.x, mouse.y)
ctx.stroke()
}
var data = new Promise(resolve=>{
button.onclick = ()=>{
resolve(canvas.toDataURL('image/png'))
}
})
</script>
"""
import base64, os
from base64 import b64decode
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display, HTML
from ..logging.logging_setup import logger
import torch
class NotValid(Exception):
pass
def draw(imgm, filename="drawing.png", w=400, h=200, line_width=1):
try:
from google.colab.output import eval_js
display(
HTML(canvas_html % (w, h, w, h, filename.split(".")[-1], imgm, line_width))
)
data = eval_js("data")
binary = b64decode(data.split(",")[1])
with open(filename, "wb") as f:
f.write(binary)
logger.info(f"Created draw and saved: {filename}")
except:
raise NotValid("You need to upload the mask image. If you're trying to use the option to draw mask from a Notebook, this option is only available for colab")
# the control image of init_image and mask_image
def make_inpaint_condition(image, image_mask):
image = np.array(image.convert("RGB")).astype(np.float32) / 255.0
image_mask = np.array(image_mask.convert("L")).astype(np.float32) / 255.0
assert (
image.shape[0:1] == image_mask.shape[0:1]
), "image and image_mask must have the same image size"
image[image_mask > 0.5] = -1.0 # set as masked pixel
image = np.expand_dims(image, 0).transpose(0, 3, 1, 2)
image = torch.from_numpy(image)
return image |
class Api::V1::UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]
# GET /users
def index
@users = User.all
render json: UserSerializer.new(@users, include: [:tasks, :assigned_tasks]).serialized_json
end
# GET /users/1
def show
user_json = UserSerializer.new(@user, include: [:tasks, :assigned_tasks] ).serialized_json
render json: user_json
end
# POST /users
def create
@user = User.new(user_params)
if @user.save
session[:user_id] = @user.id
render json: UserSerializer.new(@user).serialized_json, status: :created
else
resp = {
error: @user.errors.full_messages.to_sentence
}
render json: resp, status: :unprocessable_entity
end
end
# PATCH/PUT /users/1
def update
if @user.update(user_params)
render json: UserSerializer.new(@user).serialized_json
else
render json: @user.errors, status: :unprocessable_entity
end
end
# DELETE /users/1
def destroy
@user.destroy
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a trusted parameter "white list" through.
def user_params
params.require(:user).permit(:name, :email, :password, :department_id, :supervisor)
end
end |
%
% This file is part of Pl-man
% Pl-man is a puzzle game inspired in the popular game pacman, and it is mainly aimed
% to teach programming in PROLOG and introductory courses of Artifial Intelligence.
%
% Copyright (C) 2007-2008 Francisco Gallego <ronaldo@cheesetea.com>
% Departamento de Ciencia de la Computación e Inteligencia Artificial
% Universidad de Alicante
% Campus de San Vicente
% Ap.Correos, 99
% 03080, San Vicente del Raspeig (Alicante)
%
% This program is free software: you can redistribute it and/or modify
% it under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <http://www.gnu.org/licenses/>.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% companion
%
% Controlls the behaviour of a pl-man's buddy that
% moves following a predifined sequence of moves, uses
% objects wisely and dodges enemies like a ninja
%
% Initialization
%--------------------
% companion(init, EID, MOVE_LIST, ITEMS_LIST MODIFIERS)
% EID: Entity ID of the entity to be controlled
% MOVE_LIST: List of movements to follow
% ITEMS_LIST: List of items available to get and use
% MODIFIERS: List of atoms that express modifications to the
% standard behaviour.
% - no_repeat_moves: By default it is always checked that
% movements have been effectively done. If not, they are
% repeated. This modifier disables this feature.
% - no_cycle: By default, when an entity has done all the movements
% from its list, it cycles again. This modifier disables this feature.
%
%
% Example
%--------------------
% createGameEntity(EID, 'ñ', object, 1, 1, active, companion, 0),
% companion(init, EID, [ right, left, up, up, down, down ], []).
%
% Creates a companion that will move following the move list.
% Once it has done all the movements from the list, it
% cycles again.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
:- module(companion, [ companion/1, companion/7 ]).
% d_entityStatus(EID, was_on(X, Y, Appearance), NextMoveNum, MoveList, Modifiers)
:- dynamic d_entityStatus/5.
% disarmed, not carrying a weapon; armed, carrying a weapon;
:- dynamic d_itemStatus/6.
% Init Sequence
companion(init, EID, MOVE_LIST, MODIF_LIST, ITEM_LIST, AIM_LIST, DIRECTIONS_LIST):-
number(EID),
is_list(MOVE_LIST),
is_list(MODIF_LIST),
is_list(ITEM_LIST),
is_list(AIM_LIST),
is_list(DIRECTIONS_LIST),
'pl-man':entityLocation(EID,_ , _, Ap),
retractall(d_entityStatus(EID, _, _, _, _)),
retractall(d_itemStatus(EID, _, _, _, _, _)),
assert(d_entityStatus(EID, was_on(-100,-100,Ap), 0, MOVE_LIST, MODIF_LIST)),
assert(d_itemStatus(EID, ITEM_LIST, AIM_LIST, DIRECTIONS_LIST, disarmed, _)), !.
companion(init, EID, _, _, _, _, _):-
'pl-man':lang_message(entitySequentialMovement, bad_parameters, MSG),
maplist(user:write, [MSG, EID, '\n']).
% Control to gather dots
companion(EID):-
'pl-man':entityLocation(EID, X, Y, _),
'pl-man':getDMap(Map),
'pl-man':eatDot(EID, companion, Map, X, Y), % *** functor añadido en pl-man ***
false.
% Control to gather items
% Grab a weapon
companion(EID):-
d_itemStatus(EID, L_ITEMS, L_AIM, L_DIR, disarmed, _), % Make sure companion is not carry anything
member(DIR,L_DIR),
'pl-man':see(EID, normal, DIR, WHAT),
member(WHAT, L_ITEMS),
'pl-man':entityLocation(EID, X, Y, _),
% Gather the item in its respective direction
newdir(DIR,X,Y,NewX,NewY),
'pl-man':getObjectFrom(EID,NewX,NewY),
retract(d_itemStatus(EID, _, _, _, _, _)),
assert(d_itemStatus(EID, L_ITEMS, L_AIM, L_DIR, armed, WHAT)), % Update status (companion now armed)
'pl-man':entityLocation(EID, _, _, Ap), % Recupero la apariencia para mostrarla en el mensaje
maplist(user:write, ['Tu compañero "', Ap, '" ha recogido (', WHAT, ' )\n']).
% Use a weapon
companion(EID):-
d_itemStatus(EID, L_ITEMS, L_AIM, L_DIR, armed, ITEM_APP), % Make sure companion is armed
member(DIR,L_DIR),
'pl-man':see(EID, list, DIR, SEELIST),
member(AIM, L_AIM),
member(AIM, SEELIST),
'pl-man':entityLocation(EID, X, Y, _), % Retrieve X and Y coordinates to convert them
newdir(DIR,X,Y,NewX,NewY),
'pl-man':useObjectTo(EID, DIR, NewX, NewY), % Use the object (aren't NewX and NewY unnecessary? Anyway, it works)
( not('pl-man':havingObject(EID, appearance(ITEM_APP))) ->
retract(d_itemStatus(EID, _, _, _, armed, _)),
assert(d_itemStatus(EID, L_ITEMS, L_AIM, L_DIR, disarmed, _))
;
true
).
% ---------------
% Control Sequence
companion(EID):-
retract(d_entityStatus(EID, was_on(X, Y, _), MOVE_NUM, L_MOVES, L_MODIF)),
p_moveToDo(MOVE, EID, X, Y, MOVE_NUM, L_MOVES, L_MODIF),
p_convertToAction(MOVE, ACTION, L_MOVES),
'pl-man':doAction(EID, ACTION),
p_nextMovement(NEXT_MOVE, MOVE, L_MOVES, L_MODIF),
'pl-man':entityLocation(EID, NX, NY, NAP),
assert(d_entityStatus(EID, was_on(NX,NY,NAP), NEXT_MOVE, L_MOVES, L_MODIF)).
% Subrules
%
p_moveToDo(none, _, _, _, MOVE_NUM, L_MOVES, _):-
not(nth0(MOVE_NUM, L_MOVES, _)), !.
p_moveToDo(PREV, EID, X, Y, MOVE_NUM, L_MOVES, L_MODIF):-
not(member(no_repeat_moves, L_MODIF)),
'pl-man':entityLocation(EID, X, Y, _),
p_previousMovement(PREV, MOVE_NUM, L_MOVES),
p_convertToAction(PREV, ACTION, L_MOVES),
ACTION \= move(none), !.
p_moveToDo(MOVE_NUM, _, _, _, MOVE_NUM, L_MOVES, _):-
nth0(MOVE_NUM, L_MOVES, _), !.
p_moveToDo(none, _, _, _, _, _, _).
% calculate which one will be next movement
p_nextMovement(NEXT, PRESENT, L_MOVES, _):-
NEXT is PRESENT + 1,
nth0(NEXT, L_MOVES, _), !.
p_nextMovement(NEXT, PRESENT, _, L_MODIF):-
member(no_cycle, L_MODIF),
NEXT is PRESENT + 2, !.
p_nextMovement(0, _, _, _).
% calculate previous movement
p_previousMovement(PREV, 0, L_MOVES):-
length(L_MOVES, P),
PREV is P - 1, !.
p_previousMovement(PREV, MOVE_NUM, _):-
PREV is MOVE_NUM - 1.
% Movement conversion
p_convertToAction(NUM, ACTION, L_MOVES):-
nth0(NUM, L_MOVES, MOVE),
p_convertToAction(MOVE, ACTION).
p_convertToAction(r, move(right)).
p_convertToAction(l, move(left)).
p_convertToAction(u, move(up)).
p_convertToAction(d, move(down)).
p_convertToAction(n, move(none)).
p_convertToAction(right, move(right)).
p_convertToAction(left, move(left)).
p_convertToAction(up, move(up)).
p_convertToAction(down, move(down)).
p_convertToAction(none, move(none)).
p_convertToAction(random, X):- p_convertToAction(rand([u,d,l,r,n]), X).
p_convertToAction(rnd, X):- p_convertToAction(rand([u,d,l,r,n]), X).
p_convertToAction(x, X):- p_convertToAction(rand([u,d,l,r,n]), X).
p_convertToAction(x(L), X):- is_list(L), p_convertToAction(rand(L), X).
p_convertToAction(rand(L), ACTION):-
length(L, LEN),
X is random(LEN),
nth0(X, L, CONV),
p_convertToAction(CONV, ACTION).
% Subrules to itemStatus
%%Add directions
newdir(up,X,Y,NewX,NewY):- NewX is X, NewY is Y-1.
newdir(up-right,X,Y,NewX,NewY):- NewX is X+1, NewY is Y-1.
newdir(up-left,X,Y,NewX,NewY):- NewX is X-1, NewY is Y-1.
newdir(down,X,Y,NewX,NewY):- NewX is X, NewY is Y+1.
newdir(down-right,X,Y,NewX,NewY):- NewX is X+1, NewY is Y+1.
newdir(down-left,X,Y,NewX,NewY):- NewX is X-1, NewY is Y+1.
newdir(right,X,Y,NewX,NewY):- NewX is X+1, NewY is Y.
newdir(left,X,Y,NewX,NewY):- NewX is X-1, NewY is Y. |
/*
* Copyright (c) 2015, Adrian Moser
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package ch.eskaton.asn4j.compiler.values;
import ch.eskaton.asn4j.compiler.CompilerException;
import ch.eskaton.asn4j.parser.ParserException;
import ch.eskaton.asn4j.parser.ast.values.GeneralizedTimeValue;
import ch.eskaton.asn4j.runtime.exceptions.ASN1RuntimeException;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static ch.eskaton.asn4j.compiler.CompilerTestUtils.getCompiledValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.text.MatchesPattern.matchesPattern;
import static org.junit.jupiter.api.Assertions.assertThrows;
class GeneralizedTimeValueCompilerTest {
@Test
void testResolveCStringValue() throws IOException, ParserException {
var body = """
testGeneralizedTime1 GeneralizedTime ::= "19851106210627.3Z"
""";
var compiledValue = getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime1");
var value = (GeneralizedTimeValue) compiledValue.getValue();
assertThat(value.getValue(), equalTo("19851106210627.3Z"));
}
@Test
void testResolveInvalidCStringValue() {
var body = """
testGeneralizedTime1 GeneralizedTime ::= "19851106210627,3Z"
""";
assertThrows(CompilerException.class,
() -> getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime1"));
}
@Test
void testResolveInvalidGeneralizedTimeValue() {
var body = """
testGeneralizedTime1 GeneralizedTime ::= "19851106210627.3-1900"
""";
assertThrows(ASN1RuntimeException.class,
() -> getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime1"));
}
@Test
void testResolveReference() throws IOException, ParserException {
var body = """
testGeneralizedTime1 GeneralizedTime ::= "19851106210627.3Z"
testGeneralizedTime2 GeneralizedTime ::= testGeneralizedTime1
""";
var compiledValue = getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime2");
var value = (GeneralizedTimeValue) compiledValue.getValue();
assertThat(value.getValue(), equalTo("19851106210627.3Z"));
}
@Test
void testResolveCStringValueWithTypeReference() throws IOException, ParserException {
var body = """
TestGeneralizedTime1 ::= GeneralizedTime
TestGeneralizedTime2 ::= TestGeneralizedTime1
testGeneralizedTime1 TestGeneralizedTime2 ::= "19851106210627.3Z"
""";
var compiledValue = getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime1");
var value = (GeneralizedTimeValue) compiledValue.getValue();
assertThat(value.getValue(), equalTo("19851106210627.3Z"));
}
@Test
void testResolveReferenceWithTypeReference() throws IOException, ParserException {
var body = """
TestGeneralizedTime1 ::= GeneralizedTime
TestGeneralizedTime2 ::= TestGeneralizedTime1
testGeneralizedTime1 TestGeneralizedTime2 ::= "19851106210627.3Z"
testGeneralizedTime2 GeneralizedTime ::= testGeneralizedTime1
""";
var compiledValue = getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime2");
var value = (GeneralizedTimeValue) compiledValue.getValue();
assertThat(value.getValue(), equalTo("19851106210627.3Z"));
}
@Test
void testResolveReferenceWithInvalidTypeReference() {
var body = """
TestGeneralizedTime1 ::= NumericString
testGeneralizedTime1 TestGeneralizedTime1 ::= "test"
testGeneralizedTime2 GeneralizedTime ::= testGeneralizedTime1
""";
assertThrows(CompilerException.class,
() -> getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime2"));
}
@Test
void testResolveUnsupportedCharacterStringList() {
var body = """
testGeneralizedTime1 GeneralizedTime ::= {"19851106210627.3Z"}
""";
assertThrows(CompilerException.class,
() -> getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime1"));
}
@Test
void testResolveInvalidTupleValue() {
var body = """
testGeneralizedTime1 GeneralizedTime ::= {1, 1}
""";
var exception = assertThrows(CompilerException.class,
() -> getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime1"));
assertThat(exception.getMessage(), matchesPattern(".*Tuple values not allowed for type GeneralizedTime.*"));
}
@Test
void testResolveInvalidQuadrupleValue() {
var body = """
testGeneralizedTime1 GeneralizedTime ::= {1, 1, 1, 1}
""";
var exception = assertThrows(CompilerException.class,
() -> getCompiledValue(body, GeneralizedTimeValue.class, "testGeneralizedTime1"));
assertThat(exception.getMessage(), matchesPattern(".*Quadruple values not allowed for type GeneralizedTime.*"));
}
} |
import { forwardRef, PropsWithChildren, ReactNode } from "react";
// @mui
import { Box } from "@mui/material";
import { useTheme } from "@mui/material/styles";
//
import { StyledLabel } from "./styles";
// ----------------------------------------------------------------------
type TLabelProps = {
color:
| "default"
| "primary"
| "secondary"
| "info"
| "success"
| "warning"
| "error";
variant: "filled" | "outlined" | "ghost" | "soft";
startIcon: ReactNode;
endIcon: ReactNode;
sx: {};
} & PropsWithChildren;
const Label = forwardRef((props: TLabelProps, ref) => {
const {
children,
color = "default",
variant = "soft",
startIcon,
endIcon,
sx,
...other
} = props;
const theme = useTheme();
const iconStyle = {
width: 16,
height: 16,
"& svg, img": { width: 1, height: 1, objectFit: "cover" },
};
return (
<StyledLabel
ref={ref}
component="span"
// ownerState={{ color, variant }}
sx={{
...(startIcon && { pl: 0.75 }),
...(endIcon && { pr: 0.75 }),
...sx,
}}
theme={theme}
{...other}
>
{startIcon && <Box sx={{ mr: 0.75, ...iconStyle }}> {startIcon} </Box>}
{children}
{endIcon && <Box sx={{ ml: 0.75, ...iconStyle }}> {endIcon} </Box>}
</StyledLabel>
);
});
export default Label; |
const request = require("supertest");
const app = require("../server.js"); // Import your Express app
const dao = require("../backend/aws.js"); // Import your data access object
// Mock the dao's listFilesFromBucket function
jest.mock("../backend/aws.js", () => {
return {
listFilesFromBucket: jest.fn(),
loadFileFromBucket: jest.fn(),
createStorageEngine: jest.fn(),
putFileOnBucket: jest.fn(),
};
});
describe("Testing /api/register endpoint", () => {
const newParticipant = {
firstName: "anna maria",
lastName: "doe",
contact: "john.doe@example.com",
pwd: "",
school: "",
attendance: "Yes",
};
it("should return a 500 response when User-Agent header is missing", async () => {
const response = await request(app)
.post("/api/register")
.attach("profilePhoto1998", "README.md")
.field("firstName", newParticipant.firstName)
.field("lastName", newParticipant.lastName)
.set("Authorization", "Basic someBase64String");
expect(response.status).toBe(500);
expect(response.type).toBe("application/json");
expect(response.body).toStrictEqual({ error: "Invalid Username" });
});
it("should return a 500 response when participants limit is reached", async () => {
// Mock dao.loadFileFromBucket to return a large participant list
const largeParticipantsList = {
Body: JSON.stringify(new Array(201).fill({})), // Simulate 200 participants
};
dao.loadFileFromBucket.mockResolvedValue(largeParticipantsList);
const response = await request(app)
.post("/api/register")
.attach("profilePhoto1998", "README.md")
.field("firstName", newParticipant.firstName)
.field("lastName", newParticipant.lastName)
.set("User-Agent", "anAgent")
.set("Authorization", "Basic someBase64String");
expect(response.status).toBe(500);
expect(response.type).toBe("application/json");
expect(response.body).toStrictEqual({ message: "Server is Full" });
});
// Test the successful registration scenario
it("should return a 201 response and register a new participant", async () => {
// Define a mock response from loadFileFromBucket
const mockResponse = {
Body: JSON.stringify([]),
};
// Mock the loadFileFromBucket function to resolve with the mock response
dao.loadFileFromBucket.mockResolvedValue(mockResponse);
const response = await request(app)
.post("/api/register")
//.attach("profilePhoto1998", "image1998.jpeg")
//.attach("profilePhoto2023", "image2023.jpeg")
.field("firstName", newParticipant.firstName)
.field("lastName", newParticipant.lastName)
.field("contact", newParticipant.contact)
.field("attendance", newParticipant.attendance)
.set("User-Agent", "anAgent")
.set("Authorization", "Basic someBase64String");
expect(response.status).toBe(201);
expect(response.type).toBe("application/json");
expect(response.body).toStrictEqual({ message: "Participant registered successfully" });
});
// Test the successful update participant scenario
it("should return a 200 response and update an existing participant", async () => {
// Define a mock response from loadFileFromBucket
const mockResponse = {
Body: JSON.stringify([
{ firstName: "anna-maria", lastName: "Doe", attendance: "No", contact: "", school: "1o", pwd: "" },
{ firstName: "Jane", lastName: "Doe", attendance: "Yes", contact: "", school: "2o", pwd: "" },
]),
};
// Mock the loadFileFromBucket function to resolve with the mock response
dao.loadFileFromBucket.mockResolvedValue(mockResponse);
const response = await request(app)
.post("/api/register")
//.attach("profilePhoto1998", "image1998.jpeg")
//.attach("profilePhoto2023", "image2023.jpeg")
.field("firstName", newParticipant.firstName)
.field("lastName", newParticipant.lastName)
.field("contact", newParticipant.contact)
.field("attendance", newParticipant.attendance)
.set("User-Agent", "anAgent")
.set("Authorization", "Basic someBase64String");
expect(response.status).toBe(200);
expect(response.type).toBe("application/json");
expect(response.body).toStrictEqual({ message: "Participant updated successfully" });
});
});
describe("GET /api/participants", () => {
it("responds with JSON containing participants", async () => {
// Define a mock response from loadFileFromBucket
const mockResponse = {
Body: JSON.stringify([
{ firstName: "John", lastName: "Doe", school: "1o", pwd: "random" },
{ firstName: "Jane", lastName: "Doe", school: "2o", pwd: "random2" },
{ firstName: "John", lastName: "Smith", school: "2o" },
{ firstName: "Νίκος", lastName: "Γκιούλος", school: "2o" },
{ firstName: "ΝΙΚΟΣ", lastName: "ΦΙΛΛΙΠΟΥ", school: "2o" },
]),
};
// Mock the loadFileFromBucket function to resolve with the mock response
dao.loadFileFromBucket.mockResolvedValue(mockResponse);
const response = await request(app).get("/api/participants");
expect(response.status).toBe(200);
expect(response.type).toBe("application/json");
// Add more assertions based on your specific data structure
// For example, if you expect an array of participants:
expect(Array.isArray(response.body)).toBe(true);
// You can also check for specific properties in each participant object
for (const participant of response.body) {
expect(participant).toHaveProperty("firstName");
expect(participant).toHaveProperty("lastName");
expect(participant).toHaveProperty("school");
expect(participant).not.toHaveProperty("pwd");
}
});
});
describe("Testing /api/participant-photos/:participantName/:photoName endpoint", () => {
it("should respond with a photo when found", async () => {
// Define a mock response from loadFileFromBucket
const mockResponse = {
Body: Buffer.from("Sample image data", "utf-8"),
};
// Mock the loadFileFromBucket function to resolve with the mock response
dao.loadFileFromBucket.mockResolvedValue(mockResponse);
const response = await request(app).get("/api/participant-photos/doe_john/photoProfile1998");
expect(response.status).toBe(200);
expect(response.type).toBe("image/jpeg");
expect(response.body).toStrictEqual(mockResponse.Body);
});
it("should respond with a 404 when photo is not found", async () => {
// Define a mock response from loadFileFromBucket
const mockResponse = new Error("Photo not found");
// Mock the loadFileFromBucket function to reeject with the mock response
dao.loadFileFromBucket.mockRejectedValue(mockResponse);
const response = await request(app).get("/api/participant-photos/bad_name/photoProfile1998");
expect(response.status).toBe(404);
});
});
describe("GET /admin/uploadedphotos", () => {
it("should return a list of uploaded photos", async () => {
// Define a mock response from listFilesFromBucket
const mockResponse = {
Contents: [
{ Key: "photo1.jpg", LastModified: "2" },
{ Key: "photo2.jpg", LastModified: "3" },
],
};
// Mock the listFilesFromBucket function to resolve with the mock response
dao.listFilesFromBucket.mockResolvedValue(mockResponse);
// Make a GET request to the endpoint using Supertest
const res = await request(app).get("/admin/uploadedphotos");
// Assertions
expect(res.status).toBe(200);
expect(res.body.allUploadedPhotos).toEqual(["photo1.jpg", "photo2.jpg"]);
});
it("should handle errors and return a 500 status", async () => {
// Mock the listFilesFromBucket function to reject with an error
dao.listFilesFromBucket.mockRejectedValue(new Error("An error occurred"));
// Make a GET request to the endpoint using Supertest
const res = await request(app).get("/admin/uploadedphotos");
// Assertions
expect(res.status).toBe(500);
expect(res.text).toBe("Error fetching uploaded photos");
});
});
describe("POST /api/comments", () => {
it("should add a new comment and return it", async () => {
const mockLoadFileFromBucket = dao.loadFileFromBucket;
const mockPutFileOnBucket = dao.putFileOnBucket;
mockLoadFileFromBucket.mockResolvedValue({
Body: JSON.stringify([]), // Assuming comments.json is initially empty
});
mockPutFileOnBucket.mockResolvedValue({});
// Define the request payload
const comment = {
title: "Test Title",
author: "Test Author",
message: "Test Message",
photoName: "Test Photo",
};
// Send a POST request to the endpoint with the payload
const response = await request(app).post("/api/comments").send(comment).set("Accept", "application/json");
console.log(response.body);
// Assert that the response status code is 201 (Created)
expect(response.status).toBe(201);
// Assert that the response body matches the expected comment
expect(response.body).toEqual({
...comment,
timestamp: expect.any(String), // Check if timestamp is a string
});
// Assert that the DAO methods were called correctly
expect(mockLoadFileFromBucket).toHaveBeenCalledWith("db/comments.json");
expect(mockPutFileOnBucket).toHaveBeenCalledWith("db/comments.json", JSON.stringify([response.body]));
});
it("should return a 400 error if required fields are missing", async () => {
// Define a request payload with missing fields
const invalidComment = {
title: "Test Comment",
};
// Send a POST request to the endpoint with the invalid payload
const response = await request(app).post("/api/comments").send(invalidComment).set("Accept", "application/json");
// Assert that the response status code is 400 (Bad Request)
expect(response.status).toBe(400);
// Assert that the response contains an error message
expect(response.body).toEqual({
error: "Συντάκτης και Μήνυμα είναι υποχρεωτικά πεδία",
});
});
});
describe("GET /api/comments", () => {
it("should return a list of comments with default pagination", async () => {
// Mock DAO method to return expected response
const mockLoadFileFromBucket = dao.loadFileFromBucket;
const comments = [
{ title: "Comment 1", author: "Author 1", message: "Message 1" },
{ title: "Comment 2", author: "Author 2", message: "Message 2" },
// Add more comments as needed
];
mockLoadFileFromBucket.mockResolvedValue({
Body: JSON.stringify(comments),
});
// Send a GET request to the endpoint
const response = await request(app).get("/api/comments").set("Accept", "application/json");
// Assert that the response status code is 200 (OK)
expect(response.status).toBe(200);
// Assert that the response body contains comments with default pagination
expect(response.body).toEqual(comments.slice(0, 100)); // Default pageSize is 100
});
it("should return a list of comments with custom pagination", async () => {
// Mock DAO method to return expected response
const mockLoadFileFromBucket = dao.loadFileFromBucket;
const comments = [
{ title: "Comment 1", author: "Author 1", message: "Message 1" },
{ title: "Comment 2", author: "Author 2", message: "Message 2" },
// Add more comments as needed
];
mockLoadFileFromBucket.mockResolvedValue({
Body: JSON.stringify(comments),
});
// Define custom pagination parameters
const pageSize = 50;
const pageNumber = 2;
// Send a GET request to the endpoint with custom pagination parameters
const response = await request(app)
.get(`/api/comments?pageSize=${pageSize}&pageNumber=${pageNumber}`)
.set("Accept", "application/json");
// Calculate the expected comments for the custom pagination
const startIndex = (pageNumber - 1) * pageSize;
const endIndex = startIndex + pageSize;
const expectedComments = comments.slice(startIndex, endIndex);
// Assert that the response status code is 200 (OK)
expect(response.status).toBe(200);
// Assert that the response body contains comments with custom pagination
expect(response.body).toEqual(expectedComments);
});
it("should handle errors when loading comments", async () => {
// Mock DAO method to simulate an error
const mockLoadFileFromBucket = dao.loadFileFromBucket;
mockLoadFileFromBucket.mockRejectedValue(new Error("Failed to load comments"));
// Send a GET request to the endpoint
const response = await request(app).get("/api/comments").set("Accept", "application/json");
// Assert that the response status code is 500 (Internal Server Error)
expect(response.status).toBe(500);
// Assert that the response body contains an error message
expect(response.body).toEqual({ error: "Comments not supported" });
});
});
describe("GET /api/photos/:photoName/comments", () => {
it("should return comments for a specific photo with default pagination", async () => {
// Mock DAO method to return expected response
const mockLoadFileFromBucket = dao.loadFileFromBucket;
const photoName = "example.jpg";
const comments = [
{ title: "Comment 1", author: "Author 1", message: "Message 1", photoName: `/photos/${photoName}` },
{ title: "Comment 2", author: "Author 2", message: "Message 2", photoName: `/photos/${photoName}` },
// Add more comments for the specific photo as needed
];
mockLoadFileFromBucket.mockResolvedValue({
Body: JSON.stringify(comments),
});
// Send a GET request to the endpoint for the specific photo with default pagination
const response = await request(app).get(`/api/photos/${photoName}/comments`).set("Accept", "application/json");
// Assert that the response status code is 200 (OK)
expect(response.status).toBe(200);
// Assert that the response body contains comments for the specific photo with default pagination
expect(response.body).toEqual(comments.slice(0, 10)); // Default pageSize is 10
});
it("should return comments for a specific photo with custom pagination", async () => {
// Mock DAO method to return expected response
const mockLoadFileFromBucket = dao.loadFileFromBucket;
const photoName = "example.jpg";
const comments = [
{ title: "Comment 1", author: "Author 1", message: "Message 1", photoName: `/photos/${photoName}` },
{ title: "Comment 2", author: "Author 2", message: "Message 2", photoName: `/photos/${photoName}` },
// Add more comments for the specific photo as needed
];
mockLoadFileFromBucket.mockResolvedValue({
Body: JSON.stringify(comments),
});
// Define custom pagination parameters
const pageSize = 5;
const pageNumber = 2;
// Send a GET request to the endpoint for the specific photo with custom pagination
const response = await request(app)
.get(`/api/photos/${photoName}/comments?pageSize=${pageSize}&pageNumber=${pageNumber}`)
.set("Accept", "application/json");
// Calculate the expected comments for the custom pagination
const startIndex = (pageNumber - 1) * pageSize;
const endIndex = startIndex + pageSize;
const expectedComments = comments.slice(startIndex, endIndex);
// Assert that the response status code is 200 (OK)
expect(response.status).toBe(200);
// Assert that the response body contains comments for the specific photo with custom pagination
expect(response.body).toEqual(expectedComments);
});
it("should handle errors when loading comments", async () => {
// Mock DAO method to simulate an error
const mockLoadFileFromBucket = dao.loadFileFromBucket;
mockLoadFileFromBucket.mockRejectedValue(new Error("Failed to load comments"));
// Send a GET request to the endpoint
const response = await request(app).get("/api/photos/example.jpg/comments").set("Accept", "application/json");
// Assert that the response status code is 500 (Internal Server Error)
expect(response.status).toBe(500);
// Assert that the response body contains an error message
expect(response.body).toEqual({ error: "Photo Comments not supported" });
});
});
describe("GET /api/photos", () => {
it("should return recent photo URLs", async () => {
// Mock DAO method to return a list of photo objects
const mockListFilesFromBucket = dao.listFilesFromBucket;
const photoObjects = [
{ Key: "photos/photo1.jpg", LastModified: new Date("2023-01-01T12:00:00Z") },
{ Key: "photos/photo2.jpg", LastModified: new Date("2023-01-02T12:00:00Z") },
{ Key: "photos/photo3.jpg", LastModified: new Date("2023-01-03T12:00:00Z") },
// Add more photo objects as needed
];
mockListFilesFromBucket.mockResolvedValue({
Contents: photoObjects,
});
// Send a GET request to the endpoint
const response = await request(app).get("/api/photos").set("Accept", "application/json");
// Assert that the response status code is 200 (OK)
expect(response.status).toBe(200);
// Assert that the response contains expected photo URLs with proper sorting
expect(response.body.photoURLs).toEqual([
"api/photos/photo3.jpg",
"api/photos/photo2.jpg",
"api/photos/photo1.jpg",
]);
});
it("should handle errors when listing photos", async () => {
// Mock DAO method to simulate an error
const mockListFilesFromBucket = dao.listFilesFromBucket;
mockListFilesFromBucket.mockRejectedValue(new Error("Failed to list photos"));
// Send a GET request to the endpoint
const response = await request(app).get("/api/photos").set("Accept", "application/json");
// Assert that the response status code is 500 (Internal Server Error)
expect(response.status).toBe(500);
// Assert that the response body contains an error message
expect(response.body).toEqual({ error: "Error fetching photos" });
});
});
describe("GET /api/photos/:photoName", () => {
it("should return the requested photo", async () => {
const mockLoadFileFromBucket = dao.loadFileFromBucket;
// Define a mock photo object
const mockPhoto = {
Body: Buffer.from("Mock photo data", "utf-8"), // Replace with your mock photo data
};
// Mock DAO method to return the mock photo
mockLoadFileFromBucket.mockResolvedValue(mockPhoto);
// Send a GET request to the endpoint with a mock photo name
const response = await request(app).get("/api/photos/mockphoto.jpg").set("Accept", "image/jpeg"); // Set the expected content type
// Assert that the response status code is 200 (OK)
expect(response.status).toBe(200);
// Assert that the response content type is image/jpeg
expect(response.header["content-type"]).toBe("image/jpeg");
// Assert that the response body matches the mock photo data
expect(response.body.equals(mockPhoto.Body)).toBe(true);
});
it("should handle errors when the requested photo is not found", async () => {
const mockLoadFileFromBucket = dao.loadFileFromBucket;
// Mock DAO method to simulate a "photo not found" error
mockLoadFileFromBucket.mockRejectedValue(new Error("Photo not found"));
// Send a GET request to the endpoint with a non-existent photo name
const response = await request(app).get("/api/photos/nonexistent.jpg").set("Accept", "image/jpeg"); // Set the expected content type
// Assert that the response status code is 404 (Not Found)
expect(response.status).toBe(404);
// Assert that the response body contains an error message
expect(response.body).toEqual({ error: "Photo not found" });
});
}); |
<template lang="pug">
card-container.c-modal-review(title="Move To" ref="modalWindow")
template(#controls)
c-button(type="icon" iconL="close" size="small" @click="closeModal()")
template(#content)
.grid-6
c-select(label="Destination" v-model="selectedId" :errors="errors.dir" :data="items" required)
template(#footer)
c-button(title="Cancel" type="link" @click="closeModal()")
c-button(title="Confirm" type="primary" @click="MoveToRecord()")
</template>
<script>
import { ref, inject, onMounted } from 'vue'
import cSelect from '~/components/Inputs/cSelect.vue'
import useModals from '~/store/Modals.js'
import { onClickOutside } from '@vueuse/core'
import { manualApi } from '~/core/api.js'
import { validates } from '~/core/utils.js'
import { required } from '@vuelidate/validators'
import UseData from '~/store/Data.js'
export default {
components: { cSelect },
props: {
modalId: {
type: String,
required: true
},
id: {
type: String,
default: '',
required: false
},
folderId: {
type: String,
default: '',
required: false
},
callback: {
type: Function,
default: () => 1,
required: false
}
},
setup (props) {
const records = new UseData('records')
const notification = inject('notification')
const modalWindow = ref(null)
const errors = ref({})
const { deleteModal } = useModals()
const selectedId = ref(null)
const items = ref([])
const selectedStatus = ref(null)
const closeModal = () => deleteModal(props.modalId)
onClickOutside(modalWindow, () => {
closeModal()
})
const rule = { dir: { required } }
const MoveToRecord = async () => {
errors.value = await validates(rule, { dir: selectedId.value })
if (Object.keys(errors.value).length > 0) return
try {
await records.updateDocument(props.id, { folderId: selectedId.value })
notification({
type: 'success',
title: 'Success',
message: `${selectedStatus.value} has been moved`
})
props.callback()
} catch (error) {
console.error(error)
notification({
type: 'error',
title: 'Error',
message: `${selectedStatus.value} has not been moved. Please try again.`
})
} finally {
closeModal()
}
}
const getDirectories = async () => {
const res = await manualApi({ method: 'GET', url: 'records/movetoDirs' })
if (res.dirs.length) items.value = [{ value: 'root', title: '.root', name: '' }]
items.value = [
...items.value, ...res.dirs
]
items.value.forEach(item => {
for (let i = 0; i < item.name.split('/').length - 1; i++) item.title = `-- ${item.title}`
})
}
onMounted(async () => {
await records.readDocuments(props.id)
selectedStatus.value = records.getDocument().value.status === 'folder' ? 'Folder' : 'File'
await getDirectories()
})
return { modalWindow, closeModal, errors, selectedId, items, MoveToRecord }
}
}
</script> |
<div class="reg-form">
<h1 mat-dialog-title>New User Registration</h1>
<div mat-dialog-content>
<form #registerForm="ngForm" (submit)="registerDoctor()">
<div>
<mat-form-field style="margin-right:10px">
<mat-label>Firstname</mat-label>
<input matInput type="text" name="firstname" #firstname="ngModel" [(ngModel)]="registerUser.firstname" required>
<span class="span-color" *ngIf="firstname.errors?.['required'] && firstname.touched">Firstname is required</span>
</mat-form-field>
<mat-form-field>
<mat-label>Lastname</mat-label>
<input matInput type="text" name="lastname" #lastname="ngModel" [(ngModel)]="registerUser.lastname" required>
<span class="span-color" *ngIf="lastname.errors?.['required'] && lastname.touched">Lastname is required</span>
</mat-form-field>
</div>
<div>
<mat-form-field style="margin-right:10px">
<mat-label>Password</mat-label>
<input matInput type="password" name="regPassword" #regPassword="ngModel" [(ngModel)]="registerUser.password" required>
<span class="span-color" *ngIf="regPassword.errors?.['required'] && regPassword.touched">Password is required</span>
</mat-form-field>
<mat-form-field>
<mat-label>Password Confirmation</mat-label>
<input matInput type="password" name="passwordConf" #passwordConf="ngModel" [(ngModel)]="passwordConfirmation" required>
<span class="span-color" *ngIf="passwordConf.errors?.['required'] && passwordConf.touched">The password confirmation is required</span>
<span class="span-color" *ngIf="passwordConf.value !== this.registerUser.password && passwordConf.touched">The password confirmation must match your password</span>
</mat-form-field>
</div>
<div>
<mat-label>Profile Picture</mat-label>
<input type="file" name="pic" #picture="ngModel" [(ngModel)]="pic" (change)="onFileSelected($event)" required>
<span class="span-color" *ngIf="picture.errors?.['required'] && picture.touched">Profile picture is required</span>
</div>
<div>
<mat-form-field style="margin-right:10px">
<mat-label>Role (Doctor, Administrator or Patient)</mat-label>
<mat-select #role="ngModel" [(ngModel)]="registerUser.roleName" name="role" required>
<mat-option value="Doctor">Doctor</mat-option>
<mat-option value="Patient">Patient</mat-option>
<mat-option value="Admin">Administrator</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label>Medical Speciality</mat-label>
<mat-select #speciality="ngModel" [(ngModel)]="registerUser.speciality" name="speciality" required>
<mat-option *ngFor="let speciality of specialities" [value]="speciality">{{speciality}}</mat-option>
</mat-select>
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-raised-button type="submit" class="reg-btn" [disabled]="registerForm.invalid" color="primary">Register</button>
</div>
</form>
</div>
</div> |
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:html5="http://xmlns.jcp.org/jsf/passthrough"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core">
<h:head>
<meta charset="UTF-8"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"/>
<title>Sign In | Bootstrap Based Admin Template - Material Design</title>
<!-- Favicon-->
<link rel="icon" href="../../favicon.ico" type="image/x-icon"/>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css"/>
<!-- Bootstrap Core Css -->
<link href="plugins/bootstrap/css/bootstrap.css" rel="stylesheet"/>
<!-- Waves Effect Css -->
<link href="plugins/node-waves/waves.css" rel="stylesheet" />
<!-- Animation Css -->
<link href="plugins/animate-css/animate.css" rel="stylesheet" />
<!-- Custom Css -->
<link href="css/style.css" rel="stylesheet"/>
</h:head>
<h:body class="signup-page" style="background-image: url(http://labarberia.com/wp-content/uploads/2019/12/bg_barberia.jpg)">
<div class="signup-box">
<div class="logo">
<center>
</center>
</div>
<div class="card">
<div class="body">
<h:form id="sign_up">
<div class="msg">
<img src="images/AYT.png" alt="Logo de Codigo Genial" width="100"/>
<a href="javascript:void(0);" style="font-size: 20px;"><b>AyT Information</b></a>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">pan_tool</i>
</span>
<div class="form-line">
<h:inputText id="regisId" requiredMessage="Ingrese su numero de identificación" html5:autofocus="autofocus" html5:placeholder="Numero de identificación" html5:type="text" value="#{inicioRequest.objusu.numIdentificacion}" required="true" class="form-control"/>
<h:message style="color:red" for="regisId"></h:message>
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">account_circle</i>
</span>
<div class="form-line">
<h:inputText id="regisNombre" requiredMessage="Ingrese su nombre" class="form-control" html5:type="text" value="#{inicioRequest.objusu.nombres}" required="true" html5:placeholder="Nombres" />
<h:message style="color:red" for="regisNombre"></h:message>
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">account_circle</i>
</span>
<div class="form-line">
<h:inputText id="regisApellido" requiredMessage="Ingrese sus apellidos" html5:placeholder="Apellidos" class="form-control" value="#{inicioRequest.objusu.apellidos}" required="true" />
<h:message style="color:red" for="regisApellido"></h:message>
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">contact_phone</i>
</span>
<div class="form-line">
<h:inputText id="regisTelefono" requiredMessage="Ingrese su numero de telefono" html5:type="number" class="form-control" value="#{inicioRequest.objusu.telefono}" required="true" html5:placeholder="3154520992"/>
<h:message style="color:red" for="regisTelefono"></h:message>
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">place</i>
</span>
<div class="form-line">
<h:inputText id="regisDireccion" requiredMessage="Ingrese su dirección" html5:placeholder="Calle 10 sur #38-70" value="#{inicioRequest.objusu.direccion}" required="true" class="form-control"/>
<h:message style="color:red" for="regisDireccion"></h:message>
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">email</i>
</span>
<div class="form-line">
<h:inputText id="regisCorreo" requiredMessage="Ingrese un correo electronico " html5:placeholder="ejemplo@gmail.com" value="#{inicioRequest.objusu.email}" required="true" class="form-control" />
<h:message style="color:red" for="regisCorreo"></h:message>
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">lock</i>
</span>
<div class="form-line">
<h:inputSecret id="regisContrasena" requiredMessage="Ingrese su contraseña" html5:placeholder="*******" value="#{inicioRequest.objusu.contrasena}" required="true" class="form-control" />
<h:message style="color:red" for="regisContrasena"></h:message>
</div>
</div>
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">wc</i>
</span>
<div>
<h:selectOneMenu value="#{inicioRequest.objusu.genero}" class="form-control">
<f:selectItem itemValue="Masculino" itemLabel="Masculino"/>
<f:selectItem itemValue="Femenino" itemLabel="Femenino" />
</h:selectOneMenu>
</div>
</div>
<div class="form-group">
<input type="checkbox" name="terms" id="terms" class="filled-in chk-col-pink"/>
<label for="terms">Acepta las politicas de privacidad<a href="javascript:void(0);"> terminos y condiciones</a>.</label>
</div>
<h:commandButton value="Registrar" action="#{inicioRequest.registrarUserFuera()}" class="btn btn-block btn-lg bg-pink waves-effect"/>
<div class="m-t-25 m-b--5 align-center">
<a href="index_1.xhtml">Ya tienes una cuenta</a>
</div>
</h:form>
</div>
</div>
</div>
<!-- Jquery Core Js -->
<script src="plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap Core Js -->
<script src="plugins/bootstrap/js/bootstrap.js"></script>
<!-- Waves Effect Plugin Js -->
<script src="plugins/node-waves/waves.js"></script>
<!-- Validation Plugin Js -->
<script src="plugins/jquery-validation/jquery.validate.js"></script>
<!-- Custom Js -->
<script src="js/admin.js"></script>
<script src="js/pages/examples/sign-in.js"></script>
</h:body>
</html> |
/************************************************************************
**
** Copyright (C) 2012 John Schember <john@nachtimwald.com>
** Copyright (C) 2012 Dave Heiland
**
** This file is part of Sigil.
**
** Sigil is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** Sigil 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 Sigil. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include "Dialogs/SelectImages.h"
#include "Misc/SettingsStore.h"
static const int COL_NAME = 0;
static const int COL_IMAGE = 1;
static const int THUMBNAIL_SIZE = 100;
static const int THUMBNAIL_SIZE_INCREMENT = 50;
static QString SETTINGS_GROUP = "select_images";
SelectImages::SelectImages(QString basepath, QList<Resource *> image_resources, QString default_selected_image, QWidget *parent) :
QDialog(parent),
m_Basepath(basepath),
m_ImageResources(image_resources),
m_SelectImagesModel(new QStandardItemModel),
m_PreviewLoaded(false),
m_DefaultSelectedImage(default_selected_image),
m_ThumbnailSize(THUMBNAIL_SIZE)
{
ui.setupUi(this);
ReadSettings();
SetImages();
connectSignalsSlots();
}
QStringList SelectImages::SelectedImages()
{
QList<QString> selected_images;
// Shift-click order is top to bottom regardless of starting position
// Ctrl-click order is first clicked to last clicked (included shift-clicks stay ordered as is)
if (ui.imageTree->selectionModel()->hasSelection()) {
QModelIndexList selected_indexes = ui.imageTree->selectionModel()->selectedRows(0);
foreach (QModelIndex index, selected_indexes) {
selected_images.append(m_SelectImagesModel->itemFromIndex(index)->text());
}
}
return selected_images;
}
void SelectImages::SetImages()
{
m_SelectImagesModel->clear();
QStringList header;
header.append(tr("Name" ));
if (m_ThumbnailSize) {
header.append(tr("Images"));
}
m_SelectImagesModel->setHorizontalHeaderLabels(header);
ui.imageTree->setSelectionBehavior(QAbstractItemView::SelectRows);
ui.imageTree->setModel(m_SelectImagesModel);
QSize icon_size(m_ThumbnailSize, m_ThumbnailSize);
ui.imageTree->setIconSize(icon_size);
int row = 0;
foreach (Resource *resource, m_ImageResources) {
QString filepath = "../" + resource->GetRelativePathToOEBPS();
QList<QStandardItem *> rowItems;
QStandardItem *name_item = new QStandardItem();
name_item->setText(resource->Filename());
name_item->setToolTip(filepath);
name_item->setEditable(false);
rowItems << name_item;
if (m_ThumbnailSize) {
QPixmap pixmap(resource->GetFullPath());
if (pixmap.height() > m_ThumbnailSize || pixmap.width() > m_ThumbnailSize) {
pixmap = pixmap.scaled(QSize(m_ThumbnailSize, m_ThumbnailSize), Qt::KeepAspectRatio);
}
QStandardItem *icon_item = new QStandardItem();
icon_item->setIcon(QIcon(pixmap));
icon_item->setEditable(false);
rowItems << icon_item;
}
m_SelectImagesModel->appendRow(rowItems);
row++;
}
ui.imageTree->header()->setStretchLastSection(true);
for (int i = 0; i < ui.imageTree->header()->count(); i++) {
ui.imageTree->resizeColumnToContents(i);
}
FilterEditTextChangedSlot(ui.Filter->text());
SelectDefaultImage();
}
void SelectImages::SelectDefaultImage()
{
QStandardItem *root_item = m_SelectImagesModel->invisibleRootItem();
QModelIndex parent_index;
for (int row = 0; row < root_item->rowCount(); row++) {
if (root_item->child(row, COL_NAME)->text() == m_DefaultSelectedImage) {
ui.imageTree->selectionModel()->select(m_SelectImagesModel->index(row, 0, parent_index), QItemSelectionModel::Select | QItemSelectionModel::Rows);
ui.imageTree->setCurrentIndex(root_item->child(row, 0)->index());
SetPreviewImage();
break;
}
}
}
void SelectImages::IncreaseThumbnailSize()
{
m_ThumbnailSize += THUMBNAIL_SIZE_INCREMENT;
ui.ThumbnailDecrease->setEnabled(true);
m_DefaultSelectedImage = GetLastSelectedImageName();
SetImages();
}
void SelectImages::DecreaseThumbnailSize()
{
m_ThumbnailSize -= THUMBNAIL_SIZE_INCREMENT;
if (m_ThumbnailSize <= 0) {
m_ThumbnailSize = 0;
ui.ThumbnailDecrease->setEnabled(false);
}
m_DefaultSelectedImage = GetLastSelectedImageName();
SetImages();
}
void SelectImages::ReloadPreview()
{
// Make sure we don't load when initial painting is resizing
if (m_PreviewLoaded) {
SetPreviewImage();
}
}
void SelectImages::SelectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
{
SetPreviewImage();
}
void SelectImages::SetPreviewImage()
{
QPixmap(pixmap);
QStandardItem *item = GetLastSelectedImageItem();
if (item && !item->text().isEmpty()) {
pixmap = QPixmap(m_Basepath + item->text());
// Set size to match window, with a small border
int width = ui.preview->width() - 10;
int height = ui.preview->height() - 10;
// Resize images before saving - only shrink not enlarge
if (pixmap.height() > height || pixmap.width() > width) {
pixmap = pixmap.scaled(QSize(width, height), Qt::KeepAspectRatio);
}
}
ui.preview->setPixmap(pixmap);
m_PreviewLoaded = true;
}
void SelectImages::FilterEditTextChangedSlot(const QString &text)
{
const QString lowercaseText = text.toLower();
QStandardItem *root_item = m_SelectImagesModel->invisibleRootItem();
QModelIndex parent_index;
// Hide rows that don't contain the filter text
int first_visible_row = -1;
for (int row = 0; row < root_item->rowCount(); row++) {
if (text.isEmpty() || root_item->child(row, COL_NAME)->text().toLower().contains(lowercaseText)) {
ui.imageTree->setRowHidden(row, parent_index, false);
if (first_visible_row == -1) {
first_visible_row = row;
}
}
else {
ui.imageTree->setRowHidden(row, parent_index, true);
}
}
if (!text.isEmpty() && first_visible_row != -1) {
// Select the first non-hidden row
ui.imageTree->setCurrentIndex(root_item->child(first_visible_row, 0)->index());
}
else {
// Clear current and selection, which clears preview image
ui.imageTree->setCurrentIndex(QModelIndex());
}
}
QStandardItem* SelectImages::GetLastSelectedImageItem()
{
QStandardItem *item = NULL;
if (ui.imageTree->selectionModel()->hasSelection()) {
QModelIndexList selected_indexes = ui.imageTree->selectionModel()->selectedRows(0);
if (!selected_indexes.isEmpty()) {
item = m_SelectImagesModel->itemFromIndex(selected_indexes.last());
}
}
return item;
}
QString SelectImages::GetLastSelectedImageName()
{
QString selected_entry = "";
QStandardItem *item = GetLastSelectedImageItem();
if (item) {
selected_entry = item->text();
}
return selected_entry;
}
void SelectImages::ReadSettings()
{
SettingsStore settings;
settings.beginGroup(SETTINGS_GROUP);
// The size of the window and it's full screen status
QByteArray geometry = settings.value("geometry").toByteArray();
if (!geometry.isNull()) {
restoreGeometry(geometry);
}
// The position of the splitter handle
QByteArray splitter_position = settings.value("splitter").toByteArray();
if (!splitter_position.isNull()) {
ui.splitter->restoreState(splitter_position);
}
// The thumbnail size
m_ThumbnailSize = settings.value("thumbnail_size").toInt();
if (m_ThumbnailSize <= 0) {
ui.ThumbnailDecrease->setEnabled(false);
}
settings.endGroup();
}
void SelectImages::WriteSettings()
{
SettingsStore settings;
settings.beginGroup(SETTINGS_GROUP);
// The size of the window and it's full screen status
settings.setValue("geometry", saveGeometry());
// The position of the splitter handle
settings.setValue("splitter", ui.splitter->saveState());
// The thumbnail size
settings.setValue("thumbnail_size", m_ThumbnailSize);
settings.endGroup();
}
void SelectImages::connectSignalsSlots()
{
QItemSelectionModel* selectionModel = ui.imageTree->selectionModel();
connect(selectionModel, SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)),
this, SLOT(SelectionChanged(const QItemSelection&, const QItemSelection&)));
connect(ui.imageTree, SIGNAL(doubleClicked(const QModelIndex &)), this, SLOT(accept()));
connect(this, SIGNAL(accepted()), this, SLOT(WriteSettings()));
connect(ui.Filter, SIGNAL(textChanged(QString)),
this, SLOT(FilterEditTextChangedSlot(QString)));
connect(ui.ThumbnailIncrease, SIGNAL(clicked()), this, SLOT(IncreaseThumbnailSize()));
connect(ui.ThumbnailDecrease, SIGNAL(clicked()), this, SLOT(DecreaseThumbnailSize()));
connect(ui.preview, SIGNAL(Resized()), this, SLOT(ReloadPreview()));
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
/* 注意点:width和height属性默认设置的是内容区域的大小 */
width: 380px;
height: 380px;
background-color: green;
/* 注意点:border会把盒子撑大 */
border: 10px solid #000;
/*
盒子的实际大小(宽度)=左边框+内容的宽度+右边框
= 10+400+10
= 420
解决:现在是420 , 要求400 ,多出了20px
手动内减:计算出多余的部分之后,手动在内容中减去即可
*/
}
</style>
</head>
<body>
<div></div>
</body>
</html> |
import React, {useState, useEffect} from "react";
import {useDispatch, useSelector} from "react-redux";
import {Formik, Field, Form, ErrorMessage, useField} from "formik";
import * as Yup from "yup";
import {ADD_CONSULTATION_URL} from "../../../utils/Consts";
import RequestInstance from "../../../utils/RequestInstance";
import PatientForm from "./PatientForm";
import OwnerForm from "./OwnerForm";
import ConsultationForm from "./ConsultationForm";
import "./AddConsultationPage.css"
import {useNavigate} from 'react-router-dom';
import moment from "moment";
import TimedPopup from "../../../components/popup/TimedPopup";
//remove the imports that what you don't use.
export default function ConsultationPageForm({preloadedData}) {
const initialValues = {
// patient
patientId: preloadedData.id,
patientName: preloadedData.patientName,
patientBirthdate: preloadedData.patientBirthdate,
patientWeight: preloadedData.patientWeight,
patientType: preloadedData.patientType,
patientSex: preloadedData.patientSex,
patientBreed: preloadedData.patientBreed,
patientColour: preloadedData.patientColour,
// owner
ownerFirstName: preloadedData.owner.firstName,
ownerLastName: preloadedData.owner.lastName,
ownerEmail: preloadedData.owner.email,
ownerAddress: preloadedData.owner.address,
ownerPhone: preloadedData.owner.phone,
//consultation
consultationMainConcern: "",
consultationHistoryOfConcern: "",
consultationDiagnostic: "",
consultationTreatment: "",
consultationExtraNotes: "",
};
const [submitting, setSubmitting] = useState(false);
const [isPopupVisible, setIsPopupVisible] = useState(false);
const [popupMessage, setPopupMessage] = useState("");
const [popupMessageType, setPopupMessageType] = useState("");
function checkNumber(string) {
if (!isNaN(string) && string.toString().indexOf('.') !== -1)
return true;
return /^[0-9]*$/.test(string);
}
const handleAddConsultation = (formValue) => {
const {
//patient
patientId,
patientName,
patientBirthdate,
patientWeight,
patientType,
patientSex,
patientBreed,
patientColour,
// owner
ownerFirstName,
ownerLastName,
ownerEmail,
ownerAddress,
ownerPhone,
//consultation
consultationMainConcern,
consultationHistoryOfConcern,
consultationDiagnostic,
consultationTreatment,
consultationExtraNotes
} = formValue;
if(!checkNumber(patientWeight)){
setIsPopupVisible(true);
setPopupMessage("Weight must be a number!");
setPopupMessageType("error");
return;
}
RequestInstance.post(ADD_CONSULTATION_URL, {
//patient
patientId,
patientName,
patientBirthDate:patientBirthdate,
patientWeight,
patientType,
patientSex,
patientBreed,
patientColor:patientColour,
// owner
ownerFirstName,
ownerLastName,
ownerEmail,
ownerAddress,
ownerPhone,
//consultation
consultationMainConcern,
consultationHistoryOfConcern,
consultationDiagnostic,
consultationTreatment,
consultationExtraNotes,
consultationCreationDate: moment(Date.now()).toDate(),
}).then(r => {
setIsPopupVisible(true);
setPopupMessage("Consultation added successfully! Redirecting...");
setPopupMessageType("success");
setSubmitting(false);
}).catch(error => {
setIsPopupVisible(true);
setPopupMessage(error.response.data.message);
setPopupMessageType("error");
setSubmitting(false);
});
};
const validationSchema = Yup.object().shape({
// PATIENT
patientName: Yup.string()
.test(
"len",
"The patient name must be between 3 and 20 characters.",
(val) =>
val &&
val.toString().length >= 1 &&
val.toString().length <= 20
)
.required("This field is required!"),
patientType: Yup.string()
.required("This field is required!"),
patientBreed: Yup.string()
.required("This field is required!"),
patientColour: Yup.string()
.required("This field is required!"),
patientSex: Yup.string()
.required("This field is required!"),
patientWeight: Yup.string()
.test("value",
"The weight must be between 0 and 2000",
(val) => val >= 0 && val <= 2000)
.required("This field is required!"),
patientAgeYears: Yup.number(),
patientAgeMonths: Yup.number(),
patientBirthdate: Yup.date(), // verify not future?
patientMedicalHistoryBeforeClinic: Yup.string()
.test(
"med-history-len",
"Medical history must be between 0 and 10000 characters",
(val) =>
!val || (
val.toString().length >= 0 &&
val.toString().length <= 10001)
),
// OWNER
ownerFirstName: Yup.string()
.required("This field is required!"),
ownerLastName: Yup.string()
.required("This field is required!"),
ownerEmail: Yup.string()
.email("This is not a valid email.")
.required("This field is required!"),
ownerPhone: Yup.string()
.required("This field is required!"),
ownerAddress: Yup.string()
.required("This field is required!"),
// CONSULTATION
consultationMainConcern: Yup.string()
.required("This field is required!"),
});
return (
<div>
{isPopupVisible &&
<TimedPopup message={popupMessage} isVisible={isPopupVisible} messageType={popupMessageType}
setIsVisible={setIsPopupVisible} redirect={`/medic/dashboard/patient-details/${initialValues.patientId}`} timer={2000}></TimedPopup>}
<div className="add-consultation-form-wrapper">
<div className="consultation-form">
<div className="consulation-form-title">
<h1 className="pt-5"><em>Consultation</em> Form</h1>
</div>
<div>
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
onSubmit={handleAddConsultation}
>
{({errors, touched}) => (
<Form>
<div>
<div className="consultation-form-resize">
<PatientForm errors={errors} touched={touched}/>
<OwnerForm errors={errors} touched={touched}/>
<ConsultationForm errors={errors} touched={touched}/>
</div>
</div>
<div className="consulation-form-group">
<button type="submit" className="consulation-form-submit-button">
{submitting ? "Adding consultation..." : "Add consultation"}
</button>
</div>
</Form>
)}
</Formik>
</div>
</div>
</div>
</div>
);
} |
package com.ldnel;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import java.io.*;
import java.util.ArrayList;
/**
* Created by ldnel_000 on 2015-10-25.
*/
public class Node implements Drawable {
/*
Represents the node in a graph
*/
//Tags used for XML export of node objects
final public static String startTag = "<node>";
final public static String endTag = "</node>";
final public static String IDStartTag = "<id>";
final public static String IDEndTag = "</id>";
final public static String labelStartTag = "<label>";
final public static String labelEndTag = "</label>";
final public static String locationStartTag = "<location>";
final public static String locationEndTag = "</location>";
final public static String selectedTag = "<selected/>"; //node is in selected state
//END PARSING TAGS
public static Font NODE_LABEL_FONT = Font.font("Courier New", FontWeight.BOLD, 30);
public final static int SMALL_NODE_RADIUS = 7;
public final static int MEDIUM_NODE_RADIUS = 20;
public final static int LARGE_NODE_RADIUS = 40;
public static double NODE_RADIUS = 30;
public static Color DEFAULT_NODE_COLOR = Color.CORNFLOWERBLUE;
public static Color NODE_LABEL_COLOR = Color.BLACK;
//instance variables
private int id; //used to represent the node in an data text file
//id's are set just before node is written to data file
private String label;
private Location location; //location of center of node
private boolean isSelected = false;
private ArrayList<Edge> edges;
//construction
public Node(double x, double y) {
//TO DO: should check that x and y are positive
//otherwise throw an exception
location = new Location(x, y);
edges = new ArrayList<Edge>();
}
public Node(Location aLocation) {
//TO DO: should throw exception if aLocation is null
location = aLocation;
edges = new ArrayList<Edge>();
}
public Node(Location aLocation, String aLabel) {
//TO DO: should throw exception if aLoaction is null
location = aLocation;
label = aLabel;
edges = new ArrayList<Edge>();
}
public Node(double x, double y, String aNodeLabel) {
//TO DO: should check that x and y are postive
location = new Location(x, y);
if (aNodeLabel != null && aNodeLabel.trim().length() > 0)
label = aNodeLabel;
edges = new ArrayList<Edge>();
}
//get and set methods
public int getId() {
return id;
}
public void setID(int anID) {
id = anID;
}
public String getLabel() {
return label;
}
public void setLabel(String aLabel) {
label = aLabel.trim();
}
public ArrayList<Edge> getEdges() {
return edges;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selectedIfTrue) {
isSelected = selectedIfTrue;
}
public void toggleSelected() {
isSelected = !isSelected;
}
public Location getLocation() {
return location;
}
public void setLocation(Location aLocation) {
if (aLocation != null) location = aLocation;
}
boolean containsLocation(Location aLocation) {
//answer whether aLocation is withing the drawing area of this node
if (aLocation == null) return false;
return Location.distanceBetween(location, aLocation) < NODE_RADIUS;
}
public void moveDelta(double deltaX, double deltaY) {
//move location by deltaX,deltaY
location.moveDelta(deltaX, deltaY);
}
public void drawWith(GraphicsContext thePen) {
thePen.setFill(DEFAULT_NODE_COLOR);
if (isSelected) thePen.setFill(Drawable.highlightColor);
//draw the node shape
thePen.fillOval(location.getX() - NODE_RADIUS, //upper left X
location.getY() - NODE_RADIUS, //upper left Y
2 * NODE_RADIUS, //width
2 * NODE_RADIUS); //height
//draw label if there is one
if (label != null && label.trim().length() > 0) {
Text theText = new Text(label); //create text object that can be measured
theText.setFont(NODE_LABEL_FONT); //set font of the text object
//get the width and height of the text object
double textWidth = theText.getLayoutBounds().getWidth();
double textHeight = theText.getLayoutBounds().getHeight();
//draw the node label centered on the node
thePen.setFill(NODE_LABEL_COLOR);
thePen.setFont(NODE_LABEL_FONT);
thePen.fillText(label, location.getX() - textWidth / 2, location.getY() + textHeight / 4);
}
}
public void writeToFile(String baseIndent, PrintWriter outputFile) {
//Write the node to a file in XML style tag-delimited data that
//baseIndent is current indentation white space to
// added in front of the tags for formatting
String tab = " ";
String indent = baseIndent + tab;
//write class start tag
outputFile.println(baseIndent + startTag);
//nodes are expected to have a unique ID tag in the XML data
outputFile.println(indent + IDStartTag + id + IDEndTag);
if (this.label != null && !this.label.isEmpty())
outputFile.println(indent + labelStartTag + getLabel() + labelEndTag);
outputFile.println(indent + locationStartTag + location.getX() + "," + location.getY() + locationEndTag);
if (this.isSelected()) outputFile.println(baseIndent + tab + selectedTag);
//write class end tag
outputFile.println(baseIndent + endTag);
}
public static Node parseFromFile(BufferedReader graphXMLDataStream) {
//Parse node data from xml file
// input expected to have the following from
// The start tag will have been stripped off already
//parse until the closing tag is found
/*
<node>
<id>1000</id>
<label>A</label>
<location>100.0,100.0</location>
</node>
*/
if (graphXMLDataStream == null) return null;
Node parsedNode = new Node(0, 0); //dummy location to be replaced
String inputLine; //current input line
String dataString = null;
BufferedReader inputFile;
try {
//parse until we get to the closing tag
while ((inputLine = graphXMLDataStream.readLine()) != null) {
//System.out.println(inputLine);
dataString = inputLine.trim();
if (dataString.startsWith(endTag)) return parsedNode;
else if (dataString.startsWith(IDStartTag) &&
dataString.endsWith(IDEndTag)) {
String theIDString = dataString.substring(
IDStartTag.length(),
dataString.length() - IDEndTag.length()
);
parsedNode.setID(Integer.parseInt(theIDString));
} else if (dataString.startsWith(labelStartTag) &&
dataString.endsWith(labelEndTag)) {
String theLabelString = dataString.substring(
labelStartTag.length(),
dataString.length() - labelEndTag.length()
);
parsedNode.setLabel(theLabelString.trim());
} else if (dataString.startsWith(locationStartTag) &&
dataString.endsWith(locationEndTag)) {
String theLocationString = dataString.substring(
locationStartTag.length(),
dataString.length() - locationEndTag.length()
);
String coordinates[] = theLocationString.split(",");
Location theLocation = new Location(Double.parseDouble(coordinates[0].trim()),
Double.parseDouble(coordinates[1].trim()));
parsedNode.setLocation(theLocation);
} else if (dataString.startsWith(selectedTag)) {
parsedNode.setSelected(true);
}
}
//catch file IO errors
} catch (EOFException e) {
System.out.println("VERSION PARSE Error: EOF encountered, file may be corrupted.");
return null;
} catch (IOException e) {
System.out.println("VERSION PARSE Error: Cannot read from file.");
return null;
}
return null;
}
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<link rel="stylesheet" href="css/style.css"/>
<title>ログイン</title>
<style>
h2 {
margin-top: 0;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
}
.form-group input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.form-group button {
padding: 10px 15px;
background-color: #5cb85c;
border: none;
color: white;
cursor: pointer;
}
.form-group button:hover {
background-color: #4cae4c;
}
</style>
</head>
<body>
<header>
<a href="/" class="header-left">
<img src="pictures/kazu107.png" alt="サイトのアイコン" class="icon">
<span class="site-name">Online Judge by kazu107</span>
</a>
<div id="auth-links">
<!-- 認証リンクがここに挿入されます -->
</div>
</header>
<main>
<div class="title-container">
<h1 class="main-title">ログイン</h1>
<div class="form-group">
<label for="email">メールアドレス</label>
<input type="email" id="email" required>
</div>
<div class="form-group">
<label for="password">パスワード</label>
<input type="password" id="password" required>
</div>
<div class="form-group">
<button id="login">ログイン</button>
</div>
</div>
</main>
<script>
async function fetchWithAuth(url, options = {}) {
let token = localStorage.getItem('token');
options.headers = options.headers || {};
options.headers['Authorization'] = 'Bearer ' + token;
let response = await fetch(url, options);
if (!token) {
return;
}
if (response.status === 401) { // トークンの期限切れ
const refreshToken = localStorage.getItem('refreshToken');
if (!refreshToken) {
window.location.href = '/login.html';
return;
}
const refreshResponse = await fetch('/refresh', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ refreshToken })
});
if (refreshResponse.ok) {
const refreshResult = await refreshResponse.json();
localStorage.setItem('token', refreshResult.accessToken);
localStorage.setItem('refreshToken', refreshResult.refreshToken);
options.headers['Authorization'] = 'Bearer ' + refreshResult.accessToken;
response = await fetch(url, options);
} else {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
window.location.href = '/login.html';
return;
}
}
return response;
}
document.addEventListener('DOMContentLoaded', async () => {
const authLinks = document.getElementById('auth-links');
const response = await fetchWithAuth('/profile');
if (response.ok) {
const user = await response.json();
authLinks.innerHTML = `
<a href="/dashboard.html" class="auth-link"><i class="fas fa-user"></i> ${user.username}</a>
<a href="#" id="logout" class="auth-link"><i class="fas fa-sign-out-alt"></i> ログアウト</a>
`;
document.getElementById('logout').addEventListener('click', () => {
localStorage.removeItem('token');
localStorage.removeItem('refreshToken');
location.reload();
});
} else {
authLinks.innerHTML = `
<a href="/register.html" class="auth-link"><i class="fas fa-user-plus"></i> Register</a>
<a href="/login.html" class="auth-link"><i class="fas fa-sign-in-alt"></i> Login</a>
`;
}
});
</script>
<script>
document.getElementById('login').addEventListener('click', async () => {
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const response = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ email, password })
});
const result = await response.json();
if (response.status === 200) {
localStorage.setItem('token', result.accessToken); // トークンをlocalStorageに保存
localStorage.setItem('refreshToken', result.refreshToken); // リフレッシュトークンをlocalStorageに保存
alert('ログインに成功しました');
// トークンを保存するなどの処理を行う
window.location.href = '/dashboard.html'; // ログイン後のページ
} else {
alert('ログインに失敗しました: ' + result.error);
}
});
</script>
</body>
</html> |
from datetime import datetime
import logging
import holidays
import pandas as pd
def rename_ptax_columns(df_ptax: pd.DataFrame) -> pd.DataFrame:
expected_columns = {
0: 'dt_cotacao',
1: 'cod_moeda',
2: 'tp_moeda',
3: 'sg_moeda',
4: 'vl_taxa_compra',
5: 'vl_taxa_venda',
6: 'vl_paridade_compra',
7: 'vl_paridade_venda'
}
if set(df_ptax.columns) != set(expected_columns.keys()):
raise ValueError(
"DataFrame columns do not match the expected format.")
return df_ptax.rename(columns=expected_columns)
def get_ptax_data(start_date_str: str, end_date_str: str) -> pd.DataFrame:
start_date = datetime.strptime(start_date_str, "%Y-%m-%d")
end_date = datetime.strptime(end_date_str, "%Y-%m-%d")
date_range = pd.date_range(
start=start_date, end=end_date, freq='B')
dfs = []
for current_date in date_range:
if current_date not in holidays.Brazil():
date_string = current_date.strftime("%Y%m%d")
url = (
"https://www4.bcb.gov.br/Download/fechamento/"
f"{date_string}.csv"
)
try:
ptax_data = pd.read_csv(
url, sep=';', encoding='latin1', header=None)
dfs.append(ptax_data)
except Exception as e:
error_message = (
"Error occurred for date "
f"{current_date.strftime('%Y-%m-%d')}: {e}"
)
logging.error(error_message)
if not dfs:
raise ValueError(
"No valid data found between the specified dates.")
df_ptax = pd.concat(dfs, ignore_index=True)
df_ptax = rename_ptax_columns(df_ptax)
df_ptax['dt_cotacao'] = pd.to_datetime(
df_ptax['dt_cotacao'], format='%d/%m/%Y').dt.strftime('%Y-%m-%d')
df_ptax['dt_cotacao'] = pd.to_datetime(
df_ptax['dt_cotacao'], format='%Y-%m-%d')
return df_ptax |
class Admin::ProductsController < Admin::BaseController
before_action :set_product, only: %i[show edit update destroy]
before_action :set_root_categories, only: %i[show new edit]
def index
@title = "Admin - Products"
@products = Product.all
end
def show
@title = "Admin - Product:#{params[:id]}"
end
def new
@title = "Admin - New Product"
@product = Product.new
end
def create
@product = Product.new(product_params)
if @product.save
flash[:success] = "Product was successfully created."
redirect_to admin_products_path
else
flash.now[:warning] = "Product wasn't created!"
render :new
end
end
def edit
@title = "Admin - Product:#{params[:id]}"
end
def update
if @product.update(product_params)
flash[:success] = "Product was successfully updated."
redirect_to admin_product_path(@product)
else
flash.now[:warning] = "Product wasn't updated!"
render :edit
end
end
def destroy
@product.destroy
flash[:success] = "Product was successfully deleted."
redirect_to admin_products_path
end
def remove_product_image
product = Product.find(params[:product_id])
product.image.purge
redirect_back fallback_location: request.referrer
end
private
def product_params
params.require(:product).permit(
:name,
:price,
:quantity,
:image,
:description,
:product_category_id,
:published_at,
:image
)
end
def set_product
@product = Product.find(params[:id])
end
def set_root_categories
@root_categories = ProductCategory.roots
end
end |
require "./common"
require "./novika"
module Novika::Frontend::Nkas
extend self
# Appends information about the tool to *io*.
def help(io)
io << <<-HELP
nkas - Novika image assembler for Novika #{Novika::VERSION}
Syntax:
nkas [switches] [queries] <path/to/output/image.nki>
Switches:
-c Compress with (default: do not compress)
b: Brotli
f Compress quickly (fast)!
b Compress thoroughly (best)!
g: Gzip
f Compress quickly (fast)!
b Compress thoroughly (best)!
Example:
$ nkas -cb:b repl repl.nki
Ok Bundled <yours-may-differ>
Ok Bundled <yours-may-differ>
Ok Bundled <yours-may-differ>
Ok Bundled <yours-may-differ>
Ok Bundled <yours-may-differ>
Ok Wrote repl.nki
$ nki repl.nki
[starts the repl]
Queries:
In query treatment, this tool is fully compatible with
the command-line frontend.
Purpose:
A handy tool for packing Novika images e.g. to transfer
them over the network, or distribute. Novika images can
be run by the 'nki' tool which is more restricted than
the command-line frontend.
HELP
end
def start(args = ARGV, cwd = Path[ENV["NOVIKA_CWD"]? || Dir.current])
Colorize.enabled = Novika.colorful?
if args.size < 2
help(STDOUT)
exit(0)
end
imagepath = nil
compression = Novika::Image::CompressionType::None
runnables = ARGV.map_with_index do |arg, index|
if index == ARGV.size - 1 && arg.ends_with?(".nki")
imagepath = arg
next
end
if arg =~ /-c([bg]):([fb])/
case {$1, $2}
when {"b", "f"} then compression = Novika::Image::CompressionType::BrotliFast
when {"b", "b"} then compression = Novika::Image::CompressionType::BrotliBest
when {"g", "f"} then compression = Novika::Image::CompressionType::GzipFast
when {"g", "b"} then compression = Novika::Image::CompressionType::GzipBest
else
Frontend.errln("invalid compression option: #{arg}")
exit(1)
end
next
end
arg
end.compact
unless imagepath
Frontend.errln("Please provide a 'path/to/image.nki' as the last argument.")
Frontend.noteln("This will let me know where to save the image.")
exit(1)
end
resolver = RunnableResolver.new(cwd, runnables)
resolver.on_permissions_gets do |string|
print string, " "
gets
end
resolver.on_permissions_print do |string|
print string
end
resolver.after_permissions do |hook|
designations = hook.designations
prefix = designations.size > 1 # Mixed environments in args/cwd
designations.each do |designation|
# Slurp into One Big Block.
mod = Novika::Block.new(designation.caps.block)
Frontend.wait("Bundling #{ARGV[-1]} (#{designation.label})...\n", ok: "Bundled #{ARGV[-1]} (#{designation.label})") do
designation.slurp(mod)
end
# Write the image.
File.open(img = prefix ? "#{Path[ARGV[-1]].stem}.#{designation.label}.nki" : ARGV[-1], "w") do |file|
Frontend.wait("Writing image #{img}...\n", ok: "Wrote image #{img}") do
file.write_bytes(Novika::Image.new(mod, designation.caps, compression))
end
end
end
end
unless resolver.resolve?
help(STDOUT)
exit(0)
end
rescue e : Resolver::RunnableError
e.runnable.backtrace(STDERR, indent: 2) do |io|
Frontend.err(e.message, io)
end
exit(1)
rescue e : Resolver::ResponseRejectedError
e.response.each_rejected_runnable do |runnable|
runnable.backtrace(STDERR, indent: 2) do |io|
Frontend.err(e.message, io)
end
end
exit(1)
rescue e : Resolver::MoreThanOneAppError
e.apps.each do |app|
app.backtrace(STDERR, indent: 2) do |io|
Frontend.noteln("could not run this app because it's not the only one", io)
end
end
Frontend.errln(e.message)
exit(1)
rescue e : Resolver::ResolverError
Frontend.errln(e.message)
end
end
Novika::Frontend::Nkas.start |
<!DOCTYPE html>
<html lang="nl">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/style.css">
<title>Contact</title>
<style>
/*----------- Begin Joeri poging css confirm into maincss-----------------*/
body {}
#confirm {
min-height: 777px;
}
#hidden {
text-align: center;
margin-top: 69px;
;
padding: 22px;
min-height: 444px;
display: none;
}
#test {
max-width: 150px;
min-height: 150px;
background-color: grey;
}
#koffer {
position: absolute;
left: 622px;
top: 399px;
display: none;
}
#pc {
position: absolute;
left: 1090px;
top: 300px;
display: none;
}
#hiddenimg {
position: relative;
z-index: 3;
}
#proef {
color: purple;
}
#confirm {
max-width: 666px;
margin: auto;
text-align: center;
padding-top: 69px;
margin-top: 69px;
}
/*-----------Einde Joeri poging css confirm into maincss-----------------*/
</style>
</head>
<body>
<!-- Begin Pui -->
<header>
<div class="navbar">
<div class="nav_container">
<div class="logo">
<h1><a href="https://www.vschool.be/" target="_blank">DevSchool</a></h1>
</div>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="#cursus">Cursus</a></li>
<li><a href="#cursus">Programma</a></li>
<li><a href="contact.confirm.html">Inschrijven</a></li>
<li><a target="_blank" href="https://www.vschool.be/contact/">Contact</a></li>
</ul>
</nav>
</div>
</div>
</header>
<!-- Einde Pui -->
<!-- Begin Steven -->
<div class="inschrijfform">
<main>
<form id="inschrijven">
<div class="inschrijf-titel">
<h2>Inschrijving</h2>
</div>
<div class="inputs">
<span id="naam_check" class="error"></span>
<input type="text" name="naam" id="naam" placeholder="Naam">
<span id="email_check" class="error"></span>
<input type="email" name="email" id="email" placeholder="E-mail">
</div>
<div class="opleiding">
<p>jQuery</p>
</div>
<div class="verzenden-button">
<input id="submit_button" type="submit" value="Verzenden">
</div>
</form>
</main>
</div>
<!-- Einde Steven -->
<!-- Begin Joeri -->
<section id="confirm">
<img id="koffer" src="app/img/koffer.png" />
<img id="pc" src="app/img/pc.jpg" />
<section>
<div class="check" style="display: none;"><img src="img/check.png" /></div>
<div id="hiddenimg" style="display: none;">
<img src="img/confir.png" />
</div>
<div id="hiddentekst" style="display: none;">
<p>Bedankt voor je aanvraag!</p>
<p>Wij hebben je aanvraag goed ontvangen en zullen je aanvraag zsm verwerken.</p>
<p>Je ontvangt van ons nog een e-mail ter bevestiging van je aanvraag.</p>
<hr>
</div>
<div id="newtekst2" style="display: none;">
<h2 id="typewriter2"></h2>
</div>
<div id="newtekst" style="display: none;">
<h2 id="typewriter"></h2>
<p><a href="index.html">Home</a></p>
</div>
<h3 id="h3" style="display: none;">CVO De Verdieping | vSchool</h3>
</section>
</section>
<!-- Einde Joeri -->-->
<!-- Begin Pui -->
<footer>
<div class="footer_container">
<div class="container_rows">
<div class="container_columns">
<h1>Meer info</h1>
<ul>
<li><a href="#">Opleiding</a></li>
<li><a href="#">Inschrijven</a></li>
<li><a href="https://www.vschool.be/team/">Over ons</a></li>
</ul>
</div>
<div class="container_columns">
<h1>Contact info</h1>
<ul>
<li><a href="#">011 53 87 33</a></li>
<li><a href="#">Schachtplein 1 3550</a></li>
<li><a href="#">3550 Heusden-Zolder</a></li>
</ul>
</div>
<div class="container_columns">
<h1>Volg ons</h1>
<div class="social_links">
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-instagram"></i></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Einde Pui -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-3.6.0.min.js"><\/script>')</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://rawgit.com/Ashish-Bansal/jquery-typewriter/master/jquery.typewriter.js" defer=""></script>
<script>
$(document).ready(function () {
/*Begin Steven Code */
let $button = $('#submit_button');
$button.on('click', function (e) {
e.preventDefault();
let $naam = $('#naam').val();
let $email = $('#email').val();
let $naam_border = $('#naam');
let $email_border = $('#email');
let $error = $('.error');
$error.hide();
$naam_border.removeClass('error_border');
$email_border.removeClass('error_border');
if ($naam.length == '') {
$('span#naam_check').show().html('Vul uw naam in');
$naam_border.addClass('error_border');
$('#naam').effect("shake");
}
else if ($naam.length < 3) {
$('span#naam_check').show().html('Uw naam moet 3 karakters of langer zijn');
$naam_border.addClass('error_border');
$('#naam').effect("shake");
}
if ($email.length == '') {
$('span#email_check').show().html('Vul uw email in');
$email_border.addClass('error_border');
$('#email').effect("shake");
}
else {
const $regEx = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
let $geldige_email = $regEx.test($email);
if (!$geldige_email) {
$('span#email_check').show().html('Geef een geldige email in');
$email_border.addClass('error_border');
$('#email').effect("shake");
}
}
if (!$naam_border.hasClass('error_border') && !$email_border.hasClass('error_border')) {
$('.inschrijfform').fadeOut(750);
/*Einde Steven Code */
// Begin Joeri
$('.check').fadeIn(7500).delay(1500).animate({
right: "+=250",
opacity: "toggle"
}, 333);
$('#hiddentekst').fadeIn(5000).delay(500).fadeOut(3000);
$('#hiddenimg').delay(10000).fadeIn(666);
$('#newtekst').delay(15000).fadeIn(666);
$('#h3').delay(16000).fadeIn(4666);
$('#newtekst2').delay(6666).fadeIn(666);
//Einde Joeri
/*Begin Steven en Joeri Code */
$('#koffer').delay(10000).fadeIn(250).animate({
left: "+=162px"
}, 2222);
$('#pc').delay(10000).fadeIn(250).animate({
top: "+=122px"
}, 1669);
}
});
/*Einde Steven en Joeri Code */
//Begin code Joeri
$("#typewriter").typewriter({
prefix: [""],
text: ["proef en krijg goesting", "hedendaagse helden", "digitale duizendpoten", "veel succes", "future fanatics", "web weavers", "practical programmers"],
typeDelay: 100,
waitingTime: 1500,
blinkSpeed: 800
});
});
//Einde code Joeri
</script>
</body>
</html> |
class LivrosController < ApplicationController
before_action :set_livro, only: %i[ show edit update destroy ]
before_action :authenticate_user!
# GET /livros or /livros.json
def index
@livros = Livro.all
@livros_classificados = Livro.includes(:book_reviews).where.not(book_reviews: { rating: nil })
@livros = Livro.joins(:book_reviews)
end
# GET /livros/1 or /livros/1.json
def show
end
# GET /livros/new
def new
@livro = Livro.new
end
# GET /livros/1/edit
def edit
end
# POST /livros or /livros.json
def create
@livro = Livro.new(livro_params)
respond_to do |format|
if @livro.save
format.html { redirect_to registered_book_path, notice: "Livro was successfully created." }
format.json { render :show, status: :created, location: @livro }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @livro.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /livros/1 or /livros/1.json
def update
respond_to do |format|
if @livro.update(livro_params)
format.html { redirect_to livro_url(@livro), notice: "Livro was successfully updated." }
format.json { render :show, status: :ok, location: @livro }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @livro.errors, status: :unprocessable_entity }
end
end
end
# DELETE /livros/1 or /livros/1.json
def destroy
@livro.destroy!
respond_to do |format|
format.html { redirect_to livros_url, notice: "Livro was successfully destroyed." }
format.json { head :no_content }
end
end
def avaliar
@livro = Livro.find(params[:id])
@book_review = @livro.book_reviews.new
end
def save_avaliacao
@livro = Livro.find(params[:id])
@book_review = @livro.book_reviews.new(book_review_params)
if @book_review.save
redirect_to livro_avaliacoes_path(@livro)
else
render :avaliar
end
end
def avaliacoes
@livro = Livro.find(params[:id])
@avaliacoes = @livro.book_reviews
end
def todos_livros
if params[:search]
@livros = Livro.where("titulo LIKE ? OR autores LIKE ? OR editora LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%", "%#{params[:search]}%")
else
@livros = Livro.all
end
end
def favoritar
livro = Livro.find(params[:id])
current_user.favorites.create(livro: livro)
redirect_to todos_livros_path, notice: 'Livro favoritado com sucesso.'
end
def desfavoritar
livro = Livro.find(params[:id])
current_user.favorites.find_by(livro: livro).destroy
redirect_to todos_livros_path, notice: 'Livro removido dos favoritos.'
end
private
# Use callbacks to share common setup or constraints between actions.
def set_livro
@livro = Livro.find(params[:id])
end
# Only allow a list of trusted parameters through.
def livro_params
params.require(:livro).permit(:imagem_nome, :imagem_caminho, :titulo, :autores, :ano_lancamento, :nota, :editora, :opiniao, :idiomas, :num_paginas)
end
end |
<template>
<li
v-cloak
class="nav-item"
>
<div id="notificationMenu">
<b-button
id="notification-menu-button"
:variant="buttonVariant"
:class="{'is-open': isOpen, 'has-messages': hasMessages}"
class="notification-menu-button"
data-toggle="dropdown"
role="button"
aria-haspopup="menu"
:aria-expanded="isOpen"
:title="$t('Notifications')"
:aria-label="ariaLabel"
size="sm"
>
<div class="bell-icon">
<i class="fas fa-bell" />
<span
v-if="hasMessages"
class="dot"
/>
</div>
<span
v-if="hasMessages"
class="message-count"
>{{ displayTotalCount }}</span>
</b-button>
<b-popover
v-if="shouldShowMobilePopover"
target="notification-menu-button"
offset="1"
triggers="click blur"
custom-class="notification-popover-wrapper custom-popover"
data-cy="notification-popover"
@shown="onShown"
@hidden="onHidden"
>
<div class="notification-popover">
<b-container
fluid
class=""
>
<b-row align-h="between">
<b-col>
<b-tabs>
<b-tab @click="_ => filterComments = null">
<template
#title
data-cy="notification-popover-inbox"
>
<b-badge
v-if="allCount"
pill
variant="warning lighten"
>
{{ allCount }}
</b-badge>
{{ $t('Inbox') }}
</template>
</b-tab>
<b-tab @click="_ => filterComments = false">
<template
#title
data-cy="notification-popover-notifications"
>
<b-badge
v-if="notificationsCount"
pill
variant="warning lighten"
>
{{ notificationsCount }}
</b-badge>
{{ $t('Notifications') }}
</template>
</b-tab>
<b-tab @click="_ => filterComments = true">
<template
#title
data-cy="notification-popover-comments"
>
<b-badge
v-if="commentsCount"
pill
variant="warning lighten"
>
{{ commentsCount }}
</b-badge>
{{ $t('Comments') }}
</template>
</b-tab>
</b-tabs>
</b-col>
<b-col
align-self="center"
cols="auto"
>
<a href="/notifications"><i class="fas fa-external-link-alt fa-lg pr-3 external-link" /></a>
</b-col>
</b-row>
</b-container>
<div
v-if="messages.length == 0"
class="no-notifications-mobile"
>
<img :alt="$t('All Clear')" src="/img/all-cleared.svg">
<h2>{{ $t('All Clear') }}</h2>
<h5>{{ $t('No new notifications at the moment.') }}</h5>
<b-button variant="primary" href="/notifications">{{ $t('View All Notifications') }}</b-button>
</div>
<template v-else>
<notification-card
v-for="(item, index) in filteredMessages"
:key="index"
:notification="item"
:show-time="true"
/>
</template>
</div>
</b-popover>
<b-popover
v-if="shouldShowPopover"
target="notification-menu-button"
placement="bottomleft"
offset="1"
triggers="click blur"
custom-class="notification-popover-wrapper"
@shown="onShown"
@hidden="onHidden"
>
<div class="notification-popover">
<b-container
fluid
class=""
>
<b-row align-h="between">
<b-col>
<b-tabs>
<b-tab @click="_ => filterComments = null">
<template #title>
<b-badge
v-if="allCount"
pill
variant="warning lighten"
>
{{ allCount }}
</b-badge>
{{ $t('Inbox') }}
</template>
</b-tab>
<b-tab @click="_ => filterComments = false">
<template #title>
<b-badge
v-if="notificationsCount"
pill
variant="warning lighten"
>
{{ notificationsCount }}
</b-badge>
{{ $t('Notifications') }}
</template>
</b-tab>
<b-tab @click="_ => filterComments = true">
<template #title>
<b-badge
v-if="commentsCount"
pill
variant="warning lighten"
>
{{ commentsCount }}
</b-badge>
{{ $t('Comments') }}
</template>
</b-tab>
</b-tabs>
</b-col>
<b-col
align-self="center"
cols="auto"
class="notification-popover-col"
>
<a
href="/notifications"
data-cy="notification-popover-link"
>
<i class="fas fa-external-link-alt fa-lg pr-3 external-link" />
</a>
</b-col>
</b-row>
</b-container>
<div
v-if="messages.length == 0"
class="no-notifications"
data-cy="notification-popover-no-notifications"
>
<img :alt="$t('All Clear')" src="/img/all-cleared.svg">
<h2>{{ $t('All Clear') }}</h2>
<h5>{{ $t('No new notifications at the moment.') }}</h5>
<b-button variant="primary" href="/notifications">{{ $t('View All Notifications') }}</b-button>
</div>
<div class="items" v-else>
<notification-item
v-for="(item, index) in filteredMessages"
:key="index"
:notification="item"
:show-time="true"
/>
</div>
</div>
</b-popover>
</div>
</li>
</template>
<script>
import { PopoverPlugin } from "bootstrap-vue";
import NotificationCard from "./notification-card.vue";
import NotificationItem from "./notification-item.vue";
import notificationsMixin from "../notifications-mixin";
Vue.use(PopoverPlugin);
export default {
components: { NotificationItem, NotificationCard },
mixins: [notificationsMixin],
props: {
messages: Array,
},
data() {
return {
isOpen: false,
totalMessages: 0,
incrementTotalMessages: false,
arrowStyle: {
top: "0px",
left: "0px",
},
filterComments: null,
reloadOnClose: false,
shouldShowPopover: false,
shouldShowMobilePopover: false,
};
},
computed: {
ariaLabel() {
const count = this.totalMessages;
if (count === 0) {
return this.$t("Notifications, No New Messages", { count });
} else if (count === 1) {
return this.$t("Notifications, {{count}} New Messages", { count });
}
return this.$t("Notifications, {{count}} New Messages", { count });
},
buttonVariant() {
if (this.isOpen) {
return "primary";
}
if (this.hasMessages) {
return "notification-btn-warning";
}
return "link";
},
hasMessages() {
return this.totalMessages > 0;
},
displayTotalCount() {
return this.totalMessages > 10 ? "10+" : this.totalMessages;
},
},
watch: {
messages(value, mutation) {
// update the number of messages just whe the number has been initialized (in mounted)
if (this.incrementTotalMessages) {
this.updateTotalMessages();
$(this.$el)
.find(".dropdown")
.dropdown("toggle");
}
},
},
mounted() {
this.checkScreenWidth();
window.addEventListener("resize", this.checkScreenWidth);
if ($("#navbar-request-button").length > 0) {
this.arrowStyle.top = `${$("#navbar-request-button").offset().top + 45}px`;
this.arrowStyle.left = `${$("#navbar-request-button").offset().left + 53}px`;
window.addEventListener("resize", () => {
this.arrowStyle.top = `${$("#navbar-request-button").offset().top + 42}px`;
this.arrowStyle.left = `${$("#navbar-request-button").offset().left + 32}px`;
});
}
this.updateTotalMessages();
},
methods: {
checkScreenWidth() {
const mobileScreenWidth = 768;
this.shouldShowPopover = window.innerWidth > mobileScreenWidth;
this.shouldShowMobilePopover = window.innerWidth < mobileScreenWidth;
},
onShown() {
this.isOpen = true;
this.markAsRead();
},
onHidden() {
this.isOpen = false;
this.filterComments = null;
if (this.reloadOnClose) {
this.updateTotalMessages();
}
},
icon(task) {
return ProcessMaker.$notifications.icons[task.type];
},
url(task) {
if (task.url) {
return task.url;
}
return "/notifications";
},
updateTotalMessages() {
this.incrementTotalMessages = false;
ProcessMaker.apiClient
.get("/notifications?per_page=10&filter=unread&include=user")
.then((response) => {
ProcessMaker.notifications.splice(0);
response.data.data.forEach((element) => {
ProcessMaker.pushNotification(element);
});
this.totalMessages = response.data.meta.total;
this.$nextTick(() => {
this.incrementTotalMessages = true;
});
});
},
markAsRead() {
if (!this.hasMessages) {
return;
}
const messageIds = this.messages.map((m) => m.id);
window.ProcessMaker.apiClient.put("/read_notifications", { message_ids: messageIds, routes: [] });
this.reloadOnClose = true;
},
},
};
</script>
<style>
.btn-notification-btn-warning{
background-color: #FFEABF;
border-color: #FFEABF;
}
</style>
<style lang="scss" scoped>
@import "../../../sass/variables";
.no-notifications {
text-align: center;
height: 600px;
img {
width: 190px;
margin-top: 100px;
margin-bottom: 20px;
}
}
.no-notifications-mobile {
text-align: center;
img {
width: 120px;
margin-top: 48px;
margin-bottom: 24px;
}
h5 {
margin-bottom: 24px;
}
}
.custom-popover {
background-color: rgba(255, 255, 255, 0.8);
backdrop-filter: blur(10px);
}
.notification-list {
max-height: 300px;
overflow-y: auto;
}
.lighten {
background-color: lighten($warning, 40%);;
}
.has-messages {
// background-color: lighten($warning, 20%);
// border-color: lighten($warning, 20%);
}
.button-dismiss {
font-size: 12px;
padding: 0;
}
.notification-popover {
font-size: 12px;
width: 450px;
}
.notification-popover-col {
height: auto !important;
}
.notification-popover::v-deep .tabs {
.nav-tabs {
border: 0;
font-size: 1.2em;
flex-direction: row;
}
.nav-link {
border: 0;
color: $secondary;
border-bottom: 3px solid transparent;
}
.nav-link.active {
color: $primary;
font-weight: bold;
border: 0;
border-bottom: 3px solid $primary;
}
.nav-link.hover {
border: 0;
}
}
.external-link {
color: $secondary;
}
.notification-link {
font-size: 14px;
}
.count-info {
color: #788793;
}
.count-info .badge {
font-size: 10px;
padding: 2px 5px;
position: absolute;
right: 88px;
top: 17px;
}
.count-info #info-large {
position: absolute;
right: 83px;
top: 17px;
}
.popover {
max-width: 450px;
top: -8px;
}
.items {
height: 600px;
overflow-y: scroll;
overflow-x: hidden;
}
.notification-menu-button {
color: $dark;
}
.notification-menu-button i {
color: $light;
}
.notification-menu-button.is-open,
.notification-menu-button.is-open i {
color: $light;
}
.bell-icon {
display: inline-block;
vertical-align: middle;
i {
font-size: 19px;
padding-right: 1px;
color: $secondary;
}
.dot {
height: 10px;
width: 10px;
background-color: $danger;
border-radius: 50%;
position: relative;
display: inline-block;
top: -6px;
margin-left: -10px;
}
.message-count {
}
}
@media only screen and (max-width: 600px) {
.notification-popover-wrapper.popover {
transform: translate3d(0px, 0px, 0px) !important;
right: 0;
height: auto;
max-width: 100%;
}
.notification-popover {
width: auto;
}
}
</style> |
import { StatisticItem } from 'components';
import { StatisticsList, StatisticTitle } from './Statistics.styled';
import { FaRegThumbsUp } from 'react-icons/fa';
import { MdPeople, MdOutlineProductionQuantityLimits } from 'react-icons/md';
import { GiTreeDoor } from 'react-icons/gi';
import PropTypes, { shape } from 'prop-types';
const icons = [<FaRegThumbsUp/>, <MdPeople/>, <MdOutlineProductionQuantityLimits/>, <GiTreeDoor/>];
export const Statistics = ({title, stats}) => {
return (
<>
{title && <StatisticTitle>{title}</StatisticTitle>}
<StatisticsList>
{stats.map((stat, indx) => <StatisticItem stat ={stat} key = {stat.id} icon = {icons[indx]}/>)}
</StatisticsList>
</>
);
};
Statistics.propTypes = {
title: PropTypes.string,
stats: PropTypes.arrayOf(shape({
title: PropTypes.string.isRequired,
total: PropTypes.number.isRequired
})).isRequired
}; |
import 'package:expense_tracker/models/transaction.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class TransactionList extends StatelessWidget {
final List<Transaction> transactions;
final Function deleteTx;
TransactionList(this.transactions,this.deleteTx);
@override
Widget build(BuildContext context) {
return Container(
height: 500,
child: transactions.isEmpty
? Column(
children: <Widget>[
Text('No transactions yet!',
style: Theme.of(context).textTheme.title),
SizedBox(
height: 15,
),
Container(
height: 200,
child: Image.asset('assets/images/waiting.png',
fit: BoxFit.cover)),
],
)
: ListView.builder(
itemBuilder: (ctx, index) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(vertical: 8, horizontal: 5),
child: ListTile(
leading: CircleAvatar(
radius: 30,
child: Padding(
padding: EdgeInsets.all(7),
child: FittedBox(
child: Text('\$${transactions[index].amount}')),
),
),
title: Text(
transactions[index].title,
style: Theme.of(context).textTheme.title,
),
subtitle: Text(
DateFormat.yMMMd().format(transactions[index].date)),
trailing: IconButton(
icon: Icon(Icons.delete),
color: Theme.of(context).textTheme.title.color,
onPressed: () => deleteTx(transactions[index].id),
),
),
);
},
itemCount: transactions.length,
//children: transactions.map((tx) {
//return
//}).toList(),
),
);
}
} |
import tkinter as tk
import datetime
nepali_digits = ["०", "१", "२", "३", "४", "५", "६", "७", "८", "९"]
nepali_months = ["बैशाख", "जेष्ठ", "असार", "श्रावण", "भाद्र", "आश्विन", "कार्तिक", "मंसिर", "पौष", "माघ", "फाल्गुन", "चैत"]
nepali_days_of_week = ["आइतवार", "सोमवार", "मंगलवार", "बुधवार", "बिहीवार", "शुक्रवार", "शनिवार"]
# The number of days in each Nepali month
days_in_nepali_month = [31, 31, 32, 31, 32, 30, 30, 30, 29, 30, 30, 31]
def get_nepali_digits(number):
"""Converting a number to Nepali digits."""
return ''.join(nepali_digits[int(digit)] for digit in str(number))
def get_nepali_month(month):
return nepali_months[month - 1]
def get_nepali_day_of_week(day_of_week):
return nepali_days_of_week[day_of_week]
def get_nepali_year(year):
year_str = str(year)
nepali_year = ''.join(nepali_digits[int(digit)] for digit in year_str)
return nepali_year
def get_current_nepali_time():
"""Getting the current time in Nepali digits, month, and day of the week."""
now = datetime.datetime.now()
nepali_year = get_nepali_year(now.year + 56)
nepali_month = (now.month + 8) % 12
nepali_day = (now.day + 17)%30
# Adjusting the day if it exceeds the number of days in the month
while nepali_day > days_in_nepali_month[nepali_month]:
nepali_month += 1
if nepali_month >= len(days_in_nepali_month):
nepali_month = 0
nepali_year += 1
nepali_day -= days_in_nepali_month[nepali_month]
nepali_month = get_nepali_month(nepali_month + 1)
nepali_day = get_nepali_digits(nepali_day)
nepali_hour = get_nepali_digits(now.hour)
nepali_minute = get_nepali_digits(now.minute)
nepali_second = get_nepali_digits(now.second)
# Here the day of the week is calculated using the Unix epoch as a reference
days_since_epoch = (now - datetime.datetime(1970, 1, 1)).days
day_of_week = (days_since_epoch + 4) % 7
nepali_day_of_week = get_nepali_day_of_week(day_of_week)
return nepali_year, nepali_month, nepali_day, nepali_hour, nepali_minute, nepali_second, nepali_day_of_week
def update_clock():
""" the clock label with the current time."""
nepali_year, nepali_month, nepali_day, nepali_hour, nepali_minute, nepali_second, nepali_day_of_week = get_current_nepali_time()
clock_label.config(text=f"{nepali_day} {nepali_month} {nepali_year},{nepali_day_of_week}\n{nepali_hour}:{nepali_minute}:{nepali_second}")
root.after(1000, update_clock)
# main window for the app
root = tk.Tk()
root.title("Nepali Digital Clock")
root.configure(bg='black')
# Create a label to display the clock
clock_label = tk.Label(root, font=("Helvetica", 36), bg='black', fg='#808A87')
clock_label.pack(padx=20, pady=20)
# Update the clock initially and start the clock update loop
update_clock()
# Start the Tkinter event loop
root.mainloop() |
#pragma once
template <typename T>
class Stack
{
private:
struct Node
{
T* value;
Node* next;
Node(T* value) {
this->value = value;
this->next = nullptr;
}
};
int size;
Node* head;
public:
Stack() {
this->head = nullptr;
this->size = 0;
}
int get_size() {
return this->size;
}
bool is_empty() {
return this->head == nullptr;
}
void push(T* item) {
Node* node = new Node(item);
this->size++;
if (this->is_empty()) {
this->head = node;
return;
}
node->next = this->head;
this->head = node;
}
T* peek() {
return this->head->value;
}
T* pop() {
T* item = this->head->value;
this->head = this->head->next;
this->size--;
return item;
}
}; |
import { CompetitionDatabaseMock } from "./../mocks/CompetitionDatabaseMock";
import { CompetitionBusiness } from "./../../src/business/CompetitionBusiness";
import { IdGeneratorMock } from "./../mocks/IdGeneratorMock";
import { BaseError } from "../../src/errors/BaseError";
describe("Testanto create da CompetitionBusiness", () => {
const competitionBusiness = new CompetitionBusiness(
new CompetitionDatabaseMock(),
new IdGeneratorMock()
);
test("Caso de sucesso", async () => {
const name: string = "athlete-mock";
const attempts: number = 3;
const result = await competitionBusiness.create(name, attempts);
expect(result.message).toEqual("Competição criada com sucesso");
});
test("Caso de erro, criando uma competição sem nome", async () => {
expect.assertions(2);
try {
const name: string = "";
const attempts: number = 1;
await competitionBusiness.create(name, attempts);
} catch (error) {
if (error instanceof BaseError) {
expect(error.message).toEqual(
"Deve ser passado o nome e a quantidade de chances da competição"
);
expect(error.statusCode).toEqual(400);
}
}
});
test("Caso de erro, criando uma competição sem chances", async () => {
expect.assertions(2);
try {
const name: string = "competition-mock";
const attempts: number = 0;
await competitionBusiness.create(name, attempts);
} catch (error) {
if (error instanceof BaseError) {
expect(error.message).toEqual(
"Deve ser passado o nome e a quantidade de chances da competição"
);
expect(error.statusCode).toEqual(400);
}
}
});
test("Caso de erro, criando uma competição com nome que não é do tipo string", async () => {
expect.assertions(2);
try {
const name: any = true;
const attempts: number = 1;
await competitionBusiness.create(name, attempts);
} catch (error) {
if (error instanceof BaseError) {
expect(error.message).toEqual(
"Parâmetro 'name' inválido: deve ser uma string"
);
expect(error.statusCode).toEqual(400);
}
}
});
test("Caso de erro, criando uma competição com attempts que não é do tipo number", async () => {
expect.assertions(2);
try {
const name: string = "competition-mock";
const attempts: any = "attempts-mock";
await competitionBusiness.create(name, attempts);
} catch (error) {
if (error instanceof BaseError) {
expect(error.message).toEqual(
"Parâmetro 'attempts' inválido: deve ser um number"
);
expect(error.statusCode).toEqual(400);
}
}
});
test("Caso de erro, criando uma competição com um nome que já existe", async () => {
expect.assertions(2);
try {
const name: string = "competition-mock";
const attempts: number = 3;
await competitionBusiness.create(name, attempts);
} catch (error) {
if (error instanceof BaseError) {
expect(error.message).toEqual("Competição já cadastrada");
expect(error.statusCode).toEqual(409);
}
}
});
}); |
import "./App.css";
import Header from "./components/Header";
import Home from "./components/Home";
import VideoSection from "./components/VideoSection";
import EventSchedule from "./components/EventSchedule";
import OurSpeaker from "./components/OurSpeaker";
import EventGift from "./components/EventGift";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import RegistrationPage from "./components/RegistrationPage";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
import SelectLanguage from "./components/SelectLanguage";
import HindiRegistrationPage from "./components/HindiRegistrationPage";
import QrCode from "./components/QrCode";
import "./App.css";
import { ScrollToTopController } from "./components/ScrollToTop";
function App() {
return (
<div className="App">
<BrowserRouter>
<ScrollToTopController />
<Header />
<Navbar />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/Home" element={<Home />} />
{/* <Route path='/VideoSection' element={<VideoSection/>}/> */}
{/* <Route path='/EventSchedule' element={ <EventSchedule/>}/> */}
{/* <Route path='/OurSpeaker' element={ <OurSpeaker/>}/> */}
<Route path="/EventGift" element={<EventGift />} />
<Route path="/RegistrationPage" element={<RegistrationPage />} />
<Route
path="/HindiRegistrationPage"
element={<HindiRegistrationPage />}
/>
<Route path="/SelectLanguage" element={<SelectLanguage />} />
<Route path="/VideoSection" element={<VideoSection />} />
<Route path="/EventSchedule" element={<EventSchedule />} />
<Route path="/OurSpeaker" element={<OurSpeaker />} />
<Route path="/QrCode" element={<QrCode />} />
</Routes>
<Footer />
</BrowserRouter>
</div>
);
}
export default App; |
import React, { useEffect, useRef } from "react";
import { connect } from "react-redux";
import ReactPlayer from "react-player/youtube";
import PropTypes from "prop-types";
import {
isPlaying,
currentSong,
setProgress,
setVideoDuration,
setPercentage,
setSeeking,
setArtist,
setTitle,
setSeekKeyboard,
setSeekTo,
} from "../../../redux/actions/playerActions";
import {
lastPlayedIndexPlaylistDetails,
setPlaylistImage,
} from "../../../redux/actions/playlistDetailsActions";
function Player({
player,
isPlaying,
currentSong,
playlistSongsById,
setVideoDuration,
setProgress,
setPercentage,
playlistDetails,
setArtist,
setTitle,
lastPlayedIndexPlaylistDetails,
setPlaylistImage,
setSeekKeyboard,
setSeekTo,
}) {
const playerRef = useRef(null);
useEffect(() => {
if (player.seekKeyboard !== null) {
playerRef.current.seekTo(player.seekKeyboard, "fraction");
}
setSeekKeyboard(null);
}, [player.seekKeyboard]);
const findPlaylistIndex = playlistDetails.findIndex(
(element) => element.playlistId === player.currentActivePlaylistId,
);
const afterSongEnds = () => {
const currIndex = playlistDetails[findPlaylistIndex].currentIndex;
if (
playlistDetails[findPlaylistIndex].currentIndex <
playlistSongsById[player.currentActivePlaylistId].length - 1
) {
const lastPlayedObj = {
currentIndex: playlistDetails[findPlaylistIndex].currentIndex + 1,
playlistId: player.currentActivePlaylistId,
};
lastPlayedIndexPlaylistDetails(lastPlayedObj);
currentSong(
playlistSongsById[player.currentActivePlaylistId][currIndex + 1]
?.snippet.resourceId.videoId,
);
} else if (
playlistDetails[findPlaylistIndex].currentIndex ===
playlistSongsById[player.currentActivePlaylistId].length - 1
) {
// empty
}
};
const handleEnd = () => {
if (
playlistDetails[findPlaylistIndex].currentIndex ===
playlistSongsById[player.currentActivePlaylistId].length
) {
// empty
isPlaying(false);
} else {
afterSongEnds();
}
};
// When some songs can't be played outside of youtube this function will trigger
// and playlist the next song, or if it is the last the playlist will end
const handleError = () => {
const currIndex = playlistDetails[findPlaylistIndex].currentIndex;
if (currIndex === playlistDetails[findPlaylistIndex].playlistLength) {
isPlaying(false);
} else afterSongEnds();
};
useEffect(() => {
if (player.seeking === true && player.seekTo !== null) {
playerRef.current.seekTo(player.seekTo);
setSeeking(false);
setSeekTo(null);
}
}, [player.seekTo]);
const handlePlay = () => {
isPlaying(true);
};
const handlePause = () => {
isPlaying(false);
};
const getTitleAndArtist = (title, ownerTitle) => {
try {
const joinedTitleAndOwnerTitle = [title, ownerTitle];
if (title === "Private video") {
return title;
}
if (joinedTitleAndOwnerTitle[0].includes(" - ")) {
const regex = /^(.*?)-(.*)$/;
const match = joinedTitleAndOwnerTitle[0].match(regex);
const [, artist, title] = match;
return [title, artist];
}
if (joinedTitleAndOwnerTitle[0].includes("//")) {
const regex = /^(.*?)\s\/\/\s(.*)$/;
const match = joinedTitleAndOwnerTitle[0].match(regex);
const [, artist, title] = match;
return [title, artist];
}
if (joinedTitleAndOwnerTitle[1].includes(" - Topic")) {
const regex = /^(.*?)\s-\sTopic$/;
const match = joinedTitleAndOwnerTitle[1].match(regex);
const artist = match[1];
return [title, artist];
}
return [title, ownerTitle];
} catch (error) {
return title;
}
};
const handleReady = () => {
const [title, artist] = getTitleAndArtist(
playlistSongsById[player.currentActivePlaylistId][
playlistDetails[findPlaylistIndex].currentIndex
].snippet.title,
playlistSongsById[player.currentActivePlaylistId][
playlistDetails[findPlaylistIndex].currentIndex
].snippet.videoOwnerChannelTitle,
);
setTitle(
`${playlistDetails[findPlaylistIndex].currentIndex + 1} - ${title}`,
);
setArtist(artist);
setProgress(0);
setVideoDuration(playerRef.current.getDuration());
isPlaying(true);
const obj = {
playlistId: player.currentActivePlaylistId,
playlistImage: `https://i.ytimg.com/vi/${player.currentSong}/mqdefault.jpg`,
};
setPlaylistImage(obj);
};
const getPercentage = (a, b) => {
const trimmedA = Math.floor(a);
const percentage = (trimmedA / b) * 100;
setPercentage(Math.floor(percentage));
};
const handleProgress = (e) => {
setProgress(Math.floor(e.playedSeconds));
getPercentage(e.playedSeconds, player.videoDuration);
};
return (
<div className="player h-full aspect-auto md:w-full md:mx-2 md:h-full">
<ReactPlayer
playing={player.isPlaying}
ref={playerRef}
muted={player.isMutedActive}
passive="true"
onProgress={(e) => handleProgress(e)}
onError={() => handleError()}
onPlay={() => handlePlay()}
onPause={() => handlePause()}
light
config={{
youtube: {
playerVars: {
color: "white",
},
},
}}
onReady={() => handleReady()}
onEnded={() => handleEnd()}
volume={player.volume}
width="100%"
height="100%"
controls
loop={player.isLoopActive}
url={`https://www.youtube.com/embed/${player.currentSong}`}
/>
</div>
);
}
Player.propTypes = {
player: PropTypes.shape({
isPlaying: PropTypes.bool.isRequired,
currentSong: PropTypes.string.isRequired,
isShuffleActive: PropTypes.bool.isRequired,
isLoopActive: PropTypes.bool.isRequired,
currentActivePlaylistId: PropTypes.string.isRequired,
isMutedActive: PropTypes.bool.isRequired,
videoDuration: PropTypes.number.isRequired,
volume: PropTypes.number.isRequired,
seeking: PropTypes.bool.isRequired,
seekTo: PropTypes.number,
title: PropTypes.string.isRequired,
seekKeyboard: PropTypes.number,
}).isRequired,
playlistDetails: PropTypes.arrayOf(
PropTypes.shape({
playlistName: PropTypes.string.isRequired,
playlistId: PropTypes.string.isRequired,
playlistImage: PropTypes.string.isRequired,
playlistEtag: PropTypes.string.isRequired,
currentIndex: PropTypes.number.isRequired,
playlistLength: PropTypes.number,
}),
).isRequired,
isPlaying: PropTypes.func.isRequired,
currentSong: PropTypes.func.isRequired,
setPercentage: PropTypes.func.isRequired,
playlistSongsById: PropTypes.objectOf(PropTypes.arrayOf).isRequired,
setProgress: PropTypes.func.isRequired,
setVideoDuration: PropTypes.func.isRequired,
setTitle: PropTypes.func.isRequired,
setArtist: PropTypes.func.isRequired,
lastPlayedIndexPlaylistDetails: PropTypes.func.isRequired,
setPlaylistImage: PropTypes.func.isRequired,
setSeekKeyboard: PropTypes.func.isRequired,
setSeekTo: PropTypes.func,
};
Player.defaultProps = {
setSeekTo: null,
};
const mapDispatchToProps = {
isPlaying,
currentSong,
setProgress,
setVideoDuration,
setPercentage,
lastPlayedIndexPlaylistDetails,
setTitle,
setArtist,
setPlaylistImage,
setSeekKeyboard,
setSeekTo,
};
const mapStateToProps = (state) => ({
player: state.player,
playlistSongsById: state.playlistSongsById,
playlistDetails: state.playlistDetails,
});
export default connect(mapStateToProps, mapDispatchToProps)(Player); |
package FS::cust_note_class;
use base qw( FS::class_Common );
use strict;
=head1 NAME
FS::cust_note_class - Object methods for cust_note_class records
=head1 SYNOPSIS
use FS::cust_note_class;
$record = new FS::cust_note_class \%hash;
$record = new FS::cust_note_class { 'column' => 'value' };
$error = $record->insert;
$error = $new_record->replace($old_record);
$error = $record->delete;
$error = $record->check;
=head1 DESCRIPTION
An FS::cust_note_class object represents a customer note class. Every customer
note (see L<FS::cust_main_note) has, optionally, a note class. This class
inherits from FS::class_Common. The following fields are currently supported:
=over 4
=item classnum
primary key
=item classname
classname
=item disabled
disabled
=back
=head1 METHODS
=over 4
=item new HASHREF
Creates a new customer note class. To add the note class to the database,
see L<"insert">.
Note that this stores the hash reference, not a distinct copy of the hash it
points to. You can ask the object for a copy with the I<hash> method.
=cut
sub table { 'cust_note_class'; }
sub _target_table { 'cust_main_note'; }
=item insert
Adds this record to the database. If there is an error, returns the error,
otherwise returns false.
=cut
=item delete
Delete this record from the database.
=cut
=item replace OLD_RECORD
Replaces the OLD_RECORD with this one in the database. If there is an error,
returns the error, otherwise returns false.
=cut
=item check
Checks all fields to make sure this is a valid note class. If there is
an error, returns the error, otherwise returns false. Called by the insert
and replace methods.
=cut
=back
=head1 BUGS
=head1 SEE ALSO
L<FS::cust_main_note>, L<FS::Record>, schema.html from the base documentation.
=cut
1; |
import React from 'react';
import ReactDOM from 'react-dom';
import PrimeraApp from './PrimeraApp';
import './index.css';
// document hace referencia al documento html: https://developer.mozilla.org/en-US/docs/Web/API/Document
// querySelector sirve para buscar un elemento por id o clase en el html
const divRoot = document.querySelector('#root');
// la función render del ReactDOM añade un componente de react en el elemento indicado. En este caso, saludo en divRoot
// ReactDOM: https://es.reactjs.org/docs/react-dom.html
// DOM: https://developer.mozilla.org/es/docs/Web/API/Document_Object_Model/Introduction#.c2.bfqu.c3.a9_es_el_dom.3f
// ReactDOM.render( <PrimeraApp saludo='Hola kps!'/>, divRoot);
// PropTypes: Si no envíamos el prop saludo, sacará un error.
ReactDOM.render( <PrimeraApp nombre='Demoni!'/>, divRoot); |
import { useContext, useEffect, useState } from "react";
import { ToastContainer, toast } from 'react-toastify';
import { useNavigate, useLoaderData } from "react-router-dom";
import 'react-toastify/dist/ReactToastify.css';
import './styles.css'
import { handleUpdateUser, handleDeleteUser, handleUpdatePassword, updateUser } from "../../services/UserService";
import { errors, isResponseError400 } from "../../services/ErrorHandler";
import { setCookie } from "../../services/cookies/CookieService";
import { handleFetchCategoryByID } from "../../services/CategoryServices";
import { UserType, PasswordDTO, UserAuth } from "../../types/User";
import { ResponseType } from "../../types/Http";
import { CategorySearchType } from "../../types/Category";
import ReviewContainer from "../../components/ReviewContainer";
import UserDetailCard from "./components/UserDetailCard";
import UserCategoriesColumnCard from "./components/UserCategoriesColumnCard";
import Button from "../../components/Button";
import Breadcrumbs from "../../components/Breadcrumbs";
import { UserContext } from "../../layouts/PageBase";
import Modal from "../../components/Modal";
const UserDetails = () => {
const context = useContext(UserContext);
const {
userContext
} = context || {};
const [userContextState, setUserContextState] = userContext;
const [categoryList, setCategoryList] = useState<CategorySearchType[]>();
const [showModal, setShowModal] = useState<boolean>(false);
const [showModalDeleteAccount, setShowModalDeleteAccount] = useState<boolean>(false);
const [showModalPassword, setShowModalPassword] = useState<boolean>(false);
const [userName, setUserName] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [oldPassword, setOldPassword] = useState<string>("");
const [newPassword, setNewPassword] = useState<string>("");
const navigate = useNavigate();
const userLoader: ResponseType = useLoaderData() as ResponseType;
const user = userLoader.data as UserType;
const getCategoryList = async (): Promise<CategorySearchType[]> => {
const list: CategorySearchType[] = [];
try {
const responses = await Promise.all(
user.subscriptionsIDs?.map(async (c) => {
try {
const response = await handleFetchCategoryByID(c);
if (isResponseError400(errors.ERR_GET_CATEGORIES, response)) return null;
return response.data as CategorySearchType;
} catch (error) {
console.error(errors.ERR_GET_CATEGORIES, error);
toast.error(`${errors.ERR_GET_CATEGORIES}${error}`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
return null;
}
}) ?? []
);
list.push(...responses.filter((response): response is CategorySearchType => response !== null));
return list;
} catch (error) {
console.error(errors.ERR_GET_CATEGORIES, error);
toast.error(`${errors.ERR_GET_CATEGORIES}${error}`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
return [];
}
}
useEffect(() => {
const fetchData = async () => {
try {
if(!user) return;
const result = await getCategoryList();
setCategoryList(result)
} catch (error) {
console.error(errors.ERR_GET_CATEGORIES, error);
toast.error(`${errors.ERR_GET_CATEGORIES}${error}`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
});
return [];
}
}
fetchData();
},[])
const handleSaveUser = async () => {
const userInDTO: UserType = {
id: user.id,
email: user.email,
username: userName,
password: password
}
try {
const response = await handleUpdateUser(userInDTO, user.id)
if (isResponseError400(errors.ERR_LOGIN, response)) return;
toast.success("Novo username salvo com sucesso!", {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
})
setShowModal(false)
setTimeout(() => window.location.reload(), 3000);
} catch(error) {
console.error(errors.ERR_UPDATE_USERNAME, error);
toast.error(`${errors.ERR_UPDATE_USERNAME}${error}`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
})
setTimeout(() => window.location.reload(), 3000);
}
}
const handleDeleteAccount = async () => {
try {
const body: UserAuth = {
username: user.username,
email: user.email,
password: password
}
const response = await handleDeleteUser(body)
if (isResponseError400(errors.ERR_DELETE_ACCOUNT, response)) return;
toast.success("Conta excluída com sucesso!", {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
})
setCookie("accessToken", "", 7);
setCookie("refreshToken", "", 7);
setCookie("userID", "", 7);
setUserContextState(null);
setShowModal(false)
navigate("/");
} catch (error) {
console.error(errors.ERR_DELETE_ACCOUNT, error);
toast.error(`${errors.ERR_DELETE_ACCOUNT}${error}`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
})
setTimeout(() => window.location.reload(), 3000);
}
}
const updatePassword = async () => {
const passwordDTO: PasswordDTO = {
oldPassword,
newPassword,
}
try {
const response = await handleUpdatePassword(passwordDTO, user.id)
if (isResponseError400(errors.ERR_UPDATE_PASSWORD, response)) return;
toast.success("Senha alterada com sucesso!", {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
})
setShowModal(false)
await updateUser(setUserContextState, { ...user, password: newPassword })
setTimeout(() => window.location.reload(), 3000);
} catch (error) {
console.error(errors.ERR_UPDATE_PASSWORD, error);
toast.error(`${errors.ERR_UPDATE_PASSWORD}${error}`, {
position: "top-center",
autoClose: 3000,
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
draggable: true,
progress: undefined,
theme: "light",
})
setTimeout(() => window.location.reload(), 3000);
}
}
return (
<>
<Breadcrumbs />
<div className="user-detail flex-row">
<UserDetailCard user={user} categoryList={categoryList ?? []} setShowModal={setShowModal} setUserName={setUserName} setShowModalPassword={setShowModalPassword}/>
<UserCategoriesColumnCard categoryList={categoryList ?? []} />
</div>
<ReviewContainer reviewList={user.reviewList ?? []} user={user}/>
<Button
text="Excluir conta"
className="delete-account"
onClick={() => setShowModalDeleteAccount(true)}
/>
{showModal
&&
<Modal
title="Troca de username"
handleOnSave={handleSaveUser}
contentText="Digite sua senha para confirmar a mudança do seu username:"
buttonText="Salvar"
inputValue={password}
setInputValue={setPassword}
showModal={setShowModal} />
}
{showModalDeleteAccount
&&
<Modal
title="Deletar conta"
handleOnSave={handleDeleteAccount}
contentText="Digite sua senha para deletar a sua conta permanentemente:"
buttonText="Confirmar"
inputValue={password}
setInputValue={setPassword}
showModal={setShowModalDeleteAccount} />
}
{showModalPassword
&&
<Modal
title="Alterar senha"
handleOnSave={updatePassword}
contentText="Senha antiga:"
buttonText="Confirmar"
inputValue={oldPassword}
setInputValue={setOldPassword}
showModal={setShowModalPassword}
secondText="Senha nova:"
secondInputValue={newPassword}
setSecondInputValue={setNewPassword} />
}
<ToastContainer />
</>
)
}
export default UserDetails; |
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="ctp" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>exfactory.jsp</title>
<jsp:include page="/include/bs4.jsp"></jsp:include>
<script>
'use strict';
function searchCheck() {
let searchString = $("#searchString").val();
if(searchString.trim() == "") {
alert("찾고자 하는 검색어를 입력하세요!");
searchForm.searchString.focus();
}
else {
searchForm.submit();
}
}
</script>
</head>
<body>
<jsp:include page="/include/nav.jsp"/>
<p><br/><p>
<div class="container">
<form name="searchForm" method="post" action="${ctp}/checkDOsearch.sh">
<b>검색 : </b>
<select name="search">
<option value="recipient_company">회사명</option>
<option value="recipient_country">회사국가</option>
</select>
<input type="text" name="searchString" id="searchString"/>
<input type="button" value="검색" onclick="searchCheck()" class="btn btn-primary btn-sm"/>
<input type="button" value="전체검색" onclick="location.href='${ctp}/checkDO.sh';" class="btn btn-primary btn-sm"/>
<input type="hidden" name="pag" value="${pag}"/>
<input type="hidden" name="pageSize" value="${pageSize}"/>
</form>
<table class="table table-hover text-center">
<tr class="table-info">
<th>번호</th>
<th>거래 회사 번호</th>
<th>거래 회사 국가</th>
<th>거래 회사 이름</th>
<th>거래 회사 연락처</th>
<th>운송 방법</th>
<th>제품 번호</th>
<th>제품 수량</th>
<th>제작자</th>
<th></th>
</tr>
<c:set var="curScrStartNo" value="${curScrStartNo}"/>
<c:forEach var="vo" items="${vos}" varStatus="st">
<tr>
<td>${vo.idx}</td>
<td>${vo.recipient_idx}</td>
<td>${vo.recipient_country}</td>
<td>${vo.recipient_company}</td>
<td>${vo.recipient_tel}</td>
<td>${vo.recipient_method}</td>
<td>${vo.product_idx}</td>
<td>${vo.product_quantity}</td>
<td>${vo.writer}</td>
<td><button onclick="location.href='${ctp}/detailDOCheck.sh?idx=${vo.idx}'" class ="btn btn-outline-primary btn-sm">V</button></td>
</tr>
<c:set var="curScrStartNo" value="${curScrStartNo-1}"/>
</c:forEach>
<tr><td colspan="7" class="m-0 p-0"></td></tr>
</table>
</div>
<br/>
<!-- 블록 페이지 시작 -->
<div class="text-center">
<ul class="pagination justify-content-center">
<c:if test="${pag > 1}">
<li class="page-item"><a class="page-link text-primary" href="${ctp}/checkDO.sh?pag=1">첫페이지</a></li>
</c:if>
<c:if test="${curBlock > 0}">
<li class="page-item"><a class="page-link text-primary" href="${ctp}/checkDO.sh?pag=${(curBlock-1)*blockSize + 1}">이전블록</a></li>
</c:if>
<c:forEach var="i" begin="${(curBlock)*blockSize + 1}" end="${(curBlock)*blockSize + blockSize}" varStatus="st">
<c:if test="${i <= totPage && i == pag}">
<li class="page-item active"><a class="page-link bg-primary border-primary" href="${ctp}/checkDO.sh?pag=${i}">${i}</a></li>
</c:if>
<c:if test="${i <= totPage && i != pag}">
<li class="page-item"><a class="page-link text-primary" href="${ctp}/checkDO.sh?pag=${i}">${i}</a></li>
</c:if>
</c:forEach>
<c:if test="${curBlock < lastBlock}">
<li class="page-item"><a class="page-link text-primary" href="${ctp}/checkDO.sh?pag=${(curBlock+1)*blockSize + 1}">다음블록</a></li>
</c:if>
<c:if test="${pag < totPage}">
<li class="page-item"><a class="page-link text-primary" href="${ctp}/checkDO.sh?pag=${totPage}">마지막페이지</a></li>
</c:if>
</ul>
</div>
<!-- 블록 페이지 끝 -->
<p><br/></p>
</body>
</html> |
import { AfterInsert, AfterRemove, AfterUpdate, AfterLoad, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: string;
@Column()
email: string;
@Column()
password: string;
@AfterInsert()
logInsert() {
console.log("User inserted with id: ", this.id)
}
@AfterUpdate()
logUpdate() {
console.log("User updated with id: ", this.id)
}
@AfterRemove()
logRemove() {
console.log("User updated with id: ", this.id)
}
@AfterLoad()
logLoad() {
console.log("Loaded ", this.id)
}
} |
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { RootState } from "app/store";
import axios from "axios";
import { ApiStatus, API_URL_USER } from "features/Utils";
interface IUpdateTeacherInfoState {
status: ApiStatus;
showModal: boolean;
code: null | string;
}
const initialState: IUpdateTeacherInfoState = {
status: ApiStatus.idle,
showModal: false,
code: null
}
interface IUpdateTeacherInfoRequest {
email: string;
first_name: string;
last_name: string;
token: string;
}
interface IUpdateTeacherInfoResponse {
code: string;
}
interface IUpdateTeacherInfoError {
code: string;
}
export const updateTeacherInfoAsync = createAsyncThunk(
'user/admin/updateTeacherInfo',
async (request: IUpdateTeacherInfoRequest, {rejectWithValue}) => await axios
.post(
API_URL_USER + "/admin/teachers",
request,
{
headers: {
Authorization: `Bearer ${request.token}`
}
}
)
.then((response) => {
return response.data;
})
.catch((error) => {
if(error.code === 'ERR_NETWORK'){
return rejectWithValue({
'code': 'ERR_NETWORK'
})
}
return rejectWithValue(error.response.data);
})
)
export const updateTeacherInfoSlice = createSlice({
name: 'updateTeacherInfo',
initialState,
reducers: {
revertUpdateTeacherInfo: () => {
return initialState;
}
},
extraReducers: (builder) => {
builder
.addCase(updateTeacherInfoAsync.pending, (state) => {
state.showModal = true;
state.status = ApiStatus.loading;
})
.addCase(updateTeacherInfoAsync.fulfilled, (state, action) => {
const res = action.payload as IUpdateTeacherInfoResponse;
state.code = res.code;
state.showModal = true;
state.status = ApiStatus.success;
})
.addCase(updateTeacherInfoAsync.rejected, (state, action) => {
const res = action.payload as IUpdateTeacherInfoError;
state.code = res.code;
state.showModal = true;
state.status = ApiStatus.failed;
})
}
});
export const { revertUpdateTeacherInfo } = updateTeacherInfoSlice.actions;
export const updateTeacherInfoStatus = (root: RootState) => root.updateTeacherInfo.status;
export const updateTeacherInfoShowModal = (root: RootState) => root.updateTeacherInfo.showModal;
export const updateTeacherInfoCode = (root: RootState) => root.updateTeacherInfo.code;
export default updateTeacherInfoSlice.reducer; |
package com.example.termproject.ui.dashboard;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.example.termproject.AddShoppingActivity;
import com.example.termproject.ChoiceFridgeActivity;
import com.example.termproject.DeletePopup;
import com.example.termproject.R;
import com.example.termproject.databinding.FragmentDashboardBinding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
import java.util.List;
public class DashboardFragment extends Fragment {
private FragmentDashboardBinding binding;
private ListView listView;
private FirebaseUser curUser = FirebaseAuth.getInstance().getCurrentUser();
final FirebaseFirestore db = FirebaseFirestore.getInstance();
private FirebaseDatabase mDatabase = FirebaseDatabase.getInstance("https://mobile-programming-91257-default-rtdb.asia-southeast1.firebasedatabase.app/");
private DatabaseReference mReference = mDatabase.getReference();
private DatabaseReference reference = mDatabase.getReference();
String uid = curUser != null ? curUser.getUid() : null;
public static String foodName;
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
MenuInflater inflater1 = getActivity().getMenuInflater();
inflater1.inflate(R.menu.menu_add_shopping, menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
// Toast.makeText(getActivity(), "checked!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getActivity(), AddShoppingActivity.class);
startActivity(intent);
return super.onOptionsItemSelected(item);
}
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
Log.d("HomeFragment", "들어옴");
ViewGroup rootView= (ViewGroup) inflater.inflate(R.layout.fragment_dashboard , container, false);
listView= (ListView) rootView.findViewById(R.id.shoppingList_listView);
mReference.child("USER").child(uid).child("shoppingList").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
List<String> data = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);
for(int i=1; i<100; i++)
{
if(snapshot.hasChild(Integer.toString(i))){
for(DataSnapshot dataSnapshot : snapshot.child(Integer.toString(i)).getChildren()){
String key = dataSnapshot.getKey();
if(key.equals("productName")){
String name=""+dataSnapshot.getValue().toString();
data.add(name);
Log.e("name", name);
}
// 이걸 해줘야 add 가 반영됨
adapter.notifyDataSetChanged();
}
}
else{
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
mReference.child("USER").child(uid).child("shoppingList").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
if(snapshot.hasChild(Integer.toString(index+1))){
for(DataSnapshot dataSnapshot : snapshot.child(Integer.toString(index+1)).getChildren())
{
String key = dataSnapshot.getKey();
if(key.equals("productName")){
String pName = "" + dataSnapshot.getValue().toString();
foodName = pName;
Toast.makeText(getActivity(), pName + " checked!", Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), pName + " checked!", Toast.LENGTH_SHORT).show();
Log.e("gg", pName);
reference.child("USER").child(uid).child("shoppingList").child(Integer.toString(index+1)).removeValue();
Intent intent = new Intent(getActivity(), ChoiceFridgeActivity.class);
intent.putExtra("fName",pName);
startActivity(intent);
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getActivity(), DeletePopup.class);
intent.putExtra("index", Integer.toString(i+1));
intent.putExtra("root", "shoppingList");
startActivity(intent);
return true;
}
});
setHasOptionsMenu(true);
return rootView;
}
@Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
} |
// eslint-disable-next-line @next/next/no-document-import-in-page
import Document, { Html, Head, Main, NextScript, DocumentContext } from 'next/document'
import flush from 'styled-jsx/server';
import React from 'react';
import { ServerStyleSheets } from '@material-ui/core';
class MyDocument extends Document {
static async getInitialProps(ctx: DocumentContext) {
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () =>
originalRenderPage({
enhanceApp: (App) => (props) => sheets.collect(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
return {
...initialProps,
styles: (
<React.Fragment>
{sheets.getStyleElement()}
</React.Fragment>
),
};
}
render() {
return (
<Html>
<head>
<meta charSet="utf-8" />
</head>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument |
<script setup lang="ts">
import PureRadio from '@/Components/Pure/PureRadio.vue'
import { BannerWorkshop } from '@/types/BannerWorkshop'
import { useSolidColor } from '@/Composables/useStockList'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { faCheck } from '@fal'
import { library } from '@fortawesome/fontawesome-svg-core'
library.add(faCheck)
const props = defineProps<{
fieldName?: string | []
fieldData?: {
options: {
label: string
name: string
}[]
}
data: BannerWorkshop
}>()
if (!props.data.navigation) {
props.data.navigation = {
sideNav: {
value: true,
type: 'arrow'
},
bottomNav: {
value: true,
type: 'bullet' // button
}
}
}
const bottomNavOptions = [
{
value: 'bullets'
},
{
value: 'buttons'
},
]
</script>
<template>
<div class="mt-2">
<div class="ml-3 w-fit bg-gray-100 border border-gray-300 rounded px-2 py-2 space-y-2 mb-2">
<div class="leading-none text-xs text-gray-500">
Colors
</div>
<div class="flex gap-x-1">
<div v-for="color in useSolidColor" @click="() => data.navigation.colorNav = color"
:style="{ 'background-color': color }"
class="relative h-5 aspect-square rounded overflow-hidden shadow cursor-pointer transition-all duration-200 ease-in-out"
:class="{ 'scale-110': data.navigation?.colorNav == color }"
>
<transition name="slide-bot-to-top">
<div v-if="color == data.navigation?.colorNav"
class="absolute flex items-center justify-center bg-black/20 inset-0">
<FontAwesomeIcon fixed-width icon='fal fa-check' class='text-white' aria-hidden='true' />
</div>
</transition>
</div>
</div>
</div>
<tbody class="divide-y divide-gray-200">
<tr v-for="(option, index) in fieldData?.options" :key="index">
<td class="whitespace-nowrap px-3 text-sm text-gray-500 text-center flex py-1.5">
<input v-model="data.navigation[option.name].value" :id="`item-${index}`" :name="`item-${index}`"
type="checkbox" :titles="`I'm Interested in ${option.label}`"
class="h-6 w-6 rounded cursor-pointer border-gray-300 hover:border-gray-500 text-gray-600 focus:ring-gray-600" />
</td>
<td class="">
<label :for="`item-${index}`"
class="whitespace-nowrap block py-2 pr-3 text-sm font-medium text-gray-500 hover:text-gray-600 cursor-pointer">
{{ option.label }}
</label>
<PureRadio v-if="data.navigation?.[option.name].value && option.name == 'bottomNav'"
v-model="data.navigation[option.name].type" :options="bottomNavOptions" />
</td>
</tr>
</tbody>
</div>
</template> |
import stringTotime from "jercel/helper/stringTotime";
import { useRouter } from "next/router";
import React from "react";
import Iframe from "react-iframe";
export interface ProjectDetails {
latestDeploymentId: string;
domain: string;
status: string;
createdAt: string;
lastUpdatedAt: string;
gitURL: string;
}
export default function ProjectDisplayCard(props: ProjectDetails) {
const router = useRouter();
const { hours, minutes, seconds } = stringTotime(props.createdAt);
return (
<React.Fragment>
<div className="w-full h-full flex">
<Iframe
url={props.domain}
width={"40%"}
className="rounded-md"
allowFullScreen
overflow="hidden"
/>
<div className="ml-10">
<div className=" text-gray-400">Latest DeploymentId</div>
<a
className="mt-1 hover:underline hover:cursor-pointer"
onClick={() => {
router.push(
`/projects/${router.query.projectId}/${props.latestDeploymentId}`
);
}}>
{props.latestDeploymentId}
</a>
<div className="mt-5 text-gray-400">Domain</div>
<a
className="mt-1 hover:underline hover:cursor-pointer"
href={props.domain}>
{props.domain}
</a>
<div className="mt-5 flex">
<div>
<div className="text-gray-400">Status</div>
<div className="mt-1">{props.status}</div>
</div>
<div className="ml-8">
<div className="text-gray-400">CreatedAt</div>
<div className="mt-1">
{hours
? hours + " hrs"
: minutes
? minutes + " min"
: seconds + " sec"}{" "}
ago{" "}
</div>
</div>
</div>
<div className="mt-5 text-gray-400">GitURL</div>
<a
className="mt-1 hover:underline hover:cursor-pointer"
href={props.gitURL}>
{props.gitURL}
</a>
</div>
</div>
</React.Fragment>
);
} |
<?php
namespace App\Services;
use App\Jobs\ProcessUrlsJob;
use App\Models\Hotel;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Cache;
class RateService
{
/**
* @param int $rateFrom
* @param int $rateTo
* @return void
* @throws \Exception
*/
public function getHotelDirectoryURLs(int $rateFrom, int $rateTo): void
{
$latestRevision = Cache::get(LATEST_REVISION) ?? 0;
$response = $this->callGiataAPICURL(env('HOTEL_DIRECTORY_URL') . '?after=' . $latestRevision);
$data = json_decode($response, true);
Cache::forever(LATEST_REVISION, $data['latestRevision']);
$this->checkValidGiataId($data['urls'], $rateFrom, $rateTo);
}
/**
* @param array $urls
* @param $rateFrom
* @param $rateTo
* @return void
*/
public function checkValidGiataId(array $urls, $rateFrom, $rateTo): void
{
$ratingArr = range($rateFrom + 1, $rateTo - 1);
$chunkUrls = array_chunk($urls, 100);
foreach ($chunkUrls as $chunkUrl) {
Http::pool(function (Pool $pool) use ($urls, $chunkUrl, $ratingArr, &$responses) {
collect($chunkUrl)->each(function ($url, $key) use ($pool, $chunkUrl, $ratingArr, &$responses) {
preg_match('/\/(\d+)\//', $url, $matches);
$giataId = (int)$matches[1];
for ($x = 0; $x < count($ratingArr); $x++) {
if ($giataId % $ratingArr[$x] != 0) {
continue;
}
$pool->get($url)->then(function ($response) use ($url, $key, &$responses) {
$response = $response->json();
if ($response['source'] == SOURCE) {
$hotelName = $response['names'][0]['value'] ?? null;
$giataId = $response['giataId'] ?? null;
$rate = str_replace(',', '.', $response['ratings'][0]['value']) ?? null;
if (fmod($giataId, $rate) == 0) {
log::info('giataId: ' . $giataId);
log::info('rate: ' . $rate);
ProcessUrlsJob::dispatch(['name' => $hotelName, 'GIATA_id' => $giataId, 'rate' => $rate, 'batchKey' => $key]);
}
}
});
break;
}
});
});
}
// echo 'URLS dispatched successfully';
}
/**
* @param $url
* @return bool|string
*/
public function callGiataAPICURL($url): bool|string
{
try {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30000,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: */*",
"accept-language: en-US,en;q=0.8",
"content-type: application/json",
),
));
$response = curl_exec($curl);
curl_close($curl);
return $response;
} catch (\Exception $exception) {
Log::error($exception->getMessage());
throw $exception;
}
}
/**
* @return string
* @throws \Exception
*/
public function countUrlsWithoutReminder($request): string
{
$check = $this->callGiataAPICURL(env('HOTEL_DIRECTORY_URL') . '?after=' . Cache::get(LATEST_REVISION));
$data = json_decode($check, true);
if ($data['urls']) {
$this->checkValidGiataId($data['urls'], $request['rate_from'], $request['rate_to']);
}
if ($data['deletedUrls']) {
foreach ($data['deletedUrls'] as $deletedUrl) {
preg_match('/\/(\d+)\//', $deletedUrl, $matches);
$deletedGiataId[] = (int)$matches[1];
}
Hotel::whereIn('GIATA_id', $deletedGiataId)->delete();
}
if ($data['latestRevision'] != Cache::get(LATEST_REVISION)) {
Cache::forget(LATEST_REVISION);
Cache::put(LATEST_REVISION, $data['latestRevision']);
}
return Hotel::count();
}
} |
/*
Copyright (C) 2019 3NSoft Inc.
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>. */
import { HeaderChunkInfo, SegsChunk } from "./file-layout";
export const V1_FILE_START = Buffer.from('1xsp', 'utf8');
/**
* @param u is an unsigned integer up to 32-bits to be stored big-endian way in
* 4 bytes.
* @return a byte array with number stored in it.
*/
function uintTo4Bytes(u: number): Buffer {
if (u >= 0x100000000) { throw new Error(
'Cannot store number bigger than 2^32-1'); }
const x = Buffer.allocUnsafe(4);
x[0] = u >>> 24;
x[1] = u >>> 16;
x[2] = u >>> 8;
x[3] = u;
return x;
}
/**
* @param x
* @param i
* @return unsigned integer (up to 32 bits), stored big-endian way
* in 4 bytes of x, starting at index i.
*/
function uintFrom4Bytes(x: Uint8Array, i = 0): number {
if (x.length < i+4) { throw new Error(
'Given array has less than 4 bytes, starting with a given index.'); }
return ((x[i] << 24) | (x[i+1] << 16) | (x[i+2] << 8) | x[i+3]);
}
/**
* @param u is an unsigned integer up to 53-bits to be stored big-endian way in
* 8 bytes.
* @return a byte array with number stored in it.
*/
export function uintTo8Bytes(u: number): Buffer {
if (u > Number.MAX_SAFE_INTEGER) { throw new Error(
'Cannot store number bigger than 2^53-1'); }
const x = Buffer.allocUnsafe(8);
const h = Math.floor(u / 0x100000000);
const l = u % 0x100000000;
x[0] = h >>> 24;
x[1] = h >>> 16;
x[2] = h >>> 8;
x[3] = h;
x[4] = l >>> 24;
x[5] = l >>> 16;
x[6] = l >>> 8;
x[7] = l;
return x;
}
/**
* @param x
* @param i
* @return unsigned integer (up to 53 bits), stored big-endian way
* in 8 bytes of x, starting at index i.
*/
export function uintFrom8Bytes(x: Uint8Array, i = 0): number {
if (x.length < i+8) { throw new Error(
'Given array has less than 8 bytes, starting with a given index.'); }
const h = (x[i] << 24) | (x[i+1] << 16) | (x[i+2] << 8) | x[i+3];
const l = (x[i+4] << 24) | (x[i+5] << 16) | (x[i+6] << 8) | x[i+7];
return (h*0x100000000 + l);
}
namespace headerChunkInfo {
export function toBytes(hInfo: HeaderChunkInfo): Buffer {
const buf = Buffer.allocUnsafe(12);
buf.set(uintTo4Bytes(hInfo.len));
buf.set(uintTo8Bytes(hInfo.fileOfs), 4);
return buf;
}
export function fromBytes(b: Uint8Array, i: number):
{ hInfo: HeaderChunkInfo; bytesRead: number; } {
let bytesRead = 0;
const len = uintFrom4Bytes(b, i + bytesRead);
bytesRead += 4;
const fileOfs = uintFrom8Bytes(b, i + bytesRead);
bytesRead += 8;
const hInfo: HeaderChunkInfo = { len, fileOfs };
return { hInfo: Object.freeze(hInfo), bytesRead };
}
}
Object.freeze(headerChunkInfo);
namespace segsChunkInfo {
const IS_ENDLESS_BITMASK = 0b00000001;
const FILE_OFS_PRESENT_BITMASK = 0b00000010;
const BASE_VER_OFS_PRESENT_BITMASK = 0b00000100;
export function toBytes(sInfo: SegsChunk): Buffer {
let flag = 0;
let bufSize = 17;
if ((sInfo.type === 'new-on-disk') || (sInfo.type === 'base-on-disk')) {
flag |= FILE_OFS_PRESENT_BITMASK;
bufSize += 8;
}
if ((sInfo.type === 'base') || (sInfo.type === 'base-on-disk')) {
flag |= BASE_VER_OFS_PRESENT_BITMASK;
bufSize += 8;
}
const buf = Buffer.allocUnsafe(bufSize);
let i = 0;
buf[i] = flag;
i += 1;
buf.set(uintTo8Bytes(sInfo.thisVerOfs), i);
i += 8;
if (sInfo.type !== 'new-endless') {
buf.set(uintTo8Bytes(sInfo.len), 9);
i += 8;
}
if ((sInfo.type === 'new-on-disk') || (sInfo.type === 'base-on-disk')) {
buf.set(uintTo8Bytes(sInfo.fileOfs), i);
i += 8;
}
if ((sInfo.type === 'base') || (sInfo.type === 'base-on-disk')) {
buf.set(uintTo8Bytes(sInfo.baseVerOfs), i);
}
return buf;
}
export function fromBytes(b: Uint8Array, i: number):
{ sInfo: SegsChunk; bytesRead: number; } {
let bytesRead = 0
const flag = b[i + bytesRead];
bytesRead += 1;
const thisVerOfs = uintFrom8Bytes(b, i + bytesRead);
bytesRead += 8;
let len: number|undefined = undefined;
if ((flag & IS_ENDLESS_BITMASK) === 0) {
len = uintFrom8Bytes(b, i + bytesRead);
bytesRead += 8;
}
let fileOfs: number|undefined = undefined;
if (flag & FILE_OFS_PRESENT_BITMASK) {
fileOfs = uintFrom8Bytes(b, i + bytesRead);
bytesRead += 8;
}
let baseVerOfs: number|undefined = undefined;
if (flag & BASE_VER_OFS_PRESENT_BITMASK) {
baseVerOfs = uintFrom8Bytes(b, i + bytesRead);
bytesRead += 8;
}
const isOnDisk = (fileOfs !== undefined);
const isBase = (baseVerOfs !== undefined);
const isFinite = (len !== undefined);
let sInfo: SegsChunk;
if (isOnDisk) {
if (!isFinite) { throw new Error(`Obj file segments chunk flag says that bytes are on disk, when chunk is infinite`); }
if (isBase) {
sInfo = {
type: 'base-on-disk',
thisVerOfs,
len: len!,
fileOfs: fileOfs!,
baseVerOfs: baseVerOfs!
};
} else {
sInfo = {
type: 'new-on-disk',
thisVerOfs,
len: len!,
fileOfs: fileOfs!
};
}
} else {
if (isBase) {
sInfo = {
type: 'base',
thisVerOfs,
len: len!,
baseVerOfs: baseVerOfs!
};
} else if (isFinite) {
sInfo = {
type: 'new',
thisVerOfs,
len: len!
};
} else {
sInfo = {
type: 'new-endless',
thisVerOfs
};
}
}
return { sInfo, bytesRead };
}
}
Object.freeze(segsChunkInfo);
export namespace layoutV1 {
const HEADER_PRESENT_BITMASK = 0b00000001;
const BASE_PRESENT_BITMASK = 0b00000010;
const SEGS_LAYOUT_FROZEN_BITMASK = 0b00000100;
const TOTAL_SIZE_NOT_SET_BITMASK = 0b00001000;
const VERSION_FILE_COMPLETE_BITMASK = 0b00010000;
const ALL_BASE_BYTES_IN_FILE_BITMASK = 0b00100000;
export interface Attrs {
fileComplete: boolean;
segsChunks: SegsChunk[];
headerChunk?: HeaderChunkInfo;
segsLayoutFrozen: boolean;
baseVersion?: number;
sizeUnknown: boolean;
allBaseBytesInFile: boolean;
}
function validateAttrs(attrs: Attrs): void {
// XXX check consistency of attrs
}
export function toBytes(a: Attrs): Buffer {
let flag = 0;
let baseBytes: Buffer|undefined = undefined;
if (a.baseVersion !== undefined) {
flag |= BASE_PRESENT_BITMASK;
baseBytes = uintTo8Bytes(a.baseVersion);
if (a.allBaseBytesInFile) {
flag |= ALL_BASE_BYTES_IN_FILE_BITMASK;
}
}
let headerInfoBytes: Buffer|undefined = undefined;
if (a.headerChunk) {
flag |= HEADER_PRESENT_BITMASK;
headerInfoBytes = headerChunkInfo.toBytes(a.headerChunk);
if (a.fileComplete) {
flag |= VERSION_FILE_COMPLETE_BITMASK;
}
}
if (a.segsLayoutFrozen) {
flag |= SEGS_LAYOUT_FROZEN_BITMASK;
}
if (a.sizeUnknown) {
flag |= TOTAL_SIZE_NOT_SET_BITMASK;
}
const segsInfoBytes = a.segsChunks.map(s => segsChunkInfo.toBytes(s));
const buf = Buffer.allocUnsafe(1 +
(baseBytes ? 8 : 0) +
(headerInfoBytes ? headerInfoBytes.length : 0) +
totalLenOf(segsInfoBytes));
buf[0] = flag;
let i = 1;
if (baseBytes) {
buf.set(baseBytes, i);
i += 8;
}
if (headerInfoBytes) {
buf.set(headerInfoBytes, i);
i += headerInfoBytes.length;
}
for (const chunk of segsInfoBytes) {
buf.set(chunk, i);
i += chunk.length;
}
return buf;
}
export function fromBytes(b: Uint8Array, i: number): Attrs {
const flag = b[i];
i += 1;
let baseVersion: number|undefined = undefined;
if (flag & BASE_PRESENT_BITMASK) {
baseVersion = uintFrom8Bytes(b, i);
i += 8;
}
let headerChunk: HeaderChunkInfo|undefined = undefined;
if (flag & HEADER_PRESENT_BITMASK) {
const { hInfo, bytesRead } = headerChunkInfo.fromBytes(b, i);
headerChunk = hInfo;
i += bytesRead;
}
const fileComplete = !!(flag & VERSION_FILE_COMPLETE_BITMASK);
const segsLayoutFrozen = !!(flag & SEGS_LAYOUT_FROZEN_BITMASK);
const sizeUnknown = !!(flag & TOTAL_SIZE_NOT_SET_BITMASK);
const allBaseBytesInFile = !!(flag && ALL_BASE_BYTES_IN_FILE_BITMASK);
const segsChunks: SegsChunk[] = [];
while (i < b.length) {
const { sInfo, bytesRead } = segsChunkInfo.fromBytes(b, i);
segsChunks.push(sInfo);
i += bytesRead;
}
const attrs = { fileComplete, segsChunks, headerChunk, segsLayoutFrozen,
baseVersion, sizeUnknown, allBaseBytesInFile };
validateAttrs(attrs);
return attrs;
}
}
Object.freeze(layoutV1);
function totalLenOf(arrs: Uint8Array[]): number {
let totalLen = 0;
for (const arr of arrs) {
totalLen += arr.length;
}
return totalLen;
}
Object.freeze(exports); |
import * as React from 'react'
import 'prismjs/components/prism-jsx'
import 'prismjs/components/prism-tsx'
import 'prismjs/components/prism-css'
import 'prismjs/components/prism-markup'
import {GlobalTheme} from "../ThemeManager";
import {MarkdownBlock, NoCSSControlView} from "./NoCSSControlView";
import {Label} from "../../lib/components";
import {stylable} from "../../lib/core";
export const NoCSSStylableComponent = ({theme}: { theme: GlobalTheme }) => {
return <NoCSSControlView controlLink='stylable'
theme={theme}
title='Stylable Component'
subTitle='<div>'>
<MarkdownBlock title="1. By default we can attach a style to a UIComponent only in a react-function"
markdown1={block1NoCSSTxt}
theme={theme}>
<UIComponent title='This interface offers only a title-property'/>
</MarkdownBlock>
<MarkdownBlock title="2. Stylable-wrapper can help decorate a UIComponent"
markdown1={block2NoCSSTxt}
theme={theme}>
<StylableUIComponent title='Stylable UIComponent'
padding='50px'
border='20px solid #8851ae'
cornerRadius='10px'
bgColor='#874083'/>
</MarkdownBlock>
</NoCSSControlView>
}
const UIComponent = ({title}: { title: string }) => {
return (
<Label text={title}
textColor='#ccd7da'
borderBottom='2px solid #ccd7da'/>
)
}
const StylableUIComponent = stylable(({title}: { title: string }) => {
return (
<Label text={title}
textColor='#ccd7da'
borderBottom='2px solid #ccd7da'/>
)
})
/*
Block 1
*/
const block1NoCSSTxt = `\`\`\`tsx
const App = () => {
return (
<UIComponent title='This interface offers only a title-property'/>
)
}
const UIComponent = ({title}: { title: string }) => {
return (
<Label text={title}
textColor='#ccd7da'
borderBottom='2px solid #ccd7da'/>
)
}
\`\`\``
/*
Block 2
*/
const block2NoCSSTxt = `\`\`\`tsx
const App = () => {
return (
<StylableUIComponent title='Stylable UIComponent'
padding='50px'
border='20px solid #8851ae'
cornerRadius='10px'
bgColor='#874083'/>
)
}
const StylableUIComponent = stylable(({title}: { title: string }) => {
return (
<Label text={title}
textColor='#ccd7da'
borderBottom='2px solid #ccd7da'/>
)
})
\`\`\`` |
import { useEffect } from 'react';
import closeIcon from '../../assets/images/close-icon.svg';
import { OrderProps } from '../../types/Order';
import { formatCurrency } from '../../utils/formatCurrency';
import { ModalBody, ModalOverlay, OrderActions, OrderDetailsContainer } from './styles';
interface OrderModalProps {
visible: boolean;
order: OrderProps | null;
onClose: () => void;
onCancelOrder: () => Promise<void>;
onChangeOrderStatus: () => Promise<void>;
isLoading: boolean
}
export function OrderModal({ visible, order, onClose, onCancelOrder, onChangeOrderStatus, isLoading }:OrderModalProps) {
useEffect(() => {
function handleKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
onClose();
}
}
document.addEventListener('keydown', handleKeydown);
return () => {
document.removeEventListener('keydown', handleKeydown);
};
}, [onClose]);
if (!visible || !order) {
return null;
}
const totalOrderPrice = order.products.reduce((total, { product, quantity }) => {
return total + (product.price * quantity);
}, 0);
return (
<ModalOverlay>
<ModalBody>
<header>
<strong>Mesa {order.table}</strong>
<button type='button' onClick={onClose}>
<img src={closeIcon} alt="Fechar" />
</button>
</header>
<div className='status-container'>
<small>Status do Pedido</small>
<div>
<span>
{order.status === 'WAITING' && '⏰'}
{order.status === 'IN_PRODUCTION' && '👩🍳'}
{order.status === 'DONE' && '✅'}
</span>
<strong>
{order.status === 'WAITING' && 'Fila de Espera'}
{order.status === 'IN_PRODUCTION' && 'Em produção'}
{order.status === 'DONE' && 'Pronto'}
</strong>
</div>
</div>
<OrderDetailsContainer>
<strong>Itens</strong>
<div className="items-container">
{order.products.map(({ _id, product, quantity }) => (
<div className="item-box" key={_id}>
<img
src={`http://localhost:3001/uploads/${product.imagePath}`}
alt={product.name}
/>
<span className='item-quantity'>{quantity}x</span>
<div className='item-details'>
<strong>{product.name}</strong>
<span>{formatCurrency(product.price)}</span>
</div>
</div>
))}
</div>
<div className="total-order-price">
<span>Total</span>
<strong>{formatCurrency(totalOrderPrice)}</strong>
</div>
</OrderDetailsContainer>
<OrderActions>
{order.status !== 'DONE' && (
<button
type='button'
className='next-stage'
disabled={isLoading}
onClick={onChangeOrderStatus}
>
{order.status === 'WAITING' ? (
<>
<span>👩🍳</span>
<span>Iniciar produção</span>
</>
) : (
<>
<span>✅</span>
<span>Finalizar pedido</span>
</>
)}
</button>
)}
<button
type='button'
className='cancel-order'
onClick={onCancelOrder}
disabled={isLoading}
>
{order.status === 'DONE'
? <span>Remover pedido</span>
: <span>Cancelar pedido</span>}
</button>
</OrderActions>
</ModalBody>
</ModalOverlay>
);
} |
<script setup lang="ts">
import type { QInput, ValidationRule } from 'quasar';
import { useQuasar } from 'quasar';
import { ref } from 'vue';
import { useAuth } from '~/composable/useAuth';
import { useI18n } from '~/composable/useI18n';
import { useSignInMutation } from '../apis/useSignInMutation';
const { t } = useI18n();
const auth = useAuth();
const $q = useQuasar();
const mutation = useSignInMutation();
const formValues = ref({ username: '', password: '', remember: 0 });
const emailField = ref<QInput | null>(null);
const emailRules: ValidationRule<string>[] = [
(value) => !!value || t('this_field_is_required'),
(value) => value.length <= 64 || t('the_length_is_from_1_to_64_characters'),
];
const isPwd = ref(true);
const passwordField = ref<QInput | null>(null);
const passwordRules: ValidationRule<string>[] = [
(value) => !!value || t('this_field_is_required'),
(value) => 6 <= value.length || t('this_value_is_too_short'),
];
const onSubmit = () => {
emailField.value?.validate();
passwordField.value?.validate();
if (emailField.value?.error || passwordField.value?.error) return;
mutation.mutate(formValues.value, {
onSuccess: ({ data }) => {
let profile = data.profile;
profile.permission = data.permission;
auth.signIn({
accessToken: data.accessToken,
expiresAt: data.expiresAt,
profile: profile,
});
},
onError: ({ response }) => {
response?.data.error.forEach(
(val: { message: string | undefined; [key: string]: string | object | undefined }) => {
$q.notify({
message: val.message,
position: 'bottom-right',
type: 'negative',
actions: [{ label: 'Dismiss', color: 'white' }],
});
},
);
},
});
};
</script>
<template>
<q-form class="q-form form" @submit="onSubmit">
<q-input
ref="emailField"
v-model="formValues.username"
:label="t('email')"
class="custom-input"
:rules="emailRules"
@focus="true"
autogrow
@keydown.enter.prevent=""
/>
<q-input
ref="passwordField"
v-model="formValues.password"
:label="t('password')"
:rules="passwordRules"
class="custom-input"
:type="isPwd ? 'password' : 'text'"
>
<template v-slot:append>
<q-icon
:name="isPwd ? 'visibility_off' : 'visibility'"
class="cursor-pointer"
@click="isPwd = !isPwd"
/>
</template>
</q-input>
<q-btn
class="q-mt-lg"
type="submit"
:loading="mutation.isLoading.value"
data-testid="sign-in-btn"
data-cy="sign-in-btn"
>
{{ t('sign_in') }}
</q-btn>
</q-form>
</template>
<style lang="scss" scoped>
.form {
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
}
.custom-input {
margin: 5px;
}
</style> |
"""nanosip - Simply ring a phone."""
import asyncio
import hashlib
import os
import random
import re
import string
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import Any, NamedTuple, Optional, Union, List
class SIPError(Exception):
"""Raised when some SIP-protocol related error happens."""
class SIPAuthCreds(NamedTuple):
"""A named tuple that stores username and password for SIP authentication."""
username: str
password: str
class Transaction(ABC):
"""Class for a SIP transaction.
A SIP transaction consists of a single request and any responses to
that request, which include zero or more provisional responses and
one or more final responses. (rfc3261#section-17).
Note: If a request needs to be repeated for Authorization, this will
also be handled by the same Transaction.
"""
check_func: Optional[Callable[[], None]]
pending_requests: list[Union[str, Any]]
realm: Optional[str]
nonce: Optional[str]
errors: List[str]
class TerminationMarker:
"""Used as a pseudo request to mark the end of a transaction.
Note that we use the class, not an instance of it.
"""
def __init__(
self,
uri_from: str,
uri_to: str,
uri_via: str,
auth_creds: SIPAuthCreds,
) -> None:
"""Construct a Transaction object."""
self.check_func = None # Callback to notify Protocol of new pending requests
self.uri_from = uri_from
self.uri_to = uri_to
self.uri_via = uri_via
self.cseq = 1
self.send_ack_unauthorized = False
self.branch = self._generate_branch()
self.call_id = self._generate_call_id()
self.tag = self._generate_tag()
self.errors = []
self.pending_requests = []
self.auth_creds = auth_creds
self.realm = None
self.nonce = None
self.req_pending = None
self.remaining_auth_tries = 2 # Try authorization at most 2 times.
@abstractmethod
def method(self) -> str:
"""Override to return the name of the implemented method."""
raise NotImplementedError
@abstractmethod
def get_request(self, additional_headers: Optional[list] = None) -> str:
"""Override and return the request headers for this method."""
raise NotImplementedError
def get_next_request(self) -> Optional[Union[str, Any]]:
"""Return the next request this transaction wants to send if any."""
if len(self.pending_requests) > 0:
return self.pending_requests.pop(0)
return None
def handle_response(self, resp: str):
"""Upon receiving a new response, handle it."""
status, reason, header_vals = self._parse_response_status(resp)
if status == 401 or status == 407: # Unauthorized
if self.remaining_auth_tries <= 0:
self.pending_requests.append(self.TerminationMarker)
self.errors.append(f"{status} Unauthorized")
raise SIPError
self.remaining_auth_tries -= 1
if status == 401:
auth_header = header_vals["WWW-Authenticate"]
else:
auth_header = header_vals["Proxy-Authenticate"]
match_realm = re.search(r"realm\s*=\s*\"([^\"]+)\"", auth_header)
match_nonce = re.search(r"nonce\s*=\s*\"([^\"]+)\"", auth_header)
assert isinstance(match_realm, re.Match), f"Cannot parse SIP realm in '{auth_header}'"
assert isinstance(match_nonce, re.Match), f"Cannot parse SIP nonce in '{auth_header}'"
self.realm = match_realm.group(1)
self.nonce = match_nonce.group(1)
# Add ACK and next request
if self.send_ack_unauthorized:
self.pending_requests.append(self._generate_headers(["Content-Length: 0"], method="ACK") + "\r\n\r\n")
self.branch = self._generate_branch()
self.cseq += 1
auth_values = {
"username": self.auth_creds.username,
"realm": self.realm,
"nonce": self.nonce,
"uri": self.uri_to,
"response": self._generate_authorization(self.auth_creds, self.realm, self.nonce),
}
if status == 401:
auth_header_name = "Authorization"
else:
auth_header_name = "Proxy-Authorization"
self.pending_requests.append(
self.get_request(
[f"{auth_header_name}: Digest " + ",".join([f'{k}="{v}"' for k, v in auth_values.items()])]
)
)
elif status == 487: # Request cancelled
# Add ACK
self.pending_requests.append(self._generate_headers(["Content-Length: 0"], method="ACK") + "\r\n\r\n")
# We don't store an error here, since we want to cancel the request
elif status == 200:
# OK
pass
elif status == 100:
# Trying
pass
elif 180 <= status <= 183:
# Ringing, Forwarded, Queued, Session Progress
pass
else:
# Some other failure (e.g. BUSY, bad request, etc.)
self.errors.append(f"{status} {reason}")
raise SIPError
def _generate_branch(self, length=32) -> str:
branchid = "".join(random.choices(string.hexdigits, k=length - 7))
return f"z9hG4bK{branchid}"
def _generate_call_id(self) -> str:
hhash = hashlib.sha256(os.urandom(32)).hexdigest()
return f"{hhash[0:32]}"
def _generate_tag(self) -> str:
rand = str(os.urandom(32)).encode("utf8")
return hashlib.md5(rand).hexdigest()[0:8]
def _generate_headers(
self,
additional_headers: Optional[list] = None,
method: Optional[str] = None,
cseq_method: Optional[str] = None,
):
if additional_headers is None:
additional_headers = []
if method is None:
method = self.method()
if cseq_method is None:
cseq_method = method
return "\r\n".join(
[
f"{method} {self.uri_to} SIP/2.0",
f"Via: SIP/2.0/UDP {self.uri_via};rport;branch={self.branch}",
f"To: <{self.uri_to}>",
f"From: <{self.uri_from}>;tag={self.tag}",
f"Contact: <{self.uri_from}>",
f"CSeq: {self.cseq} {cseq_method}",
f"Call-ID: {self.call_id}",
"Max-Forwards: 70",
"User-Agent: NanoSIP/0.1",
]
+ additional_headers
)
def _parse_response_status(self, response: str):
lines = response.split("\r\n")
sip_version, status_code, reason = lines[0].split(" ", maxsplit=2)
assert sip_version == "SIP/2.0"
header_vals = {}
for line in lines[1:]:
l_cont = line.strip()
if l_cont == "":
break
# To be improved: This parsing is not correct. Improve
key, val = l_cont.split(":", maxsplit=1)
header_vals[key] = val
return int(status_code), reason, header_vals
def _generate_authorization(self, creds: SIPAuthCreds, realm: str, nonce: str) -> str:
ha1 = hashlib.md5((creds.username + ":" + realm + ":" + creds.password).encode("utf8")).hexdigest()
ha2 = hashlib.md5(("" + self.method() + ":" + self.uri_to).encode("utf8")).hexdigest()
bytes_to_hash = (ha1 + ":" + nonce + ":" + ha2).encode("utf8")
response = hashlib.md5(bytes_to_hash).hexdigest()
return response
class Invite(Transaction):
"""See rfc3261#section-17.1.1."""
def __init__(self, uri_from: str, uri_to: str, uri_via: str, auth_creds: SIPAuthCreds) -> None:
"""Construct a new Invite transaction object."""
super().__init__(uri_from, uri_to, uri_via, auth_creds)
self.send_ack_unauthorized = True
self.pending_requests.append(self.get_request())
def method(self) -> str:
"""Return that this is the INVITE method."""
return "INVITE"
def get_request(self, additional_headers: Optional[list] = None):
"""Generate and return the headers for an INVITE."""
if additional_headers is None:
additional_headers = []
return self._generate_headers(["Content-Length: 0"] + additional_headers) + "\r\n\r\n"
def cancel(self):
"""Cancel this INVITE."""
self.pending_requests.append(
self._generate_headers(["Content-Length: 0"], method="CANCEL", cseq_method="CANCEL") + "\r\n\r\n"
)
self.pending_requests.append(self.TerminationMarker)
if self.check_func:
self.check_func()
class Register(Transaction):
"""See rfc3261#section-17.1.1."""
def __init__(
self,
uri_from: str,
uri_to: str,
uri_via: str,
auth_creds: SIPAuthCreds,
uri_contact: str,
) -> None:
"""Construct a new Register transaction object."""
super().__init__(uri_from, uri_to, uri_via, auth_creds)
self.uri_contact = uri_contact
self.pending_requests.append(self.get_request())
def method(self) -> str:
"""Return that this is the REGISTER method."""
return "REGISTER"
def get_request(self, additional_headers: Optional[list] = None):
"""Generate and return the headers for a REGISTER."""
if additional_headers is None:
additional_headers = []
return (
self._generate_headers(
[f"Contact: <{self.uri_contact}>", "Expires: 60", "Content-Length: 0"] + additional_headers
)
+ "\r\n\r\n"
)
class TransactionProcessor:
"""Processes a given transaction and manages the connection needed for that transaction.
Passes UDP messages in and out.
The run method returns a list of error strings. If the list is empty, everything is ok.
"""
transport: Optional[asyncio.DatagramTransport]
class UDPProtocol(asyncio.DatagramProtocol):
"""Manage the UDP connection and handle incoming messages."""
def __init__(self, transaction: Transaction, done_future: asyncio.Future) -> None:
"""Construct the UDPProtocol object."""
self.transaction = transaction
self.transaction.check_func = self.maybe_send_new_requests
self.done_future = done_future
self.transport = None
def maybe_send_new_requests(self):
"""Send messages as long as our transaction object has new messages to send."""
if self.done_future.done():
return
assert self.transport, "Need to make a connection before sending or receiving SIP datagrams."
while True:
next_req = self.transaction.get_next_request()
if isinstance(next_req, str):
self.transport.sendto(next_req.encode())
elif next_req is Transaction.TerminationMarker:
self.transport.close()
self.transport = None
self.done_future.set_result(True)
break
else:
break
def connection_made(self, transport):
"""Start sending messages as soon as we are connected."""
self.transport = transport
self.maybe_send_new_requests()
def datagram_received(self, data, addr):
"""Handle any response we receive."""
try:
self.transaction.handle_response(data.decode())
except SIPError:
if self.transport:
self.transport.close()
self.transport = None
self.done_future.set_result(True)
if self.transport:
self.maybe_send_new_requests()
def error_received(self, exc):
"""Close the connection if we receive an error."""
if self.transport:
self.transport.close()
if not self.done_future.done():
self.done_future.set_exception(exc)
def connection_lost(self, exc):
"""If the connection is lost, let the outer loop know about it."""
if not self.done_future.done():
self.done_future.set_result(True)
def __init__(self, transaction: Transaction, sip_server: Optional[str] = None) -> None:
"""Construct the TransactionProcessor."""
self.transaction = transaction
self.sip_server = sip_server
self.errors = []
def _extract_ip(self, uri: str):
if "@" in uri:
return uri.split("@", maxsplit=1)[-1]
return uri
async def run(self):
"""Start the main loop of the transaction processor."""
loop = asyncio.get_running_loop()
done_future = loop.create_future()
sip_server = self.sip_server
if sip_server is None:
# If no sip server is given, we take the domain of the FROM-URI
sip_server = self._extract_ip(self.transaction.uri_from)
transport, protocol = await loop.create_datagram_endpoint(
lambda: self.UDPProtocol(self.transaction, done_future),
remote_addr=(sip_server, 5060),
)
udp_errors = []
try:
await done_future
except OSError as e:
# We will catch UDP Protocol related errors here.
udp_errors = [str(e)]
finally:
transport.close()
# Errors related to SIP, are stored by the Transaction object, we add them here.
return udp_errors + self.transaction.errors
async def async_call_and_cancel(inv: Invite, duration: int, sip_server: Optional[str] = None):
"""Make a call and cancel it after `duration` seconds.
Note that this simple SIP implementation is not capable of establishing
an actual audio connection. It just rings the other phone.
"""
tp = TransactionProcessor(inv, sip_server=sip_server)
async def cancel_call(inv):
await asyncio.sleep(duration)
inv.cancel()
tp_task = asyncio.create_task(tp.run())
cancel_task = asyncio.create_task(cancel_call(inv))
try:
tp_ret = await asyncio.wait_for(tp_task, duration+1)
except asyncio.TimeoutError:
print("Hit Iimeout")
cancel_task.cancel()
return
cancel_task.cancel()
# tp_ret, _ = await asyncio.gather(tp.run(), cancel_call(inv))
if len(tp_ret) > 0:
raise OSError("nanosip error: " + "; ".join(tp_ret))
def call_and_cancel(inv: Invite, duration: int, sip_server: Optional[str] = None):
"""Make a call and cancel it after `duration` seconds.
Note that this simple SIP implementation is not capable of establishing
an actual audio connection. It just rings the other phone.
"""
return asyncio.run(async_call_and_cancel(inv, duration, sip_server)) |
A. Service Description:
"itemservice" is a micro-service that provides the following RESTful API:
1. Add a new Item, (assuming the creation date is updated while adding the item)
2. Change the description of an Item
3. Mark an item status as “done” or “not done” (assuming the item status “done” can be marked as “not done”)
4. Get all the Items
5. Get details of a specific item
B. Tech Stack used:
Below are the Tech Stack used in developing this micro-service:
a. Spring Boot version 2.7.2
b. Java version 1.8
c. H2 Database runtime
d. Eclipse version 2019-09
e. Postman for testing RESTful API
f. Docker Desktop version 20.10.17
C. How to build the “itemservice-v1.0.jar” service:
a. Set the "Environmental Variables"
JAVA_HOME = D:\Downloaded-Software\openjdk-8u262-x64
JDK_HOME = D:\Downloaded-Software\openjdk-8u262-x64
Path --> Add --> D:\Downloaded-Software\openjdk-8u262-x64\bin
b. Goto the Command Prompt
java –version
openjdk version "1.8.0-262"
c. Open GIT CMD, git clone https://github.com/pkumar52/mitigant.git
c. open Eclipse, File/Import/Existing Maven Projects
Select the "itemservice" directory, and click on Finish
Right click on project -> Build Path -> Configure Build Path
Add Library --> JRE System Library --> Installed JREs --> Add
--> D:\Downloaded-Software\openjdk-8u262-x64
Right click on “itemservice“ project --> Maven -> Update Project
Right click on “itemservice“ project --> Run As -> Run Configuration
Double Click on "Maven Build"
Name: itemservice
click on Workspace -> select the work space
Goals: clean compile install
Select "Skip Tests", "Resolve Workspace artifacts"
Click on Apply, Run
D. How to run automated tests:
Please find below the steps to run the JUnit test cases:
a. Open the "itemservice" project in Eclipse
b. Click on “src/test/java“
c. Right click on “com.itservice.java./ ItemControllerMockitoTests.java” file
d. Click on “Run As”, and the “JUnit Test”
E. How to run the “itemservice” service locally:
Please find below the steps to run the service:
a. Install Docker Desktop
b. Open power shell and Goto directory where DockerFile is present
c. Enter “docker login”, Enter username and password
d. Execute the following commands
• docker build -t itemservicev1.0 .
• docker run -p 8083:8083 itemservicev1.0
e. The service is available at http://localhost:8083 |
{% load static %}
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet"
integrity="sha512-/12X9/KcvG3Bz7zWZ4zYyURhM7K8Dv9XkX1FRA3yF8+2x/ZnpbFRnS3aUpRpIrw38xxiE6OeDucwHqmbwwRMQ=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
<title>Editar Punto</title>
<link rel="shortcut icon" type="image/x-icon" href="{% static 'imagenes/logo.png' %}">
</head>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
body {
background-color: #0d6efd;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.form-container {
max-width: 400px;
width: 100%;
background-color: #c5e8ef;
border-radius: 10px;
padding: 20px;
margin: 10px; /* Agrega un pequeño espacio en los bordes */
}
.alert-message {
position: fixed;
top: 50%;
left: 20px; /* Ajustar la distancia del mensaje al borde izquierdo */
transform: translateY(-50%);
padding: 10px;
background-color: #f8d7da; /* Color de fondo para los mensajes de error */
border-radius: 10px;
width: 300px; /* Ancho del mensaje de alerta */
z-index: 9999;
opacity: 1;
transition: opacity 1s ease; /* Transición de opacidad */
}
.messages li {
margin: 5px 0;
list-style: none;
}
.alert-message.hide {
display: none;
}
</style>
<body>
{% block content %}
<div class="container">
<div class="form-container">
<h2 class="mb-4">Añadir Punto</h2>
<form id="crearPuntoForm" method="post" enctype="multipart/form-data"
action="{% url 'crear_punto'%}">
{% csrf_token %}
<div class="mb-3">
<label for="codigo" class="form-label">Código:</label>
<input type="text" class="form-control" id="codigo" name="codigo" required value="{{ punto.codigo }}">
</div>
<div class="mb-3">
<label for="latitud" class="form-label">Latitud:</label>
<input type="text" class="form-control" id="latitud" name="latitud" required value="{{ punto.latitud }}">
</div>
<div class="mb-3">
<label for="longitud" class="form-label">Longitud:</label>
<input type="text" class="form-control" id="longitud" name="longitud" required value="{{ punto.longitud }}">
</div>
<div class="mb-3">
<label for="descripcion" class="form-label">Descripción:</label>
<input type="text" class="form-control" id="descripcion" name="descripcion" required value="{{ punto.descripcion }}">
</div>
<div class="mb-3">
<label for="facultad" class="form-label">Facultad:</label>
<select class="form-select" id="facultad" name="facultad" required>
{% if bloque.facultad %}
<option value="{{ punto.facultad.id }}" selected>{{ punto.facultad.nombre }}</option>
{% else %}
<option value="" selected>Seleccione una facultad</option>
{% endif %}
{% for facultad in facultades %}
<option value="{{ facultad.id }}" {% if punto.facultad and punto.facultad.id == facultad.id %} selected {% endif %}>{{ facultad.nombre }}</option>
{% endfor %}
</select>
</div>
{% if messages %}
<div class="modal fade" id="modalAlert" tabindex="-1" aria-labelledby="modalAlertLabel" aria-hidden="true" data-message="{{ messages }}">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalAlertLabel">Mensaje de Alerta</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<ul class="list-group">
{% for message in messages %}
<li class="list-group-item{% if message.tags %} {{ message.tags }}{% endif %}">{{ message }}</li>
{% endfor %}
</ul>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
{% endif %}
<div class="modal-footer">
<a href="{% url 'gestionar_bloques_puntos' %}" class="btn btn-secondary" id="cancelarEditar">Cancelar</a>
<button type="submit" class="btn btn-primary" id="crearPunto">Crear Punto</button>
</div>
</form>
</div>
</div>
<div class="modal fade" id="modalAlert" tabindex="-1" aria-labelledby="modalAlertLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalAlertLabel">Mensaje de Alerta</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<p id="modalAlertMessage"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
{% endblock %}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.3/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function () {
// Obtener el elemento de la ventana modal y el mensaje de alerta
const modalAlert = document.getElementById("modalAlert");
const modalAlertMessage = document.getElementById("modalAlertMessage");
// Verificar si hay un mensaje de alerta
const message = modalAlert.getAttribute("data-message");
if (message) {
modalAlertMessage.textContent = message;
$('#modalAlert').modal('show'); // Mostrar la ventana modal
}
});
</script>
</body>
</html> |
/***************************************************************************************
* File Name : file.h
* CopyRight : 1.0
* ModuleName :
*
* Create Data : 2016/01/06
* Author/Corportation : ZhuoJianhuan
*
* Abstract Description : file管理函数的声明文件
*
*--------------------------------Revision History--------------------------------------
* No version Data Revised By Item Description
* 1 v1.0 2016/01/06 ZhuoJianhuan Create this file
*
***************************************************************************************/
/**************************************************************
* Multi-Include-Prevent Section
**************************************************************/
#ifndef __FILE_H
#define __FILE_H
/**************************************************************
* Debug switch Section
**************************************************************/
/**************************************************************
* Include File Section
**************************************************************/
/**************************************************************
* Macro Define Section
**************************************************************/
/**************************************************************
* Struct Define Section
**************************************************************/
struct FILEINFO {
unsigned char name[8]; //文件名
unsigned char ext[3]; //拓展名
unsigned char type; //类型
char reserve[10]; //保留,可以拓展
unsigned short time; //时间
unsigned short date; //日期
unsigned short clustno; //簇号
unsigned int size; //大小
};
/**************************************************************
* Global Variable Declare Section
**************************************************************/
/**************************************************************
* Prototype Declare Section
**************************************************************/
/**
* @description 设置文件管理系统的参数
* @param fatp:FAT表地址
* finfop:根目录文件信息表首地址
* imgp:文件磁盘映像地址
* @notice
*/
void setupFS(int *fatp, struct FILEINFO *finfop, unsigned char *imgp);
/**
* @description 从映像中读取FAT表
* @param fat:FAT保存目标地址
* img:映像
*/
void file_readfat(int *fat, unsigned char *img);
/**
* @description 读取文件
* @param clustno:起始簇号
* size:文件总大小
* buf:文件读取后保存地址
*/
void file_loadfile(int clustno, int size, char *buf);
/**
* @description 新建一个文件
* @param filename:文件名
* ext:拓展文件名
* dir:当前目录,若在根目录下则为0
* isFolder:0为文件,1为目录
* @return 0创建成功,-1同名目录,
*/
int createFile(char *filename, char *ext, struct FILEINFO *dir, int isFolder);
/**
* @description 将指定长度的内容追加到文件中
* @param fileInfo:目标文件
* contp:存放追加内容的指针
* size:内容长度
*/
void append(struct FILEINFO * fileInfo, char *contp, int size);
/**
* @description 在指定文件信息表中搜索文件
* @param name:欲搜索的文件名,需要是个全名
* finfo:文件信息表,根目录为0
* @return 查找失败返回0,成功返回该文件信息
*/
struct FILEINFO *fileSearch(char *name, struct FILEINFO *finfo);
/**
* @description 检查指定文件信息项是否为目录
* @param finfo:文件信息表
* @return 是目录返回1,否则返回0
*/
int isFolder(struct FILEINFO *finfo);
/**
* @description 从指定目录中删除指定文件名的文件
* @param name:文件名
* dir:指定目录,0为根目录
* @return 0:删除成功
* 1:文件不存在
* 2:文件为目录
*/
int deleteByName(char* name, struct FILEINFO * dir);
/**
* @description 清空文件
* @param fileInfo:欲清空的文件,不得是根目录
*/
void cleanFile(struct FILEINFO * fileInfo);
/**************************************************************
* End-Multi-Include-Prevent Section
**************************************************************/
#endif |
import { Instance, SnapshotOut, types } from 'mobx-state-tree';
/**
* Model description here for TypeScript hints.
*/
export const GlobalModel = types
.model('Global', {
isLoading: types.optional(types.boolean, false),
example: types.optional(types.number, 0)
})
.props({})
.views((self) => ({})) // eslint-disable-line @typescript-eslint/no-unused-vars
.actions((self) => ({
setLoading(isLoading: boolean) {
self.isLoading = isLoading;
},
setRandomExample() {
self.example = Math.random();
}
})); // eslint-disable-line @typescript-eslint/no-unused-vars
/**
* Un-comment the following to omit model attributes from your snapshots (and from async storage).
* Useful for sensitive data like passwords, or transitive state like whether a modal is open.
* Note that you'll need to import `omit` from ramda, which is already included in the project!
* .postProcessSnapshot(omit(["password", "socialSecurityNumber", "creditCardNumber"]))
*/
type GlobalType = Instance<typeof GlobalModel>;
export interface Global extends GlobalType {}
type GlobalSnapshotType = SnapshotOut<typeof GlobalModel>;
export interface GlobalSnapshot extends GlobalSnapshotType {} |
<?php
namespace App\Http\Controllers\Backend;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCategoryRequest;
use App\Models\Modal;
use App\Models\ProductModel;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
class ProductModelController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('backend.product-models.index');
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('backend.product-models.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StoreCategoryRequest $request)
{
Modal::create([
'name' => $request->name,
]);
return to_route('product.model')->with('created', 'Model created Successfully');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$productModel = Modal::findOrFail($id);
return view('backend.product-models.edit', compact('productModel'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(StoreCategoryRequest $request, $id)
{
$productModel = Modal::findOrFail($id);
$productModel->name = $request->name;
$productModel->save();
return to_route('product.model')->with('updated', 'Model updated successfully');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Modal::findOrFail($id)->delete();
return 'success';
}
public function serverSide()
{
$productModel = Modal::orderBy('id','desc');
return datatables($productModel)
->addColumn('action', function ($each) {
$edit_icon = '<a href="'.route('product.model.edit', $each->id).'" class="btn btn-sm btn-success mr-3 edit_btn"><i class="mdi mdi-square-edit-outline btn_icon_size"></i></a>';
$delete_icon = '<a href="#" class="btn btn-sm btn-danger delete_btn" data-id="'.$each->id.'"><i class="mdi mdi-trash-can-outline btn_icon_size"></i></a>';
return '<div class="action_icon">'.$edit_icon. $delete_icon .'</div>';
})
->toJson();
}
} |
// Variables
//
// Variables should follow the `$component-state-property-size` formula for
// consistent naming. Ex: $nav-link-disabled-color and $modal-content-box-shadow-xs.
// Tables
//
// Customizes the `.table` component with basic values, each used across all table variations.
// scss-docs-start table-variables
$table-cell-padding-y: .5rem !default;
$table-cell-padding-x: .5rem !default;
$table-cell-padding-y-sm: .25rem !default;
$table-cell-padding-x-sm: .25rem !default;
$table-cell-vertical-align: top !default;
$table-color: $body-color !default;
$table-bg: transparent !default;
$table-accent-bg: transparent !default;
$table-th-font-weight: null !default;
$table-striped-color: $table-color !default;
$table-striped-bg-factor: .05 !default;
$table-striped-bg: rgba($black, $table-striped-bg-factor) !default;
$table-active-color: $table-color !default;
$table-active-bg-factor: .1 !default;
$table-active-bg: rgba($black, $table-active-bg-factor) !default;
$table-hover-color: $table-color !default;
$table-hover-bg-factor: .075 !default;
$table-hover-bg: rgba($black, $table-hover-bg-factor) !default;
$table-border-factor: .1 !default;
$table-border-width: $border-width !default;
$table-border-color: $border-color !default;
$table-striped-order: odd !default;
$table-group-separator-color: currentColor !default;
$table-caption-color: $text-muted !default;
$table-bg-scale: -80% !default;
// scss-docs-end table-variables
// scss-docs-start table-loop
$table-variants: (
"primary": shift-color($primary, $table-bg-scale),
"secondary": shift-color($secondary, $table-bg-scale),
"success": shift-color($success, $table-bg-scale),
"info": shift-color($info, $table-bg-scale),
"warning": shift-color($warning, $table-bg-scale),
"danger": shift-color($danger, $table-bg-scale),
"light": $light,
"dark": $dark,
) !default;
// scss-docs-end table-loop
// Forms
// scss-docs-start form-text-variables
$form-text-margin-top: .25rem !default;
$form-text-font-size: $small-font-size !default;
$form-text-font-style: null !default;
$form-text-font-weight: null !default;
$form-text-color: $text-muted !default;
// scss-docs-end form-text-variables
// scss-docs-start form-label-variables
$form-label-margin-bottom: .5rem !default;
$form-label-font-size: null !default;
$form-label-font-style: null !default;
$form-label-font-weight: null !default;
$form-label-color: null !default;
// scss-docs-end form-label-variables
// scss-docs-start form-input-variables
$input-padding-y: $input-btn-padding-y !default;
$input-padding-x: $input-btn-padding-x !default;
$input-font-family: $input-btn-font-family !default;
$input-font-size: $input-btn-font-size !default;
$input-font-weight: $font-weight-base !default;
$input-line-height: $input-btn-line-height !default;
$input-padding-y-sm: $input-btn-padding-y-sm !default;
$input-padding-x-sm: $input-btn-padding-x-sm !default;
$input-font-size-sm: $input-btn-font-size-sm !default;
$input-padding-y-lg: $input-btn-padding-y-lg !default;
$input-padding-x-lg: $input-btn-padding-x-lg !default;
$input-font-size-lg: $input-btn-font-size-lg !default;
$input-bg: $body-bg !default;
$input-disabled-bg: $gray-200 !default;
$input-disabled-border-color: null !default;
$input-color: $body-color !default;
$input-border-color: $gray-400 !default;
$input-border-width: $input-btn-border-width !default;
$input-box-shadow: $box-shadow-inset !default;
$input-border-radius: $border-radius !default;
$input-border-radius-sm: $border-radius-sm !default;
$input-border-radius-lg: $border-radius-lg !default;
$input-focus-bg: $input-bg !default;
$input-focus-border-color: tint-color($component-active-bg, 50%) !default;
$input-focus-color: $input-color !default;
$input-focus-width: $input-btn-focus-width !default;
$input-focus-box-shadow: $input-btn-focus-box-shadow !default;
$input-placeholder-color: $gray-600 !default;
$input-plaintext-color: $body-color !default;
$input-height-border: $input-border-width * 2 !default;
$input-height-inner: add($input-line-height * 1em, $input-padding-y * 2) !default;
$input-height-inner-half: add($input-line-height * .5em, $input-padding-y) !default;
$input-height-inner-quarter: add($input-line-height * .25em, $input-padding-y * .5) !default;
$input-height: add($input-line-height * 1em, add($input-padding-y * 2, $input-height-border, false)) !default;
$input-height-sm: add($input-line-height * 1em, add($input-padding-y-sm * 2, $input-height-border, false)) !default;
$input-height-lg: add($input-line-height * 1em, add($input-padding-y-lg * 2, $input-height-border, false)) !default;
$input-transition: border-color .15s ease-in-out,
box-shadow .15s ease-in-out !default;
$form-color-width: 3rem !default;
// scss-docs-end form-input-variables
// scss-docs-start form-check-variables
$form-check-input-width: 1em !default;
$form-check-min-height: $font-size-base * $line-height-base !default;
$form-check-padding-start: $form-check-input-width + .5em !default;
$form-check-margin-bottom: .125rem !default;
$form-check-label-color: null !default;
$form-check-label-cursor: null !default;
$form-check-transition: null !default;
$form-check-input-active-filter: brightness(90%) !default;
$form-check-input-bg: $input-bg !default;
$form-check-input-border: 1px solid rgba($black, .25) !default;
$form-check-input-border-radius: .25em !default;
$form-check-radio-border-radius: 50% !default;
$form-check-input-focus-border: $input-focus-border-color !default;
$form-check-input-focus-box-shadow: $input-btn-focus-box-shadow !default;
$form-check-input-checked-color: $component-active-color !default;
$form-check-input-checked-bg-color: $component-active-bg !default;
$form-check-input-checked-border-color: $form-check-input-checked-bg-color !default;
$form-check-input-checked-bg-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'><path fill='none' stroke='#{$form-check-input-checked-color}' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10l3 3l6-6'/></svg>") !default;
$form-check-radio-checked-bg-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'><circle r='2' fill='#{$form-check-input-checked-color}'/></svg>") !default;
$form-check-input-indeterminate-color: $component-active-color !default;
$form-check-input-indeterminate-bg-color: $component-active-bg !default;
$form-check-input-indeterminate-border-color: $form-check-input-indeterminate-bg-color !default;
$form-check-input-indeterminate-bg-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'><path fill='none' stroke='#{$form-check-input-indeterminate-color}' stroke-linecap='round' stroke-linejoin='round' stroke-width='3' d='M6 10h8'/></svg>") !default;
$form-check-input-disabled-opacity: .5 !default;
$form-check-label-disabled-opacity: $form-check-input-disabled-opacity !default;
$form-check-btn-check-disabled-opacity: $btn-disabled-opacity !default;
$form-check-inline-margin-end: 1rem !default;
// scss-docs-end form-check-variables
// scss-docs-start form-switch-variables
$form-switch-color: rgba(0, 0, 0, .25) !default;
$form-switch-width: 2em !default;
$form-switch-padding-start: $form-switch-width + .5em !default;
$form-switch-bg-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'><circle r='3' fill='#{$form-switch-color}'/></svg>") !default;
$form-switch-border-radius: $form-switch-width !default;
$form-switch-transition: background-position .15s ease-in-out !default;
$form-switch-focus-color: $input-focus-border-color !default;
$form-switch-focus-bg-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'><circle r='3' fill='#{$form-switch-focus-color}'/></svg>") !default;
$form-switch-checked-color: $component-active-color !default;
$form-switch-checked-bg-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'><circle r='3' fill='#{$form-switch-checked-color}'/></svg>") !default;
$form-switch-checked-bg-position: right center !default;
// scss-docs-end form-switch-variables
// scss-docs-start input-group-variables
$input-group-addon-padding-y: $input-padding-y !default;
$input-group-addon-padding-x: $input-padding-x !default;
$input-group-addon-font-weight: $input-font-weight !default;
$input-group-addon-color: $input-color !default;
$input-group-addon-bg: $gray-200 !default;
$input-group-addon-border-color: $input-border-color !default;
// scss-docs-end input-group-variables
// scss-docs-start form-select-variables
$form-select-padding-y: $input-padding-y !default;
$form-select-padding-x: $input-padding-x !default;
$form-select-font-family: $input-font-family !default;
$form-select-font-size: $input-font-size !default;
$form-select-indicator-padding: $form-select-padding-x * 3 !default; // Extra padding for background-image
$form-select-font-weight: $input-font-weight !default;
$form-select-line-height: $input-line-height !default;
$form-select-color: $input-color !default;
$form-select-bg: $input-bg !default;
$form-select-disabled-color: null !default;
$form-select-disabled-bg: $gray-200 !default;
$form-select-disabled-border-color: $input-disabled-border-color !default;
$form-select-bg-position: right $form-select-padding-x center !default;
$form-select-bg-size: 16px 12px !default; // In pixels because image dimensions
$form-select-indicator-color: $gray-800 !default;
$form-select-indicator: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'><path fill='none' stroke='#{$form-select-indicator-color}' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/></svg>") !default;
$form-select-feedback-icon-padding-end: $form-select-padding-x * 2.5 + $form-select-indicator-padding !default;
$form-select-feedback-icon-position: center right $form-select-indicator-padding !default;
$form-select-feedback-icon-size: $input-height-inner-half $input-height-inner-half !default;
$form-select-border-width: $input-border-width !default;
$form-select-border-color: $input-border-color !default;
$form-select-border-radius: $border-radius !default;
$form-select-box-shadow: $box-shadow-inset !default;
$form-select-focus-border-color: $input-focus-border-color !default;
$form-select-focus-width: $input-focus-width !default;
$form-select-focus-box-shadow: 0 0 0 $form-select-focus-width $input-btn-focus-color !default;
$form-select-padding-y-sm: $input-padding-y-sm !default;
$form-select-padding-x-sm: $input-padding-x-sm !default;
$form-select-font-size-sm: $input-font-size-sm !default;
$form-select-padding-y-lg: $input-padding-y-lg !default;
$form-select-padding-x-lg: $input-padding-x-lg !default;
$form-select-font-size-lg: $input-font-size-lg !default;
$form-select-transition: $input-transition !default;
// scss-docs-end form-select-variables
// scss-docs-start form-range-variables
$form-range-track-width: 100% !default;
$form-range-track-height: .5rem !default;
$form-range-track-cursor: pointer !default;
$form-range-track-bg: $gray-300 !default;
$form-range-track-border-radius: 1rem !default;
$form-range-track-box-shadow: $box-shadow-inset !default;
$form-range-thumb-width: 1rem !default;
$form-range-thumb-height: $form-range-thumb-width !default;
$form-range-thumb-bg: $component-active-bg !default;
$form-range-thumb-border: 0 !default;
$form-range-thumb-border-radius: 1rem !default;
$form-range-thumb-box-shadow: 0 .1rem .25rem rgba($black, .1) !default;
$form-range-thumb-focus-box-shadow: 0 0 0 1px $body-bg,
$input-focus-box-shadow !default;
$form-range-thumb-focus-box-shadow-width: $input-focus-width !default; // For focus box shadow issue in Edge
$form-range-thumb-active-bg: tint-color($component-active-bg, 70%) !default;
$form-range-thumb-disabled-bg: $gray-500 !default;
$form-range-thumb-transition: background-color .15s ease-in-out,
border-color .15s ease-in-out,
box-shadow .15s ease-in-out !default;
// scss-docs-end form-range-variables
// scss-docs-start form-file-variables
$form-file-button-color: $input-color !default;
$form-file-button-bg: $input-group-addon-bg !default;
$form-file-button-hover-bg: shade-color($form-file-button-bg, 5%) !default;
// scss-docs-end form-file-variables
// scss-docs-start form-floating-variables
$form-floating-height: add(3.5rem, $input-height-border) !default;
$form-floating-line-height: 1.25 !default;
$form-floating-padding-x: $input-padding-x !default;
$form-floating-padding-y: 1rem !default;
$form-floating-input-padding-t: 1.625rem !default;
$form-floating-input-padding-b: .625rem !default;
$form-floating-label-opacity: .65 !default;
$form-floating-label-transform: scale(.85) translateY(-.5rem) translateX(.15rem) !default;
$form-floating-transition: opacity .1s ease-in-out,
transform .1s ease-in-out !default;
// scss-docs-end form-floating-variables
// Form validation
// scss-docs-start form-feedback-variables
$form-feedback-margin-top: $form-text-margin-top !default;
$form-feedback-font-size: $form-text-font-size !default;
$form-feedback-font-style: $form-text-font-style !default;
$form-feedback-valid-color: $success !default;
$form-feedback-invalid-color: $danger !default;
$form-feedback-icon-valid-color: $form-feedback-valid-color !default;
$form-feedback-icon-valid: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'><path fill='#{$form-feedback-icon-valid-color}' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/></svg>") !default;
$form-feedback-icon-invalid-color: $form-feedback-invalid-color !default;
$form-feedback-icon-invalid: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='#{$form-feedback-icon-invalid-color}'><circle cx='6' cy='6' r='4.5'/><path stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/><circle cx='6' cy='8.2' r='.6' fill='#{$form-feedback-icon-invalid-color}' stroke='none'/></svg>") !default;
// scss-docs-end form-feedback-variables
// scss-docs-start form-validation-states
$form-validation-states: (
"valid": ("color": $form-feedback-valid-color,
"icon": $form-feedback-icon-valid ),
"invalid": ("color": $form-feedback-invalid-color,
"icon": $form-feedback-icon-invalid )) !default;
// scss-docs-end form-validation-states
// Z-index master list
//
// Warning: Avoid customizing these values. They're used for a bird's eye view
// of components dependent on the z-axis and are designed to all work together.
// scss-docs-start zindex-stack
$zindex-dropdown: 1000 !default;
$zindex-sticky: 1020 !default;
$zindex-fixed: 1030 !default;
$zindex-offcanvas-backdrop: 1040 !default;
$zindex-offcanvas: 1045 !default;
$zindex-modal-backdrop: 1050 !default;
$zindex-modal: 1055 !default;
$zindex-popover: 1070 !default;
$zindex-tooltip: 1080 !default;
// scss-docs-end zindex-stack
// Dropdowns
//
// Dropdown menu container and contents.
// scss-docs-start dropdown-variables
$dropdown-min-width: 10rem !default;
$dropdown-padding-x: 0 !default;
$dropdown-padding-y: .5rem !default;
$dropdown-spacer: .125rem !default;
$dropdown-font-size: $font-size-base !default;
$dropdown-color: $body-color !default;
$dropdown-bg: $white !default;
$dropdown-border-color: rgba($black, .15) !default;
$dropdown-border-radius: $border-radius !default;
$dropdown-border-width: $border-width !default;
$dropdown-inner-border-radius: subtract($dropdown-border-radius, $dropdown-border-width) !default;
$dropdown-divider-bg: $dropdown-border-color !default;
$dropdown-divider-margin-y: $spacer * .5 !default;
$dropdown-box-shadow: $box-shadow !default;
$dropdown-link-color: $gray-900 !default;
$dropdown-link-hover-color: shade-color($dropdown-link-color, 10%) !default;
$dropdown-link-hover-bg: $gray-200 !default;
$dropdown-link-active-color: $component-active-color !default;
$dropdown-link-active-bg: $component-active-bg !default;
$dropdown-link-disabled-color: $gray-500 !default;
$dropdown-item-padding-y: $spacer * .25 !default;
$dropdown-item-padding-x: $spacer !default;
$dropdown-header-color: $gray-600 !default;
$dropdown-header-padding: $dropdown-padding-y $dropdown-item-padding-x !default;
// scss-docs-end dropdown-variables
// scss-docs-start dropdown-dark-variables
$dropdown-dark-color: $gray-300 !default;
$dropdown-dark-bg: $gray-800 !default;
$dropdown-dark-border-color: $dropdown-border-color !default;
$dropdown-dark-divider-bg: $dropdown-divider-bg !default;
$dropdown-dark-box-shadow: null !default;
$dropdown-dark-link-color: $dropdown-dark-color !default;
$dropdown-dark-link-hover-color: $white !default;
$dropdown-dark-link-hover-bg: rgba($white, .15) !default;
$dropdown-dark-link-active-color: $dropdown-link-active-color !default;
$dropdown-dark-link-active-bg: $dropdown-link-active-bg !default;
$dropdown-dark-link-disabled-color: $gray-500 !default;
$dropdown-dark-header-color: $gray-500 !default;
// scss-docs-end dropdown-dark-variables
// Pagination
// scss-docs-start pagination-variables
$pagination-padding-y: .375rem !default;
$pagination-padding-x: .75rem !default;
$pagination-padding-y-sm: .25rem !default;
$pagination-padding-x-sm: .5rem !default;
$pagination-padding-y-lg: .75rem !default;
$pagination-padding-x-lg: 1.5rem !default;
$pagination-color: $link-color !default;
$pagination-bg: $white !default;
$pagination-border-width: $border-width !default;
$pagination-border-radius: $border-radius !default;
$pagination-margin-start: -$pagination-border-width !default;
$pagination-border-color: $gray-300 !default;
$pagination-focus-color: $link-hover-color !default;
$pagination-focus-bg: $gray-200 !default;
$pagination-focus-box-shadow: $input-btn-focus-box-shadow !default;
$pagination-focus-outline: 0 !default;
$pagination-hover-color: $link-hover-color !default;
$pagination-hover-bg: $gray-200 !default;
$pagination-hover-border-color: $gray-300 !default;
$pagination-active-color: $component-active-color !default;
$pagination-active-bg: $component-active-bg !default;
$pagination-active-border-color: $pagination-active-bg !default;
$pagination-disabled-color: $gray-600 !default;
$pagination-disabled-bg: $white !default;
$pagination-disabled-border-color: $gray-300 !default;
$pagination-transition: color .15s ease-in-out,
background-color .15s ease-in-out,
border-color .15s ease-in-out,
box-shadow .15s ease-in-out !default;
$pagination-border-radius-sm: $border-radius-sm !default;
$pagination-border-radius-lg: $border-radius-lg !default;
// scss-docs-end pagination-variables
// Placeholders
// scss-docs-start placeholders
$placeholder-opacity-max: .5 !default;
$placeholder-opacity-min: .2 !default;
// scss-docs-end placeholders
// Cards
// scss-docs-start card-variables
$card-spacer-y: $spacer !default;
$card-spacer-x: $spacer !default;
$card-title-spacer-y: $spacer * .5 !default;
$card-border-width: $border-width !default;
$card-border-color: rgba($black, .125) !default;
$card-border-radius: $border-radius !default;
$card-box-shadow: null !default;
$card-inner-border-radius: subtract($card-border-radius, $card-border-width) !default;
$card-cap-padding-y: $card-spacer-y * .5 !default;
$card-cap-padding-x: $card-spacer-x !default;
$card-cap-bg: rgba($black, .03) !default;
$card-cap-color: null !default;
$card-height: null !default;
$card-color: null !default;
$card-bg: $white !default;
$card-img-overlay-padding: $spacer !default;
$card-group-margin: $grid-gutter-width * .5 !default;
// scss-docs-end card-variables
// Accordion
// scss-docs-start accordion-variables
$accordion-padding-y: 1rem !default;
$accordion-padding-x: 1.25rem !default;
$accordion-color: $body-color !default;
$accordion-bg: $body-bg !default;
$accordion-border-width: $border-width !default;
$accordion-border-color: rgba($black, .125) !default;
$accordion-border-radius: $border-radius !default;
$accordion-inner-border-radius: subtract($accordion-border-radius, $accordion-border-width) !default;
$accordion-body-padding-y: $accordion-padding-y !default;
$accordion-body-padding-x: $accordion-padding-x !default;
$accordion-button-padding-y: $accordion-padding-y !default;
$accordion-button-padding-x: $accordion-padding-x !default;
$accordion-button-color: $accordion-color !default;
$accordion-button-bg: $accordion-bg !default;
$accordion-transition: $btn-transition,
border-radius .15s ease !default;
$accordion-button-active-bg: tint-color($component-active-bg, 90%) !default;
$accordion-button-active-color: shade-color($primary, 10%) !default;
$accordion-button-focus-border-color: $input-focus-border-color !default;
$accordion-button-focus-box-shadow: $btn-focus-box-shadow !default;
$accordion-icon-width: 1.25rem !default;
$accordion-icon-color: $accordion-button-color !default;
$accordion-icon-active-color: $accordion-button-active-color !default;
$accordion-icon-transition: transform .2s ease-in-out !default;
$accordion-icon-transform: rotate(-180deg) !default;
$accordion-button-icon: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='#{$accordion-icon-color}'><path fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/></svg>") !default;
$accordion-button-active-icon: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='#{$accordion-icon-active-color}'><path fill-rule='evenodd' d='M1.646 4.646a.5.5 0 0 1 .708 0L8 10.293l5.646-5.647a.5.5 0 0 1 .708.708l-6 6a.5.5 0 0 1-.708 0l-6-6a.5.5 0 0 1 0-.708z'/></svg>") !default;
// scss-docs-end accordion-variables
// Tooltips
// scss-docs-start tooltip-variables
$tooltip-font-size: $font-size-sm !default;
$tooltip-max-width: 200px !default;
$tooltip-color: $white !default;
$tooltip-bg: $black !default;
$tooltip-border-radius: $border-radius !default;
$tooltip-opacity: .9 !default;
$tooltip-padding-y: $spacer * .25 !default;
$tooltip-padding-x: $spacer * .5 !default;
$tooltip-margin: 0 !default;
$tooltip-arrow-width: .8rem !default;
$tooltip-arrow-height: .4rem !default;
$tooltip-arrow-color: $tooltip-bg !default;
// scss-docs-end tooltip-variables
// Form tooltips must come after regular tooltips
// scss-docs-start tooltip-feedback-variables
$form-feedback-tooltip-padding-y: $tooltip-padding-y !default;
$form-feedback-tooltip-padding-x: $tooltip-padding-x !default;
$form-feedback-tooltip-font-size: $tooltip-font-size !default;
$form-feedback-tooltip-line-height: null !default;
$form-feedback-tooltip-opacity: $tooltip-opacity !default;
$form-feedback-tooltip-border-radius: $tooltip-border-radius !default;
// scss-docs-end tooltip-feedback-variables
// Popovers
// scss-docs-start popover-variables
$popover-font-size: $font-size-sm !default;
$popover-bg: $white !default;
$popover-max-width: 276px !default;
$popover-border-width: $border-width !default;
$popover-border-color: rgba($black, .2) !default;
$popover-border-radius: $border-radius-lg !default;
$popover-inner-border-radius: subtract($popover-border-radius, $popover-border-width) !default;
$popover-box-shadow: $box-shadow !default;
$popover-header-bg: shade-color($popover-bg, 6%) !default;
$popover-header-color: $headings-color !default;
$popover-header-padding-y: .5rem !default;
$popover-header-padding-x: $spacer !default;
$popover-body-color: $body-color !default;
$popover-body-padding-y: $spacer !default;
$popover-body-padding-x: $spacer !default;
$popover-arrow-width: 1rem !default;
$popover-arrow-height: .5rem !default;
$popover-arrow-color: $popover-bg !default;
$popover-arrow-outer-color: fade-in($popover-border-color, .05) !default;
// scss-docs-end popover-variables
// Toasts
// scss-docs-start toast-variables
$toast-max-width: 350px !default;
$toast-padding-x: .75rem !default;
$toast-padding-y: .5rem !default;
$toast-font-size: .875rem !default;
$toast-color: null !default;
$toast-background-color: rgba($white, .85) !default;
$toast-border-width: 1px !default;
$toast-border-color: rgba(0, 0, 0, .1) !default;
$toast-border-radius: $border-radius !default;
$toast-box-shadow: $box-shadow !default;
$toast-spacing: $container-padding-x !default;
$toast-header-color: $gray-600 !default;
$toast-header-background-color: rgba($white, .85) !default;
$toast-header-border-color: rgba(0, 0, 0, .05) !default;
// scss-docs-end toast-variables
// Badges
// scss-docs-start badge-variables
$badge-font-size: .75em !default;
$badge-font-weight: $font-weight-bold !default;
$badge-color: $white !default;
$badge-padding-y: .35em !default;
$badge-padding-x: .65em !default;
$badge-border-radius: $border-radius !default;
// scss-docs-end badge-variables
// Modals
// scss-docs-start modal-variables
$modal-inner-padding: $spacer !default;
$modal-footer-margin-between: .5rem !default;
$modal-dialog-margin: .5rem !default;
$modal-dialog-margin-y-sm-up: 1.75rem !default;
$modal-title-line-height: $line-height-base !default;
$modal-content-color: null !default;
$modal-content-bg: $white !default;
$modal-content-border-color: rgba($black, .2) !default;
$modal-content-border-width: $border-width !default;
$modal-content-border-radius: $border-radius-lg !default;
$modal-content-inner-border-radius: subtract($modal-content-border-radius, $modal-content-border-width) !default;
$modal-content-box-shadow-xs: $box-shadow-sm !default;
$modal-content-box-shadow-sm-up: $box-shadow !default;
$modal-backdrop-bg: $black !default;
$modal-backdrop-opacity: .5 !default;
$modal-header-border-color: $border-color !default;
$modal-footer-border-color: $modal-header-border-color !default;
$modal-header-border-width: $modal-content-border-width !default;
$modal-footer-border-width: $modal-header-border-width !default;
$modal-header-padding-y: $modal-inner-padding !default;
$modal-header-padding-x: $modal-inner-padding !default;
$modal-header-padding: $modal-header-padding-y $modal-header-padding-x !default; // Keep this for backwards compatibility
$modal-sm: 300px !default;
$modal-md: 500px !default;
$modal-lg: 800px !default;
$modal-xl: 1140px !default;
$modal-fade-transform: translate(0, -50px) !default;
$modal-show-transform: none !default;
$modal-transition: transform .3s ease-out !default;
$modal-scale-transform: scale(1.02) !default;
// scss-docs-end modal-variables
// Alerts
//
// Define alert colors, border radius, and padding.
// scss-docs-start alert-variables
$alert-padding-y: $spacer !default;
$alert-padding-x: $spacer !default;
$alert-margin-bottom: 1rem !default;
$alert-border-radius: $border-radius !default;
$alert-link-font-weight: $font-weight-bold !default;
$alert-border-width: $border-width !default;
$alert-bg-scale: -80% !default;
$alert-border-scale: -70% !default;
$alert-color-scale: 40% !default;
$alert-dismissible-padding-r: $alert-padding-x * 3 !default; // 3x covers width of x plus default padding on either side
// scss-docs-end alert-variables
// Progress bars
// scss-docs-start progress-variables
$progress-height: 1rem !default;
$progress-font-size: $font-size-base * .75 !default;
$progress-bg: $gray-200 !default;
$progress-border-radius: $border-radius !default;
$progress-box-shadow: $box-shadow-inset !default;
$progress-bar-color: $white !default;
$progress-bar-bg: $primary !default;
$progress-bar-animation-timing: 1s linear infinite !default;
$progress-bar-transition: width .6s ease !default;
// scss-docs-end progress-variables
// List group
// scss-docs-start list-group-variables
$list-group-color: $gray-900 !default;
$list-group-bg: $white !default;
$list-group-border-color: rgba($black, .125) !default;
$list-group-border-width: $border-width !default;
$list-group-border-radius: $border-radius !default;
$list-group-item-padding-y: $spacer * .5 !default;
$list-group-item-padding-x: $spacer !default;
$list-group-item-bg-scale: -80% !default;
$list-group-item-color-scale: 40% !default;
$list-group-hover-bg: $gray-100 !default;
$list-group-active-color: $component-active-color !default;
$list-group-active-bg: $component-active-bg !default;
$list-group-active-border-color: $list-group-active-bg !default;
$list-group-disabled-color: $gray-600 !default;
$list-group-disabled-bg: $list-group-bg !default;
$list-group-action-color: $gray-700 !default;
$list-group-action-hover-color: $list-group-action-color !default;
$list-group-action-active-color: $body-color !default;
$list-group-action-active-bg: $gray-200 !default;
// scss-docs-end list-group-variables
// Image thumbnails
// scss-docs-start thumbnail-variables
$thumbnail-padding: .25rem !default;
$thumbnail-bg: $body-bg !default;
$thumbnail-border-width: $border-width !default;
$thumbnail-border-color: $gray-300 !default;
$thumbnail-border-radius: $border-radius !default;
$thumbnail-box-shadow: $box-shadow-sm !default;
// scss-docs-end thumbnail-variables
// Figures
// scss-docs-start figure-variables
$figure-caption-font-size: $small-font-size !default;
$figure-caption-color: $gray-600 !default;
// scss-docs-end figure-variables
// Breadcrumbs
// scss-docs-start breadcrumb-variables
$breadcrumb-font-size: null !default;
$breadcrumb-padding-y: 0 !default;
$breadcrumb-padding-x: 0 !default;
$breadcrumb-item-padding-x: .5rem !default;
$breadcrumb-margin-bottom: 1rem !default;
$breadcrumb-bg: null !default;
$breadcrumb-divider-color: $gray-600 !default;
$breadcrumb-active-color: $gray-600 !default;
$breadcrumb-divider: quote("/") !default;
$breadcrumb-divider-flipped: $breadcrumb-divider !default;
$breadcrumb-border-radius: null !default;
// scss-docs-end breadcrumb-variables
// Carousel
// scss-docs-start carousel-variables
$carousel-control-color: $white !default;
$carousel-control-width: 15% !default;
$carousel-control-opacity: .5 !default;
$carousel-control-hover-opacity: .9 !default;
$carousel-control-transition: opacity .15s ease !default;
$carousel-indicator-width: 30px !default;
$carousel-indicator-height: 3px !default;
$carousel-indicator-hit-area-height: 10px !default;
$carousel-indicator-spacer: 3px !default;
$carousel-indicator-opacity: .5 !default;
$carousel-indicator-active-bg: $white !default;
$carousel-indicator-active-opacity: 1 !default;
$carousel-indicator-transition: opacity .6s ease !default;
$carousel-caption-width: 70% !default;
$carousel-caption-color: $white !default;
$carousel-caption-padding-y: 1.25rem !default;
$carousel-caption-spacer: 1.25rem !default;
$carousel-control-icon-width: 2rem !default;
$carousel-control-prev-icon-bg: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='#{$carousel-control-color}'><path d='M11.354 1.646a.5.5 0 0 1 0 .708L5.707 8l5.647 5.646a.5.5 0 0 1-.708.708l-6-6a.5.5 0 0 1 0-.708l6-6a.5.5 0 0 1 .708 0z'/></svg>") !default;
$carousel-control-next-icon-bg: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='#{$carousel-control-color}'><path d='M4.646 1.646a.5.5 0 0 1 .708 0l6 6a.5.5 0 0 1 0 .708l-6 6a.5.5 0 0 1-.708-.708L10.293 8 4.646 2.354a.5.5 0 0 1 0-.708z'/></svg>") !default;
$carousel-transition-duration: .6s !default;
$carousel-transition: transform $carousel-transition-duration ease-in-out !default; // Define transform transition first if using multiple transitions (e.g., `transform 2s ease, opacity .5s ease-out`)
$carousel-dark-indicator-active-bg: $black !default;
$carousel-dark-caption-color: $black !default;
$carousel-dark-control-icon-filter: invert(1) grayscale(100) !default;
// scss-docs-end carousel-variables
// Spinners
// scss-docs-start spinner-variables
$spinner-width: 2rem !default;
$spinner-height: $spinner-width !default;
$spinner-vertical-align: -.125em !default;
$spinner-border-width: .25em !default;
$spinner-animation-speed: .75s !default;
$spinner-width-sm: 1rem !default;
$spinner-height-sm: $spinner-width-sm !default;
$spinner-border-width-sm: .2em !default;
// scss-docs-end spinner-variables
// Offcanvas
// scss-docs-start offcanvas-variables
$offcanvas-padding-y: $modal-inner-padding !default;
$offcanvas-padding-x: $modal-inner-padding !default;
$offcanvas-horizontal-width: 400px !default;
$offcanvas-vertical-height: 30vh !default;
$offcanvas-transition-duration: .3s !default;
$offcanvas-border-color: $modal-content-border-color !default;
$offcanvas-border-width: $modal-content-border-width !default;
$offcanvas-title-line-height: $modal-title-line-height !default;
$offcanvas-bg-color: $modal-content-bg !default;
$offcanvas-color: $modal-content-color !default;
$offcanvas-box-shadow: $modal-content-box-shadow-xs !default;
$offcanvas-backdrop-bg: $modal-backdrop-bg !default;
$offcanvas-backdrop-opacity: $modal-backdrop-opacity !default;
// scss-docs-end offcanvas-variables
// Code
$code-font-size: $small-font-size !default;
$code-color: $pink !default;
$kbd-padding-y: .2rem !default;
$kbd-padding-x: .4rem !default;
$kbd-font-size: $code-font-size !default;
$kbd-color: $white !default;
$kbd-bg: $gray-900 !default;
$pre-color: null !default; |
package com.example.tictactoe.manager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.example.tictactoe.enumeration.GameState;
import com.example.tictactoe.model.TicTacToe;
import com.example.tictactoe.model.dto.TicTacToeMessage;
import com.example.tictactoe.model.dto.TicTacToeMessageStorage;
/**
* Manager class for the Tic-tac-toe games.
Handles adding and removing players from games and storing and retrieving
current games.
@author Mariia Glushenkova
*/
public class TicTacToeManager {
/** Map of active games wth keyID */
private final Map <String,TicTacToe> games;
/** Map of players waiting to join a Tic-Tac-Toe game,
* players name as a key
*/
protected final Map <String, String> waitingPlayers;
public TicTacToeManager() {
games = new ConcurrentHashMap<>();
waitingPlayers = new ConcurrentHashMap<>();
}
public TicTacToeMessage gameToMessage(TicTacToe game) {
TicTacToeMessage message = new TicTacToeMessage();
TicTacToeMessageStorage.appendMessage(message);
TicTacToeMessageStorage.printMessagesToConsole();
return message;
}
/** Attempts to add player ot creates a new game function
* */
public synchronized TicTacToe joinGame(String player) {
if (games.values().stream().anyMatch(game -> game.getPlayer1().equals(player)
|| (game.getPlayer2() != null && game.getPlayer2().equals(player)))) {
return games.values().stream().filter(game -> game.getPlayer1().equals(player) ||
game.getPlayer2().equals(player)).findFirst().get();
}
for (TicTacToe game : games.values()) {
if (game.getPlayer1() != null && game.getPlayer2() == null) {
game.setPlayer2(player);
game.setGameState(GameState.PLAYER1_TURN);
return game;
}
}
TicTacToe game = new TicTacToe(player, null);
games.put(game.getGameId(), game);
waitingPlayers.put(player, game.getGameId());
return game;
}
/** Removes a player from Tic tac toe game. IF there was only one player in a game, this game history is removed. */
public synchronized TicTacToe leaveGame(String player) {
String gameId = getGameByPlayer(player) != null ? getGameByPlayer(player).getGameId() : null;
if (gameId != null) {
waitingPlayers.remove(player);
TicTacToe game = games.get(gameId);
if (player.equals(game.getPlayer1())) {
if (game.getPlayer2() != null) {
game.setPlayer1(game.getPlayer2());
game.setPlayer2(null);
game.setGameState(GameState.WAITING_FOR_PLAYER);
System.out.println("Game is over. Thank you for playing. New game began automatically");
game.setBoard(new String[3][3]);
waitingPlayers.put(game.getPlayer1(), game.getGameId());
} else {
games.remove(gameId);
return null;
}
} else if (player.equals(game.getPlayer2())) {
game.setPlayer2(null);
game.setGameState(GameState.WAITING_FOR_PLAYER);
game.setBoard(new String[3][3]);
waitingPlayers.put(game.getPlayer1(), game.getGameId());
}
return game;
}
return null;
}
public Map<String,TicTacToe> getGames() {
return this.games;
}
/**
* Return the TicTacToe game of given gameId
* @param gameId
* @return game
*/
public TicTacToe getGame(String gameId) {
return games.get(gameId);
};
/**
* Return the TicTacToe game of given playerId
*
* @param player
* @return game
*/
public TicTacToe getGameByPlayer(String player) {
return games.values().stream().filter( game -> game.getPlayer1().equals(player) ||
(game.getPlayer2() != null &&
game.getPlayer2().equals(player))).findFirst().orElse(null);
}
/**
* Removes the Tic tac toe game with given game id
* @param gameIDof the game to remove
*/
public void removeGame(String gameId) {
games.remove(gameId);
}
public Map<String,String> getWaitingPlayers() {
return this.waitingPlayers;
}
} |
import { login, getInfo, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
const state = {
token: getToken(),
name: '',
avatar: '',
roles: []
}
const mutations = {
SET_TOKEN: (state, token) => {
state.token = token
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_ROLES: (state, roles) => {
state.roles = roles
//console.log("staterole:"+state.roles,typeof(state.roles))
}
}
const actions = {
// user login
login({ commit }, userInfo) {
const { username, password } = userInfo
return new Promise((resolve, reject) => {
login({ username: username.trim(), password: password }).then(response => {
commit('SET_TOKEN', response.access_token)
setToken(response.token)
resolve()
}).catch(error => {
reject(error)
})
})
},
// get user info
getInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state.token).then(response => {
const { data } = response
// console.log(data)
if (!data) {
reject('Verification failed, please Login again.')
}
const { roles, username } = data
var role=[]
role=roles.split(',')
//console.log(role,typeof(role))
if (!role || role.length <= 0) {
reject('getInfo: roles must be a non-null array!')
}
// console.log(role,typeof(role))
commit('SET_ROLES', role)
commit('SET_NAME', username)
commit('SET_AVATAR', 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif')
resolve(data)
}).catch(error => {
reject(error)
})
})
},
// user logout
logout({ commit, state, dispatch }) {
return new Promise((resolve, reject) => {
logout(state.token).then(() => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
removeToken()
resetRouter()
// reset visited views and cached views
// to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
dispatch('tagsView/delAllViews', null, { root: true })
resolve()
}).catch(error => {
reject(error)
})
})
},
/* logout({ commit, state }) {
removeToken()
resetRouter()
commit('RESET_STATE')
},*/
// remove token
resetToken({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
removeToken()
resolve()
})
},
// dynamically modify permissions
async changeRoles({ commit, dispatch }, role) {
const token = role + '-token'
commit('SET_TOKEN', token)
setToken(token)
const { roles } = await dispatch('getInfo')
resetRouter()
// generate accessible routes map based on roles
const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
// dynamically add accessible routes
router.addRoutes(accessRoutes)
// reset visited views and cached views
dispatch('tagsView/delAllViews', null, { root: true })
}
}
export default {
namespaced: true,
state,
mutations,
actions
} |
@extends('admin.admin_master')
@section('admin')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="page-content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="card">
<div class="card-body">
<h4 class="card-title">Portfolio Page</h4>
<form method="POST" action="{{ route('store.portfolio') }}" enctype="multipart/form-data">
@csrf
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Portfolio Name</label>
<div class="col-sm-10">
<input name="portfolioName" class="form-control" type="text"
id="example-text-input">
@error('portfolioName')
<span class="text-danger">{{$message}}</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Portfolio Title</label>
<div class="col-sm-10">
<input name="portfolioTitle" class="form-control" type="text"
id="example-text-input">
@error('portfolioTitle')
<span class="text-danger">{{$message}}</span>
@enderror
</div>
</div>
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Portfolio
Description</label>
<div class="col-sm-10">
<textarea name="portfolioDescription" id="elm1"></textarea>
</div>
</div>
<div class=" row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Portfolio Image</label>
<div class="col-sm-10">
<input name="portfolioImage" class="form-control" type="file" id="image">
</div>
</div>
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label"> </label>
<img class="rounded avatar-lg" id="showImage" src="{{ url('upload/no_image.jpg') }}">
</div>
<div class="d-flex justify-content-end">
<input type="submit" class="btn btn-info waves-effect waves-light"
value="Insert Portfolio Page">
</div>
</form>
</div>
</div>
</div> <!-- end col -->
</div>
</div> <!-- container-fluid -->
</div>
<!-- End Page-content -->
<script type="text/javascript">
$(document).ready(function() {
$('#image').change(function(e) {
var reader = new FileReader();
reader.onload = function(e) {
$('#showImage').attr('src', e.target.result);
}
reader.readAsDataURL(e.target.files['0']);
})
})
</script>
@endsection |
package com.example.Diplomna.auth.controllers;
import com.example.Diplomna.auth.response.AuthenticationResponse;
import com.example.Diplomna.auth.response.ErrorResponse;
import com.example.Diplomna.auth.services.AuthenticationService;
import com.example.Diplomna.auth.request.AuthenticationRequest;
import com.example.Diplomna.auth.request.RegisterRequest;
import com.example.Diplomna.auth.request.ReloginRequest;
import com.example.Diplomna.services.ActivationLinkService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthenticationController {
private final AuthenticationService authenticationService;
private final ActivationLinkService activationLinkService;
@PostMapping("/register")
public ResponseEntity<Object> register (
@RequestBody RegisterRequest request
)
{
try {
return ResponseEntity.ok(authenticationService.register(request));
} catch (Exception ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@PostMapping("/auth")
public ResponseEntity<AuthenticationResponse> authenticate (
@RequestBody AuthenticationRequest request
) throws Exception {
return ResponseEntity.ok(authenticationService.authenticate(request));
}
@PostMapping("/refresh-auth")
public ResponseEntity<Object> refreshAuthentication(@RequestBody ReloginRequest request) {
try {
return ResponseEntity.ok(authenticationService.relogin(request));
} catch (Exception ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
@GetMapping("/activate")
public ResponseEntity<Object> activate(Long user_id, String code) {
try {
return ResponseEntity.ok(activationLinkService.activate(user_id, code));
} catch (Exception ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.BAD_REQUEST);
}
}
} |
---
title: Geyser Command Line Arguments and System Properties
description: Geyser offers a few command line arguments/system properties to allow you to configure Geyser without editing the config files.
---
# Geyser Command Line Arguments and System Properties
Geyser offers a few command line arguments/system properties to allow you to configure Geyser without editing the config files.
Additionally, you can suppress some warnings that may be printed to the console.
## Configuration system properties {#configuration-system-properties}
You can set Geyser to automatically bind to a specific address and port by using the following command line arguments.
This is primarily aimed at server hosting providers to automatically configure servers for users.
:::note
The Geyser specific properties are prioritized over the plugin properties!
:::
- ```-DgeyserUdpPort=server``` or ```-DpluginUdpPort=server```
- ```-1``` means UDP is not supported and will forcibly stop Geyser.
- ```server``` means to match the port of the TCP server.
- any other number means to use that specific port
- ```-DgeyserUdpAddress=server``` or ```-DpluginUdpAddress=server```
- ```server``` means to match the bind address of the TCP server
- any other string will be used as-is for the bind address.
## Disabling warnings and advanced configuration {#disabling-warnings-and-advanced-configuration}
You may disable some warnings that may be printed to the console by using the following command line arguments:
:::caution
Disabling Geyser warnings from being logged will not fix the real issue! Only disable them if you know what you are doing.
:::
- `-DGeyser.PrintSecureChatInformation=true`
- Allows you to disable the warning about secure chat being disabled.
Since the warning is sent when the server sends the warning, this option does not do much anymore.
- `-DGeyser.ShowScoreboardLogs=true`
- Allows you to disable warnings related to scoreboards, such as "Tried to update score without the existence of its requested objective".
- `-DGeyser.ShowResourcePackLengthWarning=true`
- Allows you to disable the warning about a resource pack having too long paths. Disabling this warning will not fix the underlying issue!
Console players might not be able to join your server at all if you have a resource pack with paths exceeding the 80 character limit.
- `-DGeyser.PrintPingsInDebugMode=true`
- Controls if pings are being logged in debug mode.
- `-DGeyser.UseDirectAdapters=true`
- Allows you to disable the usage of NMS adapters. Disabling will result in a performance penalty and should only be used for debugging.
This is Spigot-only and will not work on other platforms.
- `-DGeyser.BedrockNetworkThreads=8`
- Allows you to set the number of threads used for the Bedrock networking. This is not set to a specific number by default, but is instead calculated based on the available resources.
- `-DGeyser.AddTeamSuggestions=true`
- Allows you to turn off suggestions for teams in the scoreboard command. This is enabled by default, disabling this can help with performance if there are a lot of teams defined.
Setting "command-suggestions" to false in the config will also disable this.
- `-DGeyser.RakPacketLimit=120`
- Sets RakNet's per-ip per-tick (10ms) post-connection packet limit.
- `-DGeyser.RakOfflinePacketLimit=10`
- Sets RakNet's per-ip per-second pre-connection packet limit.
- `-DGeyser.RakGlobalPacketLimit=100000`
- Sets RakNet's per-tick (10ms) overall packet limit.
- `-DGeyser.RakRateLimitingDisabled=true`
- Completely disable RakNet's post-connection rate limiter. This should not be disabled unless initial RakNet connections are being handled by a reverse proxy.
- `-DGeyser.RakSendCookie=false`
- Disables sending and validation of a cookie challenge in [Open Connection Reply 1](https://wiki.vg/Raknet_Protocol#Open_Connection_Reply_1) packet. This should not be set to `false` unless Geyser is running behind a reverse proxy that is also sending a challenge to prevent IP spoofing.
## Geyser-Standalone Specific Options {#geyser-standalone-specific-options}
### `--config [file]` {#--config-file}
- **Alias: `-c`**
- Points to an alternative config file to use.
### `--gui` / `--nogui` {#--gui----nogui}
- **Alias: `gui` / `nogui`**:
- Forces GUI or non-GUI usage, depending on context.
## Overriding specific config values {#overriding-specific-config-values}
Overriding a standard config option (e.g. `command-suggestions`):
`--command-suggestions=false`
Overriding a nested config option(e.g. the `remote` section with `address`):
`--remote.address=test.geysermc.org` |
/*
Copyright 2023.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controllers
import (
"context"
"fmt"
"path/filepath"
"github.com/openshift-kni/lifecycle-agent/controllers/utils"
"github.com/openshift-kni/lifecycle-agent/internal/common"
lcautils "github.com/openshift-kni/lifecycle-agent/utils"
ctrl "sigs.k8s.io/controller-runtime"
lcav1alpha1 "github.com/openshift-kni/lifecycle-agent/api/v1alpha1"
corev1 "k8s.io/api/core/v1"
)
//nolint:unparam
func (r *ImageBasedUpgradeReconciler) startRollback(ctx context.Context, ibu *lcav1alpha1.ImageBasedUpgrade) (ctrl.Result, error) {
utils.SetRollbackStatusInProgress(ibu, "Initiating rollback")
stateroot, err := r.RPMOstreeClient.GetUnbootedStaterootName()
if err != nil {
utils.SetRollbackStatusFailed(ibu, err.Error())
return doNotRequeue(), nil
}
if _, err := r.Executor.Execute("mount", "/sysroot", "-o", "remount,rw"); err != nil {
utils.SetRollbackStatusFailed(ibu, err.Error())
return doNotRequeue(), nil
}
staterootVarPath := common.PathOutsideChroot(filepath.Join(common.GetStaterootPath(stateroot), "/var"))
// Save the CR for post-reboot restore
r.Log.Info("Save the IBU CR to the old state root before pivot")
filePath := filepath.Join(staterootVarPath, utils.IBUFilePath)
if err := lcautils.MarshalToFile(ibu, filePath); err != nil {
utils.SetRollbackStatusFailed(ibu, err.Error())
return doNotRequeue(), nil
}
r.Log.Info("Finding unbooted deployment")
deploymentIndex, err := r.RPMOstreeClient.GetUnbootedDeploymentIndex()
if err != nil {
utils.SetRollbackStatusFailed(ibu, err.Error())
return doNotRequeue(), nil
}
// Set the new default deployment
r.Log.Info("Checking for set-default feature")
if r.OstreeClient.IsOstreeAdminSetDefaultFeatureEnabled() {
r.Log.Info("set-default feature available")
if err = r.OstreeClient.SetDefaultDeployment(deploymentIndex); err != nil {
utils.SetRollbackStatusFailed(ibu, err.Error())
return doNotRequeue(), nil
}
} else {
r.Log.Info("set-default feature not available")
// Check to make sure the default deployment is set
if deploymentIndex != 0 {
msg := "default deployment must be manually set for next boot"
utils.SetRollbackStatusInProgress(ibu, msg)
return requeueWithError(fmt.Errorf(msg))
}
}
// Write an event to indicate reboot attempt
r.Recorder.Event(ibu, corev1.EventTypeNormal, "Reboot", "System will now reboot for rollback")
err = r.rebootToNewStateRoot("rollback")
if err != nil {
//todo: abort handler? e.g delete desired stateroot
r.Log.Error(err, "")
utils.SetUpgradeStatusFailed(ibu, err.Error())
return doNotRequeue(), nil
}
return doNotRequeue(), nil
}
//nolint:unparam
func (r *ImageBasedUpgradeReconciler) finishRollback(ctx context.Context, ibu *lcav1alpha1.ImageBasedUpgrade) (ctrl.Result, error) {
utils.SetRollbackStatusCompleted(ibu)
return doNotRequeue(), nil
}
//nolint:unparam
func (r *ImageBasedUpgradeReconciler) handleRollback(ctx context.Context, ibu *lcav1alpha1.ImageBasedUpgrade) (ctrl.Result, error) {
origStaterootBooted, err := isOrigStaterootBooted(r, ibu)
if err != nil {
//todo: abort handler? e.g delete desired stateroot
utils.SetRollbackStatusFailed(ibu, err.Error())
return doNotRequeue(), nil
}
if origStaterootBooted {
r.Log.Info("Pivot for rollback successful, starting post pivot steps")
return r.finishRollback(ctx, ibu)
} else {
r.Log.Info("Starting pre pivot for rollback steps and will pivot to previous stateroot with a reboot")
return r.startRollback(ctx, ibu)
}
} |
package edu.ntnu.fullstack.prosjekt.quizzer.mappers.impl;
import edu.ntnu.fullstack.prosjekt.quizzer.domain.dto.QuizDetailsDto;
import edu.ntnu.fullstack.prosjekt.quizzer.domain.dto.UserDto;
import edu.ntnu.fullstack.prosjekt.quizzer.domain.entities.QuizEntity;
import edu.ntnu.fullstack.prosjekt.quizzer.mappers.Mapper;
import lombok.extern.java.Log;
import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Component;
/**
* A class implementing the Mapper interface, to map between QuizDTOs and QuizEntities.
*/
@Log
@Component
public class QuizMapperImpl implements Mapper<QuizEntity, QuizDetailsDto> {
/**
* Used for Dependency Injection.
*/
private ModelMapper modelMapper;
/**
* Used for Dependency Injection.
*
* @param modelMapper The injected ModelMapper Object.
*/
public QuizMapperImpl(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
}
/**
* Method used for mapping from a QuizEntity to a QuizDTO.
*
* @param quizEntity QuizEntity object that should be mapped.
* @return Mapped QuizDTO object.
*/
@Override
public QuizDetailsDto mapTo(QuizEntity quizEntity) {
QuizDetailsDto quizDetailsDto = modelMapper.map(quizEntity, QuizDetailsDto.class);
log.info("Quiz mapped: " + quizDetailsDto);
if (quizEntity.getOwner() != null) {
quizDetailsDto.setOwner(modelMapper.map(quizEntity.getOwner(), UserDto.class));
}
return quizDetailsDto;
}
/**
* Method used for mapping from a QuizDTO to a QuizEntity.
*
* @param quizDetailsDto QuizDetailsDto object that should be mapped.
* @return Mapped QuizEntity object.
*/
@Override
public QuizEntity mapFrom(QuizDetailsDto quizDetailsDto) {
return modelMapper.map(quizDetailsDto, QuizEntity.class);
}
} |
package info.freelibrary.ark;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import info.freelibrary.util.Logger;
import info.freelibrary.ark.verticles.MainVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
/**
* An abstract base class for tests.
*/
@RunWith(VertxUnitRunner.class)
public abstract class AbstractTest {
/**
* The host used for testing.
*/
protected static final String HOST = "0.0.0.0";
/**
* A view into the test that's being run.
*/
@Rule
public TestName myTestName = new TestName();
/**
* The test context, from which the Vert.x instance can be retrieved
*/
@Rule
public RunTestOnContext myTestContext = new RunTestOnContext();
/**
* Set up our testing environment.
*
* @param aContext A test context
*/
@Before
public void setUp(final TestContext aContext) throws IOException {
final DeploymentOptions options = new DeploymentOptions();
final Async asyncTask = aContext.async();
final int port = getAvailablePort();
aContext.put(Config.HTTP_PORT, port);
options.setConfig(new JsonObject().put(Config.HTTP_PORT, port));
myTestContext.vertx().deployVerticle(MainVerticle.class.getName(), options, deployment -> {
if (deployment.succeeded()) {
try (Socket socket = new Socket(HOST, port)) {
// This is expected... do nothing
} catch (final IOException details) {
// Not necessarily an error, but a higher probability of one
getLogger().warn(MessageCodes.ARK_016, port);
}
asyncTask.complete();
} else {
aContext.fail(deployment.cause());
}
});
}
/**
* Cleans up after the test.
*
* @param aContext A test context
*/
@After
public void tearDown(final TestContext aContext) {
final Async asyncTask = aContext.async();
final int port = aContext.get(Config.HTTP_PORT);
myTestContext.vertx().close(shutdown -> {
getLogger().debug(MessageCodes.ARK_015, port);
asyncTask.complete();
});
}
/**
* The logger used in testing.
*
* @return A test logger
*/
protected abstract Logger getLogger();
/**
* Completes an Async task, if needed.
*
* @param aAsyncTask An asynchronous task
*/
protected void complete(final Async aAsyncTask) {
if (!aAsyncTask.isCompleted()) {
aAsyncTask.complete();
}
}
/**
* Gets an available port.
*
* @return An available port
*/
private int getAvailablePort() throws IOException {
try (ServerSocket socket = new ServerSocket(0)) {
return socket.getLocalPort();
}
}
} |
# 概要
リモートライトパズルゲームの仕様と設計書です。
# 仕様
## ゲーム概要
webゲーム。プレイヤーはライトパネルを操作し、指定されたパターンを再現するゲームです。カメラがライトパネルを映し出し、プレイヤーは指示された通りにライトを点灯させることを目指します。最後のステージはwebカメラ上に移った実際のLEDライトパネルを操作します。ユーザが仮想のwebゲームから実際のリアルな世界へ転換する感動を体験させることが目的です。
## ゲームデザイン
### 1.1 ステージ構成
ステージ1〜9:通常のWebゲーム。ライトの点灯パターンを再現するパズル。
ステージ10:リアルタイムのリモートライトパズル。ラズベリーパイとLEDライトパネルを使用。
### 1.2 難易度設定
ステージ1:シンプルなパターン(3つのライト)
ステージ2:ライトの数が増える(4つのライト)
ステージ3〜9:ライトの数や点灯パターンの複雑さが増していく
ステージ10:リアルタイムで同じパターンを再現する
## 設計概要
### インフラ
4つモジュールがある。
#### ラズベリーパイサーバ
リモート操作・映像送信を行う。
#### フロントサーバ
レンタルサーバを用意。ゲームソフト(html、javascript ) が表示できる。
#### シグナリングサーバ
webrtcにおいてピア同士の接続を確立するための最初の情報交換(シグナリング)を行います。これには、SDP(Session Description Protocol)メッセージやICE(Interactive Connectivity Establishment)候補の交換が含まれます。
#### STUN SERVER
役割:ピアのパブリックIPアドレスとポートを発見するために使用されます。これにより、NAT(Network Address Translation)を越えてP2P接続を確立する手助けをします。
詳細:google stun.l.google.com:19302を利用。
### 通信プロトコル
WebSocket:ブラウザとラズベリーパイ間のリアルタイム通信
HTTP API:バックエンドサーバーとのデータやスコアのやり取り
webRTC: ブラウザとラズベリーパイ間の映像通信
# 実装の詳細
## Webインターフェース実装
HTML:ステージレイアウトと基本構造
CSS:デザインとスタイル
JavaScript:ゲームロジックとユーザーインタラクション
## ラズベリーパイ実装
Python:LEDライトの制御、カメラ映像のストリーミング
WebSocketサーバー:ブラウザとのリアルタイム通信を管理(Python FAST API)
## ゲーム実装
Phaser.js
# ラズベリーパイサーバ設計
## 構成
/home/pi/remote_light_game_pi/
remote-light-puzzle/
├── src/
│ ├── app/
│ │ ├── __init__.py
│ │ ├── camera_control.py
│ │ ├── led_control.py
│ │ ├── websocket_server.py
│ │ └── utils.py
│ ├── config/
│ │ └── settings.py
│ ├── static/
│ │ ├── images/
│ │ └── css/
│ └── logs/
│ ├── app.log
│ └── errors.log
└── README.md
## 必要アプリケーション
Python 3.9.6
Python環境(pyenv, venv)
ライブラリ管理(pip)
WebSocketサーバー(FastAPI)
カメラ制御
LEDライト制御スクリプト(rpi_ws281x)
## ハードエンティティ
### Raspberrypi
Raspberrypi 3
### LEDライトパネル
BTF-LIGHTING LEDパネル WS2812B ECO RGB
8x8タイプ
### 電源
5V電源アダプター(DC 5V 3A)
### DC電源コネクタ
購入先:https://www.monotaro.com/g/06210417/
## ハード接続情報
LEDパネル 5V (赤) ------------- 5V電源アダプタの5V出力
LEDパネル GND (黒) ------------- 5V電源アダプタのGND出力
LEDパネル GND (黒) ------------- ラズベリーパイ GNDピン
LEDパネル データ (緑) ------------- ラズベリーパイ GPIO 18
# フロントサーバ設計
## 構成
~/remote_light_game_front/
├── src/
│ ├── app/
│ │ ├── __init__.py
│ │ ├── main.py
│ │ ├── templates/
│ │ │ └── index.html
│ │ ├── static/
│ │ │ ├── css/
│ │ │ │ └── style.css
│ │ │ ├── js/
│ │ │ │ ├── game.js
│ │ │ │ ├── phaser.min.js
│ │ │ │ └── webrtc_adapter.js
│ │ │ └── assets/
│ │ │ ├── images/
│ │ │ └── sounds/
│ │ └── api/
│ │ ├── score_handler.py
│ │ ├── user_handler.py
│ │ └── settings.py
│ ├── config/
│ │ └── settings.py
│ └── logs/
│ ├── app.log
│ └── errors.log
└── README.md
## 必要アプリケーション
Python 3.9.6
Python環境(pyenv, venv)
ライブラリ管理(pip)
サーバーフレームワーク(FastAPI)
## シグナリングサーバ
## 構成
~/signaling-server/
├── src/
│ ├── app/
│ │ ├── __init__.py
│ │ ├── server.py
│ │ ├── config/
│ │ │ └── stun_settings.py
│ │ ├── templates/
│ │ │ └── index.html
│ │ ├── static/
│ │ │ ├── css/
│ │ │ │ └── style.css
│ │ │ ├── js/
│ │ │ │ └── signaling_client.js
│ ├── config/
│ │ └── settings.py
│ └── logs/
│ ├── server.log
│ └── errors.log
└── README.md
## 必要アプリケーション
Python環境(pyenv, venv)
ライブラリ管理(pip)
サーバーフレームワーク(FastAPI)
# ゲーム設計
## プレイヤーの入力検知
### 1. インターフェースの設計
ライトパネル: 複数のライト(LED)を格子状に配置したパネル。
ライト: 各ライトは個別にクリックやタップで操作可能。
### 2. 入力検知の方法
クリック/タップイベント: 各ライトに対してクリックまたはタップイベントをリスンし、プレイヤーの操作を検知。
## パターンの照合ロジック
### 1. 正解パターンの生成
ランダムパターン生成: ランダムに選ばれたライトが点灯するパターンを生成。
事前定義パターン: 事前に決められたパターンを使用。
### 2. プレイヤーパターンの記録
プレイヤーが操作するたびに、現在のライトの状態を配列に記録。
### 3. 照合アルゴリズム
比較: プレイヤーの入力したパターンと正解パターンを逐一比較。
結果の判定:
全てのライトが一致すれば「正解」として次のステージへ進む。
一致しない場合は「不正解」として再挑戦させる。
``` mermaid
graph LR
A[プレイヤーの入力] --> B{入力の検知}
B --> C[ライトの状態を記録]
C --> D{正解パターンとの照合}
D --> E[正解]
D --> F[不正解]
E --> G[次のステージへ]
F --> H[再挑戦]
```
# 導入手順
## light_panel_game_front
### pyton環境構築
git clone ???
cd light_panel_game_front
python -m venv .lpgf |
package usecase
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func TestExecuteUseCase(t *testing.T) {
mockRateLimitRepository := new(mockRateLimitRepository)
mockRateLimitRepository.On("FindCurrentLimiterByKey", "key_a").Return(&FindCurrentLimiterByKeyDTO{}, nil)
mockRateLimitRepository.On("Save", mock.Anything).Return(nil)
mockConfigLimitRepository := new(mockConfigLimitRepository)
mockConfigLimitRepository.On("FindLimitConfigByKey", "key_a").Return(&FindLimitConfigByKeyDTO{}, nil)
mockConfigLimitRepository.On("FindLimitConfigByIp", "192.168.1.15").Return(&FindLimitConfigByIpDTO{}, nil)
usecase := NewRateLimitUseCase(mockRateLimitRepository, mockConfigLimitRepository)
output, err := usecase.Execute(context.Background(), RateLimitUseCaseInputDto{
Ip: "192.168.1.15",
Key: "key_a",
})
assert.Nil(t, err)
assert.True(t, output.Allow)
}
func TestExecuteUseCaseWhenNotBlockedByKey(t *testing.T) {
mockRateLimitRepository := new(mockRateLimitRepository)
mockRateLimitRepository.On("FindCurrentLimiterByKey", "key_a").Return(&FindCurrentLimiterByKeyDTO{
Count: 0,
UpdateAt: time.Now(),
}, nil)
mockRateLimitRepository.On("Save", mock.Anything).Return(nil)
mockConfigLimitRepository := new(mockConfigLimitRepository)
mockConfigLimitRepository.On("FindLimitConfigByKey", "key_a").Return(&FindLimitConfigByKeyDTO{
ExpirationTimeInMinutes: 5,
LimitPerSecond: 3,
}, nil)
mockConfigLimitRepository.On("FindLimitConfigByIp", "192.168.1.15").Return(&FindLimitConfigByIpDTO{}, nil)
usecase := NewRateLimitUseCase(mockRateLimitRepository, mockConfigLimitRepository)
output, err := usecase.Execute(context.Background(), RateLimitUseCaseInputDto{
Ip: "192.168.1.15",
Key: "key_a",
})
assert.Nil(t, err)
assert.True(t, output.Allow)
}
func TestExecuteUseCaseWhenBlockedByKey(t *testing.T) {
mockRateLimitRepository := new(mockRateLimitRepository)
mockRateLimitRepository.On("FindCurrentLimiterByKey", "key_a").Return(&FindCurrentLimiterByKeyDTO{
Count: 3,
UpdateAt: time.Now(),
StartAt: time.Now(),
}, nil)
mockRateLimitRepository.On("Save", mock.Anything).Return(nil)
mockConfigLimitRepository := new(mockConfigLimitRepository)
mockConfigLimitRepository.On("FindLimitConfigByKey", "key_a").Return(&FindLimitConfigByKeyDTO{
ExpirationTimeInMinutes: time.Minute * 5,
LimitPerSecond: 3,
}, nil)
mockConfigLimitRepository.On("FindLimitConfigByIp", "192.168.1.15").Return(&FindLimitConfigByIpDTO{}, nil)
usecase := NewRateLimitUseCase(mockRateLimitRepository, mockConfigLimitRepository)
output, err := usecase.Execute(context.Background(), RateLimitUseCaseInputDto{
Ip: "192.168.1.15",
Key: "key_a",
})
assert.Nil(t, err)
assert.False(t, output.Allow)
}
func TestExecuteUseCaseWhenNotBlockedByIp(t *testing.T) {
mockRateLimitRepository := new(mockRateLimitRepository)
mockRateLimitRepository.On("FindCurrentLimiterByKey", "192.168.1.15").Return(&FindCurrentLimiterByKeyDTO{
Count: 0,
UpdateAt: time.Now(),
StartAt: time.Now(),
}, nil)
mockRateLimitRepository.On("Save", mock.Anything).Return(nil)
mockConfigLimitRepository := new(mockConfigLimitRepository)
mockConfigLimitRepository.On("FindLimitConfigByKey", "key_a").Return(&FindLimitConfigByKeyDTO{}, nil)
mockConfigLimitRepository.On("FindLimitConfigByIp", "192.168.1.15").Return(&FindLimitConfigByIpDTO{
ExpirationTimeInMinutes: time.Minute * 5,
LimitPerSecond: 3,
}, nil)
usecase := NewRateLimitUseCase(mockRateLimitRepository, mockConfigLimitRepository)
output, err := usecase.Execute(context.Background(), RateLimitUseCaseInputDto{
Ip: "192.168.1.15",
})
assert.Nil(t, err)
assert.True(t, output.Allow)
}
func TestExecuteUseCaseWhenBlockedByIp(t *testing.T) {
mockRateLimitRepository := new(mockRateLimitRepository)
mockRateLimitRepository.On("FindCurrentLimiterByKey", "192.168.1.15").Return(&FindCurrentLimiterByKeyDTO{
Count: 3,
UpdateAt: time.Now(),
StartAt: time.Now(),
}, nil)
mockRateLimitRepository.On("Save", mock.Anything).Return(nil)
mockConfigLimitRepository := new(mockConfigLimitRepository)
mockConfigLimitRepository.On("FindLimitConfigByKey", "key_a").Return(&FindLimitConfigByKeyDTO{}, nil)
mockConfigLimitRepository.On("FindLimitConfigByIp", "192.168.1.15").Return(&FindLimitConfigByIpDTO{
ExpirationTimeInMinutes: time.Minute * 5,
LimitPerSecond: 3,
}, nil)
usecase := NewRateLimitUseCase(mockRateLimitRepository, mockConfigLimitRepository)
output, err := usecase.Execute(context.Background(), RateLimitUseCaseInputDto{
Ip: "192.168.1.15",
})
assert.Nil(t, err)
assert.False(t, output.Allow)
} |
import { BACKEND_API_LINK, API_GET_ALL_POSTS } from "../configs/config";
import Post from "../types/Post";
import React from "react";
import { useState, useEffect } from "react";
import axios from "axios";
const SeePosts: React.FC = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
const fetchPosts = async () => {
try {
const response = await axios.get(BACKEND_API_LINK + API_GET_ALL_POSTS);
setPosts(response.data);
} catch (error) {
console.error("Error fetching posts:", error);
}
};
fetchPosts();
}, []);
return (
<div>
<h2>All Posts</h2>
<ul>
{posts.map((post: Post) => (
<>
<li key={post.postid}>
<strong>{post.title}</strong>
<br />
{post.content}
<ul>
Made by user ID: <strong>{post.userid}</strong>
</ul>
<ul>
Reputation score: <strong>{post.reputation}</strong>
</ul>
</li>
<br />
</>
))}
</ul>
</div>
);
};
export default SeePosts; |
// 199. Binary Tree Right Side View
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> rightSideView(TreeNode* root) {
vector<int> results;
if (!root) return results;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode* currentNode = q.front();
q.pop();
if (i == size - 1) {
results.push_back(currentNode->val);
}
if (currentNode->left)
q.push(currentNode->left);
if (currentNode->right)
q.push(currentNode->right);
}
}
return results;
}
}; |
import React, { useState, useEffect } from 'react';
import { AppBar, Drawer, List, ListItem, ListItemButton, ListItemIcon, ListItemText, Toolbar, Typography, Grid, Button } from "@mui/material"
import { useTheme } from "@mui/material/styles";
import LogoutIcon from '@mui/icons-material/Logout';
import RecInovLogo from '../../assets/images/logo.png';
import Avatar from '@mui/material/Avatar';
import AccountCircleIcon from '@mui/icons-material/AccountCircle';
import { deepOrange } from '@mui/material/colors';
import { Home, DesktopMac, Person, FormatListBulleted, Storage } from '@mui/icons-material';
import { Link } from 'react-router-dom';
import axios from 'axios'; // Make sure to import axios if using it for HTTP requests
const handleLogout = async () => {
// Clear JWT from localStorage or sessionStorage
sessionStorage.removeItem('token');
sessionStorage.removeItem('candidatId');
sessionStorage.removeItem('candidatName');
window.location.href = '/signin/candidate';
};
const drawerWidth = 240;
const themedStyles = (theme) => ({
menuButton: {
marginRight: 2
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
background: 'linear-gradient(180deg, #1565c0, #fff)',
height: 80, // Increase the height of the AppBar
},
drawer: {
width: drawerWidth,
"& .MuiBackdrop-root": {
display: "none"
}
},
drawerPaper: {
width: drawerWidth,
backgroundColor: 'linear-gradient(180deg, #FDFEFF, #fff)'
},
content: {
padding: 3,
maxWidth: 720,
minWidth: 375,
marginLeft: drawerWidth + 8,
},
avatar: {
backgroundColor: deepOrange[500],
marginRight: theme.spacing(2),
marginLeft: theme.spacing(140)
},
userName: {
flexGrow: 1,
marginLeft: theme.spacing(150)
}
});
export default function CustomZIndexAppBar() {
const theme = useTheme();
const [candidatName, setCandidatName] = useState('');
useEffect(() => {
// Récupérer le nom du candidat depuis le sessionStorage
const candidatNameFromStorage = sessionStorage.getItem('candidatName');
if (candidatNameFromStorage) {
setCandidatName(candidatNameFromStorage);
}
}, []);
return (
<div>
<AppBar position="fixed" sx={themedStyles(theme).appBar}>
<Toolbar>
<Avatar sx={{ m: 1 }} src={RecInovLogo} />
<Typography variant="h6" >
Rec_inov
</Typography>
<Grid container alignItems="center">
<Grid container justifyContent="flex-end" alignItems="center">
<Avatar sx={{ bgcolor: theme.palette.secondary.main }}>
<AccountCircleIcon />
</Avatar>
<Typography component="div" variant="h6" sx={{ marginRight: 2 }}>
{candidatName}
</Typography>
<Button color="inherit" onClick={handleLogout} startIcon={<LogoutIcon />} sx={{ marginLeft: 1 }}>
Logout
</Button>
</Grid>
</Grid>
</Toolbar>
</AppBar>
<Drawer disableEnforceFocus
variant="temporary"
open={true}
sx={themedStyles(theme).drawer}
PaperProps={{
sx: themedStyles(theme).drawerPaper,
elevation: 9
}}>
<List sx={{ mt: "5rem" }}>
<ListItem button component={Link} to="/candidate/DashboardCandidat">
<ListItemIcon>
<Home />
</ListItemIcon>
<ListItemText primary="Tableau de bord" />
</ListItem>
<ListItemButton component={Link} to="/candidate/AddCondidat" >
<ListItemIcon>
<DesktopMac />
</ListItemIcon>
<ListItemText primary="Profil"/>
</ListItemButton>
<ListItem button component={Link} to="/candidate/ListeOffres">
<ListItemIcon>
<FormatListBulleted />
</ListItemIcon>
<ListItemText primary="Liste Offres" />
</ListItem>
<ListItem button component={Link} to="/candidate/JobApplicationHistory" >
<ListItemIcon>
<Storage />
</ListItemIcon>
<ListItemText primary="Mes Candidatures" />
</ListItem>
</List>
</Drawer>
<Toolbar />
</div>
)
} |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
/* woah */
import {TransferUtils} from "../../../utils/TransferUtils.sol";
import {ISharedErrors} from "../../shared/ISharedErrors.sol";
/**
* @title FeeManager
*/
contract FeeManager {
address public immutable feeRecipient;
uint256 public immutable fee;
error Fee_Transfer_Failed();
error Cannot_Set_Recipient_To_Zero_Address();
constructor (address _feeRecipient, uint256 _fee) {
feeRecipient = _feeRecipient;
fee = _fee;
if (_feeRecipient == address(0)) {
revert Cannot_Set_Recipient_To_Zero_Address();
}
}
function getFees(uint256 numStorageSlots) external returns (uint256) {
return fee * numStorageSlots;
}
function _handleFees(uint256 numStorageSlots) internal {
uint256 totalFee = fee * numStorageSlots;
if (msg.value != totalFee) revert ISharedErrors.Incorrect_Msg_Value();
if (!TransferUtils.safeSendETH(
feeRecipient,
totalFee,
TransferUtils.FUNDS_SEND_LOW_GAS_LIMIT
)) revert Fee_Transfer_Failed();
}
} |
<?php
/**
Цель: Предоставляет объект-заместитель для контроля доступа к другому объекту.
Характеристики: Применяется для ограничения доступа, ленивой инициализации или кэширования.
**/
interface Subject {
public function request();
}
class RealSubject implements Subject {
public function request() {
return "Real Subject request";
}
}
class Proxy implements Subject {
private $realSubject;
public function __construct(RealSubject $realSubject) {
$this->realSubject = $realSubject;
}
public function request() {
return "Proxy: " . $this->realSubject->request();
}
}
$realSubject = new RealSubject();
$proxy = new Proxy($realSubject);
echo $proxy->request(); |
import React from "react";
import Navbar from "react-bootstrap/Navbar";
import Nav from "react-bootstrap/Nav";
import NavDropdown from "react-bootstrap/NavDropdown";
import { LinkContainer } from "react-router-bootstrap";
import NavLink from "react-bootstrap/NavLink";
import logo from "./assets/logo.svg";
import "./Header.scss";
import { withRouter } from "react-router-dom";
class Header extends React.Component {
constructor(props) {
super(props);
this.logout = this.logout.bind(this);
}
logout() {
window.localStorage.clear("token");
this.props.history.push("/login");
}
render() {
const user = JSON.parse(window.localStorage.getItem("user"));
return (
<header>
<Navbar bg="dark" variant="dark" expand="md">
<LinkContainer to="/">
<Navbar.Brand>
<img
src={logo}
height="30"
className="d-inline-block align-top"
alt="NoTe logo"
/>
</Navbar.Brand>
</LinkContainer>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<LinkContainer to="/">
<NavLink>Plantas</NavLink>
</LinkContainer>
<Nav className="mr-auto" />
<NavDropdown
title={user ? user.name : "Usuario"}
id="basic-nav-dropdown"
>
<LinkContainer to="/profile">
<NavDropdown.Item> Perfil </NavDropdown.Item>
</LinkContainer>
<NavDropdown.Divider />
<NavDropdown.Item onClick={this.logout}>Salir</NavDropdown.Item>
</NavDropdown>
</Navbar.Collapse>
</Navbar>
</header>
);
}
}
export default withRouter(Header); |
#define _CRT_SECURE_NO_WARNINGS
#define PROGRAM_FILE "op_test.cl"
#define KERNEL_FUNC "op_test"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef MAC
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif
/* Find a GPU or CPU associated with the first available platform */
cl_device_id create_device() {
cl_platform_id platform;
cl_device_id dev;
int err;
/* Identify a platform */
err = clGetPlatformIDs(1, &platform, NULL);
if (err < 0) {
perror("Couldn't identify a platform");
exit(1);
}
/* Access a device */
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &dev, NULL);
if (err == CL_DEVICE_NOT_FOUND) {
err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, 1, &dev, NULL);
}
if (err < 0) {
perror("Couldn't access any devices");
exit(1);
}
return dev;
}
/* Create program from a file and compile it */
cl_program build_program(cl_context ctx, cl_device_id dev,
const char *filename) {
cl_program program;
FILE *program_handle;
char *program_buffer, *program_log;
size_t program_size, log_size;
int err;
/* Read program file and place content into buffer */
program_handle = fopen(filename, "r");
if (program_handle == NULL) {
perror("Couldn't find the program file");
exit(1);
}
fseek(program_handle, 0, SEEK_END);
program_size = ftell(program_handle);
rewind(program_handle);
program_buffer = (char *)malloc(program_size + 1);
program_buffer[program_size] = '\0';
fread(program_buffer, sizeof(char), program_size, program_handle);
fclose(program_handle);
/* Create program from file */
program = clCreateProgramWithSource(ctx, 1, (const char **)&program_buffer,
&program_size, &err);
if (err < 0) {
perror("Couldn't create the program");
exit(1);
}
free(program_buffer);
/* Build program */
err = clBuildProgram(program, 0, NULL, NULL, NULL, NULL);
if (err < 0) {
/* Find size of log and print to std output */
clGetProgramBuildInfo(program, dev, CL_PROGRAM_BUILD_LOG, 0, NULL,
&log_size);
program_log = (char *)malloc(log_size + 1);
program_log[log_size] = '\0';
clGetProgramBuildInfo(program, dev, CL_PROGRAM_BUILD_LOG, log_size + 1,
program_log, NULL);
printf("%s\n", program_log);
free(program_log);
exit(1);
}
return program;
}
int main() {
/* OpenCL data structures */
cl_device_id device;
cl_context context;
cl_command_queue queue;
cl_program program;
cl_kernel kernel;
cl_int i, err;
/* Data and buffers */
int test[4];
cl_mem test_buffer;
/* Create a device and context */
device = create_device();
context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
if (err < 0) {
perror("Couldn't create a context");
exit(1);
}
/* Build the program and create a kernel */
program = build_program(context, device, PROGRAM_FILE);
kernel = clCreateKernel(program, KERNEL_FUNC, &err);
if (err < 0) {
perror("Couldn't create a kernel");
exit(1);
};
/* Create a write-only buffer to hold the output data */
test_buffer =
clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(test), NULL, &err);
if (err < 0) {
perror("Couldn't create a buffer");
exit(1);
};
/* Create kernel argument */
err = clSetKernelArg(kernel, 0, sizeof(cl_mem), &test_buffer);
if (err < 0) {
perror("Couldn't set a kernel argument");
exit(1);
};
/* Create a command queue */
queue = clCreateCommandQueueWithProperties(context, device, NULL, &err);
if (err < 0) {
perror("Couldn't create a command queue");
exit(1);
};
/* Enqueue kernel */
const size_t global_work_offset[] = {0};
const size_t global_work_size[] = {4};
const size_t local_work_size[] = {1};
err =
clEnqueueNDRangeKernel(queue, kernel, 1, global_work_offset,
global_work_size, local_work_size, 0, NULL, NULL);
if (err < 0) {
perror("Couldn't enqueue the kernel");
exit(1);
}
/* Read and print the result */
err = clEnqueueReadBuffer(queue, test_buffer, CL_TRUE, 0, sizeof(test), &test,
0, NULL, NULL);
if (err < 0) {
perror("Couldn't read the buffer");
exit(1);
}
for (i = 0; i < 3; i++) {
printf("%d, ", test[i]);
}
printf("%d\n", test[3]);
/* Deallocate resources */
clReleaseMemObject(test_buffer);
clReleaseKernel(kernel);
clReleaseCommandQueue(queue);
clReleaseProgram(program);
clReleaseContext(context);
return 0;
} |
import { styles } from "../styles/mainCss";
import { Text, View, Image, Pressable, TouchableHighlight, SafeAreaView } from "react-native";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import { themeColors } from "../styles/base";
import { useState } from "react";
import Header from "./Header";
import { useIsFocused } from "@react-navigation/native";
import { API_URL, API_TOKEN } from "@env";
import React from "react";
import axios from "axios";
import Ionicons from "@expo/vector-icons/Ionicons";
export default function Saved({ navigation }) {
const [isSaved, setIsSaved] = useState(true);
const isFocused = useIsFocused();
const [saved, setSaved] = useState();
const [interested, setInterested] = useState();
React.useEffect(() => {
if (isFocused) {
axios.get(`${API_URL}/items/getSavedInterested`).then((items) => {
if (items.data.status === 200) {
if (items.data && items.data.items) {
setInterested(items.data.items);
}
}
});
}
}, [isFocused]);
return (
<View style={styles.containerFlex}>
<View style={styles.topBottomFlex}>
<Header name={"Saved"}></Header>
</View>
<View style={styles.body}>
<KeyboardAwareScrollView>
{isSaved ? (
<View>
{interested && interested.length > 0 ? (
<View style={styles.savedInterestedView}>
{interested.map((item, index) => {
return (
<TouchableHighlight
key={index}
onPress={() => navigation.navigate("ViewItem", { data: item.listingId })}
underlayColor="#DDDDDD"
>
<View
style={[
styles.savedInterestedViewItem,
{ backgroundColor: index % 2 === 0 ? "white" : themeColors.peimarynext },
]}
>
<View style={[styles.itemImage, styles.savedInterestedViewItemImage]}>
<Image style={styles.infoImage} resizeMode="cover" src={item.images[0]}></Image>
</View>
<View style={styles.savedInterestedViewItemText}>
{item.title ? <Text style={{ marginTop: 5 }}>{item.title}</Text> : ""}
{item.address && item.address.addressText ? (
<View style={styles.addressFlexItem}>
<Ionicons name="pin" size={35} color="#7a9e9f" />
<Text style={{ flex: 1 }}>{item.address.addressText}</Text>
</View>
) : (
""
)}
</View>
</View>
</TouchableHighlight>
);
})}
</View>
) : (
<View>
<Text>Interested items not found</Text>
</View>
)}
</View>
) : (
<View>
{saved && saved.length > 0 ? (
<View style={styles.savedInterestedView}>
{saved.map((item, index) => {
return (
<View
key={index}
style={[
styles.savedInterestedViewItem,
{ backgroundColor: index % 2 === 0 ? "white" : themeColors.peimarynext },
]}
>
<View style={[styles.itemImage, styles.savedInterestedViewItemImage]}>
<Image style={styles.infoImage} resizeMode="cover" src={item.images[0]}></Image>
</View>
<View style={styles.savedInterestedViewItemText}>
{item.title ? <Text style={{ marginTop: 5 }}>{item.title}</Text> : ""}
{item.address && item.address.addressText ? (
<View style={styles.addressFlexItem}>
<Ionicons name="pin" size={35} color="#7a9e9f" />
<Text style={{ flex: 1 }}>{item.address.addressText}</Text>
</View>
) : (
""
)}
</View>
</View>
);
})}
</View>
) : (
<View>
<Text>Saved items not found</Text>
</View>
)}
</View>
)}
</KeyboardAwareScrollView>
</View>
</View>
);
} |
import React from 'react';
import LandsStore from '../stores/landsStore'
import LandsActions from '../actions/landsActionCreators'
import Constants from '../constants'
import Utils from '../utils/utils'
import AnalysisScreenLayout from '../components/analysisScreenLayout'
const AnalysisScreenLayoutContainer = React.createClass({
getInitialState: LandsStore.getState,
componentDidMount() {
LandsStore.addChangeListener(this.onChange);
LandsActions.updateNumberOfLands(this.state.numberOfEachColour);
LandsActions.runSimulation(this.state.numberOfEachColour);
},
componentWillUnmount() {
LandsStore.removeChangeListener(this.onChange);
},
onChange() {
this.setState(LandsStore.getState());
},
handleRunSimulation() {
LandsActions.runSimulation(this.state.numberOfEachColour);
},
handleBarSelected(barClicked) {
var selectedTurn = barClicked === this.state.selectedTurn ? null : barClicked;
LandsActions.updateSelectedTurn(selectedTurn);
},
handleSliderChanged(colour, newValue) {
var numberOfEachColourCopy = Utils.createColoursObject(this.state.numberOfEachColour);
numberOfEachColourCopy[colour] = parseInt(newValue);
LandsActions.updateNumberOfLands(numberOfEachColourCopy);
},
handleQueryNumbersChanged(colour, event) {
var queryNumbersCopy = Utils.objectMap(this.state.queryNumbers, x => x);
var int = parseInt(event.target.value)
if (int || int === 0) {
queryNumbersCopy[colour] = parseInt(event.target.value);
LandsActions.updateQueryNumbers(queryNumbersCopy);
} else if (event.target.value === "") {
queryNumbersCopy[colour] = "";
LandsActions.updateQueryNumbers(queryNumbersCopy);
}
},
render() {
return (
<AnalysisScreenLayout
isSimulationRunning={this.state.isSimulationRunning}
selectedTurn={this.state.selectedTurn}
averages={this.state.averages}
mostCommonLandScenarios={this.state.mostCommonLandScenarios}
queryNumbers={this.state.queryNumbers}
probability={this.state.probability}
numberOfEachColour={this.state.numberOfEachColour}
simulationError={this.state.simulationError}
onRunSimulation={this.handleRunSimulation}
onBarSelected={this.handleBarSelected}
onSliderChanged={this.handleSliderChanged}
onQueryNumbersChanged={this.handleQueryNumbersChanged}
/>
)
}
});
export default AnalysisScreenLayoutContainer; |
# Description:
# A way to interact with the Google Images API.
#
# Configuration
# HUBOT_GOOGLE_CSE_KEY - Your Google developer API key
# HUBOT_GOOGLE_CSE_ID - The ID of your Custom Search Engine
# HUBOT_MUSTACHIFY_URL - Optional. Allow you to use your own mustachify instance.
# HUBOT_GOOGLE_IMAGES_HEAR - Optional. If set, bot will respond to any line that begins with "image me" or "animate me" without needing to address the bot directly
# HUBOT_GOOGLE_SAFE_SEARCH - Optional. Search safety level.
# HUBOT_GOOGLE_IMAGES_FALLBACK - The URL to use when API fails. `{q}` will be replaced with the query string.
#
# Commands:
# hubot image me <query> - The Original. Queries Google Images for <query> and returns a random top result.
# hubot animate me <query> - The same thing as `image me`, except adds a few parameters to try to return an animated GIF instead.
# hubot mustache me <url|query> - Adds a mustache to the specified URL or query result.
module.exports = (robot) ->
robot.respond /(image|img)( me)? (.+)/i, (msg) ->
imageMe msg, msg.match[3], (url) ->
msg.send url
robot.respond /animate( me)? (.+)/i, (msg) ->
imageMe msg, msg.match[2], true, (url) ->
msg.send url
# pro feature, not added to docs since you can't conditionally document commands
if process.env.HUBOT_GOOGLE_IMAGES_HEAR?
robot.hear /^(image|img) me (.+)/i, (msg) ->
imageMe msg, msg.match[2], (url) ->
msg.send url
robot.hear /^animate me (.+)/i, (msg) ->
imageMe msg, msg.match[1], true, (url) ->
msg.send url
robot.respond /(?:mo?u)?sta(?:s|c)h(?:e|ify)?(?: me)? (.+)/i, (msg) ->
if not process.env.HUBOT_MUSTACHIFY_URL?
msg.send "Sorry, the Mustachify server is not configured."
, "http://i.imgur.com/BXbGJ1N.png"
return
mustacheBaseUrl =
process.env.HUBOT_MUSTACHIFY_URL?.replace(/\/$/, '')
mustachify = "#{mustacheBaseUrl}/rand?src="
imagery = msg.match[1]
if imagery.match /^https?:\/\//i
encodedUrl = encodeURIComponent imagery
msg.send "#{mustachify}#{encodedUrl}"
else
imageMe msg, imagery, false, true, (url) ->
encodedUrl = encodeURIComponent url
msg.send "#{mustachify}#{encodedUrl}"
imageMe = (msg, query, animated, faces, cb) ->
cb = animated if typeof animated == 'function'
cb = faces if typeof faces == 'function'
googleCseId = process.env.HUBOT_GOOGLE_CSE_ID
if googleCseId
# Using Google Custom Search API
googleApiKey = process.env.HUBOT_GOOGLE_CSE_KEY
if !googleApiKey
msg.robot.logger.error "Missing environment variable HUBOT_GOOGLE_CSE_KEY"
msg.send "Missing server environment variable HUBOT_GOOGLE_CSE_KEY."
return
q =
q: query,
searchType:'image',
safe: process.env.HUBOT_GOOGLE_SAFE_SEARCH || 'high',
fields:'items(link)',
cx: googleCseId,
key: googleApiKey
if animated is true
q.fileType = 'gif'
q.hq = 'animated'
q.tbs = 'itp:animated'
if faces is true
q.imgType = 'face'
url = 'https://www.googleapis.com/customsearch/v1'
msg.http(url)
.query(q)
.get() (err, res, body) ->
if err
if res.statusCode is 403
msg.send "Daily image quota exceeded, using alternate source."
deprecatedImage(msg, query, animated, faces, cb)
else
msg.send "Encountered an error :( #{err}"
return
if res.statusCode isnt 200
msg.send "Bad HTTP response :( #{res.statusCode}"
return
response = JSON.parse(body)
if response?.items
image = msg.random response.items
cb ensureResult(image.link, animated)
else
msg.send "Oops. I had trouble searching '#{query}'. Try later."
((error) ->
msg.robot.logger.error error.message
msg.robot.logger
.error "(see #{error.extendedHelp})" if error.extendedHelp
) error for error in response.error.errors if response.error?.errors
else
msg.send "Google Image Search API is no longer available. " +
"Please [setup up Custom Search Engine API](https://github.com/hubot-scripts/hubot-google-images#cse-setup-details)."
deprecatedImage(msg, query, animated, faces, cb)
deprecatedImage = (msg, query, animated, faces, cb) ->
# Show a fallback image
imgUrl = process.env.HUBOT_GOOGLE_IMAGES_FALLBACK ||
'http://i.imgur.com/CzFTOkI.png'
imgUrl = imgUrl.replace(/\{q\}/, encodeURIComponent(query))
cb ensureResult(imgUrl, animated)
# Forces giphy result to use animated version
ensureResult = (url, animated) ->
if animated is true
ensureImageExtension url.replace(
/(giphy\.com\/.*)\/.+_s.gif$/,
'$1/giphy.gif')
else
ensureImageExtension url
# Forces the URL look like an image URL by adding `#.png`
ensureImageExtension = (url) ->
if /(png|jpe?g|gif)$/i.test(url)
url
else
"#{url}#.png" |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import expect from '@kbn/expect';
import { FtrProviderContext } from '../../../../../common/ftr_provider_context';
import { getUrlPrefix, getTestRuleData, ObjectRemover } from '../../../../../common/lib';
// eslint-disable-next-line import/no-default-export
export default function createWithCircuitBreakerTests({ getService }: FtrProviderContext) {
const supertest = getService('supertest');
const objectRemover = new ObjectRemover(supertest);
describe('Create with circuit breaker', () => {
afterEach(async () => {
await objectRemover.removeAll();
});
it('should prevent rules from being created if max schedules have been reached', async () => {
const { body: createdRule } = await supertest
.post(`${getUrlPrefix('space1')}/api/alerting/rule`)
.set('kbn-xsrf', 'foo')
.send(getTestRuleData({ schedule: { interval: '10s' } }))
.expect(200);
objectRemover.add('space1', createdRule.id, 'rule', 'alerting');
const {
body: { message },
} = await supertest
.post(`${getUrlPrefix('space1')}/api/alerting/rule`)
.set('kbn-xsrf', 'foo')
.send(getTestRuleData({ schedule: { interval: '10s' } }))
.expect(400);
expect(message).eql(
`Error validating circuit breaker - Rule 'abc' cannot be created. The maximum number of runs per minute would be exceeded. - The rule has 6 runs per minute; there are only 4 runs per minute available. Before you can modify this rule, you must increase its check interval so that it runs less frequently. Alternatively, disable other rules or change their check intervals.`
);
});
it('should prevent rules from being created across spaces', async () => {
const { body: createdRule } = await supertest
.post(`${getUrlPrefix('space1')}/api/alerting/rule`)
.set('kbn-xsrf', 'foo')
.send(getTestRuleData({ schedule: { interval: '10s' } }))
.expect(200);
objectRemover.add('space1', createdRule.id, 'rule', 'alerting');
const {
body: { message },
} = await supertest
.post(`${getUrlPrefix('space2')}/api/alerting/rule`)
.set('kbn-xsrf', 'foo')
.send(getTestRuleData({ schedule: { interval: '10s' } }))
.expect(400);
expect(message).eql(
`Error validating circuit breaker - Rule 'abc' cannot be created. The maximum number of runs per minute would be exceeded. - The rule has 6 runs per minute; there are only 4 runs per minute available. Before you can modify this rule, you must increase its check interval so that it runs less frequently. Alternatively, disable other rules or change their check intervals.`
);
});
it('should allow disabled rules to go over the circuit breaker', async () => {
const { body: createdRule1 } = await supertest
.post(`${getUrlPrefix('space1')}/api/alerting/rule`)
.set('kbn-xsrf', 'foo')
.send(getTestRuleData({ schedule: { interval: '10s' } }))
.expect(200);
objectRemover.add('space1', createdRule1.id, 'rule', 'alerting');
const { body: createdRule2 } = await supertest
.post(`${getUrlPrefix('space1')}/api/alerting/rule`)
.set('kbn-xsrf', 'foo')
.send(
getTestRuleData({
enabled: false,
schedule: { interval: '10s' },
})
)
.expect(200);
objectRemover.add('space1', createdRule2.id, 'rule', 'alerting');
});
});
} |
import React from 'react';
import PropTypes from 'prop-types';
import useLanguage from '../../../../hooks/useLanguage';
import { Link } from 'gatsby-plugin-react-i18next';
import UpArrow from '../../../../svg/arr-up.svg';
import { scroller } from 'react-scroll';
const FooterRight = ({ title, links, navigationData }) => {
const langToggle = useLanguage;
function scrollToSection() {
scroller.scrollTo('top-section', {
duration: 800,
delay: 0,
smooth: 'easeInOutQuart',
});
}
return (
<div className="footer-right footer__item">
<div className="footer-right__up">
<button className="up__button" aria-label="scroll to Up" onClick={scrollToSection}>
<div className="up__text">
{langToggle(title.upButton_ua, title.upButton_ru, title.upButton_en)}
</div>
<div className="up__icon">
<UpArrow className="up__icon-icon" />
</div>
</button>
</div>
<div className="footer-right__menu-wrapper">
<div className="footer-right__menu-content">
<ul className="footer-right__menu-item">
{navigationData.map((item, index) => {
return (
<li className="footer-right__menu-liks" key={index}>
<Link to={item.slug} className="footer-right__menu-item">
{langToggle(item.title_ua, item.title_ru, item.title_en)}
</Link>
</li>
);
})}
</ul>
</div>
</div>
<div className="footer-right__confidentiality">
<div className="confidentiality-container">
<div className="footer-right__confidentiality-links">
<Link to={links.link_confidentiality} className="link">
{langToggle(
links.confidentiality_ua,
links.confidentiality_ru,
links.confidentiality_en,
)}
</Link>
</div>
<div className="footer-right__contract-links">
<Link to={links.link_contract} className="link">
{langToggle(links.contract_ua, links.contract_ru, links.contract_en)}
</Link>
</div>
</div>
</div>
</div>
);
};
FooterRight.propTypes = {
title: PropTypes.object,
menuData: PropTypes.object,
links: PropTypes.object,
navigationData: PropTypes.array,
};
export default FooterRight; |
import { applyGravity } from './applyGravity';
import { DeltaTime } from './deltaTime';
import { getAngleBetweenTwoPoints } from './getAngleBetweenTwoPoints';
import { getXFromAngle } from './getXFromAngle';
import { getYFromAngle } from './getYFromAngle';
import { Globals } from './globals';
import { PlayerDTO, Vector } from './types.dto';
export class Player {
private readonly globals: Globals;
private readonly deltaTime: DeltaTime;
private id: string;
private position: Vector;
private name: string;
private movingVelocity: Vector;
private color: number;
private direction: number;
private grounded: boolean;
public constructor(id: string, data: PlayerDTO) {
this.globals = Globals.getInstance();
this.deltaTime = DeltaTime.getInstance();
this.id = id;
this.position = data.position;
this.name = data.name;
this.movingVelocity = data.movingVelocity;
this.color = data.color;
this.direction = data.direction;
this.grounded = true;
}
public applyGravity() {
this.movingVelocity = {
...applyGravity(this.movingVelocity, this.deltaTime.getDeltaTime()),
};
console.log(this.movingVelocity);
}
public resetVelocity() {
this.movingVelocity = { x: 0, y: 0 };
}
public updatePosition(position: Vector): void {
this.position = { ...position };
}
public updateDirection(direction: number): void {
this.direction = direction;
}
public updateColor(color: number): void {
this.color = color;
}
public getId(): string {
return this.id;
}
public getPosition(): Vector {
return { ...this.position };
}
public getName(): string {
if (this.isMyself() && localStorage.getItem('username')) {
return localStorage.getItem('username');
}
return this.name;
}
public setName(name: string): void {
this.name = name;
}
public getColor(): number {
return this.color;
}
public getDirection(): number {
return this.direction;
}
public isGrounded(): boolean {
return this.grounded;
}
public setGrounded(grounded: boolean): void {
this.grounded = grounded;
}
public getMovingVelocity(): Vector {
return { ...this.movingVelocity };
}
public swapColor(): void {
this.color = this.color === 0 ? 1 : 0;
}
public getJumpPower(): number {
return Math.abs(getXFromAngle(Date.now() / 1000) * 1.4);
}
private _getJumpDirection(x: number, y: number) {
return getAngleBetweenTwoPoints(
{
x: this.position.x + this.globals.playerSize.x / 2,
y: this.position.y + this.globals.playerSize.y / 2,
},
{
x: x * this.globals.canvasScale,
y: y * this.globals.canvasScale,
},
);
}
public jump(click: Vector): void {
const jumpPower = this.getJumpPower();
const angle = this._getJumpDirection(click.x, click.y);
this.movingVelocity.x = getXFromAngle(angle) * jumpPower;
this.movingVelocity.y = getYFromAngle(angle) * jumpPower;
this.direction = this.movingVelocity.x > 0 ? 1 : 0;
console.log(this.movingVelocity, this.direction);
}
public move(): void {
this.position.x += this.movingVelocity.x * this.deltaTime.getDeltaTime();
this.position.y += this.movingVelocity.y * this.deltaTime.getDeltaTime();
}
public touchBottom(resetPoint: number) {
this.position.y = resetPoint - this.globals.playerSize.y - 1;
this.grounded = true;
if (this.isMyself()) {
if(this.globals.platform.is('cordova')) {
this.globals.nativeAudio.play('land').then(console.log, console.error);
} else {
this.globals.sounds[1].play();
}
}
this.resetVelocity();
}
public touchTop(resetPoint: number) {
this.position.y = resetPoint + 1;
this.resetVelocity();
}
public touchLeft(resetPoint: number) {
this.position.x = resetPoint + 1;
this.resetVelocity();
}
public touchRight(resetPoint: number) {
this.position.x = resetPoint - this.globals.playerSize.x - 1;
this.resetVelocity();
}
public isMyself(): boolean {
return this.id === this.globals.socketId;
}
public draw() {
this.globals.context.drawImage(
this.globals.playerImages[this.color * 2 + this.direction],
this.position.x,
this.position.y,
this.globals.playerSize.x,
this.globals.playerSize.y,
);
this.globals.context.fillStyle = 'black';
this.globals.context.textAlign = 'center';
this.globals.context.font = '25px Arial';
this.globals.context.fillText(
this.getName(),
this.position.x + this.globals.playerSize.x / 2,
this.position.y - 30,
);
}
} |
if (!require("ggplot2")) install.packages("ggplot2")
if (!require("stringr")) install.packages("stringr")
if (!require("dplyr")) install.packages("dplyr")
if (!require("tidyverse")) install.packages("tidyverse")
library(tidyverse)
library(dplyr)
library(forcats)
# ENVIRONNEMENT -------------------------
source("R/fonctions.R")
api_token <- yaml::read_yaml("secrets.yaml")$JETON_API
fonction_de_stat_agregee(rnorm(10))
fonction_de_stat_agregee(rnorm(10), "ecart-type")
fonction_de_stat_agregee(rnorm(10), "variance")
# IMPORT DONNEES ------------------
df <- readr::read_csv2(
"individu_reg.csv",
col_select = c(
"region", "aemm", "aged", "anai", "catl", "cs1", "cs2", "cs3",
"couple", "na38", "naf08", "pnai12", "sexe", "surf", "tp",
"trans", "ur"
)
)
# RETRAITEMENT DONNEES -------------------
df$sexe <- df$sexe %>%
as.character() %>%
fct_recode(Homme = "1", Femme = "2")
# STATISTIQUES DESCRIPTIVES --------------------
summarise(group_by(df, aged), n())
# part d'homme dans chaque cohort
df %>%
group_by(aged, sexe) %>%
summarise(SH_sexe = n()) %>%
group_by(aged) %>%
mutate(SH_sexe = SH_sexe / sum(SH_sexe)) %>%
filter(sexe == 1) %>%
ggplot() +
geom_bar(aes(x = as.numeric(aged), y = SH_sexe), stat = "identity") +
geom_point(aes(x = as.numeric(aged), y = SH_sexe), stat = "identity",
color = "red") +
coord_cartesian(c(0, 100))
# stats trans par statut
df2 <- df %>%
group_by(couple, trans) %>%
summarise(x = n()) %>%
group_by(couple) %>%
mutate(y = 100 * x / sum(x))
df %>%
filter(sexe == "Homme") %>%
mutate(aged = as.numeric(aged)) %>%
pull(aged) %>%
fonction_de_stat_agregee()
df %>%
filter(sexe == "Femme") %>%
mutate(aged = as.numeric(aged)) %>%
pull(aged) %>%
fonction_de_stat_agregee()
# GRAPHIQUES -----------
ggplot(df) +
geom_histogram(aes(x = 5 * floor(as.numeric(aged) / 5)), stat = "count")
p <- ggplot(df2) +
geom_bar(aes(x = trans, y = y, color = couple), stat = "identity",
position = "dodge")
ggsave("p.png", p)
# MODELISATION ---------------------
df %>%
select(surf, cs1, ur, couple, aged) %>%
filter(surf != "Z") %>%
MASS::polr(factor(surf) ~ cs1 + factor(ur), .) |
import { Badge, Center, Flex, Heading, Tab, TabList, Tabs, Tag, Text } from "@chakra-ui/react";
import ProblemPlayground from "components/Playground/ProblemPlayground";
import UserPreview from "components/User/UserPreview";
import { useNotify } from "hooks";
import PageLayout from "layouts/PageLayout/PageLayout";
import { toJS } from "mobx";
import { inject, observer } from "mobx-react";
import * as React from "react";
import { FaBan } from "react-icons/fa";
import { useParams } from "react-router-dom";
import { AuthStore, GameStore, PlaygroundStore } from "stores";
interface Props {
gameStore?: GameStore;
authStore?: AuthStore;
}
const GamePage = ({ gameStore, authStore }: Props) => {
const [selectedUserIdx, setSelectedUserIdx] = React.useState<any>(null);
const { id: gameId } = useParams();
const notify = useNotify();
const getUserTabIdx = (user: User): number => (user.id === game?.user1.id ? 0 : 2);
const getTabUser = (): User => (selectedUserIdx === 0 ? game?.user1 : game?.user2)!;
const game = React.useMemo(() => gameStore?.game, [gameStore?.game]);
const gameFinished = game?.status === "finished";
const hideOpponentTab = React.useMemo(() => {
if (!authStore?.user) return false;
const userTabIdx = getUserTabIdx(authStore?.user);
return userTabIdx !== selectedUserIdx && !gameFinished;
}, [selectedUserIdx]);
const onCodeProcessed = React.useCallback(async (runtimeId: number) => {
await gameStore?.notifyGamePlayers(runtimeId);
}, []);
const onRuntimeFinishedEvent = (data) => {
const user = authStore?.user?.id === gameStore?.game?.user1 ? gameStore?.game?.user1 : gameStore?.game?.user2;
notify(
<Flex gap={5} color={"background.dark"}>
<UserPreview user={user!} />
<Badge colorScheme="background.dark">failed={data.failed}</Badge>
<Badge colorScheme="background.dark">passed={data.passed}</Badge>
</Flex>,
"info",
);
if (!data.failed && data.passed) {
notify(`${user?.full_name} won the game!`, "success");
}
};
React.useEffect(() => {
gameStore?.setup(gameId, onRuntimeFinishedEvent);
}, []);
React.useEffect(() => {
if (authStore?.user) {
const idx = getUserTabIdx(authStore.user);
setSelectedUserIdx(idx);
}
}, [game]);
const getTabGradient = () => {
if (!game || !gameFinished) return "";
const dir = {
[game?.user1.id]: "r",
[game?.user2.id]: "l",
};
return `linear(to-${dir[game.winner_id!]}, blue.500, background.dark, red.400)`;
};
if (!game || selectedUserIdx === null) {
return "";
}
return (
<PageLayout size="middle">
<Tabs
index={selectedUserIdx}
my={5}
isFitted
colorScheme="gray"
variant={gameFinished ? "line" : "enclosed"}
onChange={(idx) => setSelectedUserIdx(idx)}
bgGradient={getTabGradient()}
>
<TabList borderColor={"outline"}>
<Tab>
<UserPreview user={game.user1} />
</Tab>
<Tab isDisabled _disabled={{ cursor: "pointer" }}>
<Flex flexDir={"column"}>
<Text>VS</Text>
{gameFinished && <Text color="yellow.300">(Finished)</Text>}
</Flex>
</Tab>
<Tab>
<UserPreview user={game.user2} isInverted />
</Tab>
</TabList>
</Tabs>
{!hideOpponentTab ? (
<ProblemPlayground
lproblemId={game.lang_problem_id}
gameId={game.id}
userId={getTabUser().id}
viewOnly={game.status === "finished"}
onCodeProcessed={onCodeProcessed}
/>
) : (
<Center mt={"15vh"}>
<Flex flexDir={"column"} alignItems={"center"} gap={5} color={"yellow.300"}>
<Heading size={"md"}>You can not see opponent's code during the game</Heading>
<FaBan fontSize={"50px"} />
</Flex>
</Center>
)}
</PageLayout>
);
};
export default inject("gameStore", "authStore")(observer(GamePage)); |
require "application_system_test_case"
class PaymentCardsTest < ApplicationSystemTestCase
setup do
@payment_card = payment_cards(:one)
end
test "visiting the index" do
visit payment_cards_url
assert_selector "h1", text: "Payment cards"
end
test "should create payment card" do
visit payment_cards_url
click_on "New payment card"
fill_in "Card brand", with: @payment_card.card_brand
fill_in "Card network", with: @payment_card.card_network
click_on "Create Payment card"
assert_text "Payment card was successfully created"
click_on "Back"
end
test "should update Payment card" do
visit payment_card_url(@payment_card)
click_on "Edit this payment card", match: :first
fill_in "Card brand", with: @payment_card.card_brand
fill_in "Card network", with: @payment_card.card_network
click_on "Update Payment card"
assert_text "Payment card was successfully updated"
click_on "Back"
end
test "should destroy Payment card" do
visit payment_card_url(@payment_card)
click_on "Destroy this payment card", match: :first
assert_text "Payment card was successfully destroyed"
end
end |
import axios from 'axios';
import React, { useState } from 'react';
import SignUpView from './SignUpView';
/**
* 회원가입
*
* @author yblee
* @since 2023. 12. 15.
*/
function SignUp() {
const ERROR_MSG = {
registerUser: '[User] 사용자 등록 실패',
};
const [input, setInput] = useState({});
/**
* 사용자 정보 저장
*
* @param {*} e 이벤트 발생
*
* @author yblee
* @since 2023. 12. 15.
*/
const inputUser = (e) => {
setInput({
...input,
[e.target.name]: e.target.value,
});
};
/**
* 사용자 정보 등록
*
* @author yblee
* @since 2023. 12. 15.
*/
const registerUser = async () => {
try {
const response = await axios.post(`/user/add`, input);
const msg = response.data.data;
if (response.data.status === 400) {
window.confirm(msg);
} else {
window.confirm(msg);
}
} catch (error) {
console.log('Error:', ERROR_MSG['registerUser']);
}
};
const props = {
inputUser,
registerUser,
};
return (
<div>
<SignUpView {...props} />
</div>
);
}
export default SignUp; |
public class Loop_Statements {
public static void main(String[] args) {
// While Loop
int a=1;
while (a<=10) {
System.out.println(a+" Shubham");
a=a+1;
}
System.out.println("While Loop Ended successfully!!");
// Do-while Loop
int i=100;
do {
System.out.println(i);
i +=1;
} while (i<10);
// For Loop
for(int b=5;b>0;b--){
System.out.println(b);
}
// For- Each Loop
String[] friends = { "Shubham", "Apurv", "Bhavesh", "suraj", "Jitendra", "Omkaar", "lokesh" };
// Displaying an array (Array traversal)
for (int k = 0; i < friends.length; k++) {
System.out.println(friends[k]);
}
// In reverse order printing
for (int j = friends.length - 1; j >= 0; j--) {
System.out.println(friends[j]);
}
// for each loop
for (String str : friends) {
System.out.println(str);
}
// Break and Continue
int n=1;
do {
System.out.println(n);
if (n==5) {
System.out.println("Loop ends here");
break;
}n++;
} while (n<10);
for(int c=0;c<10;c++){
if (c>=5 && c<8) {
continue;
}
System.out.println(c);
}
}
}
// Practice
// Q.1. Write a program to sum first n natural numbers (n taken from input)
// Q.2. Write a program to print multiplication table of given numbers using while loop(n=13)
// Q.3. Write a program to print the factorial of given number using for loop |
import { EmbedBuilder } from 'discord.js'
function lotteryCommand (msg, args, userBalances) {
const ticketPrice = 100
const userBalance = userBalances.get(msg.author.id) || 0
if (!args.length) {
const embed = new EmbedBuilder()
.setColor('#3498DB')
.setTitle('🎟️ ¡Bienvenido a la Gran Lotería! 🎟️')
.setDescription('Participa en nuestra emocionante lotería y gana premios increíbles. Elige un número de 3 digitos y podrías ser el próximo gran ganador.')
.addFields(
{ name: '💰 Precio del boleto', value: `${ticketPrice} <:Coin:1232427012702994533>` },
{ name: '🥇 Premio mayor (1er lugar)', value: '10000 <:Coin:1232427012702994533>' },
{ name: '🥈 Segundo lugar (2er lugar)', value: '5000 <:Coin:1232427012702994533>' },
{ name: '🥉 Tercer lugar (3er lugar)', value: '1000 <:Coin:1232427012702994533>' }
)
return msg.channel.send({ embeds: [embed] })
}
if (userBalance < ticketPrice) {
const embed = new EmbedBuilder()
.setColor('#E74C3C')
.setDescription('💸 **Oh no, parece que no tienes suficientes <:Coin:1232427012702994533> para comprar un boleto de lotería.**')
.addFields({ name: '💼 Saldo actual', value: `${userBalance} <:Coin:1232427012702994533>` })
return msg.channel.send({ embeds: [embed] })
}
userBalances.set(msg.author.id, userBalance - ticketPrice)
const winningNumbers = [Math.floor(Math.random() * 1000), Math.floor(Math.random() * 1000), Math.floor(Math.random() * 1000)]
if (isNaN(userNumber) || userNumber < 0 || userNumber > 999) {
const embed = new EmbedBuilder()
.setColor('#E74C3C')
.setDescription('❌ **Ups, parece que hubo un error. Debes elegir un número entre 000 y 999.**')
return msg.channel.send({ embeds: [embed] })
}
let prize
if (winningNumbers.includes(userNumber)) {
const place = winningNumbers.indexOf(userNumber) + 1
switch (place) {
case 1:
prize = 10000
break
case 2:
prize = 5000
break
case 3:
prize = 1000
break
}
} else {
prize = 0
}
userBalances.set(msg.author.id, userBalances.get(msg.author.id) + prize)
const embed = new EmbedBuilder()
.setColor(prize > 0 ? '#2ECC71' : '#E74C3C')
.setDescription(prize > 0 ? `🎉 ¡Felicidades! Has ganado ${prize} <:Coin:1232427012702994533>.` : '😢 Lo siento, no has ganado esta vez. ¡No te desanimes y sigue intentándolo!')
.addFields(
{ name: '💼 Tu nuevo saldo', value: `${userBalances.get(msg.author.id)} <:Coin:1232427012702994533>` }
)
msg.channel.send({ embeds: [embed] })
const winningEmbed = new EmbedBuilder()
.setColor('#3498DB')
.setTitle('🎟️ Números ganadores 🎟️')
.setDescription(`🥇 1er lugar: \`${winningNumbers[0]}\`, 🥈 2do lugar: \`${winningNumbers[1]}\`, 🥉 3er lugar: \`${winningNumbers[2]}\`.`)
return msg.channel.send({ embeds: [winningEmbed] })
}
export default lotteryCommand |
// Approach 2 : Recursive Method
// TC : O(logN) SC : O(logN)
#include <iostream>
const int MOD = 1000000007;
// Recursive function to calculate the power of a number
long long power(long long N, long long R){
if (N == 0)
return 1;
if (R == 1)
return N % MOD;
long long res = power(N, R / 2) % MOD;
res = (res * res) % MOD;
if (R % 2 == 0)
return res;
else
return (res * N) % MOD;
}
int main() {
// Sample input 1
int N1 = 2; // Number
int R1 = 2; // Reverse of the number
// Calculate power of N1 raised to R1
int result1 = power(N1, R1);
std::cout << "Result 1: " << result1 << std::endl;
// Sample input 2
int N2 = 12; // Number
int R2 = 21; // Reverse of the number
// Calculate power of N2 raised to R2
int result2 = power(N2, R2);
std::cout << "Result 2: " << result2 << std::endl;
return 0;
} |
package final_exam.exercise4;
import java.text.Normalizer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Management {
private ArrayList<Contact> contactList;
public Management() {
contactList = new ArrayList<>();
}
public boolean isPhoneNumberExists(String phoneNumber) {
for (Contact contact : contactList) {
if (contact.getPhoneNumber().equals(phoneNumber)) {
return true;
}
}
return false;
}
public void addContact(Scanner sc, Management contactManagement) {
System.out.print("Enter name: ");
String name;
do {
System.out.print("Name: ");
name = sc.nextLine().trim();
if (name.isEmpty()) {
System.out.println("Name cannot be empty. Please try again.");
}
} while (name.isEmpty());
System.out.print("Enter phone number: ");
String phoneNumber;
boolean phoneNumberCheck;
do {
System.out.print("Phone Number: ");
phoneNumber = sc.nextLine().trim();
if (!Validator.isValidPhoneNumber(phoneNumber)) {
System.out.println("Invalid phone number. Phone number must be 10 or 11 digits. Please try again.");
phoneNumberCheck = false;
} else if (contactManagement.isPhoneNumberExists(phoneNumber)) {
System.out.println("Phone number exists. Try another number phone");
phoneNumberCheck = false;
} else {
phoneNumberCheck = true;
}
} while (!phoneNumberCheck);
contactList.add(new Contact(name, phoneNumber));
System.out.println("Contact added successfully.");
}
public void editContact(String oldPhoneNumber, String newPhoneNumber) {
boolean oldExists = false;
boolean newExists = false;
for (Contact contact : contactList) {
if (contact.getPhoneNumber().equals(oldPhoneNumber)) {
oldExists = true;
}
if (contact.getPhoneNumber().equals(newPhoneNumber)) {
newExists = true;
}
}
if (oldExists && !newExists) {
for (Contact contact : contactList) {
if (contact.getPhoneNumber().equals(oldPhoneNumber)) {
contact.setPhoneNumber(newPhoneNumber);
System.out.println("Contact updated successfully.");
return;
}
}
} else {
System.out.println("Make sure old number exists and new number does not exist. Try again!");
}
}
public void sortContacts() {
contactList.sort(Comparator.comparing(Contact::getName));
}
public void searchContact(String name) {
boolean checkSearch = false;
System.out.println("Search results for \"" + name + "\":");
System.out.println("+-----------------+-----------------+");
System.out.println("| Name | Phone Number |");
System.out.println("+-----------------+-----------------+");
for (Contact contact : contactList) {
String nameFormat = removeDiacritics(contact.getName().toLowerCase());
if (nameFormat.contains(removeDiacritics(name.toLowerCase()))) {
System.out.printf("| %-15s | %-15s |\n", contact.getName(), contact.getPhoneNumber());
checkSearch = true;
}
}
if (!checkSearch) {
System.out.println("| NO DATA MATCH |");
System.out.println("+-----------------+-----------------+");
}
}
public void display() {
if (contactList.isEmpty()) {
System.out.println("Contact list is empty.");
} else {
System.out.println("Contact list:");
System.out.println("+----+-----------------+-----------------+");
System.out.println("| ID | Name | Phone Number |");
System.out.println("+----+-----------------+-----------------+");
for (int i = 0; i < contactList.size(); i++) {
Contact contact = contactList.get(i);
System.out.printf("| %-2d | %-15s | %-15s |\n", i + 1, contact.getName(), contact.getPhoneNumber());
System.out.println("+----+-----------------+-----------------+");
}
}
}
private String removeDiacritics(String str) {
String nfdNormalizedString = Normalizer.normalize(str, Normalizer.Form.NFD);
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");
return pattern.matcher(nfdNormalizedString).replaceAll("");
}
} |
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.as.oss.networkusage.ui.user;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.AndroidAccessToCollectors.toImmutableList;
import android.util.Pair;
import com.google.android.as.oss.networkusage.db.ConnectionDetails;
import com.google.android.as.oss.networkusage.db.NetworkUsageEntity;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.Multimaps;
import java.time.LocalDate;
import java.util.Collection;
/**
* Merges groups of similar items in the list into one {@link NetworkUsageEntity} that has the total
* size and latest creationDate of the group. Items are considered similar if they have the same
* {@link ConnectionDetails}. This eliminates unnecessarily repeated entries for a single update,
* for example when an update consists of multiple downloads.
*/
class MergeSimilarEntitiesPerDayProcessor implements EntityListProcessor {
@Override
public ImmutableList<NetworkUsageItemWrapper> process(
ImmutableList<NetworkUsageItemWrapper> networkUsageItems) {
ImmutableListMultimap<Pair<ConnectionDetails, LocalDate>, NetworkUsageItemWrapper>
groupedItems =
Multimaps.index(
networkUsageItems,
item ->
Pair.create(
item.connectionDetails(),
NetworkUsageItemUtils.getLocalDate(item.latestCreationTime())
.atStartOfDay()
.toLocalDate()));
return groupedItems.asMap().values().stream().map(this::mergeItems).collect(toImmutableList());
}
// TODO: display the group of merged entities in NetworkUsageItemDetailsActivity
NetworkUsageItemWrapper mergeItems(Collection<NetworkUsageItemWrapper> networkUsageItems) {
checkArgument(!networkUsageItems.isEmpty());
return networkUsageItems.stream()
.reduce(
(item1, item2) ->
new NetworkUsageItemWrapper(
ImmutableList.<NetworkUsageEntity>builder()
.addAll(item1.networkUsageEntities())
.addAll(item2.networkUsageEntities())
.build()))
.orElseThrow(AssertionError::new);
}
} |
import { createSlice } from "@reduxjs/toolkit";
import { RootState } from "../../store";
import { User, Post } from "../../tipos/types";
import { john, mike } from "../../mockData";
type PostBookmarkedAction = { payload: Post };
const initialState: { currentUser: User } = { currentUser: john };
export const userSlice = createSlice({
name: "user",
initialState,
reducers: {
bookmarkedPost: {
prepare(post) {
return { payload: post };
},
reducer(state, action: PostBookmarkedAction) {
const post = action.payload;
const isBookmarked = state.currentUser.postsBookmarked[post.id];
if (isBookmarked) {
delete state.currentUser.postsBookmarked[post.id];
} else {
state.currentUser.postsBookmarked[post.id] = post;
}
},
},
switchUser: (state) => {
if (state.currentUser.uuid === "1") {
state.currentUser = mike;
} else {
state.currentUser = john;
}
},
},
});
export const { bookmarkedPost, switchUser } = userSlice.actions;
export const userSelector = (state: RootState) => state.user.currentUser;
export const userReducer = userSlice.reducer; |
/*******************************************************************************
* Copyright (c) 2016 Stefan Reichert
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Stefan Reichert - initial API and implementation
*******************************************************************************/
package net.wickedshell.ds.tx;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import net.wickedshell.ds.tx.internal.TransactionManager;
/**
* Aspect that provides a {@link TransactionContext} for methods annotated with
* {@link Transactional}. The aspect uses the {@link TransactionManager}
* instance from the bundle context
*
* @author Stefan Reichert
*
*/
public aspect TransactionalAspect {
pointcut transactionalMethod() : execution(@Transactional * *(..));
Object around() : transactionalMethod() {
BundleContext bundleContext = FrameworkUtil.getBundle(Transactional.class).getBundleContext();
ServiceReference<TransactionManager> serviceReference = bundleContext
.getServiceReference(TransactionManager.class);
if (serviceReference == null) {
throw new IllegalStateException("failed to handle transaction; no transaction manager available");
}
TransactionManager transactionManager = bundleContext.getService(serviceReference);
Object returnValue;
transactionManager.begin();
try {
returnValue = proceed();
transactionManager.commit();
return returnValue;
} catch (RuntimeException exception) {
transactionManager.rollback(exception);
throw exception;
} finally {
transactionManager.close();
if (serviceReference != null) {
bundleContext.ungetService(serviceReference);
}
}
}
} |
// Function.length retorna o total de argumentos da função. Function.name retorna uma string com o nome da função.
function somar(n1, n2) {
return n1 + n2;
}
somar.length; // 2
somar.name; // 'somar'
// --------------------------------------------------------------------------------------------------------------------
// function.call(this, arg1, arg2, ...) executa a função, sendo possível passarmos uma nova referência ao this da mesma.
const carro = {
marca: 'Ford',
ano: 2018
}
// como marca e ano são atributos que não foram definidos dentro da função, apenas estão sendo
// passados diretamente, então a forma de passar valores para eles na cchamada da função é usando call()
// e os valores em objetos.
function descricaoCarro() {
console.log(this.marca + ' ' + this.ano);
}
descricaoCarro() // undefined undefined
descricaoCarro.call() // undefined undefined
descricaoCarro.call(carro) // Ford 2018
// --------------------------------------------------------------------------------------------------------------------
// O valor de this faz referência ao objeto criado durante a construção do objeto (Constructor Function). Podemos trocar
// a referência do método ao this, utilizando o call().
const carros = ['Ford', 'Fiat', 'VW'];
carros.forEach((item) => {
console.log(item);
}); // Log de cada Carro
carros.forEach.call(carros, (item) => {
console.log(item);
}); // Log de cada Carro
const frutas = ['Banana', 'Pêra', 'Uva'];
// O this é carros, porém, o call altera o this, então mesmo que carros esteja ligado ao forEach, o call mudou o this para frutas
carros.forEach.call(frutas, (item) => {
console.log(item);
}); // Log de cada Fruta
// --------------------------------------------------------------------------------------------------------------------
// Exemplo real - O objeto atribuído a lista será o substituído pelo primeiro argumento de call()
// criando construtor
function Dom(seletor) {
this.element = document.querySelector(seletor)
};
// criando método ativo
Dom.prototype.ativo = function (classe) {
this.element.classList.add(classe);
};
// criando objeto que herda coisas do construtor Dom
const lista = new Dom('ul');
lista.ativo('ativar');
console.log(lista);
// O novo valor de this deve ser semelhante a estrutura do valor do this original do método.
// Caso contrário o método não conseguirá interagir de forma correta com o novo this.
// Como nesse caso que o ul é substituído por um li.
// criando um novo objeto
const novoSeletor = {
element: document.querySelector('li')
}
// acesso o Dom para alcançar o método ativo, porque o novoSeletor diferente de lista, não tem nenhuma ligação com o construtor,
// depois disso substituo o this por novoSeletor e passo a classe que será adicionada a esse novo seletor
Dom.prototype.ativo.call(novoSeletor, 'ativar');
console.log(novoSeletor);
// --------------------------------------------------------------------------------------------------------------------
// HTMLCollection, NodeList e demais objetos do Dom, são parecidos com uma array. Por isso conseguimos utilizar os mesmos
// na substituição do this em call.
const li = document.querySelectorAll('li');
const filtro = Array.prototype.filter.call(li, function (item) {
// filter no caso retorna o que for true, por isso listando as
// classes e
return item.classList.contains('ativo');
});
// filtro retorna os itens que possuem ativo
// --------------------------------------------------------------------------------------------------------------------
// O apply(this, [arg1, arg2, ...]) funciona como o call, a única diferença é que os argumentos da função são passados
// através de uma array.
// por array - se a váriavel numeros fosse uma função, teria que ser chamada dentro de [], para ser numa array
const numeros = [3, 4, 6, 1, 34, 44, 32];
Math.max.apply(null, numeros);
// direto separando por vírgula
Math.max.call(null, 3, 4, 5, 6, 7, 20);
// Podemos passar null para o valor
// de this, caso a função não utilize
// o objeto principal para funcionar
// --------------------------------------------------------------------------------------------------------------------
// bind() - a única diferença dele para apply e call é que ele não ativa a função, então depois tem que ativar
const lis = document.querySelectorAll('li');
const filtrarLi = Array.prototype.filter.bind(lis, function (item) {
return item.classList.contains('ativo');
});
filtrarLi();
// Não precisamos passar todos os argumentos no momento do bind, podemos passar os mesmos na nova função no momento
// da execução da mesma.
const carroBind = {
marca: 'Ford',
ano: 2018,
acelerar: function (aceleracao, tempo) {
return `${this.marca} acelerou ${aceleracao} em ${tempo}`;
}
}
carroBind.acelerar(100, 20);
// Ford acelerou 100 em 20
const honda = {
marca: 'Honda',
};
const acelerarHonda = carroBind.acelerar.bind(honda);
acelerarHonda(200, 10);
// Honda acelerou 200 em 10
// --------------------------------------------------------------------------------------------------------------------
// Podemos passar argumentos padrões para uma função e retornar uma nova função.
function imc(altura, peso) {
return peso / (altura * altura);
}
const imc180 = imc.bind(null, 1.80);
imc(1.80, 70); // 21.6
imc180(70); // 21.6
// --------------------------------------------------------------------------------------------------------------------
// Exercício
// Retorne a soma total de caracteres dos parágrafos acima utilizando reduce
const paragrafos = document.querySelectorAll('p');
const totalCaracteres = Array.prototype.reduce.call(paragrafos, (acumulador, item) => {
return acumulador + item.innerText.length;
}, 0)
console.log(totalCaracteres);
// Crie uma função que retorne novos elementos html, com os seguintes parâmetros tag, classe e conteudo.
function criarElemento(tag, classe, conteudo){
const elemento = document.createElement(tag);
classe ? elemento.classList.add(classe) : null;
conteudo ? elemento.innerHTML = conteudo : null;
return elemento;
}
console.log(criarElemento('div', 'ativo', 'Esse é meu conteúdo'));
// --------------------------------------------------------------------------------------------------------------------
function criarH1(conteudo){
const elemento = document.createElement('h1');
elemento.classList.add('titulo');
conteudo ? elemento.innerHTML = conteudo : null;
return elemento;
}
console.log(criarH1('Esse é meu conteúdo de h1'));
// ou
const h1Titulo = criarElemento.bind(null, 'h1', 'titulo');
console.log(h1Titulo('Cursos')); |
import {Priority} from '@prisma/client';
import React from 'react';
import {RoundedSquareBackground} from './RoundedSquareBackground';
import {priorityColors} from '../../utils/priorityColors';
import {MenuItem, Select} from '@mui/material';
import {objectKeys} from '~/utils/objectKeys';
import emotionStyled from '@emotion/styled';
type Props = {
priority: Priority;
editable?: boolean;
onChange?: (priority: Priority) => void;
}
export const PriorityTag: React.FC<Props> = (props) => {
const color = priorityColors[props.priority]
if (props.editable) {
return (
<PrioritySelect
variant='standard'
renderValue={(value) => <>{value}</>}
value={props.priority}
onChange={(evt) => {
if (props.onChange) {
props.onChange(evt.target.value as Priority)
}
}}
style={{color: color.foreground, background: color.background}}
>
{objectKeys(Priority).map(key => {
const priorityColor = priorityColors[key]
return (
<MenuItem key={key} value={key}>
<RoundedSquareBackground foregroundColor={priorityColor.foreground} backgroundColor={priorityColor.background}>
{key}
</RoundedSquareBackground>
</MenuItem>
)
})}
</PrioritySelect>
)
}
return (
<RoundedSquareBackground foregroundColor={color.foreground} backgroundColor={color.background}>
{props.priority}
</RoundedSquareBackground>
)
}
const PrioritySelect = emotionStyled(Select)({
borderRadius: `6px`,
minHeight: `24px`,
fontWeight: 700,
fontSize: `0.75rem`,
textTransform: `capitalize`,
padding: `0 6px`,
'::before': {
content: `none`,
},
'::after': {
content: `none`,
},
'& .MuiSelect-select:focus': {
background: `none`,
},
}) |
package com.dicoding.todoapp.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.dicoding.todoapp.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
//TODO 3 : Define room database class and prepopulate database using JSON
@Database(entities = [Task::class], version = 1, exportSchema = true)
abstract class TaskDatabase : RoomDatabase() {
abstract fun taskDao(): TaskDao
companion object {
@Volatile
private var INSTANCE: TaskDatabase? = null
fun getInstance(context: Context): TaskDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
TaskDatabase::class.java,
"task.db"
).fallbackToDestructiveMigration().build()
INSTANCE = instance
val preferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE)
val isLoad = preferences.getBoolean("isLoad", false)
if(!isLoad){
preferences.edit().putBoolean("isLoad", true).apply()
runBlocking{
withContext(Dispatchers.IO) {
fillWithStartingData(
context,
instance.taskDao()
)
}
}
}
instance
}
}
private fun fillWithStartingData(context: Context, dao: TaskDao) {
val task = loadJsonArray(context)
try {
if (task != null) {
for (i in 0 until task.length()) {
val item = task.getJSONObject(i)
dao.insertAll(
Task(
item.getInt("id"),
item.getString("title"),
item.getString("description"),
item.getLong("dueDate"),
item.getBoolean("completed")
)
)
}
}
} catch (exception: JSONException) {
exception.printStackTrace()
}
}
private fun loadJsonArray(context: Context): JSONArray? {
val builder = StringBuilder()
val `in` = context.resources.openRawResource(R.raw.task)
val reader = BufferedReader(InputStreamReader(`in`))
var line: String?
try {
while (reader.readLine().also { line = it } != null) {
builder.append(line)
}
val json = JSONObject(builder.toString())
return json.getJSONArray("tasks")
} catch (exception: IOException) {
exception.printStackTrace()
} catch (exception: JSONException) {
exception.printStackTrace()
}
return null
}
}
} |
import React from "react";
import { useEffect } from "react";
import ReactPlayer from "react-player";
import { useLocation } from "react-router-dom";
import { useResultContext } from "../../contexts/ResultContextProvider";
import { Loading } from "../Loading";
import {
ImagesWrapper,
ImageWrapper,
PlayerWrapper,
VideosWrapper,
VideoWrapper,
Wrapper,
} from "./style";
export const Results = ({ darkTheme }) => {
const { getResults, results, loading, searchTerm } = useResultContext();
const location = useLocation();
useEffect(() => {
if (searchTerm) {
if (location.pathname === "/video")
getResults(`/search/q=${searchTerm} video`);
else getResults(`${location.pathname}/q=${searchTerm}&num=30`);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchTerm, location.pathname]);
if (loading) return <Loading />;
switch (location.pathname) {
case "/search":
return (
<Wrapper darkTheme={darkTheme}>
{results?.results?.map(({ link, title }, index) => (
<a href={link} target="_blank" rel="noreferrer" key={index}>
<p>{link.length > 30 ? link.substring(0, 30) : link}</p>
<h2>{title}</h2>
</a>
))}
</Wrapper>
);
case "/news":
return (
<Wrapper darkTheme={darkTheme}>
{results?.entries?.map(({ link, title }, index) => (
<a href={link} target="_blank" rel="noreferrer" key={index}>
<p>{link.length > 30 ? link.substring(0, 30) : link}</p>
<h2>{title}</h2>
</a>
))}
</Wrapper>
);
case "/video":
return (
<VideosWrapper>
{results?.results?.map((video, index) => (
<VideoWrapper key={index} darkTheme={darkTheme}>
<a href={video?.link}>
<p>{video?.link}</p>
<h2>{video?.title}</h2>
</a>
{video?.additional_links?.[0]?.href && (
<PlayerWrapper>
<ReactPlayer
url={video?.additional_links?.[0]?.href}
controls
className="videoPlayer"
key={index}
/>
<div>
<p style={{ marginBottom: "10px" }}>{video?.description}</p>
<p>{video?.title}</p>
</div>
</PlayerWrapper>
)}
</VideoWrapper>
))}
</VideosWrapper>
);
case "/image":
return (
<ImagesWrapper darkTheme={darkTheme}>
{results?.image_results?.map(({ link, image }, index) => (
<a href={link.href} target="_blank" rel="noreferrer" key={index}>
<ImageWrapper>
<img src={image.src} alt={image.alt} />
</ImageWrapper>
<p>{link?.title}</p>
</a>
))}
</ImagesWrapper>
);
default:
return "ERROR!";
}
}; |
from apps.hitmen.mixins import (
AdminAndManagersPermissionMixin,
AutheticatedPermissionMixin,
)
from apps.hits.forms import HitAddForm, HitAddBulkForm, HitUpdateForm
from apps.hits.models import Hits
from django.views.generic import DetailView, ListView, UpdateView
from django.views.generic.edit import FormView
from apps.hitmen.managers import UserManager
from apps.hitmen.models import User
from django.shortcuts import redirect
from django.urls import reverse_lazy
class HitRegisterView(AdminAndManagersPermissionMixin, FormView):
template_name = "hits/register.html"
form_class = HitAddForm
success_url = reverse_lazy("hits_app:hit-list")
def get_form(self, form_class=None):
if form_class is None:
form_class = self.get_form_class()
return form_class(user=self.request.user, **self.get_form_kwargs())
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super(HitRegisterView, self).form_valid(form)
class HitAddBulkView(AdminAndManagersPermissionMixin, FormView):
template_name = "hits/bulk.html"
form_class = HitAddBulkForm
success_url = "/hits"
def form_valid(self, form):
Hits.objects.create_hit(
form.cleaned_data["assigne"],
form.cleaned_data["description"],
form.cleaned_data["target_name"],
form.cleaned_data["status"],
form.cleaned_data["creator"],
)
return super(HitAddBulkView, self).form_valid(form)
class HitDetailView(AutheticatedPermissionMixin, UpdateView):
model = Hits
template_name = "hits/detail.html"
success_url = reverse_lazy("hits_app:hit-list")
form_class = HitUpdateForm
# def post(self, request, *args, **kwargs):
# self.object = self.get_object()
# return super().post(request, *args, **kwargs)
# def form_valid(self, form):
# self.object = form.save(commit=False)
# self.object.save()
# return super(HitDetailView, self).form_valid(form)
class HitListView(AutheticatedPermissionMixin, ListView):
template_name = "hits/list.html"
context_object_name = "hits"
paginate_by = 5
def get_queryset(self):
if self.request.user.is_superuser:
return Hits.objects.all()
else:
return Hits.objects.hits_of_hitmen(self.request.user.id) |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NetCoreSample.Classes;
using NetCoreSample.Interfaces;
using NetCoreSample.Models.DTO;
namespace NetCoreSample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DatabaseContext>(options => options.UseNpgsql(Configuration["ConnectionStrings:SampleDatabase"]));
services.AddTransient<JobTaskRepository>();
services.AddSingleton<IJobTaskRunner, JobTaskRunner>();
services.AddControllers();
services.AddSwaggerGen();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DatabaseContext databaseContext)
{
databaseContext.Database.Migrate();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
c.RoutePrefix = string.Empty;
});
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
} |
var chalk = require('chalk');
var util = require('util');
function NestedReporter(extendBaseReporter, formatError, config, options) {
var self = this;
extendBaseReporter(self);
// Allow ourselves to call superclass methods.
self._super = {
specFailure: self.specFailure.bind(self)
};
options = options || {};
options.icon = options.icon || {};
options.icon.failure = options.icon.failure || '✘ ';
options.icon.indent = options.icon.indent || 'ட ';
options.color = options.color || {};
options.color.should = options.color.should || 'red';
options.color.browser = options.color.browser || 'yellow';
if (config.colors) {
self.USE_COLORS = true;
self.LOG_SINGLE_BROWSER = '%s: ' + chalk.cyan('%s') + '\n';
self.LOG_MULTI_BROWSER = '%s %s: ' + chalk.cyan('%s') + '\n';
self.SPEC_FAILURE = chalk.red('%s %s FAILED') + '\n';
self.SPEC_SLOW = chalk.yellow('%s SLOW %s: %s') + '\n';
self.ERROR = chalk.red('%s ERROR') + '\n';
self.FINISHED_ERROR = chalk.red(' ERROR');
self.FINISHED_SUCCESS = chalk.green(' SUCCESS');
self.FINISHED_DISCONNECTED = chalk.red(' DISCONNECTED');
self.X_FAILED = chalk.red(' (%d FAILED)');
self.TOTAL_SUCCESS = chalk.green('TOTAL: %d SUCCESS') + '\n';
self.TOTAL_FAILED = chalk.red('TOTAL: %d FAILED, %d SUCCESS') + '\n';
}
self.onBrowserComplete = function() {
self.write('\n');
self.write(self._refresh());
};
self.onBrowserStart = function(browser) {
self._browsers.push(browser);
if (self._isRendered) {
self.write('\n');
}
self.write(self._refresh());
};
self.onRunStart = function() {
self._browsers = [];
self._isRendered = false;
};
self.specFailure = function(browser, result) {
var depth = result.suite.length;
return self._super.specFailure.call(self, browser, {
log: result.log,
description:
'\n' +
self._repeat(depth, ' ') +
options.icon.indent +
options.icon.failure +
result.description,
suite: result.suite.map(function(description, i) {
return '\n' + self._repeat(i, ' ') + options.icon.indent + description;
})
});
};
}
NestedReporter.prototype._repeat = function(n, str) {
var res = [];
var i;
for (i = 0; i < n; ++i) {
res.push(str);
}
return res.join('');
};
NestedReporter.prototype._remove = function() {
var cmd = '';
if (!this._isRendered) {
return '';
}
this._browsers.forEach(function() {
cmd += '\x1B[1A' + '\x1B[2K';
});
this._isRendered = false;
return cmd;
};
NestedReporter.prototype._render = function() {
this._isRendered = true;
return this._browsers.map(this.renderBrowser).join('\n') + '\n';
};
NestedReporter.prototype._refresh = function() {
return this._remove() + this._render();
};
// Register with Karma
// ---------------------------------------------------------------------------
NestedReporter.$inject = [
'baseReporterDecorator',
'formatError',
'config',
'config.nestedReporter'
];
module.exports = {
'reporter:nested': ['type', NestedReporter]
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.